text
stringlengths 37
1.41M
|
---|
def baseConverter(decNumber,base):
digits = "0123456789ABCDEF"
newString = ""
while decNumber > 0:
rem = decNumber % base
decNumber = decNumber // base
newString = digits[rem] + newString
return newString
print("Decimal to binary:", baseConverter(1001,2))
print("Decimal to hexadecimal:", baseConverter(1001,16))
print("Decimal to octal:", baseConverter(1001,8))
def octal_to_decimal(number):
i = 1
decimal = 0
while (number != 0):
reminder = number % 10
number /= 10
decimal += reminder * i
i *= 8
return decimal
print("Octal to decimal:", octal_to_decimal(144))
print("Octal to octal:", baseConverter(octal_to_decimal(144),2))
print("Octal to hexadecimal:", baseConverter(octal_to_decimal(144),16))
def binary_to_decimal(bin):
bin=str(bin)
n=len(bin)
res=0
for i in range(1,n+1):
res = res + int(bin[i-1])*2**(n-i)
return res
print("Binary to decimal:", binary_to_decimal(1101))
print("Binary to octal:", baseConverter(binary_to_decimal(1101),8))
print("Binary to hexadecimal:", baseConverter(binary_to_decimal(1101),16))
def hex_to_decimal(hex):
n=len(hex)
res=0
b=0
for i in range(0,n):
if hex[i] == "A":
b = 10
elif hex[i] == "B":
b = 11
elif hex[i] == "C":
b = 12
elif hex[i] == "D":
b = 13
elif hex[i] == "E":
b = 14
elif hex[i] == "F":
b = 15
else:
if hex[i].isalpha():
break
else:
b = hex[i]
res = res + int(b) * 16**((n-1)-i)
return res
print("Hexadecimal to decimal:", hex_to_decimal("3E9"))
print("Hexadecimal to octal:", baseConverter(hex_to_decimal("3E9"),8))
print("Hexadecimal to binary:", baseConverter(hex_to_decimal("3E9"),2))
|
# Python3 program to find maximum difference
# between node and its ancestor
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None left
# and right poers.
class newNode:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
"""
Recursive function to calculate maximum
ancestor-node difference in binary tree.
It updates value at 'res' to store the
result. The returned value of this function
is minimum value in subtree rooted with 't' """
def maxDiffUtil(t, res):
""" Returning Maximum value if node
is not there (one child case) """
if (t == None):
return _MAX, res
""" If leaf node then just return
node's value """
if (t.left == None and t.right == None):
return t.key, res
""" Recursively calling left and right
subtree for minimum value """
a, res = maxDiffUtil(t.left, res)
b, res = maxDiffUtil(t.right, res)
val = min(a, b)
""" Updating res if (node value - minimum
value from subtree) is bigger than res """
res = max(res, t.key - val)
""" Returning minimum value got so far """
return min(val, t.key), res
""" This function mainly calls maxDiffUtil() """
def maxDiff(root):
# Initialising result with minimum value
res = _MIN
x, res = maxDiffUtil(root, res)
return res
# Driver Code
if __name__ == '__main__':
root = newNode(8)
root.left = newNode(15)
root.left.left = newNode(1)
root.left.right = newNode(6)
root.left.right.left = newNode(4)
root.left.right.right = newNode(7)
root.right = newNode(10)
root.right.right = newNode(14)
root.right.right.left = newNode(13)
print("Maximum difference between a node and", "its ancestor is :", maxDiff(root))
|
def partition(lst, start, end):
pos = start # condition was obsolete, loop won't
# simply run for empty range
for i in range(start, end): # i must be between start and end-1
if lst[i] < lst[end]: # in your version it always goes from 0
lst[i],lst[pos] = lst[pos],lst[i]
pos += 1
lst[pos],lst[end] = lst[end],lst[pos] # you forgot to put the pivot
# back in its place
return pos
def quick_sort_recursive(lst, start, end):
if start < end: # this is enough to end recursion
pos = partition(lst, start, end)
quick_sort_recursive(lst, start, pos - 1)
quick_sort_recursive(lst, pos + 1, end)
# you don't need to return the list
# it's modified in place
example = [3,45,1,2,34]
quick_sort_recursive(example, 0, len(example) - 1)
print(example)
|
# Binary Tree Traversal: O(n) complexity
class Node:
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to print the height of binary tree
def printLevelOrder(root):
# Base Case
if root is None:
return
# Create an empty queue for level order traversal using queue
queue = []
# Enqueue Root and initialize height
queue.append(root)
while(len(queue) > 0):
# Print front of queue and remove it from queue
print(queue[0].data),
node = queue.pop(0)
#Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
# Iterative function for inorder tree traversal using stack
def inOrder(root):
# Set current to root of binary tree
current = root
s = [] # initialze stack
done = 0
while(not done):
# Reach the left most Node of the current Node
if current is not None:
# Place pointer to a tree node on the stack
# before traversing the node's left subtree
s.append(current)
current = current.left
# BackTrack from the empty subtree and visit the Node
# at the top of the stack; however, if the stack is
# empty you are done
else:
if(len(s) >0 ):
current = s.pop()
print(current.data),
# We have visited the node and its left
# subtree. Now, it's right subtree's turn
current = current.right
else:
done = 1
# Iterative function for preorder tree traversal using stack
def preOrder(root):
# Set current to root of binary tree
current = root
s = [] # initialze stack
done = 0
while(not done):
# Reach the left most Node of the current Node
if current is not None:
print(current.data),
# Place pointer to a tree node on the stack
# before traversing the node's left subtree
s.append(current)
current = current.left
# BackTrack from the empty subtree and visit the Node
# at the top of the stack; however, if the stack is
# empty you are done
else:
if(len(s) >0):
current = s.pop()
# We have visited the node and its left
# subtree. Now, it's right subtree's turn
current = current.right
else:
done = 1
def peek(stack):
if len(stack) > 0:
return stack[-1]
return None
# A iterative function to do postorder traversal using stack
def postOrder(root):
# Check for empty tree
if root is None:
return
stack = []
while(True):
while (root):
# Push root's right child and then root to stack
if root.right is not None:
stack.append(root.right)
stack.append(root)
# Set root as root's left child
root = root.left
# Pop an item from stack and set it as root
root = stack.pop()
# If the popped item has a right child and the
# right child is not processed yet, then make sure
# right child is processed before root
if (root.right is not None and
peek(stack) == root.right):
stack.pop() # Remove right child from stack
stack.append(root) # Push root back to stack
root = root.right # change root so that the
# righ childis processed next
# Else print root's data and set root as None
else:
print(root.data),
root = None
if (len(stack) <= 0):
break
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Level Order Traversal:")
printLevelOrder(root)
print("Inorder Traversal:")
inOrder(root)
print("Preorder Traversal:")
preOrder(root)
print("Postorder Traversal:")
postOrder(root)
|
#!/usr/bin/env python3
from inspect import signature
def curry(fn):
num_args = len(signature(fn).parameters)
def init(*args, **kwargs):
def call(*more_args, **more_kwargs):
all_args = args + more_args
all_kwargs = dict(**kwargs, **more_kwargs)
if len(all_args) + len(all_kwargs) >= num_args:
return fn(*all_args, **all_kwargs)
else:
return init(*all_args, **all_kwargs)
return call
return init()
def f(a, b, c):
return a + b + c
g = curry(f)
a = g(2)(4)(6)
print(f'a = {a}')
@curry
def sum(a, b, c, d):
return a + b + c + d
print(sum(1)(2, 4)(3))
print(sum(1, 2, 3)(4))
print(sum(1, 2, 3, 4))
|
#!/usr/bin/env python3
# Exercise
# Using a generator expression, define a generator for the series:
# (0, 2).. (1, 3).. (2, 4).. (4, 6).. (5, 7)
# This is a "generator expression"
g = ((a, b) for a, b in zip(range(0, 6), range(2, 8)) if a != 3)
for i in g:
print(i)
# This is a "list comprehension""
g = [(a, b) for a, b in zip(range(0, 6), range(2, 8)) if a != 3]
for i in g:
print(i)
|
#!/usr/bin/env python3
class Foo:
def __init__(self, x=0, name=None):
self.x = x
self.name = name
def __repr__(self):
return '{} -> x = {}'.format(self.name, self.x)
# AFAICT, the type annotations have no bearing at runtime. They
# are only relevant to the static type checker, so returning
# a float from a function that returns int is not a runtime error.
def foo(obj: Foo) -> int:
return obj.x + 3.3
if __name__ == '__main__':
x = Foo(5, "doug")
print(x)
a = foo(x)
print(a)
|
#!/usr/bin/env python2.7
from collections import namedtuple
Thing = namedtuple('Thingy', ['one', 'two'])
a = Thing('foo','bar')
c, b = a
print "a=", a # a is a Thingy
print "b=", b # b is 'bar'
print "c=", c # c is 'foo'
print "a.one = ", a.one
print "a.two = ", a.two
# Note that the naming of the fields can also done with a
# string containing a space or comma separated list
SThing = namedtuple('Thingy', 'one, two')
a = SThing(5, 6)
print('a.one = {}'.format(a.one))
|
#!/usr/bin/env python3
import itertools
a = (1, 2, 3, 4)
b = ("a", "b", "c")
# Stop when b is exhausted (similar to python2's itertools.izip)
for i in zip(a, b):
print(i)
# Fill in short lists with NULL (in python3, this is izip_longest)
for i in itertools.zip_longest(a, b):
print(i)
for i, (a, b) in enumerate(zip(a, b)):
print(i, a, b)
|
#!/usr/bin/env python3
"""
https://docs.python.org/3/glossary.html#term-sequence
An iterable which supports efficient element access using integer
indices via the __getitem__() special method and defines a __len__()
method that returns the length of the sequence. Some built-in
sequence types are list, str, tuple, and bytes.
"""
a = "abcdef"
for i, c in enumerate(a):
print(f"i = {i}, c = {c}")
|
#!/usr/bin/env python
from operator import itemgetter
# Sort tuple by 2nd index
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
# sort by .[2]
a = sorted(student_tuples, key=lambda student: student[2])
print('sorted by age:')
for x in a: print(x)
# sort by .[1], then by .[2]
a = sorted(student_tuples, key=itemgetter(1,2))
print('sorted by grade, then age:')
for x in a: print(x)
# For named attributes, use operator.attrgetter
class foo:
def __init__(self, a, b):
self.a = a
self.b = b
# define __lt__ to get sort method for free
def __lt__(self, other):
return self.a < other.a
def __repr__(self):
return f'{self.a}'
a = [foo(1,2), foo(5,6), foo(2,3)]
a.sort()
print(a)
|
"""
THIS IS MEANT TO BE THE REVERSE OF bomb_baby.py's SOLUTION
instead of starting from 1,1 and searching downwards, start from tm, tf and work backwards towards 1,1
If 1,1 is reachable, return the shortest number of moves to get there
If 1,1 is NOT reachable, return "impossible"
TUTORIALS USED:
https://www.youtube.com/watch?v=7QcoJjSVT38
https://www.youtube.com/watch?v=5MpT0EcOIyM&t=192s
"""
import copy
import time
#import numpy as np
import logging
logging.basicConfig(filename='bomb_baby_reverse_log', level=logging.DEBUG)
def solution(m, f):
tm = long(m)
tf = long(f)
'''# if one of the targets (m or f) is greater than the other by one, it exists.
# it exists in the tree at the level of the smaller target value
if tm == tf - 1 or tf == tm - 1:
return str(min(tm, tf))
# otherwise, if both values are 1, it exists at 0 depth of the tree
elif tm == tf and tf == 1:
return str(0)
# otherwise, if one of the values equal to half of the other, it will not exist in the tree
elif tm == tf / 2 or tf == tm / 2:
return "impossible"
# otherwise if one of the values is 1, and the other is any number greater than it, it exists
# at depth level of (larger value)-1
elif min(tm, tf) == 1 and max(tm, tf) > 1:
return str(max(tm, tf) - 1)'''
# the initial depth limit of the IDDFS is 0
depth_limit = 0
# the root of the tree to be generated in the search is the target value pair (depth=0)
root = ((tm, tf), 0)
# initialize the "failed" boolean flag to False
failed = False
'''BEGIN ITERATIVE-DEEPENING DEPTH-FIRST SEARCH'''
# this list will be used to store the unique values at the maximum depth level of a given
# depth-limited DFS
first_encounters = []
while not failed:
# print()
# print('depth_limit = {}'.format(depth_limit))
# time.sleep(2)
'''BEGIN DEPTH-BOUNDED DEPTH-FIRST SEARCH'''
# perform a depth-bounded search
if depth_limit == 0:
# if depth limit is zero, check if the input == 1,1
if (1, 1) == root[0]:
# if the input == 1,1 return 0 as the depth
return root[1]
else:
if depth_limit == 1:
# if the depth limit is 1, set the first_encounters list to contain only the root
first_encounters = [root]
# the previous_first_encounters list keeps track of all of the newly encountered sets from the last
# iteration of the loop, which will be used (in the following loop) to calculate the values in the next
# depth layer of the tree
previous_first_encounters = copy.deepcopy(first_encounters)
# empty out first_encounters in preparation for beginning to search a new depth layer
first_encounters = []
# use the newly encountered values from the previous depth layer to generate the values in this current
# depth layer
# while there are still values left to process, do the following for each...
while len(previous_first_encounters) > 0:
# remove a tree node from the stack, to be processed
node = previous_first_encounters.pop()
# assign the values to their own variables for easy access later
mach = long(node[0][0])
facula = long(node[0][1])
# assign the depth value to its own variable, for easy access later
node_depth = node[1]
'''DETERMINE WHETHER OR NOT A NODE IS THE GOAL NODE'''
# the goal node is (1,1)
if (mach, facula) == (1, 1):
# if this node is the goal node, return the depth at which it was found within the tree as a string
return str(node_depth)
else:
# if this is not the goal node, do the following...
# if the node is not at the deepest point allowed in the search...
if node_depth < depth_limit:
# increment the node_depth
# this variable now represents the depth of the soon-to-be-generated child nodes
node_depth += 1
# keep track of how many of the child nodes will be pushed to the stack
# (0 <= pushed_nodes <= 2)
pushed_nodes = 0
'''LEFT CHILD NODE'''
# if the left child's smallest value will be >= 1 (if the child node's values are valid) AND...
# if the depth of the left child is equal to the depth_limit (if the node is in the newest,
# and therefore un-explored depth layer)...
if mach - facula >= 1 and node_depth == depth_limit:
# generate the left child node
node_to_push = ((mach - facula, facula), node_depth)
# push the left child node to the stack of newly encountered nodes
first_encounters.append(node_to_push)
# increment the pushed_nodes counter by one, because a node was pushed to the stack
pushed_nodes += 1
# delete the node_to_push to save on memory
del node_to_push
'''RIGHT CHILD NODE'''
# if the right child's smallest value will be >= 1 (if the child node's values are valid) AND...
# if the depth of the right child is equal to the depth_limit (if the node is in the newest,
# and therefore un-explored depth layer)...
if facula - mach >= 1 and node_depth == depth_limit:
# generate the right child node
node_to_push = ((mach, facula - mach), node_depth)
# push the right child node to the stack of newly encountered nodes
first_encounters.append(node_to_push)
# increment the pushed_nodes counter by one, because a node was pushed to the stack
pushed_nodes += 1
# delete the node_to_push to save on memory
del node_to_push
# if there were no VALID newly encountered nodes, stop searching.
if len(first_encounters) == 0:
failed = True
'''END DEPTH-BOUNDED SEARCH'''
depth_limit += 1
return "impossible"
def solution2(M, F):
def trace_backwards(mach, facula, depth):
print(mach, facula)
if mach == 1 and facula > 1:
return str(depth + facula - 1)
elif mach > 1 and facula == 1:
return str(depth + mach - 1)
elif mach == 1 and facula == 1:
return str(depth)
elif mach == facula or max(mach, facula) % min(mach, facula) == 0:
return 'impossible'
else:
if mach > facula:
goes_into_times = mach//facula
return trace_backwards(mach-facula*goes_into_times, facula, depth+goes_into_times)
elif facula > mach:
goes_into_times = facula//mach
return trace_backwards(mach, facula-mach*goes_into_times, depth+goes_into_times)
tm, tf = long(M), long(F)
return trace_backwards(tm, tf, 0)
print(solution2('8', '3'))
'''print('4, 7...')
print(solution('4', '7'))
time.sleep(2)
print('2, 1...')
print(solution('2', '1'))
time.sleep(2)
print('2, 4...')
print(solution('2', '4'))
time.sleep(2)
print('10, 12...')
print(solution('10', '12'))
time.sleep(2)
print('10, 11...')
print(solution('10', '11'))
time.sleep(2)
print('13, 21...')
print(solution('13', '21'))
time.sleep(2)
print('123, 456...')
print(solution('123', '456'))
time.sleep(2)
print('1234, 567...')
print(solution('1234', '567'))
print('1234, 5678...')
print(solution('1234', '5678'))
time.sleep(2)
print('10000, 10000')
print(solution('10000', '10000'))
time.sleep(2)
print('10000, 9999')
print(solution('10000', '9999'))
time.sleep(2)
print('10**5, (10**5)-1')
print(solution(str(10 ** 5), str((10 ** 5 - 1))))
time.sleep(2)
print('10**50, (10**50)-1')
print(solution(str(10 ** 50), str((10 ** 50) - 1)))
time.sleep(2)
print('10**50, 10**5')
print(solution(str(10 ** 50), str(10 ** 5)))'''
|
import numpy as np
x = np.array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
print(x.shape)
y = np.expand_dims(x, axis=2)
print(y.shape)
print(y)
z = np.concatenate([y] * 3, 2)
print(z)
|
from datetime import *
def date_converter(date_string):
dates = date_string.split("-")
date_item = [int(item) for item in dates]
try:
new_date = date(date_item[0],date_item[1],date_item[2])
return new_date
except ValueError:
return date(9030,12,30)
def period_start_dates(last_period, cycle_averages,start_str, end_str):
last_period_date = date_converter(last_period)
end_date = date_converter(end_str)
start_date = date_converter(start_str)
if last_period_date>start_date:
return {"error":"date not in range"}
if start_date>end_date:
return {"error":"date not in range"}
date_list = []
while last_period_date < end_date :
cycle_average = timedelta(days=cycle_averages)
last_period_date = last_period_date + cycle_average
if start_date <= last_period_date <= end_date:
date_list.append(last_period_date)
return date_list
|
#!/usr/bin/env python3
def prime(n):
i = 2;
if n <= 1:
return False
while i * i <= n:
if n % i == 0:
return False
i = i + 1
return True
def main():
sum = 2
for i in range(3, 2000001, 2):
if prime(i):
# print(i)
sum += i
# print(sum)
print(("result is %d\n" % sum))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
#
# $ python3 14.py |sort -k2 -nr|head
# 837799 524
# 626331 508
# 939497 506
# 704623 503
# 927003 475
# 910107 475
# 511935 469
# 796095 467
# 767903 467
# 970599 457
#
def count(num):
c = 0
while True:
if num <= 1:
break
if num % 2 == 0:
num = num / 2
else:
num = num * 3 + 1
c += 1
return c
def main():
for i in range(800000, 1000000):
print((i, count(i)))
if __name__ == "__main__":
main()
|
####################################################################################################
## A simple feed forward network using tensorflow and some of its visualization tools
##Architecture
## 2 hidden layers 1 input and 1 output layers
## input layer : 10 neurons corresponding to season, mnth,holiday,weekday,workingday, weathersit, temp, atemp, hum, windspeed
##hidden layers with 5 and 3 neurons respectively
##output neuron. This is a regression type of problem where the output value predicts the answer "cnt" in the dataset.
####################################################################################################
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from matplotlib import pyplot as plt
#preprocessing the data
path="day.csv"
dataset=pd.read_csv(path)
costHistory=[]
learningRate=0.5
totalepoch=3000
samplesize=90
dataset=dataset.drop(['instant','dteday','casual','registered','yr'],axis=1)
#factors being used are season, mnth,holiday,workingday, weathersit, temp, atemp, hum, windspeed, cnt
dataset=shuffle(dataset)
####create tensor graph
#create placeholder to inject input to the tensorgraph
X=tf.placeholder(dtype="float",shape=[None,10],name="x-input")
Y=tf.placeholder(dtype="float",shape=[None,1],name='output')
weights={'w1':tf.Variable(tf.random_uniform([10,5],minval=1,maxval=9)),
'w2':tf.Variable(tf.random_uniform([5,1],minval=1,maxval=9))} #weights and biases as a dictionary
biases={'b1':tf.Variable(tf.constant(0.5)),
'b2':tf.Variable(tf.constant(0.3))}
layer1_output=tf.nn.relu6(tf.matmul(X,weights['w1']))
layer2_output=tf.nn.sigmoid(tf.matmul(layer1_output,weights['w2']))
cost=tf.reduce_sum(tf.pow((Y-layer2_output),1),axis=1)
optimizer=tf.train.GradientDescentOptimizer(learning_rate=learningRate).minimize(cost)
#run the graph
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(0,totalepoch):
trainingSample = dataset.sample(samplesize)
cnt = np.asarray(trainingSample['cnt']).reshape([samplesize,1])
trainingSample.drop(['cnt'], axis=1)
inparray=np.asarray([trainingSample['season'],trainingSample['mnth'],trainingSample['holiday'],trainingSample['weekday'],trainingSample['workingday'],trainingSample['weathersit'],trainingSample['temp'],trainingSample['atemp'],trainingSample['hum'],trainingSample['windspeed']])
inparray=inparray.transpose()
#print(inparray.shape)
#print(cnt.shape)
sess.run(optimizer,feed_dict={X:inparray,Y:cnt})
cst =sess.run(cost,feed_dict={X:inparray,Y:cnt})
costHistory.append(cst)
plt.plot(range(len(costHistory)), costHistory)
plt.show()
|
### Small: Single hotel
# The goal of the small exercise is to get practice with the syntax for querying and manipulating the data in a single, nested dictionary.
# Write functions to:
# - is_vacant(which_hotel, '101')
# - check if a room is occupied
# - check_in('101', guest_dictionary)
# - assign a person to a room
# - check_out('101')
# - returns the person dictionary in that room
# Please look back at any notes or slides for how to perform any of these actions.
###
# if hotel['101'] == {}:
# print(f'Room 101 is vacant.')
# Create dictionary for each additional guest
hotel = {
'101': {
'guest': {
'name': 'Peggy Sue',
'phone': '3331234',
}
},
'102': {},
'103': {},
'104': {},
'105': {},
}
# Creates a guest dictionary
guest1 = {
'name': 'Tracy Ellis',
'phone': '3331234',
}
# if hotel['101'] == {}:
# print(True)
# else:
# print(False)
# Creates a function call to check if a room is vacant
def is_vacant(which_hotel, room_number):
if which_hotel[room_number] == {}:
return f'Room {room_number} is vacant.'
else:
return f'Room {room_number} is occupied'
# Defines a function that adds a guest to a specific room
def check_in(room_number, guest_dictionary):
hotel[room_number]['guest'] = guest_dictionary
# Defines a function that returns the guest dictionary for room number
def check_out(room_number):
return f'{hotel[room_number]["guest"]}'
print(is_vacant(hotel, '102'))
check_in('102', guest1)
print(check_out('102'))
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
m=0
p=0
z=0
for i in arr:
if i <0:
m=m+1
elif i>0:
p=p+1
else:
z=z+1
sum=float(p+m+z)
print(float(p/sum))
print(m/sum)
print(z/sum)
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
|
import re
import requests
from bs4 import BeautifulSoup
from requests import Response
class GitHubConnector:
"""Class to access the GitHub API."""
def __init__(self, oauthToken: str = None) -> None:
"""Initalizes the class.
Parameters:
oauthToken (str): The personal access token needed to access the GitHub API.
Returns:
None: The class is initalized.
"""
self.token = oauthToken
def openConnection(self, url: str) -> Response:
"""Sends a request to a GitHub API endpoint.
Configures all of the headers prior to sending the request.
Parameters:
url (str): The GitHub API endpoint that is to be accessed.
Returns:
Reponse: The response data sent back to the application from the GitHub API endpoint.
"""
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Metrics-Dashboard",
"Authorization": "token {}".format(self.token),
}
return requests.get(url=url, headers=headers)
def parseResponseHeaders(self, response: Response) -> dict:
"""Get specific information from the response headers.
The data that is carred about is the rate limit and reset, as well as the next and last pages of the request if the response has been truncated.
Parameters:
response (Response): The response object sent back to the application from a request.
Returns:
dict: A dictionary of key-value pairs that only has the important information needed for the application to function properly.
"""
def _findLastPage() -> int:
"""Finds the last page within the header data.
Returns:
int: Returns the value of the last page of a request.
"""
try:
links = response.headers["Link"].split(",")
for link in links:
if link.find('rel="last"') != -1:
try:
return int("".join(re.findall("&page=([0-9]+)>", link)))
except ValueError:
return int("".join(re.findall("&page=([0-9]+)&", link)))
return -1
except KeyError:
return -1
return {
"Status-Code": response.status_code,
"X-RateLimit-Limit": response.headers["X-RateLimit-Limit"],
"X-RateLimit-Remaining": response.headers["X-RateLimit-Remaining"],
"X-RateLimit-Reset": response.headers["X-RateLimit-Reset"],
"Last-Page": _findLastPage(),
}
def returnRateLimit(self) -> int:
"""Gets the current rate limit of the oauthToken.
Returns:
int: The current rate limit of the oauthToken provided to the application.
"""
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Metrics-Dashboard",
"Authorization": "token {}".format(self.token),
}
data = requests.get(
url="https://api.github.com/rate_limit", headers=headers
).json()
return data["resources"]["core"]["remaining"]
class GitHubCommitWebScraper:
"""Class to scrape HTML content from GitHub commit pages."""
def __init__(self) -> None:
"""Initalizes the class."""
pass
def openConnection(self, url: str) -> BeautifulSoup:
"""Creates a BeautifulSoup object that is stored as a class variable.
Parameters:
url: A string that is formatted: https://github.com/{user}/{repo}/{commit}. Will be accessed via a GET request and its HTML content will be made availible as a BeautifulSoup object accessible via the *soup* class variable.
Returns:
An instance of a BeautifulSoup Web Scraper.
"""
resp = requests.get(url=url).text
return BeautifulSoup(markup=resp, features="html.parser")
|
# a = ['d', 's', 'a']
# b = ''.join(a)
# print(b)
# c = {1,2,3,4}
# d = {4,5,6,7,8}
# print(c & d)
# a = [1,2,3,4,5,5,5,5,7]
# b = set(a)
# a = list(b)
# print(a)
# phone_book = {'서울': '02', '경기': '031', '인청': '032'}
# print(phone_book.items())
# for i in range(2, 10):
# print('{}단'.format(i))
# for j in range(1, 10):
# print(f'{i} x {j} = {i*j}')
# word = input()
# vowels = 0
# consonants = 0
# for i in word:
# if i in 'aeiou':
# vowels += 1
# else:
# consonants += 1
# print(vowels, consonants)
# classroom = ['Kim', 'Hong', 'kang']
# print(list(enumerate(classroom, start=1)))
# basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
# fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
# fruit_num = 0
# fruit_numx = 0
# for k, v in basket_items.items():
# if k in fruits:
# fruit_num += v
# else:
# fruit_numx += v
# print(fruit_num, fruit_numx)
# city = {
# '서울': [-6, -10, 5],
# '대전': [-3, -5, 2],
# '광주': [0, -2, 10],
# '부산': [2, -2, 9],
# }
# cold = 0
# hot = 0
# count = 0
# hot_city = ""
# cold_city = ""
# for k, v in city.items():
# if max(v) > hot:
# hot = max(v)
# hot_city = k
# if min(v) < cold:
# cold = min(v)
# cold_city = k
# print(hot, hot_city, cold, cold_city)
# words = "hI! Everyone, I'm kim"
# print(words.swapcase())
# print('woooooowooo'.replace('o', '', 2))
# caffe = ['starbucks', 'tomntoms', 'hollys']
# caffe.append(['asfds'])
# caffe.extend(['adasfd'])
# print(caffe)
# print(dir(list))
# numbers = [2, 5, 4, 1, 7, 5]
# result = sorted(numbers, reverse=True)
# numbers.sort(reverse=True)
# print(result) # return값
# print(numbers) # 원본
# import random
# a = random.sample(numbers, 2)
# print(a)
my_dict = {'apple': '사과', 'banana': '바나나'}
a= my_dict.get('melon', True)
print(a)
|
import numpy as np
def get_n_click(bid, customer):
"""Function that returns a stochastic number of daily clicks of new users (i.e., that have never clicked before
these ads) as a function depending on the bid"""
alpha = 1
beta = 1
if customer == 1:
alpha = 100 # 300
beta = 0.8 # 0.02
elif customer == 2:
alpha = 120 # 500
beta = 0.2 # 0.003
elif customer == 3:
alpha = 70
beta = 0.06 # 0.02
"""
n = -1
while n < 0:
param = np.tanh(np.random.normal(loc=bid, scale=0.6 * np.tanh(bid)) * beta)
n_click = alpha * param
n = n_click"""
param = np.tanh(np.random.normal(loc=bid, scale=0.6 * np.tanh(bid)) * beta)
n_click = alpha * param
return n_click
def get_cost_x_click(bid):
"""Function that returns a stochastic cost per click as a function of the bid"""
#cost_per_click = 0
#while cost_per_click < 0:
cost_per_click = np.random.normal(loc=np.log(bid+1)/8, scale=0.01*np.tanh(bid), size=None)
return cost_per_click
# class 1: TT
# class 2: TF
# class 3: FF
def conv_rate(price, customer):
"""Function that is a conversion rate providing the probability that a user will buy the item given a price"""
alpha = 1
if customer == 1:
alpha = - 0.25
elif customer == 2:
alpha = - 0.5
elif customer == 3:
alpha = - 1.5
conv = np.exp(alpha*price)
return conv
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 16:44:35 2018
@author: D16129083
"""
coverPrice = input("What's the price of the cover book: ")
numberOfCopies = input("How many copies do you need: ")
discount = 0.4
initialShipping = 3.0
extraShipping = 0.75
totalCover = (float(coverPrice) - (float(coverPrice) * discount)) * int(numberOfCopies)
totalExtraShipping = (int(numberOfCopies) - 1) * extraShipping
total = totalCover + initialShipping + totalExtraShipping
print("The total of the order is", total)
# Item 9 - The total wholesale cost fot 60 copies is 945.4499999999999
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 29 15:30:30 2018
@author: D16129083
"""
# This method checks if the value inputed by the user is a number, otherwise it
# calls the method again
def get_user_input(title):
input_value = input(title)
if isInt(input_value) or isFloat(input_value):
return input_value
else:
print('Please type a value with the right format.')
return get_user_input(title)
# This method checks if some value is a float
def isFloat(value):
try:
float(value)
return True
except ValueError:
return False
# This method checks if some value is an int
def isInt(value):
try:
int(value)
return True
except ValueError:
return False
# All calculations happens here based on the user's info
def calculation(age, weight, height):
dog_years = int(age) / 7
weight_on_moon = float(weight) * .17
weight_on_sun = float(weight) * 27.07
weight_in_pounds = float(weight) / 0.45359237
height_in_inches = float(height) * 0.39370079
bmi = float(weight) / float(height) ** 2 * 10000
return dog_years, weight_on_moon, weight_on_sun, weight_in_pounds, height_in_inches, bmi
def main():
# Here all the information are gatheed from the user
age = get_user_input('What is your age? ')
weight = get_user_input('What is you weight in kgs? ')
height = get_user_input('What is your height in cms? ')
info = calculation(age, weight, height)
# All the infomation are displayed using the print statement
print('-'*60)
print('Your age in dog years is', format(info[0], '.0f'))
print('Your weight on the moon is ' + format(info[1], '.1f') + ' kgs and '+
format(info[2], '.1f') + ' kgs on the sun.')
print('Your weight in pounds is ' + format(info[3], '.1f') + ' pounds.')
print('Your height in inches is ' + format(info[4], '.0f') + ' inches.')
print('You BMI (Body Mass Index) is ' + format(info[5], '.1f'))
print('-'*60)
main()
|
'''WIDGETS AND GIZMOS'''
w=int(input('Enter number of widgets = '))
g=int(input('Enter number of gizmos = '))
widget_weight=w*75
gizmos_weight=g*112
total_weight=widget_weight+gizmos_weight
print('''
Widgets = %d
Gizmos = %d
Widget weight = %d
Gizmos weight = %d
------------------------------------
Total weight = %d
'''%(w,g,widget_weight,gizmos_weight,total_weight))
|
'''DISTANCE UNITS'''
f=float(input('Enter the distance in feet: '))
i=f*12
y=f*0.333333
m=f*0.000189394
print('''
Distance in feets= %f
Distance in inche= %f
Distance in yard = %f
Distance in miles= %f'''
%(f,i,y,m))
|
'''REPALCING A WORD IN PYTHON '''
str='HELLO TO ALL PYTHON COMMUNITY'
print('Original String : %s'%(str))
print('String after replacement : %s'%(str.replace('PYTHON','PYTHON 3.6')))
|
'''CELL PHONE BILL'''
mint=int(input('Enter total minute:'))
msg=int(input('Enter total message sent:'))
print('Base charge = $15')
amint=0
amsg=0
if mint>50:
amint=(mint-50)*.25
print('Additional minute charge = $%.2f'%(amint))
if msg>50:
amsg=(msg-50)*.15
print('Additional message charge = $%.2f'%(amsg))
print('911 charge = $0.44')
total=15+amint+amsg+.44
print('Total charge = $%.2f'%(total))
tax=.05*total
print('Tax = $%.2f'%(tax))
print('Final amount to be payed = $%.2f'%(total+tax))
|
'''input a number k and an array
There is an array find all possible pairs of numbers which when added is divisible by the number k
output count of successfully divisible pairs'''
arr=[]
divisible=[]
count=0
print('Enter the array elements:')
l=input()
while l!='':
arr.append(int(l))
l=input()
k=int(input('Enter a number:'))
i=0
l=len(arr)
while i!=l:
j=i+1
while j!=l:
num=arr[i]+arr[j]
if num%k==0:
divisible.append(num)
count=count=count+1
j=j+1
i=i+1
print('Number of elements divisible by :',count)
'''TESTCASES
------------------------------------------------------------
Enter the array elements:
3
5
7
2
Enter a number:4
Number of elements divisible are: 2
---------------------------------------------------------------
Enter the array elements:
2
3
4
2
Enter a number:5
Number of elements divisible are: 2
'''
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data", one_hot = True)
n_nodes_hl1= 500
n_nodes_hl2= 500
n_nodes_hl3= 500
num_class = 10
batch_size = 100
x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')
def NN_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,n_nodes_hl1])),
'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}
hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),
'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}
hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),
'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}
output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, num_class])),
'biases': tf.Variable(tf.random_normal([num_class]))}
l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)
l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)
output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
return output
def train_NN(x):
prediction = NN_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=prediction, logits= y))
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(cost)
n_epochs = 10
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for epoch in range(n_epochs):
epoch_loss =0
for _ in range(int(mnist.train.num_examples/batch_size)):
epoch_x,epoch_y = mnist.train.next_batch(batch_size)
_ , c = sess.run([optimizer, cost], feed_dict = {x:x, y:y})
epoch_loss += c
print ('Epoch', epoch, 'completed out of', n_epochs, 'loss:', epoch_loss)
correct_answer = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_answer, 'float'))
# print ('Accuracy': accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))
train_NN(x)
|
#Write methods to implement the multiply, subtract, and divide operations for
#integers. Use only the add operator.
def multiply(a,b):
result =0
count=0
while count<b:
result=result+a
count=count+1
return result
|
##Given a positive integer, print the next smallest and the next largest number
##that have the same number of 1 bits in their binary representation.
def _getNext(n):
"""
Trick is to flip a 1 to 0 and a 0 to 1. To get the next biggest number,
what you do is
1. Get the FIRST NON-TRAILING 0 when you read from right to left
Mark that point as p.
2. Get the count of 1's (c1) and 0's (c0) to the right of p
2.5. if c1+c0==32 or ==0, return -1
3. Flip the 0 at p (c1+c0) to 1
4. Clear out all the bits to the right of p
5. Add c1-1 ones at the right-most end
"""
c=n
c0=0
c1=1
while c&1==0 and c!=0:
c0+=1
c=c>>1
while c&1==1 and c!=0:
c1+=1
c=c>>1
#if number is 111..11000..000, no number bigger w/ same # of ones
if c0+c1==31 or c0+c1==0:
return -1
p=c0+c1
n=n^(1<<p) #set p to 1
n=n&~((1<<p)-1) #set everything after p to 0
n=n^((1<<(c1-1))-1)
return n
def _getPrevious(n):
"""
Just like getNext but the opposite. :D
p is FIRST NON-TRAILING 1
"""
c=n
c0=0
c1=0
while c&1==1:
c1+=1
c=c>>1
if c==0: #check if n was 1111..1111 or 00000..0011...111
return -1
while c&1==0 and c!=0:
c0+=1
c=c>>1
p=c0+c1
n=n<<~(1<<(p+1)-1) #clear from p onwards
n=n^((1<<(c1+1)-1)<<(c0-1))
return n
def getPrevNext(n):
a=_getNext(n)
b=_getPrevious(n)
return [a,b]
|
##Write a method to replace all spaces in a string with'%20'. You may assume that
##the string has sufficient space at the end of the string to hold the additional
##characters, and that you are given the "true" length of the string.
#Method1: Using built-in function
def replace1(string):
string=string.replace(" ","%20")
return string
|
##4.4 Given a binary tree, design an algorithm which creates a linked list of all the
##nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked
##lists).
def BTtoLL(node):
if node==None:
return
LL=[]
current=LinkedList(node)
while current.size()!=0:
LL.append(current)
parent=current
temp=parent
current=LinkedList()
while temp:
if temp.left:
current.insert(temp.left)
if temp.right:
current.insert(temp.right)
temp=temp.next
toDel=current
current=current.next
toDel.next=None
return LL
|
##4.6 Write an algorithm to find the 'next'node (i.e., in-order successor) of a given node
##in a binary search tree. You may assume that each node has a link to its parent.
def next_node(node):
if node==None:
return
if node.right:
return fetchLeftMost(node.right)
cur=node
par=cur.parent
while par!=None and par.right==cur:
cur=par
par=par.parent
return par
def fetchLeftMost(node):
if node==None:
return
while node.left:
node=node.left
return node
|
def countWaysBookWay(n):
if n<0:
return 0
elif n==0:
return 1
else:
return countWaysBookWay(n-1)+countWaysBookWay(n-2)+countWaysBookWay(n-3)
|
##9.3 A magic index in an array A [0. . .n-1] is defined to be an index such that A[i]
##= i. Given a sorted array of distinct integers, write a method to find a magic
##index, if one exists, in array A.
"""
Brute force would be to iterate through array and check index against value in array
Since values are sorted and distict, this can be solved using a binary search approach
"""
def magicIndex(array, start, end):
if start>end or start<0 or end>len(array)-1:
return -1
mid=(start+end)/2
if array[mid]==mid:
return mid
elif array[mid]>mid:
return magicIndex(array, start, mid)
else:
return magicIndex(array, mid+1, end)
|
from barcode import EAN13 # a type of format
from barcode.writer import ImageWriter #to save the barcode as a png file
def barcode_create(file_name, digits):
with open(file_name, 'wb') as f: #write in binary mode
#numbers written in barcode where the last one is automatically generated
EAN13(digits, writer=ImageWriter()).write(f)
if __name__ == "__main__":
#Command to run: python3 barcode_creation.py
file_name = "workshop_barcode.png"
digits = "346297563925697"
barcode_create(file_name, digits)
|
"""
This script uses logistic regression to provide prediction probabilities to each
individual entry
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
class Classifier:
def __init__(self, dataset, trainpath, testpath, x_train, y_train):
"""
Initializes the Classifier class with the following parameters
Argument
--------
dataset : string
Name of the dataset on which user wants to run Classifier
trainpath : string
Local path of the csv file that contains the training dataset
testpath : string
Local path of the csv file that contains the testing dataset
y_train : string
Name of target column
"""
self.dataset = dataset
self.trainpath = trainpath
self.testpath = testpath
def log_reg(self):
"""
Uses logistic regression to get prediction scores
"""
train = pd.read_csv(self.trainpath)
test = pd.read_csv(self.testpath)
train_copy = train.copy()
test_copy = test.copy()
test[y_train] = 0
# combining train and test datasets
combi = pd.concat([train, test])
# checking the shape of the combined dataset
print(combi.shape)
# Imputing the missing values in train dataset
head_train= list(train_copy)
for i in head_train:
train[i].fillna(train[i].mode()[0], inplace = True)
train.isnull().any()
# Imputing the missing values in test dataset
head_test= list(test_copy)
for i in head_test:
test[i].fillna(test[i].mode()[0], inplace = True)
test.isnull().any()
train = train.drop(columns = 'Loan_ID')
test = test.drop(columns = 'Loan_ID')
# checking the new shapes
print(train.shape)
print(test.shape)
x = train.drop('Loan_Status', axis = 1)
y = train.Loan_Status
print(x.shape)
print(y.shape)
# converting categorical variables into numerical values
# One Hot Encoding
x = pd.get_dummies(x)
train = pd.get_dummies(train)
test = pd.get_dummies(test)
# checking the new shape
print(x.shape)
# splitting x and y
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
# LOGISTIC REGRESSION
from sklearn.linear_model import LogisticRegression
import math
model = LogisticRegression()
model.fit(x_train, y_train)
y_pred1 = model.predict(x_test)
y_pred = model.predict_proba(x_test)
print("Training Accuracy :", model.score(x_train, y_train))
print("Testing Accuracy :", model.score(x_test, y_test))
train = pd.read_csv(self.trainpath)
train = train.drop(train.index[0:429])
LS = train['Loan_Status']
train = train.drop('Loan_Status', axis = 1)
train['Loan_Status'] = 10*np.around(y_pred[:,1], decimals=1)
train['Actual_Status'] = LS
train.to_csv("new_loan.csv")
|
"""nombre = input("Cual es tu nombre?\n")
print("Hola "+nombre)
edad =int(input("Cuál es tu edad?\n"))
edad = edad -10
print(edad)
Mentira= False
Verdad = True
print(Mentira or Verdad)"""
"""Diccionario ={"paella":"comida"}
print(Diccionario["paella"])
A=input("Entrada diccionario\n")
B=input("Entrada descripción\n")
Diccionario[A]=B
print(Diccionario[A])"""
"""
numero = int(input("Numero: "))
if numero>-3 and numero<0:
print("pertenece")
elif numero<6 and numero>=3:
print("pertence")
else:
print("no pertence")
"""
"""
n = int(input("Numero: "))
i=0
for x in range(2,n):
if n % x==0:
i+=1
if i!=0:
print(f"{n}no es primo")
else:
print(f"{n}es primo")
"""
"""
frase = input()
print(frase.count("a"))
n=0
for i in range(len(frase)):
if frase[i]=="a":
n+=1
print(n)
"""
"""
usuarios = {"juanito":1245613, "eva":9109201, "santi":9239367}
usuario = input()
if usuario in usuarios:
print(usuarios[usuario])
else:
print("no encontrado")
"""
"""
Usuarios={"Fitzgerald":"111mKj","Laura":"CasarDE","Adam":"lololo1212","Bob":"ee3345","Emma":"333kjf"}
A=input("Introduzca su usuario\n")
if A in Usuarios:
B=input("Introduzca contraseña\n")
if B==Usuarios[A]:
print("Contraseña correcta\n")
else:
print("Contraseña errónea\n")
else:
print("Usuario no existente\n")
"""
"""
def correo(email):
n=len(email)
B=False
if "@" in email:
if email[n-4:n]==".com":
B=True
return B
print(correo("[email protected]"))
"""
"""
def esprimo(n):
if n<2:
return False
else:
for i in range(2,n):
if n%i == 0:
return False
return True
def factorial(n):
B=1
for i in range(1,n+1):
B=i*B
return B
"""
# El enunciado está mal redactado, en la primera parte se pide hacer un programa que calcule el factorial de un numero.
# En la segunda parte se nos pide que el script responda a si un número es factorial o no
# Haré la primera variante
import Comprobar
N=int(input("Introduzca un número entero\n"))
print("¿EL número introducido es primo?:\n",Comprobar.esprimo(N))
print("El factorial del número introducido es\n",Comprobar.factorial(N))
|
from collections import deque
antrian = deque([1,2,3,4,5])
print('data sekarang: ',antrian)
# menambahkan data
antrian.append(6)
print('data masuk: ',6)
print('data sekarang: ',antrian)
# mengurangi data
out = antrian.popleft()
print('data keluar: ',out)
print('data sekarang: ',antrian)
out = antrian.popleft()
print('data keluar: ',out)
print('data sekarang: ',antrian)
# menambah data
antrian.append(8)
print('data masuk: ',8)
print('data sekarang: ',antrian)
# cek ukuran antrian
print(len(antrian))
|
from driveable import Driveable
class Vehicle(Driveable):
def __init__(self, gas_tank, engine, wheels):
self.gas_tank = gas_tank
self.engine = engine
self.wheels = wheels.get_count()
self.speed = 0
def get_wheels_count(self):
if self.wheels == 0:
print("Корабель немає коліс")
else:
print('Кількість коліс ' + str(self.wheels))
def accelerate(self):
self.speed = self.speed + self.gas_tank.get()
print('Присторення до ' + str(self.speed) + 'км/год')
def turn(self, side):
print('Поворот на ' + str(side))
def brake(self):
while self.speed != 0:
self.speed = self.speed - (self.speed / 2)
if self.speed == 1:
self.speed = 0
break
print('Швидкість: ' + str(self.speed) + 'км/год')
break
print('stop')
|
# https://www.codingame.com/ide/puzzle/codingame-sponsored-contest
import sys
import math
def get_distance(pos1, pos2):
distance = math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2)
print("{}{}:{}".format(pos1, pos2, distance), file=sys.stderr)
return distance
def get_closest_player(my_pos, others_pos):
min_distance = 99999999
nearest_pos = ()
for pos in others_pos:
distance = get_distance(my_pos, pos)
if distance < min_distance:
nearest_pos = pos
min_distance = distance
return nearest_pos
def get_all_next_pos(players_pos):
p = [1, -1]
all_pos = []
for pos in players_pos:
for index, value in enumerate(pos):
for v in p:
new_pos = list(pos)
new_pos[index] = value + v
all_pos.append(tuple(new_pos))
# print("All possible pos:{}".format(all_pos), file=sys.stderr)
return all_pos
def get_next_pos(pos, direction):
col_delta = row_delta = 0
if direction == "left":
col_delta = -1
elif direction == "right":
col_delta = 1
elif direction == "up":
row_delta = -1
else:
row_delta = 1
new_row = pos[0] + row_delta
new_col = pos[1] + col_delta
return new_row, new_col
col_num = int(input())
row_num = int(input())
players_num = int(input())
print("{} {} {}".format(col_num, row_num, players_num), file=sys.stderr)
direct_sequence = ["left", "down", "right", "up"]
command_map = {"left": "C", "down": "A", "right": "D", "up": "E", "still": "B"}
my_foot_print = []
# game loop
while True:
players_pos = []
my_pos = ()
# decode allowed directions
allowed_directions = []
for i in range(4):
input_direction = input()
if input_direction == "_":
allowed_directions.append(direct_sequence[i])
print(allowed_directions, file=sys.stderr)
# add players data to defined variable
for i in range(players_num):
row, col = [int(j) for j in input().split()]
players_pos.append((row, col))
my_pos = players_pos.pop()
my_foot_print.append(my_pos)
print(players_pos, file=sys.stderr)
print(my_pos, file=sys.stderr)
# start to calculate what is the next step
closest_player = get_closest_player(my_pos, players_pos) # used by the longest distance strategy
longest_distance = 1 # used by the longest distance strategy
longest_direction = "" # used by the longest distance strategy
next_move = "still" # if all strategy are not valid, keep still
candidate_directions = [] # every strategy have its own weights, final selection based on the weights
all_possible_pos = get_all_next_pos(players_pos) # used to check whether next move will conflict with others
# start to check every direction
for d in allowed_directions:
print("checking:{}".format(d), file=sys.stderr)
candidate_directions.append(d)
# calculate new pos for current direction
new_row, new_col = get_next_pos(my_pos, d)
# just skip it since this will cause end of the game
if (new_row, new_col) in all_possible_pos:
print("conflict!", file=sys.stderr)
candidate_directions.remove(d)
continue
# skip these point in history, but still keep these in candidate since it is still the available options
if (new_row, new_col) not in my_foot_print:
distance_to_new_pos = get_distance(closest_player, (new_row, new_col))
if distance_to_new_pos > longest_distance:
longest_direction = d
longest_distance = distance_to_new_pos
else:
print("in foot_print!", file=sys.stderr)
print("longest_direction:{}".format(longest_direction), file=sys.stderr)
# just use longest_direction
next_move = longest_direction if longest_direction != "" else next_move
# no longest_direction but still have some valid direction
if len(candidate_directions) > 0 and next_move == "still":
next_move = candidate_directions[0]
print(next_move, file=sys.stderr)
print(command_map[next_move])
|
def findMedianSortedArrays(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
added = sorted(nums1 + nums2)
added_len = len(added)
half = added_len // 2
median = 0
if added_len % 2:
median = added[half]
else:
median = 0.5 * (added[half] + added[half-1])
return median
print(findMedianSortedArrays([1,2],[3,4]))
|
import sys
import math
def print_debug(msg):
print("{}".format(msg), file=sys.stderr)
def list_to_str(list1):
str_list = ' '.join(str(e) for e in list1[-2:])
return str_list
class Graph():
def __init__(self, graph_dict=None):
""" initializes a graph object
If no dictionary or None is given, an empty dictionary will be used
"""
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
self.weights = {}
self.edges = graph_dict
def get_nodes(self):
""" returns the nodes of a graph """
return list(self.__graph_dict.keys())
def get_edges(self):
""" returns the edges of a graph """
return self.__generate_edges()
def __generate_edges(self):
""" A static method generating the edges of the
graph "graph". Edges are represented as sets
with one (a loop back to the vertex) or two
vertices
"""
edges = []
for node in self.__graph_dict:
for neighbor in self.__graph_dict[node]:
if {neighbor, node} not in edges:
edges.append({node, neighbor})
return edges
def __str__(self):
res = "nodes: "
for k in self.__graph_dict:
res += str(k) + " "
res += "\nlinks: "
for link in self.__generate_links():
res += str(link) + " "
return res
def add_edge(self, from_node, to_node, weight):
# Note: assumes edges are bi-directional
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.weights[(from_node, to_node)] = weight
self.weights[(to_node, from_node)] = weight
def add_node(self, node):
""" If the vertex "vertex" is not in
self.__graph_dict, a key "vertex" with an empty
list as a value is added to the dictionary.
Otherwise nothing has to be done.
"""
if node not in self.__graph_dict:
self.__graph_dict[node] = []
def find_path(self, start_node, end_node, path=[]):
""" find a path from start_node to end_node
in graph """
graph = self.__graph_dict
path = path + [start_node]
if start_node == end_node:
return path
if start_node not in graph:
return None
for node in graph[start_node]:
if node not in path:
extended_path = self.find_path(node,
end_node,
path)
if extended_path:
return extended_path
return None
def find_all_paths(self, start_node, end_node, path=[]):
""" find all paths from start_node to
end_node in graph """
graph = self.__graph_dict
path = path + [start_node]
if start_node == end_node:
return [path]
if start_node not in graph:
return []
paths = []
for node in graph[start_node]:
if node not in path:
extended_paths = self.find_all_paths(node,
end_node,
path)
for p in extended_paths:
paths.append(p)
return paths
def find_shortest_path(self, start_node, end_node, path=[]):
graph = self.__graph_dict
path = path + [start_node]
if start_node == end_node:
return path
if start_node not in graph.keys():
return None
shortest = None
for node in graph[start_node]:
if node not in path:
newpath = self.find_shortest_path(node, end_node, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
def dijsktra(self, initial, end):
# whose value is a tuple of (previous node, weight)
shortest_paths = {initial: (None, 0)}
current_node = initial
visited = set()
while current_node != end:
visited.add(current_node)
destinations = self.edges[current_node]
weight_to_current_node = shortest_paths[current_node][1]
for next_node in destinations:
weight = self.weights[(current_node, next_node)] + weight_to_current_node
if next_node not in shortest_paths:
shortest_paths[next_node] = (current_node, weight)
else:
current_shortest_weight = shortest_paths[next_node][1]
if current_shortest_weight > weight:
shortest_paths[next_node] = (current_node, weight)
next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited}
if not next_destinations:
return "Route Not Possible"
# next node is the destination with the lowest weight
current_node = min(next_destinations, key=lambda k: next_destinations[k][1])
# Work back through destinations in shortest path
path = []
while current_node is not None:
path.append(current_node)
next_node = shortest_paths[current_node][0]
current_node = next_node
# Reverse path
path = path[::-1]
return path
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
# n: the total number of nodes in the level, including the gateways
# l: the number of links
# e: the number of exit gateways
n, l, e = [int(i) for i in input().split()]
graph = Graph()
# add empty nodes
for i in range(n):
graph.add_node(i)
# add edges for each node, current weigh is set to 1
for i in range(l):
# n1: N1 and N2 defines a link between these nodes
n1, n2 = [int(j) for j in input().split()]
weight = 1
graph.add_edge(n1, n2, weight)
gates = []
# collect the gateway node into gates
for i in range(e):
ei = int(input()) # the index of a gateway node
gates.append(ei)
print_debug('gates:{}'.format(gates))
#print_debug('nodes:{}'.format(graph.get_nodes()))
# game loop
while True:
current_node = int(input()) # The index of the node on which the Skynet agent is positioned this turn
escape_paths = []
for gate_node in gates:
shortest_path_to_gate = graph.dijsktra(current_node, gate_node)
print_debug('node({}) to gate({}):{}'.format(current_node, gate_node, shortest_path_to_gate))
escape_paths.append(shortest_path_to_gate)
# find the shortest path between gates
cut_path = []
for path in escape_paths:
if len(path) < len(cut_path) or len(cut_path) == 0:
cut_path = path
print(list_to_str(cut_path))
|
# https://www.codingame.com/ide/puzzle/defibrillators
import sys
import math
def distance(pos_a: tuple, pos_b: tuple) -> float:
# pos is tuple (lon, lat) in degrees
lon_a = math.radians(pos_a[0])
lat_a = math.radians(pos_a[1])
lon_b = math.radians(pos_b[0])
lat_b = math.radians(pos_b[1])
x = (lon_b - lon_a) * math.cos((lat_a + lat_b)/2)
y = lat_b - lat_a
d = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) * 6371
return d
lon = float(input().replace(',', '.'))
lat = float(input().replace(',', '.'))
n = int(input())
user_pos = (lon, lat)
closest_d = 6371
closest_name = ""
for i in range(n):
defib = input().split(';')
d = distance(user_pos, (float(defib[4].replace(',', '.')), float(defib[5].replace(',', '.'))))
if d < closest_d:
closest_d = d
closest_name = defib[1]
print(closest_name)
|
import random
import string
import sys
def get_letter():
alphabet = string.ascii_letters + " !'."
return random.choice(alphabet)
def create_chromosome(size):
chromosome = ""
for _ in range(size):
chromosome += get_letter()
return chromosome
def get_answer():
answer = 'This is a robot!'
return answer
def is_answer(answer):
# print(answer)
if answer == get_answer():
return True
return False
def get_score(chrom):
key = get_answer()
score = 0
for i in range(len(key)):
if i < len(chrom) and chrom[i] == key[i]:
score += 1
return score/len(key)
def score(chrom):
return get_score(chrom)
def get_mean_score(population):
total_score = 0
for chrom in population:
total_score += score(chrom)
return total_score/len(population)
def selection(chromosomes_list):
GRADED_RETAIN_PERCENT = 0.3 # percentage of retained best fitting individuals
# percentage of retained remaining individuals (randomly selected)
NONGRADED_RETAIN_PERCENT = 0.2
selected_chromesomes = []
chromo_score = {}
for chromosome in chromosomes_list:
chromo_score[chromosome] = score(chromosome)
sorted_chromesome_list = [k for k in sorted(
chromo_score, key=chromo_score.get, reverse=True)]
best_fitting_count = int(GRADED_RETAIN_PERCENT * len(chromosomes_list))
random_count = int(NONGRADED_RETAIN_PERCENT * len(chromosomes_list))
selected_chromesomes += sorted_chromesome_list[:best_fitting_count]
selected_chromesomes += random.choices(
population=sorted_chromesome_list[best_fitting_count+1:], k=random_count)
return selected_chromesomes
def crossover(parent1, parent2):
# * Select half of the parent genetic material
# * child = half_parent1 + half_parent2
# * Return the new chromosome
# * Genes should not be moved
child = parent1[:int(len(parent1)/2)] + parent2[int(len(parent2)/2):]
return child
def mutation(chrom):
# * Random gene mutation : a character is replaced
index = random.randint(0, len(chrom))
new_chrom = ""
for i in range(len(chrom)):
if i == index:
new_chrom += get_letter()
else:
new_chrom += chrom[i]
return new_chrom
def create_population(pop_size, chrom_size):
# use the previously defined create_chromosome(size) function
population = []
for _ in range(pop_size):
chrom = create_chromosome(chrom_size)
population.append(chrom)
return population
def generation(population):
# selection
# use the selection(population) function created on exercise 2
#print("population:{}".format(population), file=sys.stderr)
select = selection(population)
#print("selected:{}".format(select), file=sys.stderr)
# reproduction
# As long as we need individuals in the new population, fill it with children
children = []
while len(children) < len(select):
# crossover
rand_nums = random.choices(population=range(0, len(select)), k=2)
#print("rand_nums:{}".format(rand_nums), file=sys.stderr)
parent1 = select[rand_nums[0]] # randomly selected
parent2 = select[rand_nums[1]] # randomly selected
# use the crossover(parent1, parent2) function created on exercise 2
#print("patent1:{},parent2:{}".format(parent1,parent2), file=sys.stderr)
child = crossover(parent1, parent2)
#print("child:{}".format(child), file=sys.stderr)
# mutation
# use the mutation(child) function created on exercise 2
child = mutation(child)
#print("mutated child:{}".format(child), file=sys.stderr)
children.append(child)
# return the new generation
#print("children:{}".format(children), file=sys.stderr)
return select + children
def algorithm():
chrom_size = len(get_answer())
population_size = 10
# create the base population
population = create_population(population_size, chrom_size)
#print("base population:{}".format(population), file=sys.stderr)
answers = []
# while a solution has not been found :
while not answers:
# create the next generation
population = generation(population)
# display the average score of the population (watch it improve)
print(get_mean_score(population), file=sys.stderr)
# check if a solution has been found
for chrom in population:
if is_answer(chrom):
answers.append(chrom)
print(answers)
algorithm()
|
# https://www.codingame.com/ide/puzzle/scrabble
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
def get_score(letter):
scores = [
("eaionrtlsu", 1),
("dg", 2),
("bcmp", 3),
("fhvwy", 4),
("k", 5),
("jx", 8),
("qz", 10),
]
for chars, v in scores:
if letter in chars:
return v
n = int(input())
words = []
for i in range(n):
words.append(input())
letters = input()
biggest_point = 0
word = ""
for w in words:
print("checking {}".format(w), file=sys.stderr)
skip = False
total = 0
temp_letters = letters
for c in w:
if c not in temp_letters:
total = 0
skip = True
break
else:
total += get_score(c)
index_l = temp_letters.index(c)
temp_letters = temp_letters[:index_l] + temp_letters[index_l+1:]
print("total={}".format(total), file=sys.stderr)
if skip:
continue
if total > biggest_point:
biggest_point = total
word = w
print("current:{}, {}".format(word, biggest_point), file=sys.stderr)
print(word)
|
import sys
def cal_next(r: int) -> int:
for d in str(r):
r += int(d)
return r
# r_1 = int(input())
# r_2 = int(input())
r_1 = 32
r_2 = 47
while r_1 != r_2:
if r_1 > r_2:
r_2 = cal_next(r_2)
else:
r_1 = cal_next(r_1)
print("r1:{}".format(r_1), file=sys.stderr)
print("r2:{}".format(r_2), file=sys.stderr)
print(r_1)
|
class Timer:
def __init__(self, target, interval, time_func, sleep_func):
self.start_time = time_func()
self.end_time = self.start_time + target if target else None
self.intermediate_time = self.start_time + interval
self.interval = interval
self.time_func = time_func
self.sleep_func = sleep_func
def __iter__(self):
self.intermediate_time = self.start_time + self.interval
return self
def __next__(self):
if self.expired(): raise StopIteration()
while not self.update():
self.sleep_func(self.intermediate_time - self.time_func())
return self.time_func() - self.start_time
def update(self):
if self.time_func() > self.intermediate_time:
self.intermediate_time += self.interval
return True
return False
def expired(self):
return self.end_time and (self.end_time == self.start_time or self.end_time < self.intermediate_time)
|
perguntas = {
'Pergunta 1': {
'pergunta': 'Quanto é 2+2? ',
'respostas': {'a': '1', 'b': '5', 'c': '4'},
'respostas_certa': 'c',
},
'Pergunta 2': {
'pergunta': 'Quanto é 20-7? ',
'respostas': {'a': '1', 'b': '5', 'c': '13'},
'respostas_certa': 'c',
},
'Pergunta 3': {
'pergunta': 'Quanto é 12/2? ',
'respostas': {'a': '1', 'b': '6', 'c': '4'},
'respostas_certa': 'b',
},
'Pergunta 4': {
'pergunta': 'Quanto é 2*5? ',
'respostas': {'a': '10', 'b': '5', 'c': '4'},
'respostas_certa': 'a',
},
}
print()
respostas_certas = 0
for pk, pv in perguntas.items():
print(f'{pk}: {pv["pergunta"]}')
print('Escolha uma das opções abaixo: ')
for rk, rv in pv['respostas'].items():
print(f'[{rk}]: {rv}')
resposta_usuario = input('Sua resposta: ')
if resposta_usuario == pv['respostas_certa']:
print('EHHHH! Você acertou!!!')
respostas_certas += 1
else:
print('AHHHH Não! Você errou!!!')
print()
qtd_perguntas = len(perguntas)
procentagem_acerto = respostas_certas / qtd_perguntas * 100
print(f'Você acertou {procentagem_acerto}% das perguntas.')
|
# Tipos de Dados
"""
str - string - textos
int - inteiro - 123456789 -> 99999999
float - real/ponto flutuante - 10.50 1.5 - 10.99
bool - booleano/logico - True/False
"""
print('Marcelo', type('Marcelo'))
print(True, type(True))
print(10, type(10))
print(10.1, type(10.1))
# type casting
print('Marcelo', type('Marcelo'), bool('Marcelo'))
# String: nome
print('Marcelo', type('Marcelo'))
# Idade: int
print(29, type(29))
# Altura: float
print(1.75, type(1.75))
# É maior de idade 10 > 20
print(29 > 18, type(29 > 18))
|
variavel = 'valor'
def func():
print(variavel)
# Não da pra alterar valor de variaveis globais de dentro da função
def func2():
# global variavel -> Não é uma boa pratica de programação
variavel = 'Outro valor'
print(variavel)
func()
func2()
|
# While
# while True: # Loop infinite
# nome = input('Qual é o seu nome? ')
# print(f'Olá {nome}')
# break
# x = 0
# while x < 10:
# if x == 3:
# x += 1
# continue
# print(x)
# x += 1
# x = 0
# while x < 10:
# y = 0
# while y < 5:
# print(f'X vale {x} e Y vale {y}')
# y += 1
# x += 1
while True:
print()
num_1 = input('Qual e o numero: ')
num_2 = input('Qual e o outro numero: ')
operador = input('Qual e o operador: ')
sair = input('Deseja sair? [s]im ou [n]ão: ')
if sair == 's':
break
if not num_1.isnumeric() or not num_2.isnumeric():
print('Voce precisa digitar um numero')
continue
num_1 = int(num_1)
num_2 = int(num_2)
# + - / *
if operador == '+':
print(num_1 + num_2)
elif operador == '-':
print(num_1 - num_2)
elif operador == '/':
print(num_1 / num_2)
elif operador == '*':
print(num_1 * num_2)
else:
print('Operador inválido')
|
from datetime import datetime
import csv
""" Converts time into datetime format """
def convert_time(time):
return datetime.strptime(time, "%Y-%m-%d %H:%M:%S.%f")
""" Calculates the difference in times in terms of seconds """
def time_diff(start, end):
return (convert_time(end) - convert_time(start)).total_seconds()
""" Loads a csv file, converting timestamps to time intervals """
def load_csv(filename):
f = csv.reader(open(filename))
labels = {}
num = 0
for label in f.next():
labels[label] = num
num += 1
prev_time = None
cur = None
data = []
prev = None
for row in f:
if prev is None:
prev = row[0]
continue
features = [float(x) for x in row[1:]]
features.insert(0,time_diff(prev, row[0]))
prev = row[0]
data.append(features)
return (labels, data)
""" Gets a list of features and their classification """
def get_features(data, i):
'''prev = data[0]
ys = []
for d in data[1:]:
ys.append(d[i] - prev[i])
prev = d
return data[:-1], ys'''
return data[:-1], [x[i] for x in data[1:]]
|
"""
This script generates a word cloud from the article words. Uploads it to Imgur and returns back the url.
"""
import os
import random
import numpy as np
import requests
import wordcloud
from PIL import Image
import config
MASK_FILE = "./assets/cloud.png"
FONT_FILE = "./assets/sofiapro-light.otf"
IMAGE_PATH = "./temp.png"
COLORMAPS = ["spring", "summer", "autumn", "Wistia"]
mask = np.array(Image.open(MASK_FILE))
def generate_word_cloud(text):
"""Generates a word cloud and uploads it to Imgur.
Parameters
----------
text : str
The text to be converted into a word cloud.
Returns
-------
str
The url generated from the Imgur API.
"""
wc = wordcloud.WordCloud(background_color="#222222",
max_words=2000,
mask=mask,
contour_width=2,
colormap=random.choice(COLORMAPS),
font_path=FONT_FILE,
contour_color="white")
wc.generate(text)
wc.to_file(IMAGE_PATH)
image_link = upload_image(IMAGE_PATH)
os.remove(IMAGE_PATH)
return image_link
def upload_image(image_path):
"""Uploads an image to Imgur and returns the permanent link url.
Parameters
----------
image_path : str
The path of the file to be uploaded.
Returns
-------
str
The url generated from the Imgur API.
"""
url = "https://api.imgur.com/3/image"
headers = {"Authorization": "Client-ID " + config.IMGUR_CLIENT_ID}
files = {"image": open(IMAGE_PATH, "rb")}
with requests.post(url, headers=headers, files=files) as response:
# We extract the new link from the response.
image_link = response.json()["data"]["link"]
return image_link
|
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 17 07:45:24 2014
@author: Dr. Olivier Wertz
"""
from __future__ import print_function
from __future__ import absolute_import
__all__ = ["Orbit"]
import math
import numpy as np
from astropy import constants as const
from astropy.time import Time
import matplotlib.pyplot as plt
from .Toolbox import timeConverter
from .KeplerSolver import MarkleyKESolver
class Orbit:
"""
Create a numerical model of a planet orbit.
Parameters
-----------
semiMajorAxis: float
The semi-major axis in AU.
eccentricity: float (0 <= e < 1)
inclinaison: float
The inclination in deg.
longitudeAscendingNode: float
The longitude of the ascending node in deg.
periastron: float
The argument of periastron in deg.
periastronTime: float or str
The time for periastron passage. This parameter can be given in iso
format (str) or directly in JD (float)
dStar: float
Distance between the star and Earth in pc.
starMass: float
The mass of the star given in solar masses.
period: float
The orbital period of the planet in year.
Notes
-----
Let us note that a, p and mStar are linked by the 3rd Kepler law:
a^3 / P^2 = G (mStar + mPlanet) / (4 pi^2) .
Since we neglect mPlanet in comparision with mStar, only two
parameters (among a, p and mStar) need to be defined.
"""
def __init__(self,semiMajorAxis = 0, period = 0, starMass = 0, eccentricity = 0, inclinaison = 0, longitudeAscendingNode = 0, periastron = 0, periastronTime = "2000-01-01 00:00:00.0", dStar = 1): #add planetTypeParameters in order to initialize the parameters according to a particular family of planet
""" The constructor of the class """
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
# Depending on which parameters (among semiMajorAxis, period and starMass) the user has initialized, we fix or calculate the others from the 3rd Kepler law
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
if semiMajorAxis == 0 and period == 0 and starMass == 0: # No parameters initialized by the user ==> Earth orbit parameters are chosen
starMass, period, semiMajorAxis = (1.,1.,1.)
elif semiMajorAxis != 0:
if period == 0 and starMass == 0: # only semiMajorAxis has been initialized by the user ==> we fix period and calculate starMass
period = 1
starMassKg = (np.power(semiMajorAxis * const.au.value,3) / np.power(period * (365.*24*3600),2)) * 4 * np.power(np.pi,2) / const.G.value
starMass = starMassKg / const.M_sun.value
elif period == 0 and starMass != 0: # semiMajorAxis and starMass have been initialized by the user ==> we calculate period
periodSecSquared = (np.power(semiMajorAxis * const.au.value,3) / (starMass * const.M_sun.value)) * 4 * np.power(np.pi,2) / const.G.value
period = np.power(periodSecSquared,1./2.) / (365.*24*3600)
elif period != 0 and starMass == 0: # semiMajorAxis and period have been initialized by the user ==> we calculate starMass
starMassKg = (np.power(semiMajorAxis * const.au.value,3) / np.power(period * (365.*24*3600),2)) * 4 * np.power(np.pi,2) / const.G.value
starMass = starMassKg / const.M_sun.value
else: # all parameters have been initialized by the user. One need to check the physical consistency of the parameters
aCube = np.power(period * (365.*24*3600),2) * const.G.value / (4 * np.power(np.pi,2)) * (starMass * const.M_sun.value)
aTest = np.power(aCube,1./3.) / const.au.value # in AU
comp = np.abs(aTest - semiMajorAxis) / aTest * 100
if comp > 3.5:
print("Warning:: the values given for the semiMajorAxis, period and starMass are not consistent with")
print("the 3rd Kepler law (error larger than {0}%). You might reconsider these values".format(int(np.floor(comp*10))/10.))
elif period != 0:
if semiMajorAxis == 0 and starMass == 0: # only period has been initialized by the user ==> we fix semiMajorAxis and calculate starMass
semiMajorAxis = 0
starMassKg = (np.power(semiMajorAxis * const.au.value,3) / np.power(period * (365.*24*3600),2)) * 4 * np.power(np.pi,2) / const.G.value
starMass = starMassKg / const.M_sun.value
elif semiMajorAxis == 0 and starMass != 0: # period and starMass have been initialized by the user ==> we calculate semiMajorAxis
semiMajorAxisMCube = np.power(period * (365.*24*3600),2) * const.G.value / (4 * np.power(np.pi,2)) * (starMass * const.M_sun.value)
semiMajorAxis= np.power(semiMajorAxisMCube,1./3.) / const.au.value # in AU
elif starMass != 0: # only starMass has been initialized by the user ==> we fix period and calculate semiMajorAxis
period = 1
semiMajorAxisMCube = np.power(period * (365.*24*3600),2) * const.G.value / (4 * np.power(np.pi,2)) * (starMass * const.M_sun.value)
semiMajorAxis= np.power(semiMajorAxisMCube,1./3.) / const.au.value # in AU
else:
print("Did I forget a case ?")
if isinstance(periastronTime, str):
periastronTime = Time(periastronTime,format='iso',scale='utc').jd
# -----------------------------
# Main part of the constructor
# -----------------------------
self.daysInOneYear = 365. #number of days of 24hrs in one year (earth's orbit: 365.256363004 days of 24hrs)
self.__semiMajorAxis = semiMajorAxis
self.__period = period
self.__starMass = starMass
self.__eccentricity = eccentricity
self.__inclinaison = math.radians(inclinaison)
self.__longitudeAscendingNode = math.radians(longitudeAscendingNode)
self.__periastron = math.radians(periastron)
self.dStar = dStar
self.__periastronTime = periastronTime
# -----------------------------
# Attribut Setters and Getters
# -----------------------------
# TODO: property !!!!
# def _get_semiMajorAxis(self):
# return self.__semiMajorAxis
# def _set_semiMajorAxis(self,newParam):
# self.__semiMajorAxis = newParam
# def _get_period(self):
# return self.__period
# def _set_period(self,newParam):
# self.__period = newParam
# def _get_starMass(self):
# return self.__starMass
# def _set_starMass(self,newParam):
# self.__starMass = newParam
# def _get_eccentricity(self):
# return self.__eccentricity
# def _set_eccentricity(self,newParam):
# self.__eccentricity = newParam
# def _get_inclinaison(self):
# return math.degrees(self.__inclinaison)
# def _set_inclinaison(self,newParam):
# self.__inclinaison = math.radians(newParam)
# def _get_longitudeAscendingNode(self):
# return math.degrees(self.__longitudeAscendingNode)
# def _set_longitudeAscendingNode(self,newParam):
# self.__longitudeAscendingNode = math.radians(newParam)
# def _get_periastron(self):
# return math.degrees(self.__periastron)
# def _set_periastron(self,newParam):
# self.__periastron = math.radians(newParam)
# def _get_periastronTime(self):
# return self.__periastronTime
# def _set_periastronTime(self,newParam):
# self.__periastronTime = Time(newParam,format='iso',scale='utc').jd
# --------
# Methods
# --------
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def whichParameters(self): #TODO : add periastronTime, ...
"""
Summary::
Return a dict-type object which contains the orbital parameters
Arguments::
None
Return::
dict-type
"""
return {"semiMajorAxis" : self.__semiMajorAxis, "period" : self.__period, "starMass" : self.__starMass,\
"eccentricity" : self.__eccentricity, "inclinaison" : self.__inclinaison, "longitudeAscendingNode" : self.__longitudeAscendingNode,\
"periastron" : self.__periastron, "periatronTime" : self.__periastronTime}
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def positionOnOrbit(self,trueAnomaly=0,pointOfView="earth",unit="au"):
"""
Summary::
Calculation of the position x and y of the planet from the use of the
orbital parameters. The position of the star is (0,0)
Arguments::
- trueAnomaly: value(s) of the true anomaly in degree (default 0). Multi-dimension requires np.array
- pointOfView: representation of the orbit viewed from the 'earth' (default)
or 'face-on'
- unit: x and y positions given in 'au' (default) or 'arcsec'
Return::
dict-type variable {"decPosition": |ndarray, size->pointNumber| , "raPosition" : |ndarray, size->pointNumber}
"""
try:
if pointOfView.lower() == "earth":
pov = 1
elif pointOfView.lower() == "face-on":
pov = 0
else:
print("The pointOfView argument must be 'earth' or 'face-on'.")
print("As a consequence, the default value has been chosen => 'earth'")
pov = 1
except AttributeError:
print("The pointOfView argument requires a string-type input ('earth' or 'face-on')")
print("As a consequence, the default value has been chosen => 'earth'")
pov = 1
try:
if unit.lower() == "au":
uni = 1
elif unit.lower() == "arcsec":
uni = 0
else:
print("The unit argument must be 'au' or 'arcsec'.")
print("As a consequence, the default value has been chosen => 'au'")
uni = 1
except AttributeError:
print("The unit argument requires a string-type input ('au' or 'arcsec')")
print("As a consequence, the default value has been chosen => 'au'")
uni = 1
v = trueAnomaly
r = self.__semiMajorAxis * (1 - np.power(self.__eccentricity,2)) / (1 + self.__eccentricity * np.cos(v))
if uni == 0: # r will be converted in arcsec thanks to the earth - star distance (dStar).
# The latter, which is initially expressed in pc, is converted in au.
# Finally, r is converted in arcsec
r = (r / (self.dStar * const.pc.value / const.au.value)) * (180 / np.pi) * 3600
x = r * (np.cos(self.__periastron + v) * np.cos(self.__longitudeAscendingNode) - np.sin(self.__periastron + v) * np.cos(self.__inclinaison * pov) * np.sin(self.__longitudeAscendingNode))
y = r * (np.cos(self.__periastron + v) * np.sin(self.__longitudeAscendingNode) + np.sin(self.__periastron + v) * np.cos(self.__inclinaison * pov) * np.cos(self.__longitudeAscendingNode))
x = np.round(x,7) # We only need 7 floating point numbers
y = np.round(y,7) #
return {"decPosition" : x, "raPosition" : y}
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def fullOrbit(self,pointNumber=100,pointOfView="earth",unit="au"):
"""
Summary::
Calculation of the full orbit of the planet based on the
orbital parameters. The position of the star is (0,0)
Arguments::
- pointNumber: number of points which compose the orbit (default 100)
- pointOfView: representation of the orbit viewed from the 'earth' (default)
or 'face-on'
- unit: x and y positions given in 'au' (default) or 'arcsec'
Return::
dict-type variable {"decPosition": |ndarray, size->pointNumber| , "raPosition" : |ndarray, size->pointNumber}
"""
return Orbit.positionOnOrbit(self,np.linspace(0,2*np.pi,pointNumber),pointOfView,unit)
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def showOrbit(self,pointOfView="earth",unit="au",addPosition=[], addPoints=[],
lim=None, show=True, link=False, figsize=(10,10), title=None,
display=True, save=(False,str()), output=False,
addPosition_options={}, invert_xaxis=True, invert_yaxis=False,
cardinal=(False,''), **kwargs):
"""
Under construction
"""
if isinstance(addPosition,list) == False:
raise ValueError("The type of the parameter 'addPosition' is {}. It should be a list containing str or float/int.".format(type(addPosition)))
o = Orbit.fullOrbit(self,300,pointOfView,unit)
if output == 'only' or output == 'onlyAll':
k = 0
if output == 'onlyAll':
for pos in addPosition:
if type(pos) == str:
pos = timeConverter(time=pos)
ta1 = Orbit.trueAnomaly(self,pos)
elif (type(pos) == float or type (pos) == int or type(pos) == np.float64) and pos > 360: # it this case, the pos value should correspond to the JD time associated to a position
ta1 = Orbit.trueAnomaly(self,pos)
else: # we consider pos as the value of the true anomaly (already in radian)
ta1 = pos
pointtemp = Orbit.positionOnOrbit(self,ta1,pointOfView,unit)
if k == 0:
point = np.array([pointtemp['raPosition'],pointtemp['decPosition']])
elif k != 0:
point = np.vstack((point,np.array([pointtemp['raPosition'],pointtemp['decPosition']])))
k += 1
return (o,point)
else:
return o
p = Orbit.positionOnOrbit(self,0,pointOfView,unit) # position of the periapsis
an = Orbit.positionOnOrbit(self,-self.__periastron + np.array([0,np.pi]),pointOfView,unit) # position of the ascending node
############
## FIGURE ##
############
if lim is None:
lim1 = np.floor(13.*np.max(np.abs(o["decPosition"]))) / 10.
lim2 = np.floor(13.*np.max(np.abs(o["raPosition"]))) / 10.
lim = np.max([lim1,lim2])
lim = [(-lim,lim),(-lim,lim)]
plt.figure(figsize = figsize)
plt.hold(True)
plt.plot(0,0,'ko') # plot the star
if show:
orbit_color = kwargs.pop('color',(1-0/255.,1-97/255.,1-255/255.))
plt.plot(o["raPosition"],o["decPosition"], color=orbit_color, linewidth=2) # plot the orbit
plt.plot(p["raPosition"],p["decPosition"],'gs') # plot the position of the periapsis
plt.plot(an["raPosition"],an["decPosition"],"k--")
plt.xlim((lim[0][0],lim[0][1]))
plt.ylim((lim[1][0],lim[1][1]))
plt.xticks(size=20)
plt.yticks(size=20)
plt.axes().set_aspect('equal')
# Ticks
# xticks_bounds = [np.ceil(lim[0][0]*10),np.floor(lim[0][1]*10)]
# xticks = np.arange(xticks_bounds[0]/10.,xticks_bounds[1]/10.,0.1)
# plt.xticks(xticks,xticks,size=20)
#
# yticks_bounds = [np.ceil(lim[1][0]*10),np.floor(lim[1][1]*10)]
# yticks = np.arange(np.floor(yticks_bounds[0]/10.),np.floor(yticks_bounds[1]/10.),0.1)
# plt.yticks(yticks,yticks,size=20)
# Title
if title != None:
plt.title(title[0], fontsize=title[1])#, fontweight='bold')
# Unit
if unit == 'au':
plt.xlabel("x' (AU)")
plt.ylabel("y' (AU)")
else:
plt.xlabel("RA ({0})".format(unit), fontsize=20)
plt.ylabel("DEC ({0})".format(unit), fontsize=20)
pointTemp = [np.zeros([len(addPosition)]) for j in range(2)];
# Add position
addPosition_marker = addPosition_options.pop('marker','s')
addPosition_markerfc = addPosition_options.pop('markerfacecolor','g')
for k, pos in enumerate(addPosition): # for all the element in the list-type addPosition, we check the type of the element.
if type(pos) == str: # if it's a str which give a date, we need to call trueAnomaly
pos = timeConverter(time=pos)
ta1 = Orbit.trueAnomaly(self,pos)
elif (type(pos) == float or type (pos) == int or type(pos) == np.float64) and pos > 360: # it this case, the pos value should correspond to the JD time associated to a position
ta1 = Orbit.trueAnomaly(self,pos)
else: # we consider pos as the value of the true anomaly (already in radian)
ta1 = pos
point = Orbit.positionOnOrbit(self,ta1,pointOfView,unit)
plt.plot(point["raPosition"],
point["decPosition"],
marker=addPosition_marker,
markerfacecolor=addPosition_markerfc,
**addPosition_options)
pointTemp[0][k] = point["raPosition"]
pointTemp[1][k] = point["decPosition"]
# Add points
if addPoints and len(addPoints) == 2: # test whether the list is empty using the implicit booleanness of the empty sequence (empty sequence are False)
plt.plot(addPoints[0], addPoints[1],'b+')
elif addPoints and len(addPoints) == 4:
plt.plot(addPoints[0], addPoints[1],'ko')
plt.errorbar(addPoints[0],addPoints[1], xerr = addPoints[2], yerr = addPoints[3], fmt = 'k.')
if link:
link_color = kwargs.pop('link_color','r')
for j in range(len(pointTemp[0])):
plt.plot([pointTemp[0][j],addPoints[0][j]],
[pointTemp[1][j],addPoints[1][j]],
color=link_color)
# Axis invert
if invert_xaxis:
plt.gca().invert_xaxis()
if invert_yaxis:
plt.gca().invert_yaxis()
# Cardinal
if cardinal[0]:
x_length = (lim[0][1] - lim[0][0])/8.
y_length = x_length
if cardinal[1] == 'br':
cardinal_center = [lim[0][0],lim[1][0]] # bottom right
elif cardinal[1] == 'bl':
cardinal_center = [lim[0][1]-1.5*x_length,lim[1][0]]
plt.plot([cardinal_center[0]+x_length/4.,cardinal_center[0]+x_length],
[cardinal_center[1]+y_length/4.,cardinal_center[1]+y_length/4.],
'k',
linewidth=1)
plt.plot([cardinal_center[0]+x_length/4.,cardinal_center[0]+x_length/4.],
[cardinal_center[1]+y_length/4.,cardinal_center[1]+y_length],
'k',
linewidth=1)
plt.text(cardinal_center[0]+x_length+x_length/3.,
cardinal_center[1]+y_length/4.-y_length/12,
'$E$',
fontsize=20)
plt.text(cardinal_center[0]+x_length/4.+x_length/8,
cardinal_center[1]+y_length+y_length/6.,
'$N$',
fontsize=20)
# Save
if save[0]:
plt.savefig(save[1]+'.pdf')
if display:
plt.show()
if output:
return o
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def trueAnomaly(self,time): # TODO :: 1) tenir compte du format de time et self_periastronTime. 2) prendre en charge les array de time
""" Under construction
Summary::
Return the true anomaly of the planet at a given time according to
the orbit parameters and the time for passage to periastron
Arguments::
time: observation time at which we want to calculate the true anomaly.
The format can be either ISO (e.g. '2000-01-01 00:00:00.0') or JD
(e.g. 2451544.5)
Return::
"""
if isinstance(time,float) == False and isinstance(time,int) == False:
time = Time(time,format='iso',scale='utc').jd # conversion in JD
meanAnomaly = (2*np.pi * ((time-self.__periastronTime)/self.daysInOneYear) / self.__period) % (2*np.pi)
ks = MarkleyKESolver() # call the Kepler equation solver
eccentricAnomaly = ks.getE(meanAnomaly,self.__eccentricity)
mA1 = 2 * math.atan(math.sqrt((1+self.__eccentricity)/(1-self.__eccentricity)) * math.tan(eccentricAnomaly / 2)) # TODO il faut tester l'unicité de la solution
return mA1 % (2*np.pi)
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def eccentricAnomaly(self,x): # TODO :: 1) tenir compte du format de time et self_periastronTime. 2) prendre en charge les array de time
""" Under construction
Summary::
Arguments::
Return::
"""
if x == 0:
return 0
elif x > 1:
x = x-2
wrap = True
else:
wrap = False
beta = 7*np.pi**2/60.
gamma = 7./(3.*beta)*(1-2*(beta-1)*(1+self.__eccentricity)) - 1
x2 = 3./4.-self.__eccentricity/(2**(1./2.)*np.pi)
F = 1/(self.__eccentricity * (1 - (3./4.)**2 * (beta -(beta - 1)*x2**2)) / (1 + (3./7.)*beta*(3./4.)**2 * (1+gamma*x2**2)))
alpha = x2**(-4)*(24/np.pi**2*(1-self.__eccentricity)**3+self.__eccentricity*x2**2)*(1+x2**2)/(1-x2**2)*((1-4*x2/3.)*F-1)
fx = 1 + alpha * x**4/(24/np.pi**2*(1-self.__eccentricity)**3+self.__eccentricity*x**2) *(1-x**2)/(1+x**2)
f0 = -x
f1 = 1 - self.__eccentricity*fx
f2 = -(3./7.)*beta*x*(1+gamma*x**2)
f3 = self.__eccentricity*fx*(beta-(beta-1)*x**2) + (3./7.)*beta*(1+gamma*x**2)
p = (1./3.) * (f1/f3 - (1./3.)*(f2/f3)**2)
q = (1./2.) * ((1./3.)*f2*f1/f3**2 - f0/f3 - (2./27.)*(f2/f3)**3)
cp = 1 + (p**3/q**2 + 1)**(1./2.)
cm = 1 - (p**3/q**2 + 1)**(1./2.)
if q >= 0:
qsigne = 1
else:
qsigne = -1
q = -q
if cm >= 0:
cmsigne = 1
else:
cmsigne = -1
cm = -cm
if cp >= 0:
cpsigne = 1
else:
cpsigne = -1
cp = -cp
temp = qsigne*q**(1./3.) * (cpsigne*cp**(1./3.) + cmsigne*cm**(1./3.))
y = -(1./3.) * f2/f3 + temp
if wrap:
return 2+y
else:
return y
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def timeFromTrueAnomaly(self, givenTrueAnomaly, output = 'iso'):
""" Under construction
Summary::
Arguments::
Return::
"""
if givenTrueAnomaly > 2*np.pi:
givenTrueAnomaly = math.radians(givenTrueAnomaly)
cosE = (self.__eccentricity+np.cos(givenTrueAnomaly))/(self.__eccentricity*np.cos(givenTrueAnomaly)+1)
sinE = np.sin(givenTrueAnomaly)/np.sqrt(1-self.__eccentricity**2)*(1-self.__eccentricity*cosE)
eccAnomaly =2*np.arctan(np.tan(givenTrueAnomaly/2.)/np.sqrt((1+self.__eccentricity)/(1-self.__eccentricity)))
if np.sin(eccAnomaly) != sinE or np.cos(eccAnomaly) != cosE:
eccAnomaly = np.mod(eccAnomaly+np.pi,2*np.pi)
date = np.mod(eccAnomaly - self.__eccentricity * sinE, 2*np.pi)/(2*np.pi)*(self.__period*self.daysInOneYear) + self.__periastronTime
if output == 'jd':
return date
elif output == 'iso':
return timeConverter(time=date,output='iso')
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def randomPositions(self,timeStart,timeEnd,number,layout='uniform',outputFormat='iso',pointOfView='earth'):
""" Under construction
Summary::
Arguments::
Return::
"""
timeStartJD = Time(timeStart,format='iso',scale='utc').jd
timeEndJD = Time(timeEnd,format='iso',scale='utc').jd
if timeStartJD > timeEndJD:
print("timeStart should be < than timeEnd. The times have been automatically inverted")
timeStart, timeEnd = timeEnd, timeStart
timeStartJD, timeEndJD = timeEndJD, timeStartJD
if layout == 'uniform':
timeJDSequence = np.linspace(timeStartJD,timeEndJD,number)
elif layout == 'random':
timeJDSequence = timeStartJD + np.random.rand(1,number)[0] * (timeEndJD - timeStartJD)
if outputFormat == 'iso':
timeJDSequence = Time(timeJDSequence,format='jd',scale='utc').iso.tolist()
elif outputFormat == 'jd':
timeJDSequence = timeJDSequence.tolist()
k = 0
trueAnomalySequence = np.zeros(len(timeJDSequence))
for z in timeJDSequence:
trueAnomalySequence[k] = Orbit.trueAnomaly(self,z)
k += 1
positionSequence = Orbit.positionOnOrbit(self,trueAnomalySequence,pointOfView,'arcsec')
result = {'timePosition' : timeJDSequence}
result.update(positionSequence)
return result
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def chiSquare(self,obs,error={}): # This method has been added in the class StatisticMCMC and should be used from that way
""" Under construction
Summary::
Arguments::
Return::
"""
if len(error) == 0:
error = {'decError' : np.ones(obs['decPosition'].size), 'raError' : np.ones(obs['raPosition'].size)}
timeSequence = obs['timePosition']
obsPositionSequence = {'decPosition' : obs['decPosition'], 'raPosition' : obs['raPosition']}
# TODO: old version. Now I should use list comprehension
k = 0
trueAnomalySequence = np.zeros(len(timeSequence))
for i in timeSequence:
trueAnomalySequence[k] = Orbit.trueAnomaly(self,i)
k += 1
modelPositionSequence = Orbit.positionOnOrbit(self,trueAnomalySequence,'earth','arcsec')
chi2Dec = np.sum(np.power(np.abs(obsPositionSequence['decPosition'] - modelPositionSequence['decPosition']) / error['decError'] , 2))
chi2Ra = np.sum(np.power(np.abs(obsPositionSequence['raPosition'] - modelPositionSequence['raPosition']) / error['raError'] , 2))
return chi2Dec+chi2Ra
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
# def transit(self, inclination, periastron, periastronTime):
# if np.abs(inclination - 90) > 0.1:
# return False
# else:
# taEarthTransit = np.mod(270 - periastron,360) # gives the true anomaly of the transit or occultation
# taEarthOccu = np.mod(90 - periastron,360)
# ------------------------------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------------------------------
def period(self, semiMajorAxis = 1, starMass = 1):
"""
"""
periodSecSquared = (np.power(semiMajorAxis * const.au.value,3) / (starMass * const.M_sun.value)) * 4 * np.power(np.pi,2) / const.G.value
period = np.power(periodSecSquared,1./2.) / (365.*24*3600)
return period
# ------------------------------------------------------------------------------------------------------------------------------------------
def semimajoraxis(self, period = 1, starMass = 1):
"""
"""
aAUcubic = const.G.value * (starMass * const.M_sun.value) / (4 * np.power(np.pi,2)) * (period * 365.*24*3600)**2
a = np.power(aAUcubic,1./3.) / const.au.value
return a
|
# D:\Users\Administrator\Anaconda3\python.exe
# -*- coding: UTF-8 -*-
# @Author : Steve
# @File : 07_Queue.py
# @Software: PyCharm
# @Time : 2020-11-17 上午 11:32
class Queue(object):
"""队列"""
def __init__(self):
self.__list = []
def is_empty(self):
"""判断一个队列是否为空"""
return self.__list == []
def size(self):
"""返回队列的大小"""
return len(self.__list)
def enqueue(self,item):
"""往队列中添加一个item元素"""
# 以列表末尾为队列尾部
self.__list.append(item)
"""
1.入队操作较多时,选用顺序表尾部添加,入队append()时间复杂度为O(1)
2.出队操作较多时,选用顺序表头部添加,出队pop()时间复杂度为O(1)
"""
def dequeue(self):
"""从队列头部删除一个元素"""
self.__list.pop(0)
if __name__ == '__main__':
q = Queue()
print(q.is_empty())
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
print(q.size())
print(q.dequeue())
|
# D:\Users\Administrator\Anaconda3\python.exe
# -*- coding: UTF-8 -*-
# @Author : Steve
# @File : 17_归并排序.py
# @Software: PyCharm
# @Time : 2020-11-17 下午 11:31
def merge_sort(alist):
"""归并排序"""
if len(alist) <= 1:
return alist
# 递归拆分,拆分成单个元素时结束递归
mid = len(alist) // 2
left_li = merge_sort(alist[:mid])
right_li = merge_sort(alist[mid:])
# 合并
left_point, right_point = 0, 0
result = []
while left_point < len(left_li) and right_point < len(right_li):
if left_li[left_point] < right_li[right_point]:
result.append(left_li[left_point])
left_point += 1
else:
result.append(right_li[right_point])
right_point += 1
# 退出循环时,一个数组为空,最后把另一个数组的剩余部分添加到result过来即可
result += left_li[left_point:]
result += right_li[right_point:]
return result
if __name__ == '__main__':
test_list = [504, 2, 48, 119, 16, 157, 63, 148, 50, 48]
print("merge_sort:", merge_sort(test_list))
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @param B : integer
# @return a list of list of integers
solutions = []
def pathSumUtil(self, root, req_sum, current_path ):
if root==None:
return
current_path.append(root.val)
# print(current_path)
if root.left==None and root.right ==None:
if req_sum == root.val:
self.solutions.append(current_path)
# print(current_path,self.solutions)
return
else:
return
self.pathSumUtil(root.left,req_sum-root.val,list(current_path))
self.pathSumUtil(root.right,req_sum-root.val,list(current_path))
def pathSum(self, A, B):
dummy = []
self.solutions = []
self.pathSumUtil(A,B,list(dummy))
return self.solutions
|
import numpy as np
from layers import *
from fast_layers import *
from layer_utils import *
from util import *
class Transformer(object):
'''
A multilayer perceptron whose purpose is to transform input images by applying
a nonlinear transformation. We constrain the output by imposing a penalty for
correlation between it and the original input image.
'''
def __init__(self, input_dim=32*32*3, hidden_dim=1000, use_batchnorm=True,
weight_scale=1e-3, reg=0.0, dtype=np.float32):
'''
Initialize the transformer network as a multilayer perceptron from the input
space back into it. The hidden dimension, or "code" dimension, is typically
smaller than the input dimension, so we are using a trick similar to autoencoders,
but instead of reconstructing the input, we try to apply a useful transformation
to it.
The structure of this network is: affine - relu - affine.
Note that there is no softmax
input:
input_dim: the number of input nodes to the network (CIFAR-10 size by default)
hidden_dim: the number of nodes in the hidden layer of the netowork
use_batchnorm: whether or not to use batch normalization
weight_scale: the scale about which to initialize model parameters
reg: hyperparameter penalizing the magnitude of model parameters
dtype: data type of the input to the network
'''
self.use_batchnorm = use_batchnorm
self.params = {}
self.reg = reg
self.dtype = dtype
# initializing weights, biases
self.params['W1'] = np.random.normal(loc=0, scale=weight_scale, size=(input_dim, hidden_dim))
self.params['b1'] = np.zeros(hidden_dim)
self.params['W2'] = np.random.normal(loc=0, scale=weight_scale, size=(hidden_dim, input_dim))
self.params['b2'] = np.zeros(input_dim)
# initializing gammas, betas
self.params['gamma1'] = np.ones((hidden_dim))
self.params['beta1'] = np.zeros((hidden_dim))
# setting batchnorm parameters
self.bn_params = []
if self.use_batchnorm:
self.bn_params = [{'mode': 'train'} for i in xrange(1)]
# setting correct datatype
for k, v in self.params.iteritems():
self.params[k] = v.astype(dtype)
def forward(self, X):
'''
Forward pass of the network. We are simply passing the input through an
affine - relu - affine structure.
input:
X: minibatch array of input data, of shape (N, d_1, ..., d_k)
output:
transformed minibatch input data
'''
# setting the network operation mode
mode = 'test'
# initializing cache dictionary
self.cache = {}
# adding input minibatch array to cache
self.cache['X'] = X
# are we using batchnorm? if so...
if self.use_batchnorm:
for bn_param in self.bn_params:
bn_param[mode] = mode
# compute first layer's hidden unit activations and apply nonlinearity (thanks to layer_utils module)
hidden, self.cache['hidden'] = affine_norm_relu_forward(X, self.params['W1'], self.params['b1'], self.params['gamma1'], self.params['beta1'], self.bn_params[0])
# compute second layer's hidden unit activations
transform, self.cache['output'] = affine_forward(hidden, self.params['W2'], self.params['b2'])
# we returned the transformed input
return transform
def backward(self, transform, loss, dtransform):
'''
Computing loss and gradient for a minibatch of data. This will simply be
the loss and gradient passed back from the discriminator network, combined
with the correlation loss we define between the input and output of this network.
input:
transform: the output of the network from the forward pass
loss: the loss output from the discriminator network (we want to maximize the log of this!)
dtransform: the gradient of the tranform output from the forward pass
y: Array of labels, of shape (N,). y[i] gives the label for X[i]
output:
If y is None, then run a test-time forward pass of the fully-connected
network, and output the transformed image.
If y is not None, then run a training-time forward and backward pass and
return a tuple of:
Scalar value giving the loss
Dictionary with the same keys as self.params, mapping parameter
names to gradients of the loss with respect to those parameters.
'''
# initializing variables for loss and gradients (we try to maximize the log
# loss of the discriminator model as in the Goodfellow paper)
grads = {}
# adding correlation loss between the original input and the transformed input
X = self.cache['X']
X = X.reshape(transform.shape)
# TODO: figure out how to incorporate the correlation loss...
# corr_loss, dout = correlation_loss(X, transform)
# dtransform += dout
# adding regularization loss to the total loss
# this is calculated by summing over all squared weights of the network
loss += 0.5 * (self.reg * (np.sum(np.square(self.params['W1'])) + np.sum(np.square(self.params['W2']))))
# computing the gradient of the weights of each layer with respect to the upstream gradient of the class predictions
dhidden, grads['W2'], grads['b2'] = affine_backward(dtransform, self.cache['output'])
dinput, grads['W1'], grads['b1'], grads['gamma1'], grads['beta1'] = affine_norm_relu_backward(dhidden, self.cache['hidden'])
# adding regularization to the weight gradients (using its derivative w/ respect to the weights)
grads['W1'] += self.reg * self.params['W1']
grads['W2'] += self.reg * self.params['W2']
# returning the calculated loss and gradients
return loss, grads
|
from datetime import datetime
class UserID (object):
""" Constructor """
def __init__(self, name):
"""
Construct a new object.
:param name: STRING, The user name.
startDate: The date of the account was created.
"""
self.__username = name
self.__startDate = datetime.now().date().today() # This attributes will not be change ever once it has been initialized.
""" Methods """
def getName(self):
"""
Gets the name of the user.
:return: the username of the user.
"""
return self.__username
def setName(self, newName):
"""
Change the user's username.
:param newName: The new username that will replaced.
:return: None
"""
self.__username = newName
def getStartDate(self):
"""
Gets the birth of the account.
:return: The date of the time the account was created.
"""
return self.__startDate
""" TEST CASES FOR UserID CLASS """
if __name__ == '__main__':
actor = UserID("Adrian")
name = actor.getName()
if name != "Adrian":
print("Error: self.username expected value is (Adrian)")
print(" value got is,", actor.getName())
exit()
actor.setName("Maicaella")
updatedName = actor.getName()
if updatedName != "Maicaella":
print("Error: self.username does not change to (Maicaella)")
print(" the value is still,", actor.getName())
exit()
time = actor.getStartDate()
if time != actor.getStartDate():
print("Error: getStartDate() does not match to self.startDate")
print(" the value is,", actor.getStartDate())
exit()
print("**** TEST COMPLETE ****")
|
# generate a random derangement of a range
# ref http://local.disia.unifi.it/merlini/papers/Derangements.pdf
# http://stackoverflow.com/questions/25200220/generate-a-random-derangement-of-a-list
import random
def random_derangement(n):
while True:
v = range(n)
for j in range(n - 1, -1, -1):
p = random.randint(0, j)
if v[p] == j:
break
else:
v[j], v[p] = v[p], v[j]
else:
if v[0] != 0:
return tuple(v)
# demo
N = 4
# enumerate all derangements for testing
import itertools
counter = {}
for p in itertools.permutations(range(N)):
if all(p[i] != i for i in p):
counter[p] = 0
# final values should be close to M
M = 5000
for _ in range(M*len(counter)):
# generate a random derangement
p = random_derangement(N)
# is it really?
assert p in counter
# ok, record it
counter[p] += 1
# the distribution looks uniform
for p, c in sorted(counter.items()):
print p, c
|
'''
利用parse模块模拟post请求
分析百度词典
分析步骤:
1. 打开F12
2. 尝试输入单词girl,发现每敲一个字母后都有请求
3. 请求地址是 http://fanyi.baidu.com/sug
4. 利用NetWork-All-Hearders,查看,发现FormData的值是 kw:girl
5. 检查返回内容格式,发现返回的是json格式内容==>需要用到json包
'''
from urllib import request, parse
# 负责处理json格式的模块
import json
import chardet
'''
大致流程是:
1. 利用data构造内容,然后urlopen打开
2. 返回一个json格式的结果
3. 结果就应该是girl的释义
'''
baseurl = 'http://fanyi.baidu.com/sug'
# 存放用来模拟form的数据一定是dict格式
data = {
# girl是翻译输入的英文内容,应该是由用户输入,此处使用硬编码
'kw': 'refactor'
}
# 需要使用parse模块对data进行编码
data = parse.urlencode(data).encode("utf-8")
#print(type(data))
# 我们需要构造一个请求头,请求头部应该至少包含传入的数据的长度
# request要求传入的请求头是一个dict格式
headers = {
# 因为使用post,至少应该包含content-length 字段
'Content-Length':len(data)
}
# 可以直接尝试发出请求
# rsp = request.urlopen(baseurl, data=data)
# 或通过request发送带headers的请求
# 这是构造一个Request的实例
req = request.Request(url=baseurl, data=data, headers=headers)
# req.add_header("User-Agent","````") #注:可以通过add_header()添加头
# 因为已经构造了一个Request的请求实例,则所有的请求信息都可以封装在Request实例中
# urlopen可以打开URL 而URL,可以是字符串或Request对象
rsp = request.urlopen(req)
json_data = rsp.read()
# 利用 chardet自动检测
cs = chardet.detect(json_data)
#print(type(cs))
#print(cs)
json_data = json_data.decode(cs.get("encoding", "utf-8"))
#print( type(json_data))
#print(json_data)
# 把json字符串转化成字典
json_data = json.loads(json_data)
#print(type(json_data))
#print(json_data)
for item in json_data['data']:
print(item['k'], "--", item['v'])
|
#! /usr/bin/env python
# To check presence of alphanumeric, alphabets, digits in a string.
str1 = raw_input().strip()
alnum = False
alpha = False
digit = False
lower = False
upper = False
for ch in str1:
if (ch >= 'a' and ch <= 'z'):
alnum = True
lower = True
alpha = True
if (ch >= '0' and ch <= '9'):
alnum = True
digit = True
if (ch >= 'A' and ch <= 'Z'):
alnum = True
upper = True
alpha = True
print alnum
print alpha
print digit
print lower
print upper
|
#! /usr/bin/env python
# capitalize each word in a sentence.
str1 = raw_input().strip()
str1 = str1 + " "
for i in range(0,len(str1)):
if str1[i-1] == ' ':
str1 = str1[:i] + str1[i].upper() + str1[i+1:]
print str1
|
n=int(input("Enter the number of terms : "))
result = list(map(lambda x: 2**x,range(n)))
print("The total number of terms are : ",n)
for i in range(n):
print("2^",i,"=",result[i])
|
from tkinter import *
root=Tk()
#Window Appearancw
root.title("House")
c=Canvas(root,bg='white',height=700,width=1500)
#----------------------------------House Front------------------------------------------------
c.create_polygon(600,250,700,150,800,250,800,400,600,400,width=2,fill="yellow",outline='black')
c.create_rectangle(650,275,750,390,fill="pink")#------------------House door--------------------------
c.create_polygon(800,250,900,150,1000,250,1000,400,800,400,width=2,fill="blue",outline='black')#-------------------house side------------------------------------
c.create_rectangle(850,275,900,327,fill="grey")#----------------------------Window-------------------------------------
c.create_polygon(700,150,800,250,1000,250,900,150,width=2,fill="brown",outline='black')
c.create_oval(680,180,725,250, width=0.5, fill='red')#--------------------------circlr above the door------------------------------------------------------------
c.pack()
root.mainloop()
|
#WAP to convert the number from decimal to binary using Reccursion
def Convert(n):
if n > 1:
Convert(n//2)
print(n%2,end = ' ')
a=int(input("Enter the decimal number to conver into Binary : "))
Convert(a)
|
mylist=[] #emptylist
mylist=[1,2,3,4] #list of integers
print(mylist)
mylist=[1,"Heello",3.6]
print(mylist)
mylist=[1,[1,8,9,8,[1.89,87,],(4,5,6)]] #nested list
print(mylist)
mylist=(1,2,5,[5,6],8) #list inside the tuple
print(mylist)
a=["mouse",['a']];
print(a);
a=['maa','iiiiggggugg','l','a','n','h','a',['c','o']]
print(a[0]) #print first element of the list
print(a[2]) #print third element of the list
print(a[0][1]) #print the first elemnet of the zeroth element
print(a[1][4]) #print the fourth element of the first element
print(a[-1])
print(a[-5])
even=[1,2,4,6,8] #mistake values
even[0]=0 #update the mistakes
print(even)
even.append(10) #Append a element
print(even)
even.extend((10,12,14,16)) #extend a tuple or a list
print(even)
print(even+[17,18,20]) #other ways of appending
print(even*2); #multiply the elemnts of the list
even.insert(1,6) #insrt elements in the list by giving index and value
print(even);
print(even[5:9]); #display the eements in the middle
del even[2]; #delete one element that was 2 from the list
print(even);
del even[5:9] #delete multiple elements in the given range
print(even)
even.remove(8)
print(even)
print(even.pop(1)); #pop the given element
print(even.pop()); #pop the last element
even.clear() #delete all the element
print(even)
even=[1,2,4,6,8]
print(even)
even[:2]=[] # delete the elemeentss
print(even)
print(even.index(6)) #find out the index
#print(even.sort())
even.sort() #sort the elements in the ascending order
print(even)
even.reverse() #reverse a string
print(even)
m=even.copy();
print(m)
pow2=[2**x for x in range(20)]
print(pow2)
pow2=[2**x for x in range(20) if x>5 and x<8]
print(pow2)
lastname=['Aswani','kulchandani','hotchandani','mulchandani']
print("%s" % lastname[1])
print("%s" % lastname[0][2])
|
#Converting given given temperature in Fahrenheit into degree Celsius.
temperature_in_farhrenheit = float(input("Enter temperature in fahrenheit:"))
celsius = (temperature_in_farhrenheit - 32) * 5 / 9
print("Temperature in celsius: " , celsius)
|
"""
Write a Python function which accepts a string and returns a string made of the first 2 and the last 2 characters of the given string.
If the string length is less than 2, return -1.
Note: If the string length is equal to 2, consider the 2 characters to be the first as well as the last two characters.
Sample Input Expected Output
w3resource w3ce
w3 w3w3
A -1
"""
def new_string(string):
if len(string)<2:
return -1
else:
return string[0:2]+string[-2:]
print(new_string('abacus'))
print(new_string('vi'))
print(new_string('v'))
|
list1=[5,4,15,3,1,0]
print(list1)
for i in range(len(list1)):
min_val=min(list1)
min_ind=list1.index(min_val)
list1[i],list1[min_ind]=list1[min_ind],list1[i]
print(list1)
|
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, data=None):
self.root = None
if data:
self.root = TreeNode(data)
def insert(self, data):
current = self.root # a pointer to the current node
parent = None # suppose, the parent of the new node is None
while current:
parent = current # update the parent
if data > current.data:
current = current.right
else:
current = current.left
if self.root is None:
self.root = TreeNode(data)
elif data > parent.data:
parent.right = TreeNode(data)
else:
parent.left = TreeNode(data)
def inorder(self, current):
if current is None:
return
self.inorder(current.left)
print(current.data)
self.inorder(current.right)
def print_inorder(self):
self.inorder(self.root)
btree = BinaryTree(1)
btree.insert(7)
btree.insert(3)
btree.insert(4)
btree.insert(5)
btree.print_inorder()
|
"""
Example:
Given an array of distinct integer values, count the number of pairs of integers that have
given difference k. For example, given the array {1, 7, 5, 9, 2, 12, 3} and the difference
k = 2, there are four pairs with difference 2: (1, 3), (3, 5), (5, 7), (7, 9).
"""
def diff_k(arr=[], k=2):
dictionary = {}
index = 0
for val in arr:
dictionary[val] = index
index += 1
checked = {} # empty dictionary for values whether they are processed or not
for val in arr:
checked[val] = False
for val in dictionary:
if val - k in dictionary and checked[val-k] is False:
print(val, ",", val - k)
if val + k in dictionary and checked[val+k] is False:
print(val, ",", val + k)
checked[val] = True
arr = [1, 7, 5, 9, 2, 12, 3]
k = 2
diff_k(arr, k)
|
from CipherInterface import *
import math
# The enigma cipher in this implementation takes in a key that is 26x3 characters lone
# this is then translated into 26 character keys for each rotor
# each rotor key should only contain 1 of each character in the alphabet
# the rotor will translate a single character across its key
# the enigma class will create 3 instances of the rotor and translate each
# character of plaintext across each rotor in order to encrypt and backwards
# to decrypt
class Rotor(CipherInterface):
alphabet = "abcdefghijklmnopqrstuvwxyz"
def __init__(self):
CipherInterface.__init__(self)
self.position = 0
self.array_in = []
self.array_out = []
def setKey(self, key):
self.key = key
for i in range(0, 26):
self.array_in.append(i)
self.array_out.append(self.key.index(self.alphabet[i]))
# sets the position to the index of the char
def setPos(self, posChar):
self.position = self.alphabet.index(posChar)
# encrypts 1 character at a time
def encrypt(self, plaintext):
# set the location input to the index of the letter plus the rotation
loc_in = self.alphabet.index(plaintext) + self.position
if loc_in > 25:
loc_in = loc_in - 26
# set the location output of the rotor to the index of the input plus the position
loc_out = self.array_out.index(loc_in) + self.position
if loc_out > 25:
loc_out = loc_out - 26
# set the ciphertext to the letter at the location out
ciphertext = self.alphabet[loc_out]
return ciphertext
# decrypt 1 character at a time
def decrypt(self, ciphertext):
# set the location out side
loc_out = self.alphabet.index(ciphertext) - self.position
if loc_out > 25:
loc_out = loc_out - 26
loc_in = self.array_out[loc_out] - self.position
if loc_in > 25:
loc_in = loc_in - 26
plaintext = self.alphabet[loc_in]
return plaintext
# rotate the rotor
# if the rotation makes a full circle then return true, else return false
def rotate(self):
# rotate the rotor
self.position = self.position + 1
if self.position > 25:
self.position = 0
return True
else:
return False
class Enigma(CipherInterface):
# this implementation of the Enigma Cipher assumes a start place of A A A
# on all of the roters
alphabet = "abcdefghijklmnopqrstuvwxyz"
rotors = []
def setKey(self, key):
self.key = key
# create the list of rotors
self.rotors.append(Rotor())
self.rotors.append(Rotor())
self.rotors.append(Rotor())
# static rotor keys
self.rotors[0].setKey("dkvqfibjwpescxhtmyauolrgzn")
self.rotors[1].setKey("uolqfdkvescxhzntmyaibjwprg")
self.rotors[2].setKey("lrescxgzndkvqfimyauobjwpht")
# set the starting position of the rotors to that of the key
self.rotors[0].setPos(self.key[:1])
self.rotors[1].setPos(self.key[1:2])
self.rotors[2].setPos(self.key[2:3])
# Encrpyts the plaintext using the Railfence cipher
def encrypt(self, plaintext):
ciphertext = ""
# for each character in the plaintext
for c in plaintext:
# if its a space
if c == " ":
# append a space
ciphertext = ciphertext + c
else:
# if its not a space
# encrypt the character on each roter
for r in range(0, len(self.rotors)):
c = self.rotors[r].encrypt(c)
# rotate the rotors
for r in range(0, len(self.rotors)):
# if the rotor does not make a full rotation dont rotate the next rotor
if not self.rotors[r].rotate():
break
ciphertext = ciphertext + c
return ciphertext
# Decrypts the ciphertext using the Railfence cipher
def decrypt(self, ciphertext):
plaintext = ""
# for each character in the ciphertext
for c in ciphertext:
# if its a space
if c == " ":
# append a space
plaintext = plaintext + c
else:
# if its not a space
# decrypt the character on each rotor in reverse
for r in range(0, len(self.rotors)):
c = self.rotors[len(self.rotors) - r - 1].decrypt(c)
# rotate the rotors
for r in range(0, len(self.rotors)):
# if the rotor does not make a full rotation dont rotate the next rotor
if not self.rotors[r].rotate():
break
plaintext = plaintext + c
return plaintext
|
class Worker:
def __init__(self, surname, experience, hourly_wag, hours_work):
self.surname = surname
self.experience = max(experience, 0)
self.hourly_wage = max(hourly_wag, 0)
self.hours_work = max(hours_work, 0)
self.salary = self.calculate_salary(self.hours_work, self.hourly_wage)
self.premium = round(self.calculate_premium(self.experience, self.salary))
@staticmethod
def calculate_premium(experience, salary):
if experience < 1:
return 0
elif experience < 3:
return salary * 0.05
elif experience < 5:
return salary * 0.08
else:
return salary * 0.15
@staticmethod
def calculate_salary(hours_work, hourly_wage):
return hours_work * hourly_wage
def __str__(self):
return "Surname: " + str(self.surname) + \
"\nExperience: " + str(self.experience) + "\n" + \
str(self.surname) + " has worked: " + str(self.hourly_wage) + " hours\n" + \
"Salary: " + str(self.salary) + "\n" + "Premy: " + str(self.premium)
def in_file(self):
file_name = self.surname + ".txt"
with open(file_name, "w") as file:
file.write(self.__str__())
print("Information about", self.surname, "was written in file", file_name)
surname = input("Enter surname: ")
experience = int(input("Enter experience: "))
hourly_wage = int(input("Enter hourly wage: "))
hours_work = int(input("Enter how much worker worked: "))
worker = Worker(surname, experience, hourly_wage, hours_work)
print()
print(worker)
print()
worker.in_file()
|
def sumDigits(number) :
sum = 0;
while(number > 0) :
sum += int(number%10)
number = number /10
print(sum)
if __name__ == "__main__":
number = int(input("Enter a number"))
sumDigits(number)
|
def Add(number1 , number2) :
print("Addition is :: ",number1 + number2)
def Sub(number1 , number2) :
print("Substraction is :: ",number1 - number2)
def Mult(number1 , number2) :
print("Multiplication is :: ",number1 * number2)
def Div(number1,number2) :
print("Division is ::",number1/number2)
|
from __future__ import print_function
import math
z = 0
a = []
def series(i):
x = z
x = 0
for n in range(i+1):
x += 10 * (((math.cos((1 + 2.3 * n) / 3)) * 3) + 6)
# x += 0 + (10 * n)
# x += 250 - (4.5 * n)
print(x)
def sequence(i):
b = a
b = []
for n in range(i+1):
c = 10*(((math.cos((1+2.3*n)/3))*3)+6)
b.append(c)
one_decimals = ["%.1f" % c for c in b]
print(*one_decimals, sep = '\n')
# choose sequence or serie
# diplay choices
def display_choices():
print("\n\n*Starting off with x = 0")
print("[1]sequence")
print("[2]series")
def decision(choice):
if choice == 1:
sequence(int(input("Enter the term number: ")))
elif choice == 2:
series(int(input("Enter the term number: ")))
else:
print("Error!")
while True:
display_choices()
decision(input("Enter a choice: "))
|
z = 0
a = []
def series(i):
x = z
x = 0
for n in range(i):
x += enter_formula()
print("\n", x)
def sequence(i):
b = a
b = []
for n in range(i):
c = enter_formula()
b.append(c)
print("\n", b)
# choose sequence or serie
# diplay choices
def display_choices():
print("\n\n[1]sequence")
print("[2]series")
def decision(choice):
if choice == 1:
sequence(input("Enter the term number: "))
elif choice == 2:
series(input("Enter the term number: "))
else:
print("Error!")
def enter_formula():
formula = raw_input("\n*The term number must be n.\nEnter a formula: ")
for i in formula:
if i in ("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"):
int(i)
while True:
display_choices()
decision(input("Enter a choice: "))
|
#Program: reader.py
#Authors: Calvin Brown, Chad Gilmer
#Description: Reades a file in and does things on it like ls, stat, and info of the file
import sys
import os
import struct
from Utilities import *
from lsInfo import *
from statInfo import *
from info import *
from read import *
from changeDirectory import *
fileName = sys.argv[1]
#Loops until quit
directory = ""
newTup = ("",0)
lastDirectory = ("",0)
while True:
userInput = input("/"+directory+"] ")
if userInput == "quit":
print("Bye!")
break
elif userInput == "info":
#This will give info of the file you passed in, in the arguments
printInfo(fileName)
elif "cd" in userInput:
#if "cd .." in userInput:
#Couldn't end up getting this working
# newTup = changeDir(lastDirectory[0],fileName, lastDirectory[1])
# continue
fileToStat = userInput.split()
if(len(fileToStat) <= 1):
print("Please enter cd <dir> to go to it")
elif(len(fileToStat) > 1):
fileToStat = fileToStat[1]
newTup = changeDir(fileToStat,fileName, newTup[1])
if(newTup[0] == ""):
continue
directory = newTup[0][0]
elif "stat" in userInput:
#This is the STAT function, This ~semi~ needs the ls function since the ls can get info about the first clustor of data, and then we can get info on that from finding those files in the ls module.
fileToStat = userInput.split()
if(len(fileToStat) <= 1):
print("Please enter stat <filename> to get the statistics of it")
elif(len(fileToStat) > 1):
fileToStat = fileToStat[1]
runToStat(fileToStat,fileName, newTup[1])
elif userInput == "ls":
doLs(fileName, newTup[1])
elif "read" in userInput:
inputList = userInput.split()
readFile(inputList[1],inputList[2],inputList[3],fileName, newTup[1])
|
"""
Part 4 - Class Report: Generate Products and report on them
"""
import random
from acme import Product
# Variable Definitions for use throughout code
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(number_of_products=30):
# Variable definitions for this function
products = []
counter = 0
while(counter < number_of_products):
name = random.choice(ADJECTIVES) + ' ' + random.choice(NOUNS)
price = random.randint(5, 100)
weight = random.randint(5, 100)
flammability = random.uniform(0.0, 2.5)
products.append(Product(name, price, weight, flammability))
counter += 1
return products
def inventory_report(products):
# Variable Definitions
unique_products = []
count_unique_products = 0
avg_price = 0
avg_weight = 0
avg_flammability = 0
# Create a list of unique product names to count
for product in products:
if product.name not in unique_products:
unique_products.append(product.name)
count_unique_products = len(unique_products)
# Calculate the averages using generator expressions.
avg_price = (sum(product.price for product in products)
/ float(len(products)))
avg_weight = (sum(product.weight for product in products)
/ float(len(products)))
avg_flammability = (sum(product.flammability for product in products)
/ float(len(products)))
# Print the Report results
print('ACME CORPORATION OFFICIAL INVENTORY REPORT')
print(f'Unique product names: {count_unique_products}')
print(f'Average price: {avg_price}')
print(f'Average weight: {avg_weight}')
print(f'Average flammability: {avg_flammability}')
if __name__ == '__main__':
inventory_report(generate_products())
|
#import requests
from goose import Goose
import urllib
from bs4 import BeautifulSoup
""" this function visits the link to the article and extracts the article text
For more on requests:
http://docs.python-requests.org/en/master/user/quickstart/
http://web.stanford.edu/~zlotnick/TextAsData/Web_Scraping_with_Beautiful_Soup.html """
#def get_article(url):
# r = urllib.urlopen(url).read()
# soup = BeautifulSoup(r)
# type(soup)
# print soup.prettify()[0:1000]
# title = url + '.txt'
# f = open('hello.txt', 'w')
#f.write(article.encode('utf-8'))
#f.close()
def get_article(url):
#url = 'http://edition.cnn.com/2012/02/22/world/europe/uk-occupy-london/index.html?hpt=ieu_c2'
g = Goose()
article = g.extract(url=url)
#print article.title
return article.cleaned_text
|
print('enter any number ')
number = int(input())
n = 1
while True :
print(number,'*',n,'=',number*n)
n = n + 1
if n >= 11:
break
print('end')
|
maths = int(input('enter the markas of maths: '))
phy = int(input('enter the markas of physics: '))
chem = int(input('enter the markas of chemistry: '))
bio = int(input('enter the markas of bio: '))
m = int(input('enter the markas of computer: '))
per = (maths+phy+chem+bio+m)/5
print('percentage: ',per)
if per>=90 :
print('A')
elif per<90 and per>=80 :
print('B')
elif per<80 and per>=70 :
print('C')
elif per<70 and per>=60 :
print('D')
elif per<60 and per>=50 :
print('E')
else:
print('F')
|
#def factorial(x):
# if x==1:
# return 1
# return x * factorial(x-1)
#result = factorial(3)
#print(result)
def factorial(x):
if x==1:
return 1
result = factorial(x-1)
return x * result
result =factorial(3)
print(result)
|
# class method and static method
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
@classmethod
def object_by_year(cls,name,year):
return cls(name,2019-year)
@staticmethod
def is_adult(age):
if age>=18:
return True
else:
return False
p1 = Person("lala",4)
p2 = Person.object_by_year("sonu",2000)
print(p1.get_name(),p1.get_age(),Person.is_adult(p1.age))
print(p2.get_name(),p2.get_age(),Person.is_adult(p2.age))
|
#!/usr/bin/python
"""
main routine of the intro cutter.
1 - extract a wav file with the intro from the given video,
position and duration must be known and set in conf.py
2 - make a fingerprint from the extracted wav file
3 - iterate all video files in the given directory
3a - extract first half of the audio track of the video,
the intro is not gonna be in the seconds half, right?
3b - look for the position in the audio track that best match the fingerprint
3c - create a new video file cutting out the matched position + duration
4 - log and clean up
"""
from __future__ import print_function
from fingerprint import make_fingerprint, find_fingerprint_in_file
from ffmpeg import make_tmp_filename as tmp, ext, extract_audio_chunk, get_video_duration, remove_chunk_from_video
from conf import *
# extract the audio of the intro and make a fingerprint of it
print("extracting intro song...")
intro_wav = extract_audio_chunk(INTRO_VIDEO_FILE, tmp() + '.wav', INTRO_START_S, INTRO_DURATION_S)
print("making intro fingerprint...")
fp = make_fingerprint(intro_wav)
k = AUDIO_FRAME_RATE / float(AUDIO_WINDOW_SIZE)
fp_duration_seconds = len(fp) / k
# iterate all video file
log = '\n*** matched intro ***\n{:<12} time\n'.format('match value')
matches = []
videos = [x for x in sorted(os.listdir(INPUT_DIR)) if ext(x)[1:].lower() in VIDEO_EXT]
for i, video in enumerate(videos):
print("processing video {} of {} {}...".format(i+1, len(videos), video))
# extract the audio only for the first half of the video
duration = get_video_duration(os.path.join(INPUT_DIR, video)) / 2
target_wav = extract_audio_chunk(os.path.join(INPUT_DIR, video), tmp() + ".wav", 0, duration)
# compare the fingerprint with the audio extracted from the video
match = find_fingerprint_in_file(fp, target_wav)
#log += 'index {:9} - value {:18} {:06.2f}s - {}\n'.format(match[0], match[1], match[0] / k, video)
log += '{:<12} {:06.2f}s - {}\n'.format(match[1], match[0] / k, video)
input_video = os.path.join(INPUT_DIR, video)
output_video = os.path.join(OUTPUT_DIR, OUTPUT_PREFIX+video)
matches.append((input_video, output_video, int(match[0] / k), fp_duration_seconds, match[1]))
#print("matches:\n{}".format('\n'.join(['{} - {} {}'.format() for i, x in enumerate(matches)])))
with open('log.txt', 'w') as f:
f.write(log)
print(log)
proceed = raw_input("proceed to cut the videos? (y/n)?").lower() == 'y'
if proceed:
for i, ele in enumerate(matches):
print("removing intro from video {} of {} {}...".format(i+1, len(videos), videos[i]))
remove_chunk_from_video(*ele[:-1])
if CLEAN_TMP:
for ele in os.listdir(TMP_DIR):
os.remove(os.path.join(TMP_DIR, ele))
|
def get_hills(n,arr):
hill = 0
for i in range(1,n-1):
if arr[i]>arr[i+1] and arr[i]>arr[i-1]:
hill+=1
return hill
def get_valleys(n,arr):
valley=0
for i in range(1,n-1):
if arr[i]<arr[i+1] and arr[i]<arr[i-1]:
valley+=1
return valley
def solution(n,arr):
ans = get_hills(n,arr)+get_valleys(n,arr)
for i in range(1,n-1):
if arr[i]>arr[i+1] and arr[i]>arr[i-1]:
return ans
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int,input().split()))
print(solution(n,arr))
|
import base64
import numpy as np
import random
import rsa
import math
#TODO create function that allows user to enter a message, also allows the user to enter two separate "e" values
# and then will use the rsa public key generation function to generate a modulus N. Calculates the ciphertexts.
def userInput():
e1 = int(input("Enter an e value: "))
e2 = int(input("Enter a second e value: "))
if math.gcd(e1, e2) != 1:
raise ValueError("e1 and e2 must be coprime!")
message = encrypt(input("Enter the message: "))
pubk,_ = rsa.newkeys(nbits = 2048)
print("Your modulus is: %d" % pubk.n)
c1 = (message**e1) % pubk.n
c2 = (message**e2) % pubk.n
print(decrypt(attack(c1,c2,e1,e2,pubk.n)).decode("utf-8"))
def modinv(a, m):
#This portion calculates the extended Euclidian Algorithm (EGCD)
#We make a list of quotients used to divide the number as it will be used when the algorithm works its way up
quotients = list()
b = m
#This porition obtains the GCD for the two numbers a,b and appends b/a floored (i.e. b//a) to quotients list
while a != 0:
quotients.append(b//a)
#a becomes b%a, and and b becomes a, these operations occur until a gcd is found (i.e a ==0)
a, b = b%a, a
#we set g equal to the gcd, and then set x = 0 and y = 1 as we are going to work our way back up
#obtaining the final x,y such that ax + by = 1
gcd, x, y = b,0,1
for i in range(len(quotients)-1,-1,-1):
x,y = y - quotients[i] * x, x
return x % m, y
#this function takes in the ciphertext, computes the egcd of the exponents to obtain s1 and s2 such that
#e1*s1 + e2*s2 = 1, and return the product of C1^e1*s1 + C2^e2*s2
def attack(c1, c2, e1, e2, N):
if math.gcd(e1, e2) != 1:
raise ValueError("e1 and e2 must be coprime!")
s1,s2 = modinv(e1,e2)
#Equation C1^s1 + C2^s2 = M1^e1*s1 + M2^e2*s2
return (pow(c1,s1,N) * pow(c2,s2,N)) % N
def encrypt(message):
m_int = int(base64.b64encode(message.encode("ASCII")).hex(),base = 16)
return m_int
# The decrypted ciphertext needs to be the resulting message after undergoing the
# common modulus attack algorithm. Ciphertext must be an int!
def decrypt(ciphertext):
plaintext = base64.b64decode(bytes.fromhex(hex(ciphertext)[2:]).decode("ASCII"))
return plaintext
def main():
print('~~~~~~~~~~ Starting Common Modulus Attack ~~~~~~~~~~')
#Original values from the problem on the website
message = attack(239450055536579126410433057119955568243208878037441558052345538060429910227864196906345427754000499641521575512944473380047865623679664401229365345208068050995600248796358129950676950842724758743044543343426938845678892776396315240898265648919893384723100132425351735921836372375270138768751862889295179915967, 138372640918712441635048432796183745163164033759933692015738688043514876808030419408866658926149572619049975479533518038543123781439635367988204599740411304464710538234675409552954543439980522243416932759834006973717964032712098473752496471182275216438174279723470286674311474283278293265668947915374771552561, 3, 65537, 402394248802762560784459411647796431108620322919897426002417858465984510150839043308712123310510922610690378085519407742502585978563438101321191019034005392771936629869360205383247721026151449660543966528254014636648532640397857580791648563954248342700568953634713286153354659774351731627683020456167612375777)
print('~~~~~~~~~~ Common Modulus Attack Finished! ~~~~~~~~~~')
print('\nPlaintext message:\n%s' % decrypt(message).decode("utf-8"))
userInput()
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import json
import pdb
import os
one_word_conjunction = ['y', 'a', 'e', 'o', 'u']
char_end_allowed = ['a', 'e', 'o', 'u', 'n', 'r', 's', 'l']
def pegar_tripletas(w1, w2, w3):
separados = w1 + " " + w2 + " " + w3
if len(w1) > 1:
if len(w2) > 1: return separados
else:
if w2 in one_word_conjunction:
if w2 == 'e' or w2 == 'u':
if (w2 == 'e' and w3[0].lower() == 'i') or (w2 == 'u' and w3[0].lower() == 'o'):
return separados
else:
return w1 + " " + w2 + w3
else:
return separados
else:
return w1 + " " + w2 + w3
else:
if len(w3) > 1:
if len(w2) > 1:
if w1 in one_word_conjunction:
return separados
else:
return w1 + w2 + " " + w3
else:
if w1 == 'y':
if w2 == 'a': return separados
else:
return w1 + " " + w2 + w3
elif w2 not in char_end_allowed:
return w1 + w2 + w3
else:
if w1 in ['a', 'e', 'o', 'u']:
return w1 + w2 + " " + w3
else:
return w1 + w2 + " " + w3
else:
if len(w2) > 1:
if w1 in one_word_conjunction: return separados
else:
return w1 + w2 + " " + w3
else:
return w1 + w2 + w3
def limpiar_porcentajes(x):
return x.group(0)[:-1]
def elimina_raros(texto):
texto_limpio = re.sub(u'[^\xf1\xe1\xe9\xed\xf3\xfa\w\,\.\-\s\%\¿\?\(\)]', '', texto)
texto_limpio = re.sub('[^0-9\s]\s*%', limpiar_porcentajes, texto_limpio)
return texto_limpio
def separar(x):
return x.group(0) + " "
def quitar_espacios(text):
words = text.split()
new_text = ""
if len(words) < 3:
return text
for i in range(len(words)-2):
w1 = words[i]
w2 = words[i+1]
w3 = words[i+2]
if i != 0:
if w3 not in pegar_tripletas(w1, w2, w3).split():
new_text += w3
else:
new_text += " " + w3
else:
new_text += pegar_tripletas(w1, w2, w3)
new_text = re.sub('([0-9]+|%)', separar, new_text)
return new_text
#Elimina las mayusculas de una palabra
def separa_mayus(palabra):
try:
string_error = re.search('[a-zñ][A-Z]', palabra).group(0)
fixed_string = string_error[0] + " " + string_error[1]
return palabra.replace(string_error, fixed_string)
except:
return palabra
#Elimina las mayusculas intermedias en todo el texto
def elimina_mayus(texto):
todas = texto.split()
todas_limpias = list(map(lambda x: separa_mayus(x), todas))
return " ".join(todas_limpias)
def elimina_letras_sueltas(texto):
words = texto.split()
texto_limpio = ""
for word in words:
if len(word) ==1 and re.search('[a-zñ]', word) is not None and word not in one_word_conjunction:
texto_limpio += ""
else:
texto_limpio += word + " "
return texto_limpio
def known(words):
"""
Descarta si P(C)=0
"""
return set(w for w in words if w in NWORDS)
def known_edits2(word):
"""
Calcula el P(W/C) ----- distancia=2 y se descarta si P(C)=0
"""
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
alphabet = u'abcdefghijklmnopqrstuvwxyz\xf1\xe1\xe9\xed\xf3\xfa'
def edits1(word):
"""
Calcula el P(W/C) ----- distancia=1
"""
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes= [a + b[1:] for a, b in s if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b) > 1]
replaces= [a + c + b[1:] for a, b in s for c in alphabet if b]
inserts= [a + c + b for a, b in s for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def correct(word):
"""
funcion principal
"""
if len(re.findall("[^0-9\,\.\-\s\%\¿\?\(\)]", word)) == 0:
return word
else:
first_letter = ""
candidates = known([word.lower()]) or known(edits1(word.lower())) or known_edits2(word.lower()) or [word.lower()]
candidato = max(candidates, key = NWORDS.get)
if word[0].isupper():
answer = word[0] + candidato[1:]
return answer
else:
return candidato
def limpiar_linea(sentence):
linea = sentence.replace(",", " , ").replace(".", " . ").replace("¿", " ¿ ").replace("?", " ? ").replace("(", " ( ").replace(")", " ) ")
linea_limpia = elimina_letras_sueltas(elimina_mayus(quitar_espacios(elimina_raros(linea))))
linea_corregida = " ".join([correct(x) for x in linea_limpia.split()])
linea_corregida = linea_corregida.replace(" , ", ",").replace(" . ", ".").replace(" ? ", "?").replace(" ( ", "(").replace(" ) ", ")")
return linea_corregida
#abre el archivo de corpus
with open("Preprocesamiento_I/corpus.json", 'r') as f:
NWORDS = json.load(f)
with open("data/nombres.txt", 'r') as f:
lines = f.readlines()
for line in lines:
line=line.rstrip('\n')
tmp=line.split('/')
nombre=tmp[len(tmp)-1]
with open( line, 'r') as fread:
lineas_texto = [x.strip() for x in fread.readlines() if len(x.strip()) > 0]
#print(lineas_texto)
with open("data/limpios/"+nombre , 'a') as fwrite:
for linea in lineas_texto:
fwrite.write(limpiar_linea(linea).encode('utf-8'))
|
# Takes in a FEN-string and returns a boardMatrix on the following format:
# (yes this convertion looses some information about the game that is not relevant for drawing the board)
# [['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
# ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
# ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
# ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']]
def getBoardMatrix(fen):
exception = Exception(f"FEN-string is not valid: {fen}")
rows = fen.strip(" ").split(" ")[0].split("/")
boardMatrix = []
for row in rows:
toAppend = []
for char in row:
if char in [str(n) for n in range(1, 9)]:
toAppend += [" " for i in range(int(char))]
elif char in ["r", "n", "b", "q", "k", "p", "R", "N", "B", "Q", "K", "P"]:
toAppend.append(char)
else:
raise exception
if len(toAppend) != 8:
raise exception
boardMatrix.append(toAppend)
if len(boardMatrix) != 8:
raise exception
return boardMatrix
# Takes in a FEN-string and returns:
# - "w" if white is in the move
# - "b" if black is in the move
def getPlayerInMove(fen):
return fen.split(" ")[1].lower()
|
from Board import *
from tkinter import *
myBoard = Board()
myBoard.createBoard("easy.txt")
#myBoard.printBoard()
myEntries = []
root = Tk()
#create entries and assign them a stringVar
for row in range(9):
myEntries.append([])
for col in range(9):
entry = Entry(root, width = 2, justify = "center", font = "Helvetica 20 bold")
entry.insert(END, str(myBoard.board[row][col]))
if str(myBoard.board[row][col]) != '':
entry.config(state = DISABLED)
entry.grid(row = row, column = col, padx = 2, pady = 2)
myEntries[row].append(entry)
#print(myEntries)
def submit():
validValues = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}
for row in range(9):
for col in range(9):
entry = myEntries[row][col]
if entry.get() in validValues:
myBoard.board[row][col] = entry.get()
else:
Label(root, text = "Invalid Value").grid(row = 10, column = 0, columnspan=9)
return
if myBoard.isSolved():
Label(root, text = "Solved!!").grid(row = 10, column = 0, columnspan=9)
else:
Label(root, text = "Wrong").grid(row = 10, column = 0, columnspan=9)
submitButton = Button(root, text = "Submit", command = submit)
submitButton.grid(row = 9, column = 3, columnspan=3)
def getEntry(row, col):
entry = myEntries[row][col]
return entry
root.mainloop()
|
import tensorflow as tf #importing tensor flow librarry
hello = tf.constant('hello,Muneeba') # storing a strong as constant
sess = tf.Session() # creating a tensorflow session
print(sess.run(hello)) # sess.run is responsible for running the session
#PLACEHOLDERS
#Placeholders are the terminals/data point through which we will be feeding data into the network we will build. Its like gate point for our input and output data.
inputs=tf.placeholder('float',[None,2],name='Input') #the data type that will feed to the placeholder is float , 2nd parameter is the shape of input.
targets=tf.placeholder('float',name='Target')
#Now lets say we don’t know how many input set we are going to feed at the same time. it can be 1 it can be 100 sets at a time. So we specify that with None.
#if we set the input shape of the placeholder as [None,3] then it will be able to take any sets of data in a single shot. that is what we did in out earlier code.
#In the second case I didn’t select any shape, in this case it will accept any shape. but there is a chance of getting error in runtime if the data the network is
## expecting has a different shape than the data we provided in the placeholder.
#the third parameter name will help us to identify nodes on tenoorboard
#VARIABLES
#Variables in tensorflow are different from regular variables, unlike placeholders we will never set any specific values in these, nor use it for storing any data.
weight1=tf.Variable(tf.random_normal(shape=[2,3],stddev=0.02),name="Weight1")
biases1=tf.Variable(tf.random_normal(shape=[3],stddev=0.02),name="Biases1") #it has only output connections no input. that is it is the inpyt itself
#in this case we initialized the first one as 2×3 matrix with random values with variation of +/- 0.02. for the shape the first one is the number of input connection
## that the layer will receive. and the 2nd one is the number of output connection that the layer will produce for the next layer.
hLayer=tf.matmul(inputs,weight1)
hLayer=hLayer+biases1
#So here is two matrix operations first one is matrix multiplications of inputs and the weights1 matrix which will produce the output without bias. and in the next line
#we did matrix addition which basically performed an element by element additions.
hLayer=tf.sigmoid(hLayer, name='hActivation') #writing an activation function
#creating the output layer
weight2=tf.Variable(tf.random_normal(shape=[3,1],stddev=0.02),name="Weight2")
biases2=tf.Variable(tf.random_normal(shape=[1],stddev=0.02),name="Biases2")
#As we can see the output layer has only 1 neuron and the previous hidden layer had 3 neurons.
#So the weight matrix has 3 input and 1 output thus the shape is [3,1]. and the bias has only one neuron to connect to thus bias shape in [1]
output=tf.matmul(hLayer,weight2)
output=output+biases2
output=tf.sigmoid(output, name='outActivation')
#cost=tf.nn.softmax_cross_entropy_with_logits(logits=output,labels=targets)
# update tf.nn.softmax_cross_entropy_with_logits is for classification problems only
# we will be using tf.squared_difference()
cost=tf.squared_difference(targets, output)
cost=tf.reduce_mean(cost)
optimizer=tf.train.AdamOptimizer().minimize(cost)
#tf.squared_difference takes two input fitsr is the target value and second is the predicted value.
#SESSION
#generating inputs
import numpy as np
inp=[[0,0],[0,1],[1,0],[1,1]]
out=[[0],[1],[1],[0]]
inp=np.array(inp)
out=np.array(out)
epochs=4000 # number of time we want to repeat
with tf.Session() as sess:
tf.global_variables_initializer().run()
for i in range(epochs):
error,_ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out})
print(i,error)
with tf.Session() as sess:
tf.global_variables_initializer().run()
for i in range(epochs):
error,_ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out})
print(i,error)
while True:
a = input("type 1st input :")
b = input("type 2nd input :")
inp=[[a,b]]
inp=np.array(inp)
prediction=sess.run([output],feed_dict={inputs: inp})
print(prediction)
aver = tf.train.Saver()
with tf.Session() as sess:
tf.global_variables_initializer().run()
for i in range(epochs):
error,_ =sess.run([cost,optimizer],feed_dict={inputs: inp,targets:out})
print(i,error)
saver.save(sess, "model.ckpt") # saving the session with file name "model.ckpt"
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, "model.ckpt")
while True:
a = input("type 1st input :")
b = input("type 2nd input :")
inp=[[a,b]]
inp=np.array(inp)
prediction=sess.run([output],feed_dict={inputs: inp})
print(prediction)
|
from random import shuffle
from card import Card
from player import Player
def generate_deck():
"""Generate a deck of cards.
Returns:
a new deck containing 52 cards
"""
deck = []
order = list(range(1,53))
shuffle(order) #shuffles the order randomly
for i in order:#puts card in the deck
card = Card(i % 13, i % 4)
deck.append(card)
return deck
def deal_card(player, deck):
"""gets a card out of the deck, to hand over to player
Parameters:
player: obj -- object of player
deck: list -- list of the deck
"""
player.cards.append(deck.pop())
def check_winner(player, house, bet):
"""Check who won the game by going through the different scenarios and dertimining who won """
#Handles blackjack
if house.calc_card_value() == 21:
print("House got blackjack!")
if player.calc_card_value() == 21:
print(player.player_name + " got blackjack!")
if house.calc_card_value() > 21:
print(player.player_name + " won")
player.deposit(bet)
elif player.calc_card_value() > house.calc_card_value():
print(player.player_name + " won")
player.deposit(bet)
elif player.calc_card_value() == house.calc_card_value():
print("Tie!")
else:
print('House won')
player.withdraw(bet)
def play_game(player, house, deck, bet):
"""
Game functionality; deals cards,
handles hit and pass,
checks if player busts
Parameters:
player: obj -- player object
house: obj -- house object
deck: list -- list of deck
bet: int -- placed bet
"""
#deals 2 cards to the player, and one for the dealer
deal_card(house, deck)
deal_card(player, deck)
deal_card(player, deck)
#prints the current card on the table
player.print_current_cards()
house.print_current_cards()
bust = False
#get user input.
#if user busts, bust is set to True, and the player looses their bet
#if the user decides to hit, they are dealt another card. And the game continues
while True:
action = input('press h to hit or s to stand')
#deals a new card if user decides to hit
if action == 'h':
deal_card(player, deck)
player.print_current_cards()
#if the user decides to stand, it breaks out of the foor loop, and starts to deal cards to house
elif action == 's':
player.print_current_cards()
break
#checks if the user busts
if player.calc_card_value() > 21:
player.print_current_cards()
print(player.player_name + ' busts')
bust = True
break
if bust:
player.withdraw(bet)
else:
#computers turn if the user decides to stand
#by the rules of blackjack, the dealer stands at 17
while house.calc_card_value() < 17:
deal_card(house, deck)
house.print_current_cards()
if not bust:
check_winner(player, house, bet)
#Prints the current amount for players account
print(f'{player.player_name} you now have {player.bet_account} in your account')
def get_player_name():
"""Gets the name of the player"""
while True:
name = input('What is your name?').capitalize()
if name is not "": #check that name is not empty
return name
else:
print("You need to type a name!")
def get_deposit_amount():
"""Gets the amount the player wants to deposit """
while True:
try:
deposit = int(input('How much do you want to deposit?'))
if deposit > 0: #check if the deposit is positive and bigger than 0
return deposit
else:
print("You need to deposit more than 0")
except ValueError:
print("Not a valid deposit")
def main():
"""Initial setup. Gets player name and how much they wants to deposit, starts game """
#Print welcome message
print("-------------------------------------------")
print("Welcome to this python blackjack game!")
print("if you dont know the rules, go read them.")
print("Otherwise - Have fun!")
print("-------------------------------------------")
print()
#get player name and deposit
name = get_player_name()
deposit = get_deposit_amount()
#creates objects of player and house
player = Player(bet_account = deposit, player_name = name)
house = Player(bet_account = 10000000, player_name = "House")
stop = False
while not stop:
deck = generate_deck()
player.cards = []
house.cards = []
try:
bet = int(input('How much do you want to bet?'))
if bet <= player.bet_account and bet > 0:
#starts the game
play_game(player,house,deck,bet)
else:
print("Bet cannot be bigger than what you have, and cannot be 0")
except ValueError:
print("Not a valid bet")
want_to_stop = input('To stop write ¨s¨, to try again press enter')
if want_to_stop == "s":
stop = True
if __name__ == '__main__':
main()
|
# First of all I need to create a class that will initialize also a dictionay
# created using classe and PPO
class Budg_calculator :
def __init__ (self, amount):
self.available = amount # this is the initial amount
self.budgets = {}
self.expenditure = {}
self.first_budget = amount #added in order to offer a synthesis in the end
def add_budget (self, name, amount):
if name in self.budgets :
raise ValueError("Already Existent Voice")
if amount > self.available :
raise ValueError("Non Sufficient Funds")
self.budgets[name] = amount
self.available -= amount
self.expenditure[name] = 0
return self.available
def spend (self, name, amount ):
if name not in self.expenditure:
print ("this voice is not admitted")
self.expenditure[name] += amount
budgeted = self.budgets[name]
spent = self.expenditure[name]
return budgeted - spent
return self.expenditure # added
def print_summary (self):
print ("Budget" + " "*25 + "Expected" + " "*25 + "Spent" + " "*25 + "Residual")
print (" - - - - - - - - - - - - - - - - - - - - -")
total_budgeted = 0
total_spent = 0
total_remaining = 0
for name in self.budgets :
print (name + len("Budget")*" " + " "*(25-len(name)) + str((self.budgets[name]) )\
+ len("Expected")*" " + 25 * " " + str(dispo.expenditure[name])
# here I have to calculate the residual as difference of
# budgets and expenditure
+ 25 * " " + str( self.budgets[name] - dispo.expenditure[name] ))]
total_spent += self.expenditure[name]
print(" Initial budget: " + str(self.first_budget ))
print(" Effective expenses: " + str(total_spent ) )
print(" Savings: " + str(self.first_budget - total_spent) )
|
class Pegawai:
kenaikanGaji = 1.05
def __init__(self, nama, email, gaji):
self.namaPegawai = nama
self.emailPegawai = email + 'gmail.com'
self.gajiPegawai = gaji
def gajiCalculateMontly(self):
self.gajiPegawai = self.gajiPegawai * 30
return self.gajiPegawai
def naikJabatanPegawai(self):
self.gajiPegawai = float(self.gajiPegawai * self.kenaikanGaji)
return self.gajiPegawai
# ini merupakan contoh dari dunder biasanya method dunder (double underscore) yang paling banyak digunakan adalah
# dunder biasanya digunakan untuk overloading function yang sudah built-in didalam python.
# method __init__, __str__, __add__ dan __repr__
# __str__ digunakan untuk membuat objek untuk bisa dibaca oleh user
def __str__(self):
return "Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}".format(self.namaPegawai,self.emailPegawai,self.gajiPegawai)
# __repr__ digunakan untuk membuat objek untuk bisa dibaca oleh developer lain,
# maka dari itu ouput dari __repr__ dapat berupa kodingan dari objeknya sendiri.
def __repr__(self):
return "Pegawai('{}','{}',{})".format(self.namaPegawai,self.emailPegawai,self.gajiPegawai)
# digunakan untuk menembahkan gaji dari 2 instance
# disini parameternya menerima dua instance dari kelas Pegawai
# dan menambahkan jumlah gaji dari mereka.
def __add__(self, other):
return self.gajiPegawai + other.gajiPegawai
# digunakan untuk mengetahui panjang dari karakter namaPegawai
def __len__(self):
return len(self.namaPegawai)
pegawai1 = Pegawai("Moahmmad", "Sesuatu", 2000)
pegawai2 = Pegawai("Solihin", "Sesuatuhal", 2001)
print(Pegawai.__add__(pegawai1, pegawai2))
print(pegawai1.__len__())
print(pegawai1.__str__())
print(pegawai1.__repr__())
|
# Text 1
# Time period: 200 BC
import random
country_list = ['K*zakh-stan', 'K@z@kh-land', 'Qaz*qStepp*']
country_description = ['big', 'empty', 'large', 'enourmous', 'abanoded']
human_adjective = ['bold', 'crazy', 'creative', 'primitive']
country_name = random.choice(country_list)
group_name = ['Saka', 'Skythian', 'Massagetae']
print("Once upon a time, a country named %s was born..." % country_name)
print("The land so %s, only the %s could explore." % (random.choice(country_description), random.choice(human_adjective)))
print("Nevertheless, the %s people persisted." % random.choice(group_name))
|
# EJ (Mercy) Emelike
# May 26, 2016
# Homework 2
#LISTS
# 0) make list
numbers = [22, 90, 0, -10, 3, 22, 48]
# 1) print list
print(numbers)
# 2) print 4th element of list
print(numbers[3])
# 3) print sum of 2nd and 4th element
print(numbers[1] + numbers[3])
# 4) print 2nd largest value
numbers_sorted = sorted(numbers)
print (numbers_sorted[5])
# 5) print last element of the original unsorted list
print(numbers[6])
# 6)
for number in numbers:
if number < 10 and number % 2 == 0 and number != -10:
new_number = ((number * 30) + 6) - 1
print(new_number)
elif number < 10 and number % 2 != 0 and number != -10:
new_number = (number*30) - 1
print(new_number)
elif number < 10 and number % 2 == 0 and number == -10:
new_number = ((number * 30) + 6)
print(new_number)
elif number > 10 and number < 50 and number != -10:
new_number = (number - 1)
print(new_number)
elif number > 50 and number != -10:
new_number = (number - 10) - 1
print(new_number)
else:
print(number)
# 7) sum the result of each of the numbers divided by two
new_numbers = [number/2 for number in numbers]
sum_numbers = sum(new_numbers)
print (sum_numbers)
# 8) DICTIONARIES
movie = {'title': 'Finding Nemo', 'year': '2003', 'director': 'Andrew Stanton', 'budget': 94000000, 'revenue': 936700000 }
print ('My favorite movie is', movie['title'], 'which was released in', movie['year'], 'and was directed by', movie['director'])
#9
difference = movie['revenue'] - movie['budget']
print(difference)
# 10)
if movie['revenue'] < movie['budget']:
print ('it was a flop.')
elif movie['revenue'] >= movie['budget'] * 5:
print ('that was a good investment')
# 11)
populations = {'Manhattan': 1600000, 'Brooklyn': 2600000, 'Bronx': 1400000, 'Queens': 2300000, 'Staten Island': 470000}
# 12)
print(populations['Brooklyn'])
# 13)
tot_pop = sum(populations.values())
print (tot_pop)
# 14)
pct_Mnhttn = (populations['Manhattan'] / tot_pop)*100
print(pct_Mnhttn)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.