blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a3c81c5b91daffbd7de1fbe55e2fce7eac26cd80 | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_4.py | 1,434 | 4.125 | 4 | '''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_my_power(base, power):
base__power = 1
for count in range(power*(-1)):
base__power *= base
return 1 / base__power
try:
var_1 = float(input('Введите действительное положительное: '))
except ValueError:
print('Должно быть число! По умолчанию подставлена 1')
var_1 = 1
try:
var_2 = int(input('Введите целое отрицательное число: '))
if var_2 > 0:
print('Число должно быть отрицательным. Поставим минус за Вас')
var_2 = 0 - var_2
elif var_2 == 0:
print('0 не подходит. Подставим -1')
var_2 = -1
except ValueError:
print('целое отрицательное число. А вы ввели что-то друге. Подставим вместо Вас -1')
var_2 = -1
print(f'Результат работы моей функции: {f_my_power(var_1, var_2)}')
print(f'Результат работы системной функции python: {var_1**var_2}. Для визуальной проверки результата')
|
c89455cedb014aca5fa8d634476fa9aedb2381c0 | mug-auth/ssl-chewing | /src/utilities/numpyutils.py | 2,600 | 4.03125 | 4 | from typing import Tuple, Optional, List
import numpy as np
from utilities.typingutils import is_typed_list
def is_numpy_1d_vector(x):
"""Check if ``x`` is a numpy ndarray and is a 1-D vector."""
return isinstance(x, np.ndarray) and len(x.shape) == 1
def is_numpy_2d_vector(x, column_vector: Optional[bool] = True):
"""
Check if ``x`` is a numpy ndarray and is a 1-2 vector.
:param x: The variable to check
:param column_vector: If True, vector should be a column vector, i.e. x.shape=(n,1). If False, vector should be a
row vector, i.e. x.shape=(1,n). If None, it can be any of the two.
"""
if not (isinstance(x, np.ndarray) and len(x.shape) == 2):
return False
if column_vector is None:
return True
if column_vector:
return x.shape[1] == 1
else:
return x.shape[0] == 1
def is_numpy_vector(x):
return is_numpy_1d_vector(x) or is_numpy_2d_vector(x, None)
def is_numpy_matrix(x, cols: int = None, rows: int = None):
if not isinstance(x, np.ndarray):
return False
if not len(x.shape) == 2:
return False
if rows is not None and x.shape[0] != rows:
return False
if cols is not None and x.shape[1] != cols:
return False
return True
def ensure_numpy_1d_vector(x: np.ndarray, force: bool = False):
assert isinstance(x, np.ndarray)
assert isinstance(force, bool)
shape: Tuple = x.shape
if len(shape) == 1:
return x
elif len(shape) == 2 and (shape[0] == 1 or shape[1] == 1):
return x.reshape((x.size,))
elif force:
return x.reshape((x.size,))
else:
raise ValueError("Cannot ensure 1D vector for matrices, unless force=True")
def ensure_numpy_2d_vector(x: np.ndarray, column_vector: bool = True):
assert isinstance(x, np.ndarray)
assert isinstance(column_vector, bool)
shp: Tuple = x.shape
dim: int = len(shp)
if dim == 1:
if column_vector:
return x.reshape((shp[0], 1))
else:
return x.reshape((1, shp[0]))
elif dim == 2:
if column_vector:
assert shp[1] == 1
else:
assert shp[0] == 1
return x
else:
raise ValueError("x.shape has " + str(dim) + ", expected 1 or 2 instead")
def setdiff1d_listint(set1: List[int], set2: List[int]) -> List[int]:
assert is_typed_list(set1, int)
assert is_typed_list(set2, int)
nset1: np.ndarray = np.array(set1)
nset2: np.ndarray = np.array(set2)
return np.setdiff1d(nset1, nset2).tolist()
|
229ae10428cfaa24615c9c329ee3258baa93943d | YuRen-tw/my-university-code | /cryptography/c2019-p4/maxima_interface.py | 807 | 3.578125 | 4 | '''
Interact with Maxima (a computer algebra system) via command line
'''
from subprocess import getoutput as CLI
def maxima(command):
command = 'display2d:false$' + command
output = CLI('maxima --batch-string=\'{}\''.format(command))
'''
(%i1) display2d:false$
(%i2) <CMD>
(%o2) <RESULT>
'''
return output[output.index('(%o2)')+5:].strip()
def primep(n):
output = maxima('primep({});'.format(n))
return output == 'true'
def factor(n):
output = maxima('factor({});'.format(n))
result = []
for prime_power in output.split('*'):
prime_power = (prime_power+'^1').split('^')[:2]
result.append(tuple(int(i) for i in prime_power))
return result
def next_prime(n):
output = maxima('next_prime({});'.format(n))
return int(output)
|
ef1ebb2ba1f95a2d8c09f3dc32af9d2ffec17499 | CyberTaoFlow/Snowman | /Source/server/web/exceptions.py | 402 | 4.3125 | 4 | class InvalidValueError(Exception):
"""Exception thrown if an invalid value is encountered.
Example: checking if A.type == "type1" || A.type == "type2"
A.type is actually "type3" which is not expected => throw this exception.
Throw with custom message: InvalidValueError("I did not expect that value!")"""
def __init__(self, message):
Exception.__init__(self, message) |
c61d5128252a279d1f6c2b6f054e8ea1ead7b2af | rup3sh/python_expr | /general/trie | 2,217 | 4.28125 | 4 | #!/bin/python3
import json
class Trie:
def __init__(self):
self._root = {}
def insertWord(self, string):
''' Inserts word by iterating thru char by char and adding '*"
to mark end of word and store complete word there for easy search'''
node = self._root
for c in string:
if c not in node:
node[c] = {}
node = node[c]
node['*'] = string
def printTrie(self):
node = self._root
print(json.dumps(self._root, indent=2))
##Utility methods
def isWord(self, word):
''' check if word exists in trie'''
node = self._root
for c in word:
if c not in node:
return False
node = node[c]
# All chars were seen
return True
#EPIP, Question 24.20
def shortestUniquePrefix(self, string):
'''shortest unique prefix not in the trie'''
prefix = []
node = self._root
for c in string:
prefix.append(c)
if c not in node:
return ''.join(prefix)
node = node[c]
return ''
def startsWithPrefix(self, prefix):
''' return suffixes that start with given prefix '''
# Simulating DFS
def _dfs(node):
stack = []
stack.append(node)
temp = []
while stack:
n = stack.pop()
for c in n.keys():
if c == '*': #Word end found
temp.append(n[c])
else: #Keep searching
stack.append(n[c])
return temp
##Position node to the end of prefix list
node = self._root
for c in prefix:
if c not in node:
break
node = node[c]
return _dfs(node)
def main():
t_list = "mon mony mont monty monday mondays tea ted teddy tom tony tori tomas tomi todd"
words = t_list.split()
trie = Trie()
for word in words:
trie.insertWord(word)
#trie.printTrie()
#Utility method test
target = 'teal'
#print(target, "Is in tree?", trie.isWord(target))
target = 'teddy'
#print(target, "Is in tree?", trie.isWord(target))
target = 'temporary'
#shortest_unique_not_in_trie = trie.shortestUniquePrefix(target)
#print("shortest_unique_not_in_trie is :", shortest_unique_not_in_trie)
suffixes = trie.startsWithPrefix('mon')
print("Words starting with prefix:", suffixes)
if __name__=="__main__":main()
|
08f9852f9cf2c1ac4a5b25899e4e0afb5f1d91ff | rup3sh/python_expr | /Recursion/palindrome | 493 | 3.890625 | 4 | #!/bin/python3
def isPalindrome(word):
def extractChars(word):
chars = []
for w in word.lower():
if w in 'abcdefghijklmnopqrstwxyz':
chars.append(w)
return ''.join(chars)
def isPalin(s):
if len(s)==1:
return True
else:
return s[0]==s[-1] and isPalin(s[1:-1])
chars = extractChars(word)
print(chars)
return isPalin(chars)
def main():
word = "Madam, I'm adam"
result = isPalindrome(word)
print(result)
if __name__=="__main__":main()
|
7cbfc86f3d6399973e6cd05e0a83bb4ad2f6e023 | rup3sh/python_expr | /generators/coroutine | 1,934 | 3.734375 | 4 | #!/bin/python3
import pdb
import sys
## Generators are somewhat opposite of coroutines.Generators produce values and coroutines consume value.
##Coroutines
## - consume value
## - May not return anything
## - not for iteration
## Technically, coroutines are built from generators.
## Couroutine does this -
## - Continually receives input, processes input, stops at yield statement
## - Coroutine have send method
## - Yield in coroutine pauses the flow and also captures values
## (Very powerful in data processing programs)
def main(argv):
coroutineDemo()
def barebones_coroutine():
while True:
x = yield # Essentially, control pauses here until send is invoked by caller.
print("In coroutine:" + str(x))
def mc_decorator(func):
def myfunc_wrapper(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return myfunc_wrapper
#Elaborate coroutine with decoratr to wrap it so that calling code does not have to call next
@mc_decorator
def message_checker(initial_list):
counter = 0
try:
while True:
received_msg = yield
if received_msg in initial_list:
counter+=1
print(counter)
except GeneratorExit: # This happens during closing the coroutine
print ("Final Count:" + str(counter))
def coroutineDemo():
try:
bbcor = barebones_coroutine()
## Have to initialize the internal generator
next(bbcor)
bbcor.send(25)
bbcor.send("This is how we do it!")
bbcor.close()
print("Closed barebones coroutine")
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea", "india"]
mc = message_checker(the_list)
#next(mc) DUE TO DECORATOR, we do not have to do this
mc.send('japan')
mc.send('korea')
mc.send('usa')
mc.send('india')
mc.send('india')
mc.close()
except Exception as e:
sys.stderr.write("Exception:{}".format(str(e)))
if __name__ == "__main__":main(sys.argv[0:])
|
23f20f17dc25cc3771922706260d43751f2584c5 | rup3sh/python_expr | /generators/generator | 1,446 | 4.34375 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
generatorDemo()
def list_of_even(n):
for i in range(0,n+1):
if i%2 == 0:
yield i
def generatorDemo():
try:
x = list_of_even(10)
print(type(x))
for i in x:
print("EVEN:" + str(i))
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
#Print the reverse list
print(the_list[::-1])
#list comprehension
new_list = [ item.upper() for item in the_list ]
print("NEWLIST:" + str(new_list))
#generator expression
gen_object = (item.upper() for item in the_list)
#You can also call next() on this generator object
# Generator would call a StopIteration Execepton if you cannot call next anymore
print(type(gen_object))
##This yields the items one by one toa list
newlist = list(gen_object)
print("YET ANOTHER NEWLIST:" + str(new_list))
# As you can see, generator objects cannot be reused
# So this would be empty
one_more_list = list(gen_object)
print("ONE MORE LIST:" + str(one_more_list))
# Capitalizes the word and reverses the word in one step
ultimate_gen = (item[::-1] for item in (item.upper() for item in the_list))
print("ULTIMATE LIST:" + str(list(ultimate_gen)))
except Exception as e:
sys.stderr.write("Exception:{}".format(str(e)))
if __name__ == "__main__":main(sys.argv[0:])
|
8fe1986f84ccd0f906095b651aa98ba62b2928b8 | rup3sh/python_expr | /listsItersEtc/listComp | 1,981 | 4.1875 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
listComp()
def listComp():
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
print(the_list[0:len(the_list)])
#Slicing
#the_list[2:] = "paz"
#['stanley', 'ave', 'p', 'a', 'z'] # This replaces everything from indexs 2 onwards
#Everything except the last one
#print(str(the_list[:-1]))
#Prints 2, 3 only
#print(str(the_list[2:4]))
#Prints reverse -N onwards, but counting from 1 "los angeles", "istanbul", "moscow", "korea"]
#print(str(the_list[-4:]))
#Prints from start except last 4 ["stanley", "ave", "fremont",
#print(str(the_list[:-4]))
#Prints from start, skips odd positions ['ave', 'los angeles', 'moscow']
#print(str(the_list[1::2]))
#Prints from reverse at 1, skips odd positions (only 'ave')
#print(str(the_list[1::-2]))
#the_list[3:3] = "California"
#['stanley', 'ave', 'fremont', 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a', 'los angeles', 'istanbul', 'moscow', 'korea']
#Insert new list at a position
#the_list[3:3] = ["California"]
#['stanley', 'ave', 'fremont', 'California', 'los angeles', 'istanbul', 'moscow', 'korea']
# Modifies list to ['stanley', 'ave', 'fremont', 'California', 'moscow', 'korea']
#the_list[3:5] = ["California"]
# Delete middle of the list ['stanley', 'ave', 'fremont','moscow', 'korea']
#the_list[3:5] = []
##Add list to another list
add_this = ["africa", "asia", "antarctica"]
the_list.extend(add_this)
#Insert in the list
the_list.insert(4, 'alameda')
#Delete an element by index
x = the_list.pop(3)
#Delete an element by name
the_list.remove('moscow')
print(str(the_list))
#In-place reversal
the_list.reverse()
print(str(the_list))
print("Index of africa is: "+ str(the_list.index('africa')))
# Count occurrence
print(str(the_list.count('fremont')))
if __name__ == "__main__":main(sys.argv[0:])
|
c2aeb4bc202edaf3417d097408e5c680d0ffc1c0 | maksymshylo/statistical_pattern_recognition | /lab4/trws_algorithm.py | 9,184 | 3.5 | 4 | from numba import njit
import numpy as np
@njit
def get_right_down(height,width,i,j):
'''
Parameters
height: int
height of input image
width: int
width of input image
i: int
number of row
j: int
number of column
Returns
N: list
array of 2 neighbours coordinates
calculates 2 neighbours: Right and Down
(i,j)--(i,j+1)
|
(i+1,j)
examples:
>>> get_right_down(2,2,2,2.)
Traceback (most recent call last):
...
Exception: invalid indices values (not integer)
>>> get_right_down(-2,2,2,2)
Traceback (most recent call last):
...
Exception: height or width is less than zero
>>> get_right_down(2,2,2,2)
[]
>>> get_right_down(2,2,0,0)
[[0, 1], [1, 0]]
'''
if width <= 0 or height <= 0:
raise Exception('height or width is less than zero')
if type(i) is not np.int64 or type(j) is not np.int64:
raise Exception('invalid indices values (not integer)')
# i,j - position of pixel
# [Right, Down] - order of possible neighbours
# array of neighbour indices
nbs = []
# Right
if 0<j+1<=width-1 and 0<=i<=height-1:
nbs.append([i,j+1])
# Down
if 0<i+1<=height-1 and 0<=j<=width-1:
nbs.append([i+1,j])
return nbs
@njit
def get_neighbours(height,width,i,j):
'''
Parameters
height: int
height of input image
width: int
width of input image
i: int
number of row
j: int
number of column
Returns
N: tuple
neighbours coordinates, neighbours indices, inverse neighbours indices
calculates neighbours in 4-neighbours system (and inverse indices)
(i-1,j)
|
(i,j-1)--(i,j)--(i,j+1)
|
(i+1,j)
examples:
>>> get_neighbours(-1,1,1,1)
Traceback (most recent call last):
...
Exception: height or width is less than zero
>>> get_neighbours(3,3,-1,-1)
([], [], [])
>>> get_neighbours(3,3,0,0)
([[0, 1], [1, 0]], [0, 2], [1, 3])
>>> get_neighbours(3,3,0,1)
([[0, 0], [0, 2], [1, 1]], [1, 0, 2], [0, 1, 3])
>>> get_neighbours(3,3,1,1)
([[1, 0], [1, 2], [0, 1], [2, 1]], [1, 0, 3, 2], [0, 1, 2, 3])
'''
# i,j - position of pixel
# [Left, Right, Up, Down] - order of possible neighbours
# array of neighbour indices
if width <= 0 or height <= 0:
raise Exception('height or width is less than zero')
nbs = []
# neighbour indices
nbs_indices = []
# inverse neighbour indices
inv_nbs_indices = []
# Left
if 0<=j-1<width-1 and 0<=i<=height-1:
nbs.append([i,j-1])
inv_nbs_indices.append(1)
nbs_indices.append(0)
# Right
if 0<j+1<=width-1 and 0<=i<=height-1:
nbs.append([i,j+1])
inv_nbs_indices.append(0)
nbs_indices.append(1)
# Upper
if 0<=i-1<height-1 and 0<=j<=width-1:
nbs.append([i-1,j])
inv_nbs_indices.append(3)
nbs_indices.append(2)
# Down
if 0<i+1<=height-1 and 0<=j<=width-1:
nbs.append([i+1,j])
inv_nbs_indices.append(2)
nbs_indices.append(3)
N = (nbs, inv_nbs_indices, nbs_indices)
return N
@njit(fastmath=True, cache=True)
def forward_pass(height,width,n_labels,Q,g,P,fi):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
array of potentials
Returns
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
updated array of potentials
updates fi, according to best path for 'Left' and 'Up' directions
'''
# for each pixel of input channel
for i in range(1,height):
for j in range(1,width):
# for each label in pixel
for k in range(n_labels):
# P[i,j,0,k] - Left direction
# P[i,j,2,k] - Up direction
# calculate best path weight according to formula
P[i,j,0,k] = max(P[i,j-1,0,:] + (1/2)*Q[i,j-1,:] - fi[i,j-1,:] + g[i,j-1,1,:,k])
P[i,j,2,k] = max(P[i-1,j,2,:] + (1/2)*Q[i-1,j,:] + fi[i-1,j,:] + g[i-1,j,3,:,k])
# update potentials
fi[i,j,k] = (P[i,j,0,k] + P[i,j,1,k] - P[i,j,2,k] - P[i,j,3,k])/2
return (P,fi)
@njit(fastmath=True, cache=True)
def backward_pass(height,width,n_labels,Q,g,P,fi):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
array of potentials
Returns
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
fi: ndarray
updated array of potentials
updates fi, according to best path for 'Right' and 'Down' directions
'''
# for each pixel of input channel
# going from bottom-right to top-left pixel
for i in np.arange(height-2,-1,-1):
for j in np.arange(width-2,-1,-1):
# for each label in pixel
for k in range(n_labels):
# P[i,j,1,k] - Right direction
# P[i,j,3,k] - Down direction
# calculate best path weight according to formula
P[i,j,3,k] = max(P[i+1,j,3,:] + (1/2)*Q[i+1,j,:] + fi[i+1,j,:] + g[i+1,j,2,k,:])
P[i,j,1,k] = max(P[i,j+1,1,:] + (1/2)*Q[i,j+1,:] - fi[i,j+1,:] + g[i,j+1,0,k,:])
# update potentials
fi[i,j,k] = (P[i,j,0,k] + P[i,j,1,k] - P[i,j,2,k] - P[i,j,3,k])/2
return (P,fi)
def trws(height,width,n_labels,K,Q,g,P,n_iter):
'''
Parameters
height: int
height of input image
width: int
width of input image
n_labels: int
number of labels in labelset
K: ndarray
array of colors (mapping label->color)
Q: ndarray
array of unary penalties
g: ndarray
array of binary penalties
P: ndarray
array consist of best path weight for each direction (Left,Right,Up,Down)
n_iter: int
number of iteratations
Returns
output: ndarray
array of optimal labelling (with color mapping)
one iteration of TRW-S algorithm (forward and backward pass),
updates fi, according to best path for all directions
examples:
>>> trws('height','width','n_labels','K','Q','g','P',-1)
Traceback (most recent call last):
...
Exception: n_iter <=0
>>> trws('height','width',3,np.array([0,1]),'Q','g','P',2)
Traceback (most recent call last):
...
Exception: n_labels do not match with real number of labels
>>> trws('height','width',2,np.array([0,1]),[],'g','P',2)
Traceback (most recent call last):
...
Exception: unary or binary penalties are empty
'''
if n_iter <= 0:
raise Exception('n_iter <=0')
if len(K) != n_labels:
raise Exception('n_labels do not match with real number of labels')
if Q==[] or g ==[]:
raise Exception('unary or binary penalties are empty')
# initialise array of potentials with zeros
fi = np.zeros((height,width,n_labels))
# initialize Right and Down directions
P,_ = backward_pass(height,width,n_labels,Q,g,P,fi.copy())
for iteratation in range(n_iter):
P,fi = forward_pass(height,width,n_labels,Q,g,P,fi)
P,fi = backward_pass(height,width,n_labels,Q,g,P,fi)
# restore labelling from optimal energy after n_iter of TRW-S
labelling = np.argmax(P[:,:,0,:] + P[:,:,1,:] - fi + Q/2, axis = 2)
# mapping from labels to colors
output = K[labelling]
return output
def optimal_labelling(Q,g,K,n_iter):
'''
Parameters
Q: ndarray
updated unary penalties
g: ndarray
updated binary penalties
K: ndarray
set of labels
n_iter: int
number of iteratations
Returns
labelling: ndarray
array of optimal labelling (with color mapping)
for one channel in input image
initialize input parameters for TRW-S algorithm,
and returns best labelling
'''
height,width,_ = Q.shape
n_labels = len(K)
P = np.zeros((height,width,4,n_labels))
labelling = trws(height,width,n_labels,K,Q,g,P,n_iter)
return labelling
|
928c18324e7cfa1493ec890560c4adf3501a67f2 | jromero132/pyanimations | /animations/monte_carlo/pi.py | 5,178 | 3.546875 | 4 | from matplotlib import animation
import math
import matplotlib.pyplot as plt
import numpy as np
def is_in_circle(center: tuple, radius: float, point: tuple) -> bool:
return math.sqrt(sum((c - p) ** 2 for c, p in zip(center, point))) <= radius
class MonteCarloPiEstimation:
def __init__(self, display: "Display"):
self.display = display
@staticmethod
def expected_value():
return 3.1415
@property
def pi(self):
return 4 * self.cnt_in_points / self.cnt_all_points
def init(self):
self.cnt_in_points = 0
self.cnt_all_points = 0
def step(self):
in_points, out_points = [ [], [] ], [ [], [] ]
points = np.random.uniform(self.display.bottom_left_corner, self.display.top_right_corner, (self.display.points_per_iteration, 2))
for p in points:
if is_in_circle(self.display.center, self.display.radius, p):
in_points[ 0 ].append(p[ 0 ])
in_points[ 1 ].append(p[ 1 ])
else:
out_points[ 0 ].append(p[ 0 ])
out_points[ 1 ].append(p[ 1 ])
return in_points, out_points
def display_step(self, i: int):
in_points, out_points = self.step()
self.cnt_in_points += len(in_points[ 0 ])
self.cnt_all_points += len(in_points[ 0 ]) + len(out_points[ 0 ])
self.display.display_step(self, i, in_points, out_points)
def estimate(self):
self.init()
self.display.estimate(self.display_step)
class Display:
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: float):
self.iterations = iterations
self.points_per_iteration = points_per_iteration
self.bottom_left_corner = bottom_left_corner
self.top_right_corner = tuple(x + length for x in bottom_left_corner)
self.radius = length / 2
self.center = tuple(x + self.radius for x in self.bottom_left_corner)
class GraphicDisplay(Display):
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: float):
super(GraphicDisplay, self).__init__(iterations, points_per_iteration, bottom_left_corner, length)
def init(self):
self.fig, (self.monte_carlo_graph, self.pi_estimation_graph) = plt.subplots(1, 2)
self.fig.canvas.manager.set_window_title("Monte Carlo Pi Estimation")
self.monte_carlo_graph.set_aspect("equal")
self.monte_carlo_graph.set_xlim(self.bottom_left_corner[ 0 ], self.top_right_corner[ 0 ])
self.monte_carlo_graph.set_ylim(self.bottom_left_corner[ 1 ], self.top_right_corner[ 1 ])
self.monte_carlo_graph.set_xlabel(f"I = {self.iterations} ; N = {self.points_per_iteration}")
angle = np.linspace(0, 2 * np.pi, 180)
circle_x = self.center[ 0 ] + self.radius * np.cos(angle)
circle_y = self.center[ 1 ] + self.radius * np.sin(angle)
self.monte_carlo_graph.plot(circle_x, circle_y, color = "blue")
self.pi_estimation_graph.set_xlim(1, self.iterations)
self.pi_estimation_graph.set_ylim(0, 5)
self.pi_estimation_graph.set_title("Pi Estimation")
self.pi_estimation_graph.set_xlabel(f"Iteration")
expected_value = MonteCarloPiEstimation.expected_value()
self.pi_estimation_graph.set_ylabel(f"Pi Estimation (E = {expected_value})")
self.pi_estimation_graph.axhline(y = expected_value, color = "red", linestyle = "--")
self.fig.tight_layout()
self.estimations = [ [], [] ]
def display_step(self, obj: MonteCarloPiEstimation, i: int, in_points: list, out_points: list):
self.monte_carlo_graph.set_title(f"Iteration {i + 1} - Pi estimation: {obj.pi:.4f}")
self.monte_carlo_graph.scatter(*in_points, color = "blue", s = 1)
self.monte_carlo_graph.scatter(*out_points, color = "red", s = 1)
self.estimations[ 0 ].append(i + 1)
self.estimations[ 1 ].append(obj.pi)
self.pi_estimation_graph.plot(*self.estimations, color = "blue", linestyle = "solid", marker = '')
def estimate(self, func: "Function"):
self.init()
anim = animation.FuncAnimation(self.fig, func, frames = self.iterations, init_func = lambda: None, repeat = False)
# anim.save("demo.gif")
plt.show()
class ConsoleDisplay(Display):
def __init__(self, iterations: int, points_per_iteration: int, bottom_left_corner: tuple, length: int, *, log: bool = True):
super(ConsoleDisplay, self).__init__(iterations, points_per_iteration, bottom_left_corner, length)
self.log = log
def display_step(self, obj: MonteCarloPiEstimation, i: int, in_points: list, out_points: list):
if self.log:
print(f"Iteration {i + 1} - Pi estimation: {obj.pi:.4f}")
def estimate(self, func: "Function"):
for i in range(self.iterations):
func(i)
if __name__ == "__main__":
graph = MonteCarloPiEstimation(
display = GraphicDisplay(
iterations = 100,
points_per_iteration = 1000,
bottom_left_corner = (0, 0),
length = 1
)
)
graph.estimate()
# pi_estimation = MonteCarloPiEstimation(
# display = ConsoleDisplay(
# iterations = 1000,
# points_per_iteration = 1000,
# bottom_left_corner = (0, 0),
# length = 1,
# log = False
# )
# )
# pi_sum, trials = 0, 100
# for i in range(trials):
# pi_estimation.estimate()
# print(f"Iteration {i + 1} - Pi estimation: {pi_estimation.pi:.4f}")
# pi_sum += pi_estimation.pi
# print(f"After {trials} iterations, by the Law of Large Numbers pi estimates to: {pi_sum / trials:.4f}") |
6a13d6d6451f023372ed1583ef6d77c5ea9ca1fa | uribe-convers/Genomic_Scripts | /VCF-to-Tab_to_Fasta_IUPAC_Converter.py | 2,107 | 3.578125 | 4 | #!/usr/bin/python
def usage():
print("""
This script is intended for modifying files from vcftools that contain
biallelic information and convert them to fasta format. After the vcf file has
been exported using the vcf-to-tab program from VCFTools, and transposed in R,
or Excel, this script will change biallelic information at each site to only
one nucleotide using UIPAC conventions when the alleles are different
(heterozygous) or to the available nucleotide if both alleles are the same.
If one alle is present and the other one is missing, the script will change
the site to the available allele. All of these changes will be saved to a
new file in fasta format.
written by Simon Uribe-Convers - www.simonuribe.com
October 23rd, 2017
To use this script, type: python3.6 VCF-to-Tab_to_Fasta_IUPAC_Converter.py VCF-to-Tab_file Output_file
""")
import sys
import __future__
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
print("~~~~Error~~~~\n\nCorrect usage: python3.6 "+sys.argv[0]+" VCF-to-Tab file + Output file")
sys.exit("Missing either the VCF-to-Tab and/or the output files!")
filename = open(sys.argv[1], "r")
outfile = open(sys.argv[2] + ".fasta", "w")
# def IUPAC_converter(filename, outfile):
IUPAC_Codes = { "G/G" : "G", "C/C" : "C", "T/T" : "T", "A/A" : "A",
"-/G" : "G", "-/C" : "C", "-/T" : "T", "-/A" : "A", "G/-" : "G",
"C/-" : "C", "T/-" : "T", "A/-" : "A", "G/T" : "K", "T/G" : "K",
"A/C" : "M", "C/A" : "M", "C/G" : "S", "G/C" : "S", "A/G" : "R",
"G/A" : "R", "A/T" : "W", "T/A" : "W", "C/T" : "Y", "T/C" : "Y",
"./." : "N", "-/-" : "N", "N/N" : "N", "-/N" : "N", "N/-" : "N",
"N/." : "N", "./N" : "N"
}
for line in filename:
species_name = line.strip().split(" ")[0]
data = line.strip().split(" ")[1:]
new_data = [IUPAC_Codes[i] for i in data]
# print(new_data)
new_data2 = "".join(new_data)
outfile.write(">" + species_name + "\n" + new_data2 + "\n")
print("\n\n~~~~\n\nResults can be found in %s.fasta\n\n~~~~" %sys.argv[2])
sys.exit(0)
|
af559157ebe1d11b16c38556ed60da92a9694098 | bryanluu/AdventOfCode2020 | /Day11/Day11.py | 4,326 | 3.71875 | 4 | #!/bin/python3
import sys
import numpy as np
filename = sys.argv[1] if len(sys.argv) > 1 else "input"
part = (int(sys.argv[2]) if len(sys.argv) > 2 else None)
while part is None:
print("Part 1 or 2?")
reply = input("Choose: ")
part = (int(reply) if reply == "1" or reply == "2" else None)
# characters in problem statement
FLOOR = "."
EMPTY = "L"
OCCUPIED = "#"
# Show numpy grid
def show_grid(grid):
for row in grid:
print(" ".join(map(str, row)))
# Gets the adjacent surrounding seats of seat at r, c
def get_adjacent(seats, r, c):
neighbors = np.zeros(seats.shape, dtype=bool)
rows, cols = seats.shape
adjacent = np.array([(r+i, c+j) for i in range(-1, 2) for j in range(-1, 2)
if 0 <= r+i < rows and 0 <= c+j < cols and not (i == 0 and j == 0)])
for nr, nc in adjacent:
neighbors[nr, nc] = True
return adjacent, neighbors
# Gets visible seats from seat at r, c
def get_visible_chairs(seats, r, c):
neighbors = np.zeros(seats.shape, dtype=bool)
rows, cols = seats.shape
valid = lambda row, col: (0 <= row < rows and 0 <= col < cols and not (row == r and col == c)
and seats[row, col] != FLOOR)
first = lambda x: np.array(x[0], dtype=int) if len(x) > 0 else np.array([-1, -1], dtype=int)
W = np.array([(r, c-i) for i in range(cols) if valid(r, c-i)], dtype=int)
E = np.array([(r, c+i) for i in range(cols) if valid(r, c+i)], dtype=int)
N = np.array([(r-i, c) for i in range(cols) if valid(r-i, c)], dtype=int)
S = np.array([(r+i, c) for i in range(cols) if valid(r+i, c)], dtype=int)
NW = np.array([(r-i, c-i) for i in range(cols) if valid(r-i, c-i)], dtype=int)
NE = np.array([(r-i, c+i) for i in range(cols) if valid(r-i, c+i)], dtype=int)
SW = np.array([(r+i, c-i) for i in range(cols) if valid(r+i, c-i)], dtype=int)
SE = np.array([(r+i, c+i) for i in range(cols) if valid(r+i, c+i)], dtype=int)
visible = np.stack((first(W), first(E), first(N), first(S),
first(NW), first(NE), first(SE), first(SW)))
ok = np.all(visible >= 0, axis=1)
for nr, nc in visible[ok]:
neighbors[nr, nc] = True
return visible[ok], neighbors
def initialize_neighbors(seats, positions):
neighbors = {}
for r, c in positions[seats != FLOOR]:
neighbors[r, c] = (get_adjacent(seats, r, c) if part == 1 else get_visible_chairs(seats, r, c))
return neighbors
# Simulate one round of seating
def simulate_round(seats, positions, neighbors):
limit = (4 if part == 1 else 5)
simulation = seats.copy()
flipped = np.where(seats == EMPTY, np.full(seats.shape, OCCUPIED),
np.where(seats == OCCUPIED, np.full(seats.shape, EMPTY), np.full(seats.shape, FLOOR)))
changed = np.zeros(seats.shape, dtype=bool)
occupied = np.zeros(seats.shape, dtype=int)
if np.all(seats != OCCUPIED): # if no seats are occupied
chairs = (seats == EMPTY)
simulation[chairs] = OCCUPIED
changed[chairs] = True
else: # else check each position that might change
for r, c in positions[seats != FLOOR]:
_, isneighbor = neighbors[r, c]
occupied[r, c] = np.sum((seats[isneighbor] == OCCUPIED))
changed = (((seats == EMPTY) & (occupied == 0)) | ((seats == OCCUPIED) & (occupied >= limit)))
simulation = np.where(changed, flipped, seats)
return changed, simulation
def solve(filename):
seats = []
with open(filename) as file:
for line in file:
line = line.rstrip()
seats.append([c for c in line])
seats = np.array(seats)
rows, cols = seats.shape
positions = np.array([[(r, c) for c in range(cols)] for r in range(rows)])
round = 0
print("---Initial Layout---")
show_grid(seats)
print("Building neighbor list...")
neighbors = initialize_neighbors(seats, positions)
print("===Simulation Begin===")
while True:
changed, simulation = simulate_round(seats, positions, neighbors) # simulate round
if np.any(changed): # if any seat changed, continue, otherwise, finish
round += 1
print(f"---Round {round}---")
seats = simulation
show_grid(seats)
else:
break
print(f"===Simulation Ended after {round} rounds===")
print(f"Part {part} # occupied: {np.sum(seats == OCCUPIED)}")
if __name__ == '__main__':
print(f"Input file: {filename}")
import time
start = time.time()
solve(filename)
end = time.time()
print(f"Solve time: {end-start} seconds") |
bf9c44aa4e028f2c736743cdc88956637a73a7c7 | GuoZhouBoo/python_study | /basics/container.py | 1,605 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : container.py
# Author: gsm
# Date : 2020/5/6
def test_list():
list1 = [1, 2, 3, 4, '5']
print list1
print list1[0] # 输出第0个元素
print list1[0:3] # 输出第1-3个元素
print list1[0:] # 输出从0到最后的元素
print list1[0:-1] # 输出从0到最后第二元素
list1.append(6) # 更新列表
print list1
del list1[1] # 删除指定位置的元素
print list1
list1.reverse() # 逆置列表
print list1
print '-----------------'
def test_tuple():
# 元组无法被二次赋值,相当于一个只读列表
tuple1 = ('runoob', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print tuple1 # 输出完整元组
print tuple1[0] # 输出元组的第一个元素
print tuple1[1:3] # 输出第二个至第四个(不包含)的元素
print tuple1[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple1 + tinytuple # 打印组合的元组
print '-----------------'
def test_dict():
dict1 = {}
dict1['one'] = "This is one"
dict1[2] = "This is two"
tinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print dict1['one'] # 输出键为'one' 的值
print dict1[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
print '-----------------'
if __name__ == '__main__':
test_list()
test_tuple()
test_dict()
|
283ce2bf5201efde8d0b6998758be87d8b06db3d | shamoons/Reinforcement_Learning_Textbook_Exercises | /Chapter_5/Exercise_12/env.py | 4,713 | 3.546875 | 4 | '''
This will build the enviroment of the racetrack
'''
import numpy as np
import random
class RaceTrack():
def __init__(self):
super(RaceTrack, self).__init__()
print("Environment Hyperparameters")
print("===============================================================================")
# Initalize possible starting states
self.starting_states = [[] for i in range(6)]
for i in range(6):
self.starting_states[i] = [31, i+3]
print("Starting States: \n",self.starting_states)
# Initalize terminal states
self.terminal_states = [[] for i in range(6*4)]
for i in range(6):
for j in range(4):
self.terminal_states[(i*4) + j] = [i, 16 + j]
print("Terminal States: \n",self.terminal_states)
# Generate a set representing a square grid 32x17
self.states = [[] for i in range((32*17))]
for i in range(17):
for j in range(32):
self.states[(i*32) + j] = [j,i]
#print("States: \n",self.states)
# Make sets of locations not in possible states
bound1 = [[] for i in range(4)]
for i in range(4):
bound1[i] = [i,0]
bound2 = [[] for i in range(18)]
for i in range(18):
bound2[i] = [i + 14,0]
bound3 = [[] for i in range(3)]
for i in range(3):
bound3[i] = [i,1]
bound4 = [[] for i in range(10)]
for i in range(10):
bound4[i] = [i + 22,1]
bound5 = [[0,2]]
bound6 = [[] for i in range(3)]
for i in range(3):
bound6[i] = [i + 29,2]
bound7 = [[] for i in range(25)]
for i in range(25):
bound7[i] = [i + 7,9]
bound8 = [[] for i in range(182)]
for i in range(26):#rows
for j in range(7):#cols
bound8[(i*7) + j] = [i + 6, j +10]
bounds = bound1 + bound2 + bound3 + bound4 + bound5 + bound6 + bound7 + bound8
#print("Bounds: \n", bounds)
# Remove states in the square grid that are out of bounds
for state in bounds: self.states.remove(state)
print("===============================================================================\n")
def step(self, state, action, velocity):
'''
Given the current state, chosen action and current velocity
this function will compute the next state, velocity and whether
the episode reached its terminal state
'''
print("Step Results")
print("==========================")
print("Inital State: ", state)
print("Intial Velocity: ", velocity)
print("Action ", action)
print("--------------------------")
# Compute new velocity given action
intial_velocity = velocity
velocity = list(np.asarray(velocity) + np.asarray(action))
# Ensure velocity is within bounds
self.fix_velocity(velocity, intial_velocity, state)
# The way the gridworld is set up a negative velocity is needed to move forward
# so this just flips the sign of the vertical velocity for calculating next state
mirror_effect = [-1*velocity[0], velocity[1]]
# Calculate new state
state = list(np.asarray(state) + mirror_effect)
# Determine if the new state is out of bounds
if state not in self.states:
state = random.choice(self.starting_states)
velocity = [0,0]
# Determine if episode is over
terminate = False
if state in self.terminal_states:
terminate = True
print("Final State: ", state)
print("Final Velocity: ", velocity)
print("Episode Terminated: ", terminate)
print("==========================\n")
return state, velocity, terminate
def fix_velocity(self,velocity, intial_velocity, state):
'''
This function will limit the velocity to its max and min value and
prevent the car from coming to a stop at any point
'''
if velocity[0] > 3:
velocity[0] = 3
if velocity[0] < -3:
velocity[0] = -3
if velocity[1] > 3:
velocity[1] = 3
if velocity[1] < -3:
velocity[1] = -3
if velocity == [0,0] and state not in self.starting_states:
velocity = intial_velocity
if velocity == [0,0] and state in self.starting_states:
velocity = [1,0]
return velocity
|
86643d87a3010f92442c579b7a6fd3f7154af55f | scottfoltz/pythonpractice | /password-gen.py | 1,419 | 4.03125 | 4 | import random
print ('**********************************************')
print ('Welcome to the Welcome to the Password Generator!')
print ('**********************************************')
#define an array that will hold all of the words
lineArray = []
passwordArray = []
#prompt user
filename = input('Enter the name of the file to analyze: ')
#read in the file one line at a time without newlines
with open(filename) as my_file:
lineArray = my_file.read().splitlines()
print(*lineArray)
#we loop based on the value of numPasswords
for i in range(numPasswords):
#get first word
word1 = random.choice(wordArray)
#get second word and capitalize it
word2 = random.choice(wordArray).upper()
#get second word
word3 = random.choice(wordArray)
#get the random number within respected range
num = random.randint(1000,9999)
#find and replace I, S, O in word2
word2 = word2.replace('I','1')
word2 = word2.replace('S','$')
word2 = word2.replace('O','0')
#concantenate the final string and make sure to change num to a string
finalPassword = word1 + word2 + word3 + str(num)
#add that password to our passwordArray
passwordArray.append(finalPassword)
#Here is where we print our results
print('Here are the passwords:')
#using a for loop iterating through our passwords
for i in passwordArray:
#print each password in the list
print(i)
|
3b597cae9208d703e6479525625da55ddc18b976 | DahlitzFlorian/python-zero-calculator | /tests/test_tokenize.py | 1,196 | 4.1875 | 4 | from calculator.helper import tokenize
def test_tokenize_simple():
"""
Tokenize a very simple function and tests if it's done correctly.
"""
func = "2 * x - 2"
solution = ["2", "*", "x", "-", "2"]
assert tokenize.tokenize(func) == solution
def test_tokenize_complex():
"""
Tokenize a more complex function with different whitespaces and
operators. It also includes functions like sin() and con().
"""
func = "x*x- 3 /sin( x +3* x) + cos(9*x)"
solution = [
"x",
"*",
"x",
"-",
"3",
"/",
"sin",
"(",
"x",
"+",
"3",
"*",
"x",
")",
"+",
"cos",
"(",
"9",
"*",
"x",
")",
]
assert tokenize.tokenize(func) == solution
def test_tokenize_exponential_operator():
"""
Test if tokenizing a function including the exponential operator **
works as expected and that it does not add two times the multiplication
operator to the final list.
"""
func = "2 ** 3 * 18"
solution = ["2", "**", "3", "*", "18"]
assert tokenize.tokenize(func) == solution
|
56f1c9051a35ef64d3eb05510e2025089fb30315 | potsawee/py-tools-ged | /gedformatconvert.py | 1,861 | 3.671875 | 4 | import sys
def one_word_to_one_sentence(input, output):
with open(input, 'r') as f1:
with open(output, 'w') as f2:
newline = []
for line in f1:
if line == '\n':
if len(newline) > 0:
f2.write(' '.join(newline) + '\n')
newline = []
else:
word = line.strip().split()[0]
# ----------- Filter ----------- #
# for swb work - 8 Feb 2019
# disf = line.strip().split()[1]
# if disf != 'O':
# continue
# ------------------------------ #
newline.append(word)
print('convert one_word_to_one_sentence done!')
def one_sentence_to_one_word(input, output):
with open(input, 'r') as f1:
with open(output, 'w') as f2:
newline = []
for line in f1:
# if line == '\n':
# if len(newline) > 0:
# f2.write(' '.join(newline) + '\n')
# newline = []
# else:
# word = line.strip().split()[0]
# newline.append(word)
words = line.split()
for word in words:
f2.write(word + '\n')
f2.write('\n')
print('convert one_sentence_to_one_word done!')
def main():
if len(sys.argv) != 4:
print("Usage: python3 gedformatconvert.py [1/2] input output")
return
convert_type = sys.argv[1]
input = sys.argv[2]
output = sys.argv[3]
if convert_type == '1':
one_word_to_one_sentence(input, output)
elif convert_type == '2':
one_sentence_to_one_word(input, output)
if __name__ == '__main__':
main()
|
bf3e0d3733919a06c12fdbb8fede6596bd237db3 | potsawee/py-tools-ged | /assertdata.py | 1,286 | 3.59375 | 4 | #!/usr/bin/python3
'''
Count how many lines in the target files have zero, one, two, ... field
Args:
path: path to the target file
Output:
print the output to the terminal e.g.
linux> python3 assertdata.py clctraining-v3/dtal-exp-GEM4-1/output/4-REMOVE-DM-RE-FS.tsv
zero: 3649
one: 0
two: 0
three: 0
four: 0
five+: 69248
'''
import sys
def main():
# path = '/home/alta/BLTSpeaking/ged-pm574/artificial-error/lib/tsv/ami1.train.ged.tsv'
if len(sys.argv) != 2:
print('Usage: python3 assertdata.py path')
return
path = sys.argv[1]
zero = 0
one = 0
two = 0
three = 0
four = 0
fivemore = 0
with open(path) as file:
for line in file:
n = len(line.split())
if n == 0:
zero += 1
elif n == 1:
one += 1
elif n == 2:
two += 1
elif n == 3:
three += 1
elif n == 4:
four += 1
else:
fivemore += 1
print("zero: ", zero)
print("one: ", one)
print("two: ", two)
print("three: ", three)
print("four: ", four)
print("five+: ", fivemore)
if __name__ == "__main__":
main()
|
3d3306cf4afef96d48911f7bda81ff98f595be84 | jvcampbell/py-bits-n-bobs | /Udemy-Python-Bootcamp/Capstone Project/Caesar Cipher/Caesar Cipher.py | 2,877 | 4.03125 | 4 | # Encode/Decode text to caesar cipher. Includes a brute force method when the key is not known
import os
class CaesarCipherSimple(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
def __init__(self):
pass
def encode(self,input_text,cipher_key = 1):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
return self.__shift_letter(input_text,cipher_key)
except:
print('Error encoding')
def decode(self,input_text,cipher_key = 1):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
return self.__shift_letter(input_text,cipher_key*-1)
except:
print('Error decoding')
def brute_decode(self,input_text):
'''Encodes text by receiving an integer and shifting the letter position that number of letters to the right '''
try:
decode_list = []
for cipher_key in range(1,27):
decode_list.append(str(cipher_key) + ': ' + self.__shift_letter(input_text,cipher_key*-1))
return decode_list
except:
print('Error decoding')
def __shift_letter(self,input_text,shift_nb):
new_text = ''
for text_letter in input_text:
letter_position = CaesarCipherSimple.alphabet.find(text_letter)
letter_position += shift_nb
# Handle letters that shift off the 0-26 position spectrum of the alphabet
if shift_nb > 0:
if letter_position > 27:
letter_position -= 27
else:
pass
else:
if letter_position < 0:
letter_position += 27
new_text += self.alphabet[letter_position]
return new_text
#-----------------------------------------------#
os.system('cls')
print('-------------------------Caesar Cypher--------------------------')
action = input('Are you encoding a message or decoding a cypher? (e/d):').lower()
input_text = input('Enter the text you want to work on:').lower()
try:
input_key = int(input('Enter an integer cypher key (press Enter if you don''t know):'))
except:
input_key = None
if action == 'd' and (input_key == 0 or input_key is None):
print('\n!!! Time to brute force this thing !!!')
action = 'bd'
cypherMachine = CaesarCipherSimple()
print('\n----------OUTPUT----------------')
if action == 'e':
print(cypherMachine.encode(input_text,input_key))
elif action == 'd':
print(cypherMachine.decode(input_text,input_key))
elif action =='bd':
for attempt in cypherMachine.brute_decode(input_text):
print(attempt)
|
4b7dbbf640d118514fa306ca39a5ee336852aa05 | francoischalifour/ju-python-labs | /lab9/exercises.py | 1,777 | 4.25 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 9 - Functional Programming
# François Chalifour
from functools import reduce
def product_between(a=0, b=0):
"""Returns the product of the integers between these two numbers"""
return reduce(lambda a, b: a * b, range(a, b + 1), 1)
def sum_of_numbers(numbers):
"""Returns the sum of all the numbers in the list"""
return reduce(lambda a, b: a + b, numbers, 0)
def is_in_list(x, numbers):
"""Returns True if the list contains the number, otherwise False"""
return any(filter(lambda n: n == x, numbers))
def count(numbers, x):
"""Returns the number of time the number occurs in the list"""
return len(filter(lambda n: n == x, numbers))
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 9
======================
''')
print('1. Multiplying values')
test(product_between(0, 1), 0)
test(product_between(1, 3), 6)
test(product_between(10, 10), 10)
test(product_between(5, 7), 210)
print('\n2. Summarizing numbers in lists')
test(sum_of_numbers([]), 0)
test(sum_of_numbers([1, 1, 1]), 3)
test(sum_of_numbers([3, 1, 2]), 6)
print('\n3. Searching for a value in a list')
test(is_in_list(1, []), False)
test(is_in_list(3, [1, 2, 3, 4, 5]), True)
test(is_in_list(7, [1, 2, 1, 2]), False)
print('\n4. Counting elements in lists')
test(count([], 4), 0)
test(count([1, 2, 3, 4, 5], 3), 1)
test(count([1, 1, 1], 1), 3)
if __name__ == '__main__':
main()
|
8a8d59fe9276270dada61e63ac8037f0dc580a2c | francoischalifour/ju-python-labs | /lab4/five-in-a-row/five_in_a_row.py | 5,086 | 4.21875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Five in a row
# François Chalifour
def print_game(game):
"""
Prints the game to the console.
"""
print(' y')
y = game['height'] - 1
while 0 <= y:
print('{}|'.format(y), end='')
for x in range(game['width']):
print(get_cell_value(game, x, y), end='')
print()
y -= 1
print('-+', end='')
for x in range(game['width']):
print('-', end='')
print('x')
print(' |', end='')
for x in range(game['width']):
print(x, end='')
print(' ')
def get_cell_value(game, x, y):
"""
Returns 'X' if a cross has been placed in the cell with the given
coordinates.
Returns 'O' if a circle has been placed in the cell with the given
coordinates.
Returns ' ' otherwise.
"""
moves = game.get('moves')
for move in moves:
if move.get('x') == x and move.get('y') == y:
return move.get('player')
return ' '
def make_move(game, x, y, player):
"""
Adds a new move to the game with the information in the parameters.
"""
new_move = {'x': x, 'y': y, 'player': player}
game.get('moves').append(new_move)
def does_cell_exist(game, x, y):
"""
Returns True if the game contains a cell with the given coordinates.
Returns False otherwise.
"""
return 0 <= x and x < game.get('width') and 0 <= y and y < game.get('height')
def is_cell_free(game, x, y):
"""
Returns True if the cell at the given coordinates doesn't contain a cross
or a circle.
Returns False otherwise.
"""
moves = game.get('moves')
for move in moves:
if move.get('x') == x and move.get('y') == y:
return False
return True
def get_next_players_turn(game):
"""
Returns 'X' if a cross should be placed on the board next.
Returns 'O' if a circle should be placed on the board next.
"""
if len(game.get('moves')) == 0: return 'X'
last_player = game.get('moves')[-1].get('player')
return 'X' if last_player == 'O' else 'O'
def has_won_horizontal(game):
"""
Returns 'X' if 5 crosses in a row is found in the game.
Returns 'O' if 5 circles in a row is found in the game.
Returns None otherwise.
"""
for y in range(game.get('height')):
for x in range(game.get('width') - 4):
player = get_cell_value(game, x, y)
if player != ' ':
is_same_player = True
for dx in range(1, 5):
if get_cell_value(game, x + dx, y) != player:
is_same_player = False
break
if is_same_player:
return player
return None
def has_won_vertical(game):
"""
Returns 'X' if 5 crosses in a row is found in a col of the game.
Returns 'O' if 5 circles in a row is found in a col of the game.
Returns None otherwise.
"""
for x in range(game.get('height')):
for y in range(game.get('width') - 4):
player = get_cell_value(game, x, y)
if player != ' ':
is_same_player = True
for dy in range(1, 5):
if get_cell_value(game, x, y + dy) != player:
is_same_player = False
break
if is_same_player:
return player
return None
def has_won_diagonal(game):
"""
Returns 'X' if 5 crosses in a row is found in a diagonal of the game.
Returns 'O' if 5 circles in a row is found in a diagonal of the game.
Returns None otherwise.
"""
def get_diagonal(m, x, y, d):
return [ m[(x + i - 1) % len(m)][(y + d * i - 1) % len(m[0])] for i in range(len(m)) ]
moves = game.get('moves')
board = [ [' ' for x in range(game.get('width'))] for x in range(game.get('height')) ]
# Fill the game board
for move in moves:
board[move.get('x')][move.get('y')] = move.get('player')
# Fill the diagonal board
diagonals = [ get_diagonal(board, i, 1, 1) for i in range(1, game.get('width') + 1) ]
diagonals_inversed = [ get_diagonal(board, 1, i, -1) for i in range(1, game.get('width') + 1) ]
for diagonal in diagonals:
last_player = None
count = 1
for player in diagonal:
if player != ' ' and player == last_player: count += 1
last_player = player
if count >= 5: return player
for diagonal in diagonals_inversed:
last_player = None
count = 1
for player in diagonal:
if player != ' ' and player == last_player: count += 1
last_player = player
if count >= 5: return player
return None
def get_winner(game):
"""
Returns 'X' if the X player wins.
Returns 'O' if the O player wins.
Returns None otherwise.
"""
winner = has_won_horizontal(game)
if not winner:
winner = has_won_vertical(game)
if not winner:
winner = has_won_diagonal(game)
return winner
|
ba5bce618d68b7570c397bc50d6f96766b600fd9 | francoischalifour/ju-python-labs | /lab4/exercises.py | 1,024 | 4.1875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Dictionaries
# François Chalifour
def sums(numbers):
"""Returns a dictionary where the key "odd" contains the sum of all the odd
integers in the list, the key "even" contains the sum of all the even
integers, and the key "all" contains the sum of all integers"""
sums = {'odd': 0, 'even': 0, 'all': 0}
for x in numbers:
if x % 2 == 0:
sums['even'] += x
else:
sums['odd'] += x
sums['all'] += x
return sums
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 4
======================
''')
print('1. Computing sums')
test(sums([1, 2, 3, 4, 5]), {"odd": 9, "even": 6, "all": 15})
if __name__ == '__main__':
main()
|
86c803756a5548226d81b32cbfc0e66b04e4b240 | nano13/tambi | /interpreter/structs.py | 950 | 3.5 | 4 | # -*- coding: utf_8 -*-
class Result:
# category is one of:
# - table
# - list
# - text
# - string
# - error
# (as a string)
category = None
payload = None
metaload = None
# header is a list or None
header = None
header_left = None
# name is a string or None
name = None
error = None
cursorPosition = None
def toString(self):
result = ""
if type(self.payload) == list:
for line in self.payload:
for column in line:
result += str(column)
if type(line) == tuple or type(line) == list:
result += " | "
if type(line) == tuple or type(line) == list:
result = result[:-3]
result += "\n"
result = result.strip()
else:
result = self.payload
return result
|
a81ce65a4df9304e652af161f5a00534b35cc844 | Abuubkar/python | /code_samples/p4_if_with_in.py | 1,501 | 4.25 | 4 | # IF STATEMENT
# Python does not require an else block at the end of an if-elif chain.
# Unlike C++ or Java
cars = ['audi', 'bmw', 'subaru', 'toyota']
if not cars:
print('Empty Car List')
if cars == []:
print('Empty Car List')
for car in cars:
if car == 'bmw':
print(car.upper())
elif cars == []: # this condition wont run as if empty FOR LOOP won't run
print('No car present')
else:
print(car.title())
age_0 = 10
age_1 = 12
if(age_0 > 1 and age_0 < age_1):
print("\nYoung")
if(age_1 > age_0 or age_1 >= 11):
print("Elder")
# Check presence in list
car = 'bmw'
print("\nAudi is presend in cars:- " + str('audi' in cars))
print(car.title()+" is presend in cars:- " + str(car in cars)+"\n")
# Another way
car = 'Suzuki'
if car in cars:
print(car+' is present')
if car not in cars:
print(car+' is not present\n')
# it does not check presence in 'for loop' as output of cars is
# overwritten by for loop
# for car in cars :
# print (car)
# Checking Multiple List
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
|
42a371f596cef5ecf7185254ca45b00fa737ecb4 | Abuubkar/python | /leet_code/week_1/counting_elements/counting_elements.py | 1,744 | 3.953125 | 4 | """
Authors
---------
Primary: Abubakar Khawaja
Description:
----------
Given an integer array arr, count element x such that
x + 1 is also in arr.
If there're duplicates in arr, counts them also.
"""
# Imports
from collections import defaultdict
class Solution:
arr = []
def set_arr(self, arr: [int]):
self.arr = arr.copy()
return len(self.arr)
def countElements(self):
"""
This function takes array of integers and sorts them in descending order.
And initializes dictionary based on element of array to zero if encountered first time,
and then checks if parent key exists in dictionary if so increments by one,
in the dictionary having key as its element
and prints sum of values in dictionary.
"""
# Step 1: Defining dictionary with default value type of int
dic = defaultdict(int)
# Step 2: Traversing list in sorted(Descending) manner
for element in sorted(self.arr, reverse=True):
# Step 3: Initializing dictionary with element of array as key
# When encountered First time
if element not in dic:
dic[element] = 0
# Step 4: Checking if element+1 key is present in dictionary
# If so then adding 1 to element 1 dictionary
if element+1 in dic:
dic[element] += 1
# Step 5: adding all the values in dictionary to get total count of
# values present
# print (sum(dic.values()))
return (sum(dic.values()))
# Providing call to count element with array of integer as parameter
#solution = Solution()
#solution.set_arr([1, 3, 2, 3, 5, 0])
# solution.countElements()
|
b117d36f9a8ce6959fcbea91ffb1878efea633b1 | Abuubkar/python | /leet_code/week_1/anagram/anagram.py | 1,357 | 4.03125 | 4 | """
Authors
----------
Primary: Abubakar Khawaja
Short Description:
----------
This file contains function that will group anagrams together from given array of strings.
"""
from collections import defaultdict
def groupAnagrams(strs: [str]):
"""
This function take array of string and adding new words by using key
made by their individual character in sorted order in form of tuple
"""
# it will contain Tuple as key and List of String as value
sets = defaultdict(list)
# Traversing each Word in String list given
for word in strs:
# Making Tuple to use as key and to use it for ease of saving its other anagrams
# Saving it in dictionary in list where key is characters of word
sets[tuple(sorted(word))].append(word)
# could also use sets[''.join(sorted(word))].append(word) its better
# ''.join(list) != str(list)
# Extract List of anagrams from dictionary
print(sets.values())
return (sets.values())
groupAnagrams(["hos", "boo", "nay", "deb", "wow", "bop", "bob", "brr", "hey", "rye", "eve", "elf", "pup", "bum", "iva", "lyx", "yap", "ugh", "hem", "rod", "aha", "nam", "gap",
"yea", "doc", "pen", "job", "dis", "max", "oho", "jed", "lye", "ram", "pup", "qua", "ugh", "mir", "nap", "deb", "hog", "let", "gym", "bye", "lon", "aft", "eel", "sol", "jab"])
|
bf49e0e95c9efd7a9b08d2421709159ef6e6bbae | lujun94/Name_Your_Own_Price_Simulation | /nyop.py | 4,684 | 3.59375 | 4 | import random
class NYOP:
def __init__(self):
self.profit = 0
#WeightedPick() is cited from
#http://stackoverflow.com/questions/2570690/python-algorithm-to-randomly-select-a-key-based-on-proportionality-weight
def weightedPick(self, d):
r = random.uniform(0, sum(d.itervalues()))
s = 0.0
for k, w in d.iteritems():
s += w
if r < s: return k
return k
def compute(self, consumerList, propertyDict):
for consumer in consumerList:
bidList = consumer.get_sortedBidList()
findADeal = False
for utility, star in bidList:
#print(consumer.id, star)
visited = []
#get all the qualified properties
qualifiedProperty = propertyDict[star]
if len(qualifiedProperty) == 0:
continue
while True:
firstRoundPro = random.choice(qualifiedProperty)
if firstRoundPro.availability > 0:
break
else:
visited.append(firstRoundPro)
if len(visited) == len(qualifiedProperty):
break
if len(visited) == len(qualifiedProperty):
continue
firstRoundProPrice = firstRoundPro.get_priceList()
#if there is a property price below consumer bid price
#pick the highest price below consumer bid price
if min(firstRoundProPrice) < consumer.bidDict[star]:
findPrice = False
for price in firstRoundProPrice:
if price < consumer.bidDict[star]:
findPrice = price
break
#transation occurs
firstRoundPro.transcation_occur(findPrice)
consumer.transcation_occur(star, consumer.bidDict[star])
self.profit += consumer.bidDict[star] - findPrice
findADeal = True
#break the for utility, star in bidList when find a deal
break
else:
firstRoundPro.firstRound_denial()
#remove the first round property from the list
visited.append(firstRoundPro)
#keep doing second Round if matches not found
while len(visited) < len(qualifiedProperty):
#Randomly select one based on their past success rate
dictWithWeight = {}
for p in qualifiedProperty:
if p not in visited:
if p.availability > 0:
dictWithWeight[p] = p.get_successRate()*100
else:
visited.append(p)
if dictWithWeight == {}:
continue
pickedPro = self.weightedPick(dictWithWeight)
pickedProPrice = pickedPro.get_priceList()
#if there is a property price below consumer bid price
#pick the highest price below consumer bid price
if min(pickedProPrice) < consumer.bidDict[star]:
findPrice = False
for price in pickedProPrice:
if price < consumer.bidDict[star]:
findPrice = price
break
#transation occurs
pickedPro.transcation_occur(findPrice)
consumer.transcation_occur(star,
consumer.bidDict[star])
self.profit += consumer.bidDict[star] - findPrice
findADeal = True
break
else:
visited.append(pickedPro)
#break the for utility, star in bidList when find a deal
if findADeal == True:
break
|
e20320e6e6486193eac99150b8501fed599cdf3e | IHautaI/game-of-sticks | /hard_mode.py | 788 | 3.53125 | 4 | from sticks import Computer
import random
proto = {}
end = [0 for _ in range(101)]
for i in range(101):
proto[i] = [1, 2, 3]
class HardComputer(Computer):
def __init__(self, name='Megatron'):
super().__init__(name)
self.start_hats = proto
self.end_hats = end
def reset(self):
for i in range(101):
self.end_hats[i] = 0
def turn(self, sticks):
num = random.choice(self.start_hats[sticks])
while not 1 <= num <= 3 or not sticks - num >= 0:
num = random.choice(self.start_hats[sticks])
self.end_hats[sticks] = num
return num
def finish(self):
for indx, val in enumerate(self.end_hats):
if val is not 0:
self.start_hats[indx].append(val)
|
e5bcd3a8455d4e189132665021f26e221155addd | maiduydung/Algorithm | /M_valid_sudoku.py | 833 | 3.84375 | 4 | # https://leetcode.com/problems/valid-sudoku/
# Each row must contain the digits 1-9 without repetition.
# Each column must contain the digits 1-9 without repetition.
# Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
check = set()
for i in range(9):
for j in range(9):
current = board[i][j]
if current != ".":
if (i,current) in check or (current,j) in check or (i/3,j/3,current) in check:
return False
check.add((i,current))
check.add((current,j))
check.add((i/3,j/3,current))
print(check)
return True |
f0c35498afbb6364b93c260ddea75e15ce4b8264 | maiduydung/Algorithm | /Array - String/isPalindrome.py | 394 | 3.9375 | 4 | import string
#two pointer approach
def isPalindrome(s):
s = s.lower()
s = s.replace(" ", "")
s = s.translate(str.maketrans('', '', string.punctuation))
end = len(s)-1
for start in range(len(s)//2):
if(s[start] != s[end]):
return False
end = end - 1
print(start, end)
return True
print (isPalindrome('A man, a plan, a canal: Panama')) |
e37c122f96ffabe7349ca690a11bac98a7898b7e | maiduydung/Algorithm | /Array - String/Tribonacci.py | 391 | 3.765625 | 4 | #https://leetcode.com/problems/n-th-tribonacci-number/
#using dynamic programming
class Solution:
def tribonacci(self, n: int) -> int:
if(n==0): return 0
elif(n==1) or (n==2): return 1
arr = [0]*(n+1)
arr[0] = 0
arr[1] = 1
arr[2] = 1
for i in range(3, n+1):
arr[i] = arr[i-3] + arr[i-2] + arr[i-1]
return arr[n] |
0e3213a15f8f4f2a7f9d1d03fa9e9d0f1d886c1a | maiduydung/Algorithm | /Network Flow/find_augmentpath.py | 743 | 3.5 | 4 | #Maximum flow problem
#if there is augment path, flow can be increased
import networkx as nx
import queue
N = nx.read_weighted_edgelist('ff.edgelist', nodetype = int)
def find_augmentpath(G, s, t): #graph, source, sink
P = [s] * nx.number_of_nodes(G)
visited = set()
stack = queue.LifoQueue()
stack.put(s)
while(not stack.empty()):
v = stack.get() #pop stack
if v == t:
return (P, True)
if not v in visited:
stack.put(v)
for w in G.neighbors(v):
if (not w in visited) and (G.edges[v,w]['weight'] > 0):
stack.put(w)
P[w] = v # previous node of w is v
return (P, False)
print(find_augmentpath(N, 0, 5)) |
098bc9cec885d3f67a8e6d972af59bf4bd1f4dc9 | thiekAR/Prog_VR | /directo_01/assigment_python_02.py | 878 | 3.859375 | 4 | # ex. 8.7
def make_album(artist_name, title_name, tracks = 0):
if tracks != 0:
return {'artist': artist_name, 'title': title_name, 'tracks': tracks}
return {'artist': artist_name, 'title': title_name}
print(make_album('Bob', 'album1', 9))
print(make_album('Jack', 'album2', 1))
print(make_album('John', 'album3', 4))
print(make_album('Peter', 'album4', 14))
# ex. 8.8
def make_album(artist_name, title_name, tracks = 0):
if tracks != 0:
return {'artist': artist_name, 'title': title_name, 'tracks': tracks}
return {'artist': artist_name, 'title': title_name}
while True:
print('Enter "q" any time to quit')
artist_name = input('Enter the of the artiste: ')
if artist_name == 'q':
break
album = input('Enter the of the album: ')
if album == 'q':
break
print(make_album(artist_name, album)) |
36762d67cf6ce86b5f091e3c6e261fb37f704224 | thiekAR/Prog_VR | /directo_01/C_08/Function2.py | 250 | 3.84375 | 4 | import this
print(this)
def print_separator(width):
for w in range(width):
print("*", end="")
def print_separator_2(width):
print("*" * width)
print("This is line 1")
print_separator(50)
print("\n")
print_separator_2(50)
|
2e68dd629dddfae3f29e44e12783594272c21131 | gacl97/Artificial-Intelligence | /Problem 1/tree.py | 6,891 | 3.59375 | 4 | from node import *
class Tree:
def createNode(self, qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev):
return Node(qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev)
def compare(self, node1, node2):
if(node1.side1[0] == node2.side1[0] and node1.side1[1] == node2.side1[1] and node1.side2[0] == node2.side2[0] and node1.side2[1] == node2.side2[1] and node1.boat[0] == node2.boat[0] and node1.boat[1] == node2.boat[1]):
return False
else:
return True
def print1(self, currentNode):
if(currentNode == None):
return
self.print1(currentNode.prev)
if (currentNode.prev == None):
print("------------------------------------")
print("Qnt Missionario: ", currentNode.side1[0], "Qnt Canibal: ", currentNode.side1[1])
print("Barco: ")
print("Qnt Missionario: ", currentNode.boat[0], "Qnt Canibal: ", currentNode.boat[1])
print("Destino: ")
print("Qnt Missionario: ", currentNode.side2[0], "Qnt Canibal: ", currentNode.side2[1])
print("------------------------------------")
return
if(not currentNode.flag):
print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", end = "\n\n")
else:
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", end = "\n\n")
if(currentNode.boat[0] == 1 and currentNode.boat[1] == 1):
print("Embarca 1 missionario e 1 canibal")
elif(currentNode.boat[0] == 0 and currentNode.boat[1] == 2):
print("Embarca 2 canibais")
elif(currentNode.boat[0] == 2 and currentNode.boat[1] == 0):
print("Embarca 2 missionarios")
elif(currentNode.boat[0] == 1 and currentNode.boat[1] == 0):
print("Embarca 1 missionario")
else:
print("Embarca 1 canibal")
print()
print("Qnt Missionario: ", currentNode.side1[0], "Qnt Canibal: ", currentNode.side1[1])
print("Barco: ")
print("Qnt Missionario: ", currentNode.boat[0], "Qnt Canibal: ", currentNode.boat[1])
print("Destino: ")
print("Qnt Missionario: ", currentNode.side2[0], "Qnt Canibal: ", currentNode.side2[1])
print()
def boarding(self, currentNode):
#Embarque do lado esquerdo
if(not currentNode.flag):
mis = currentNode.side1[0] + currentNode.boat[0]
can = currentNode.side1[1] + currentNode.boat[1]
# Mandar 1 canibal e 1 missionario
if (mis >= can and mis >= 1 and can >= 1):
newNode = self.createNode(mis - 1, can - 1, 1, 1, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
#Mandar 2 missionarios
if(mis == 2 or (mis - 2 >= can and mis >= 2)):
newNode = self.createNode(mis - 2, can, 2, 0, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if(self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
#Mandar 2 canibais
if(can >= 2):
newNode = self.createNode(mis, can - 2, 0, 2, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 missionario
if ((mis >= 1 and mis - 1 >= can) or mis == 1):
newNode = self.createNode(mis - 1, can, 1, 0, currentNode.side2[0], currentNode.side2[1],
not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 canibal
if(can >= 1):
newNode = self.createNode(mis, can - 1, 0, 1, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Embarque do lado direito
else:
mis = currentNode.side2[0] + currentNode.boat[0]
can = currentNode.side2[1] + currentNode.boat[1]
# Mandar 1 canibal e 1 missionario
if (can >= 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 0, 1, mis, can - 1,
not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 2 missionarios
if (mis == 2 or (mis - 2 >= can and mis >= 2)):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 2, 0, mis - 2, can, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 2 canibais
if (can >= 2):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 0, 2, mis, can - 2, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 missionario
if ((mis >= 1 and mis - 1 >= can) or mis == 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 1, 0, mis - 1, can, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 canibal
if (mis >= can and mis >= 1 and can >= 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 1, 1, mis - 1, can - 1, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
def generateStates(self, begin):
queue = []
queue.append(begin)
while(len(queue) != 0):
x = queue.pop(0)
#Se chegar num movimento inválido (Mais canibais que missionários)
if(x.flag == False and (x.side1[0] + x.boat[0] < x.side1[1] + x.boat[1] and x.side1[0] + x.boat[0] > 0)):
continue
elif(x.flag == True and (x.side2[0] + x.boat[0] < x.side2[1] + x.boat[1] and x.side2[0] + x.boat[0] > 0)):
continue
if(x.side2[0] + x.boat[0] == 3 and x.side2[1] + x.boat[1] == 3):
self.print1(x)
self.print1(Node(0, 0, 0, 0, 3, 3, False, None))
break
self.boarding(x)
for currentSon in x.sons:
queue.append(currentSon) |
2bfe1d887f9779dff2e87dcae17132899e851175 | gacl97/Artificial-Intelligence | /Problem 2/Graph.py | 3,565 | 3.671875 | 4 | from Node import *
from queue import PriorityQueue
class graph:
colors = [-1, [0,0],[0,1],[0,3],[0,2],[0,1],[0,0],[1,1],[1,2],[1,3],[1,1],[3,3],[2,2],[2,3],[2,2]]
def createNode(self, id1, heuristDist, dist, prevColor):
return Node(id1,heuristDist,dist,prevColor)
def createGraph(self, distances, end, fileAdjList):
graph = []
graph.append([])
# Azul = 0 Amarelo = 1 Verde = 2 Vermelho = 3
for i in range(14):
adjList = []
for j in fileAdjList.readline().split():
adjList.append(self.createNode(int(j),distances[int(j)-1][end-1],distances[i][int(j)-1],""))
graph.append(adjList)
return graph
def printGraph(self):
for i in range(15):
print(i,"-> ", end="")
for j in graph[i]:
print(j.id, " ", end="")
print()
def searchCommonColor(self, prev, current):
for i in self.colors[prev]:
for j in self.colors[current.id]:
if(i == j):
current.prevColor = i
break
def printPath(self,node):
if(node.prevNode.id == node.id):
print("----------- The best way is -----------")
print()
print("Passing by the station ",node.id, "with the cost ", node.dist)
else:
self.printPath(node.prevNode)
if (node.prevColor == 0):
color = "blue"
elif(node.prevColor == 1):
color = "yellow"
elif(node.prevColor == 2):
color = "green"
else:
color = "red"
print("Passing by the station ",node.id, "with the cost ", node.cost, "by the line ", color)
def bestPath(self, begin, end, graph, dist):
visited = [0]*15
queue = PriorityQueue()
count = 0
for i in graph[begin]:
self.searchCommonColor(begin,i)
currentDist = i.dist + i.heuristDist
visited[i.id] = 1
aux = self.createNode(begin,dist[begin-1][end-1],0,"")
aux.savePrevNode(aux)
i.savePrevNode(aux)
i.saveCost(currentDist)
queue.put([currentDist,i.id,begin,count])
count += 1
while(not queue.empty()):
currentNode = queue.get()
visited[currentNode[1]] = 1
if (currentNode[1] == end):
graph[currentNode[2]][currentNode[3]].saveCost(currentNode[0])
self.printPath(graph[currentNode[2]][currentNode[3]])
print("Final cost = ", currentNode[0])
break
count = 0
for node in graph[currentNode[1]]:
if(visited[node.id] == 0):
self.searchCommonColor(currentNode[1],node)
node.savePrevNode(graph[currentNode[2]][currentNode[3]])
if(graph[currentNode[2]][currentNode[3]].prevColor != node.prevColor):
currentDist = currentNode[0] + node.dist + node.heuristDist + 2
else:
currentDist = currentNode[0] + node.dist + node.heuristDist
node.saveCost(currentDist)
queue.put([currentDist,node.id,currentNode[1],count])
count += 1
def readDistances(distances):
dist = []
for i in range(14):
dist.append(list(map(int,distances.readline().split())))
return dist |
b64e7152f33c0f6b4b7b7b600b17d5259f65322b | asiya00/Exercism | /python/anagram/anagram.py | 325 | 3.734375 | 4 | def find_anagrams(word, candidates):
result = []
word = word.lower()
for i in candidates:
candi = i.lower()
if candi!=word and len(candi)==len(word) and word!='tapper':
if set(candi) == set(word):
result.append(i)
else:
continue
return result
|
035e394d57ef25672cced5b26f08d4694efddd07 | TheJust1ce/ML_lab1 | /lab2.py | 1,193 | 3.5625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path = 'data/ex1data2.txt'
data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
data.head()
data.describe()
data = (data - data.mean()) / data.std()
data.head()
data.insert(0, 'Ones', 1)
cols = data.shape[1]
X = data.iloc[:, 0:cols-1]
y = data.iloc[:, cols-1:cols]
X = np.matrix(X.values)
y = np.matrix(y.values)
def computeCost(X, y, theta):
inner = (X * theta - y).T * (X * theta - y)
return inner[0, 0] / (2 * len(X))
def gradientDescent(X, y, theta, alpha, iters):
cost = np.zeros(iters)
for i in range(iters):
cost[i] = computeCost(X, y, theta)
theta = theta - alpha / len(X) * X.T * (X*theta - y)
return theta, cost
alpha = 0.05
iters = 1000
theta = np.array([[0], [0], [0]])
th, c = gradientDescent(X, y, theta, alpha, iters)
th2, c2 = gradientDescent(X, y, theta, 0.01, iters)
th3, c3 = gradientDescent(X, y, theta, 0.001, iters)
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(np.arange(iters), c, 'r', label='Cost')
ax.plot(np.arange(iters), c2, 'g', label='Cost')
ax.plot(np.arange(iters), c3, 'b', label='Cost')
ax.legend(loc=1)
plt.show()
|
383c07aa7a0b5ed08ec2600f0046da8687448c90 | IvanLopezMedina/MapReduce | /shuffler.py | 766 | 3.53125 | 4 | # En aquesta classe processem la llista del map i agrupem les paraules
# Retornem llista paraula : { { paraula: 1 } , {paraula: 1 } }
class Shuffler:
def __init__(self, listMapped):
self.listMapped = listMapped
self.dictionary = {}
def shuffle(self):
# Per cada paraula, si existeis una entrada al diccionari
# La afegim a la llista de paraules d'aquesta entrada
# Sino existeix una entrada, creem una nova i afegim a la llista
for word in self.listMapped:
if self.dictionary.has_key(word[0]):
self.dictionary[word[0]].append(word)
else:
self.dictionary[word[0]] = []
self.dictionary[word[0]].append(word)
return self.dictionary |
b583554675d3ec46b424ac0e808a8281a339de67 | NandanSatheesh/Daily-Coding-Problems | /Codes/2.py | 602 | 4.21875 | 4 | # This problem was asked by Uber.
#
# Given an array of integers,
# return a new array such that each element at index i of the
# new array is the product of all the numbers in the original array
# except the one at i.
#
# For example,
# if our input was [1, 2, 3, 4, 5],
# the expected output would be [120, 60, 40, 30, 24].
# If our input was [3, 2, 1], the expected output would be [2, 3, 6].
def getList(l):
product = 1
for i in l:
product *= i
newlist = [product/i for i in l ]
print(newList)
return newList
l = [1,2,3,4,5]
getList(l)
getList([3,2,1])
|
7b805bc4acdb0409bab9c84388f8fc83f4bfbbed | nincube8/Hydroponic-Automation | /Turn on Feed Pump Feed Plant.py | 1,845 | 3.796875 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# init list with pin numbers
#pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# time to sleep between operations in the main loop
#
SleepTimeL =60
# main loop
try:
#"Pin #"
#First Value is the Plant Valve Number, Second number is the Feeding Pump
#Valve 3 Is for Feeding Food Plants and drops water into Cheezits bucket to feed.
#Will cycle through to plant valves 1-6 skipping the 3rd valve
#Valve 1
GPIO.output(7, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 1")
time.sleep(SleepTimeL);
GPIO.output(7, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 2
GPIO.output(11, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 2")
time.sleep(SleepTimeL);
GPIO.output(11, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 4
GPIO.output(15, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 4")
time.sleep(SleepTimeL);
GPIO.output(15, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 5
GPIO.output(19, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 5")
time.sleep(SleepTimeL);
GPIO.output(19, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 6
GPIO.output(21, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 6")
time.sleep(SleepTimeL);
GPIO.output(21, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
# Reset GPIO settings
GPIO.cleanup()
print ("End")
# End program cleanly with keyboard
except KeyboardInterrupt:
print ("Quit")
|
9e1d837c4a2f0998e3b1344331ff4ea407de6582 | IamWilliamWang/Leetcode-practice | /2020.8/爱奇艺-2.py | 629 | 3.59375 | 4 | def nextXY(ch: str):
if ch == 'N':
nextStep = (visited[-1][0] - 1, visited[-1][1])
elif ch == 'S':
nextStep = (visited[-1][0] + 1, visited[-1][1])
elif ch == 'E':
nextStep = (visited[-1][0], visited[-1][1] + 1)
elif ch == 'W':
nextStep = (visited[-1][0], visited[-1][1] - 1)
else:
raise ValueError
if nextStep in visited:
return None
return nextStep
path = input().strip()
visited = [(0, 0)]
for selection in path:
nextStep = nextXY(selection)
if not nextStep:
print('True')
exit(0)
visited.append(nextStep)
print('False')
|
9f531639340fbd945ed2ec054629ca12cfb30675 | IamWilliamWang/Leetcode-practice | /2020.6/SpiralOrder.py | 1,476 | 3.53125 | 4 | from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
x, y = 0, 0
restCount = len(matrix) * len(matrix[0])
clockwiseTraversal = []
while restCount and left <= right and top <= bottom:
while restCount and y <= right:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if y == right:
break
y += 1
top += 1
x += 1
while restCount and x <= bottom:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if x == bottom:
break
x += 1
right -= 1
y -= 1
while restCount and y >= left:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if y == left:
break
y -= 1
bottom -= 1
x -= 1
while restCount and x >= top:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if x == top:
break
x -= 1
left += 1
y += 1
return clockwiseTraversal
print(Solution().spiralOrder([[1, 2, 3]]))
|
6c6b2f49a7531bbb887a4013e3a31268b5b24d03 | IamWilliamWang/Leetcode-practice | /2020.5/LargestNumber.py | 1,049 | 3.515625 | 4 | from typing import List
from functools import lru_cache
class Solution:
@lru_cache(maxsize=None)
def searchPotentialResult(self, restMoney: int, choicesInt: int) -> None:
if restMoney == 0:
if choicesInt > self.maxResult:
self.maxResult = choicesInt
for i in range(len(self.cost)):
if self.cost[i] == -1:
continue
if restMoney >= self.cost[i]:
choice = int(i + 1)
self.searchPotentialResult(restMoney - self.cost[i], choicesInt * 10 + choice)
def largestNumber(self, cost: List[int], target: int) -> str:
for i in range(len(cost)):
for j in range(0, i):
if cost[j] != -1 and cost[j] == cost[i]:
cost[j] = -1
self.maxResult = -2 ** 31
self.cost = cost
self.searchPotentialResult(target, 0)
return str(self.maxResult if self.maxResult != -2 ** 31 else 0)
print(Solution().largestNumber([70, 84, 55, 63, 74, 44, 27, 76, 34], 659))
|
046ec5426d71fba6f4665d11543b2af0071c4ebf | IamWilliamWang/Leetcode-practice | /2020.4/CanJump.py | 1,301 | 3.609375 | 4 | from functools import lru_cache
class Solution:
def canJump(self, nums: list) -> bool:
if nums == []:
return False
@lru_cache(maxsize=None)
def find(index: int) -> bool:
"""
寻找该位置出发有没有可能到达终点
:param index: 当前位置
:return:
"""
if index >= len(nums):
return False
if index == len(nums) - 1:
return True
for step in range(nums[index], 0, -1):
if find(index + step):
return True
return False
# 先看看每次以最大步伐向前进,有没有跨过终点
i = 0
while nums[i] > 0: # 如果碰到0就跳出
i += nums[i]
if i >= len(nums): # 如果跨过了终点,证明可能有解
return find(0) # 求解
if i == len(nums) - 1: # 如果刚好踩在终点了,完美
return True
return False
print(Solution().canJump(
[1,2,2,6,3,6,1,8,9,4,7,6,5,6,8,2,6,1,3,6,6,6,3,2,4,9,4,5,9,8,2,2,1,6,1,6,2,2,6,1,8,6,8,3,2,8,5,8,0,1,4,8,7,9,0,3,9,4,8,0,2,2,5,5,8,6,3,1,0,2,4,9,8,4,4,2,3,2,2,5,5,9,3,2,8,5,8,9,1,6,2,5,9,9,3,9,7,6,0,7,8,7,8,8,3,5,0]))
|
5a721e63b018a73a7ed2dd8a4cdfd2f3b719af9c | IamWilliamWang/Leetcode-practice | /2020.8/贝壳-最大公约数.py | 6,728 | 3.84375 | 4 | from functools import lru_cache
from itertools import islice
from math import sqrt
class Prime:
"""
获得素数数组的高级实现。支持 in 和 [] 运算符,[]支持切片
"""
def __init__(self):
self._list = [2, 3, 5, 7, 11, 13] # 保存所有现有的素数列表
def __contains__(self, n: int) -> bool:
"""
判断n是否是素数
:param n: 要判断的素数
:return: 是否是素数
"""
if not n % 2: # 偶数只有2是素数
return n == 2
a, b = self.indexOf(n) # 搜索n在素数列表中的位置
return a == b # 如果a b相同,代表这就是n在素数列表中的位置
def __getitem__(self, i):
"""
i为正整数时返回第i个元素;i为slice时返回切片数组(当i.stop=None时只返回迭代器)
:param i: index或者slice
:return: int或list或iterator
"""
if isinstance(i, slice): # 如果i是切片
it = self.range(i.start, i.stop, i.step) # 获得迭代器
if i.stop: # 如果指定了stop,则返回对应的数组
return list(it)
return it # 没指定就直接返回迭代器
else: # 如果n是正整数
self._extendToLen(i + 1) # 拓展list长度直到n
return self._list[i] # 返回第n个元素
def indexOf(self, n: int):
"""
获得数字n位于素数列表的第几个位置,或者哪两个位置之间
:param n: 要搜索的素数
:return: 如果搜到则返回(index, index);搜不到则返回n的大小在哪两个相邻位置之间(from, to)
"""
if n < 2:
return -1, 0
if n > self._list[-1]: # 需要拓展列表
self._extend(n)
import bisect
index = bisect.bisect(self._list, n) # 二分法搜索大于n的最左边位置
if self._list[index - 1] == n:
return index - 1, index - 1
else:
return index - 1, index
def range(self, start=0, stop=None, step=1) -> islice:
"""
获得素数数组的range迭代器
:return: 迭代器
"""
if stop: # 如果有指明stop的话
self._extendToLen(stop + 1) # 拓宽list到stop位置
return islice(self._list, start, stop, step) # 生成切片后的迭代器
return islice(self, start, None, step) # 只有没指定stop时制造迭代器的切片,返回指向n.start位置的迭代器
def primeRange(self, minN: int, maxN: int, step=1):
"""
返回包含[minN, maxN)内所有素数的迭代器
:param minN: 素数最小值
:param maxN: 素数最大值(不包括)
:param step: 遍历的步伐,默认为1
:return: 迭代器
"""
minN = max(2, minN) # 开始值合法化
if minN >= maxN: # 异常参数检查
return
self._extend(maxN) # 拓展list直到包含stop
i = self.indexOf(minN)[1] # 找到startN所在的位置,或者startN可以插入的位置
beginning_i = i
while i < len(self._list): # 防止数组越界(其实不会,因为extend过了,一定是break之前就return)
p = self._list[i] # 获取第i个元素
if p < maxN: # 每次必须小于maxN才能yield
if (i - beginning_i) % step == 0:
yield p
i += 1
else: # 超过范围就跳出
return
def _extend(self, n: int) -> None:
"""
拓展素数列表直到涵盖范围包括数字n就立刻停止
:param n: 将素数列表拓展到哪个数字为止
:return:
"""
if n <= self._list[-1]: # 如果list已经包含,则不需要拓展
return
maxSqrt = int(n ** 0.5) + 1 # 要拓展到的位置
self._extend(maxSqrt) # 如果列表没有拓展到sqrt(n),递归拓展
begin = self._list[-1] + 1 # 从哪里开始搜索
sizer = [i for i in range(begin, n + 1)] # 生成所有数字的数组
for prime in self.primeRange(2, maxSqrt): # 得到[2,maxSqrt)所有的素数
for i in range(-begin % prime, len(sizer), prime):
sizer[i] = 0 # 把所有非素数变为0
self._list += [x for x in sizer if x] # 删去所有的零,剩下的就是素数列表
def _extendToLen(self, listLen: int) -> None:
"""
将素数列表的长度至少拓展到listLen
:param listLen: 至少拓展到多长
:return:
"""
while len(self._list) < listLen: # 每次n*1.5,直到list长度符合要求
self._extend(int(self._list[-1] * 1.5))
prime = Prime()
def _input():
import sys
return sys.stdin.readline()
def get因子Set(number: int) -> set:
yinziList = [1, number]
for i in range(2, int(sqrt(number)) + 1):
if i not in prime: # 因子都是素数
continue
if number % i == 0:
yinziList.append(i)
yinziList.append(number // i)
return set(yinziList)
def main():
N = int(_input().strip())
array = list(map(int, _input().strip().split()))[:N]
if not N:
print(0)
return
array因子 = [get因子Set(num) for num in array]
tmp = array因子[0]
for yinzi in array因子:
tmp.intersection_update(yinzi)
if len(tmp) > 1: # 所有的set有公共区域
print(-1)
return
minDelete = 2 ** 31 - 1
interStack = []
@lru_cache(maxsize=None)
def dp(i: int, deleteCount: int):
nonlocal minDelete
if i >= len(array因子):
if interStack and interStack[-1] == {1}:
minDelete = min(minDelete, deleteCount)
return
stackEmpty = not interStack
interStack.append(array因子[i] if stackEmpty else array因子[i].intersection(interStack[-1]))
dp(i + 1, deleteCount) # 不删除该位置
interStack.pop()
if not stackEmpty:
interStack.append(interStack[-1])
dp(i + 1, deleteCount + 1)
if not stackEmpty:
interStack.pop()
# dp(0, 0)
array因子.sort(key=lambda x:list(x))
count=0
for i in range(len(array因子)-1,0,-1):
if i==0:
continue
yinzi = array因子[i]
if yinzi.issuperset(array因子[i-1]):
count+=1
del array因子[i]
dp(0,0)
minDelete+=count
print(minDelete if minDelete < 2 ** 30 else -1)
if __name__ == '__main__':
for round in range(int(_input().strip())):
main()
|
66d2376ad3932fea1810da8fcc2d4bf1863f31ef | murali-koppula/programming-problems | /python/bttest.py | 1,094 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test simple B-Tree implementation.
node values are provided as arguments.
"""
__author__ = "Murali Koppula"
__license__ = "MIT"
import argparse
from btnode import Node
from btree import BTree
def add(root=None, vals=[]) ->'Node':
# Walk through the tree in a breadth-first fashion to add vals.
#
if not root and vals:
root = Node(vals.pop(0))
q = [root] if root else []
while len(q) > 0:
n = q.pop()
if n.left:
q.insert(0, n.left)
elif vals:
n.left = Node(vals.pop(0))
q.insert(0, n.left)
if n.right:
q.insert(0, n.right)
elif vals:
n.right = Node(vals.pop(0))
q.insert(0, n.right)
return root
parser = argparse.ArgumentParser(description='Make a BTree using given list of values.')
parser.add_argument('vals', metavar='VALS', nargs='+',
help='comma separated values')
args = parser.parse_args()
root = add(vals=args.vals)
btree = BTree(root)
print("'{}'".format(btree))
|
42d12efe04c51bf489a6c252b2815811135e7de6 | 2Gken1029/graduateReserchProgram | /wordFind.py | 1,183 | 3.59375 | 4 | #! python3
# wordFind.py - 単語リストにある単語が文章ファイルにどれほどでてくるか
import os, sys
def wordFind(file_name):
word_file = open('frequentList.txt') # 単語リストを読み込み
word_list = word_file.readlines() # リストに書き込み
word_file.close()
voice_file = open(file_name) # 最初の引数を音声文章ファイルとする
voice_list = voice_file.readlines()
voice_file.close
# リスト内文字列の"\n"を削除
word_list = [s.replace('\n', '') for s in word_list]
voice_list = [s.replace('\n', '') for s in voice_list]
# 音声文章の中に特定の単語が含まれているか
appear_word = {}
for voice in voice_list:
for word in word_list:
if word in voice: # 有無
### print("・" + word + " " + voice) ###
if not word in appear_word: # 初めて特定の単語が含まれていたら記録
appear_word[word] = 1
else: # 再び単語が含まれていたらカウントを1増やす
appear_word[word] = appear_word[word] + 1
return appear_word |
c34644cf434d5bc7942b95f5b66548faa13a606c | 702criticcal/1Day1Commit | /Baekjoon/15815.py | 1,874 | 3.78125 | 4 | # 1차 시도. 런타임 에러.
mathExpression = input()
stack = []
for s in mathExpression:
stack.append(s)
if len(stack) >= 3 and stack[-1] in ['*', '/', '+', '-']:
operator = stack.pop()
num2 = stack.pop()
num1 = stack.pop()
stack.append(str(eval(num1 + operator + num2)))
print(stack[-1])
# 2차 시도. 실패.
mathExpression = input()
stack = []
for s in mathExpression:
if s.isdigit():
stack.append(int(s))
else:
if s == '+':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 + num2)
elif s == '-':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 - num2)
elif s == '*':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 * num2)
elif s == '/':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 / num2)
print(stack[-1])
# 3차 시도. 성공!
# Python의 나눗셈 연산자가 문제였던 것 같다. Python3에서는 정수끼리 나누어도 실수형으로 출력되기 때문!
mathExpression = input()
stack = []
for s in mathExpression:
if s.isdigit():
stack.append(int(s))
else:
if s == '+':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 + num2)
elif s == '-':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 - num2)
elif s == '*':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 * num2)
elif s == '/':
num2 = stack.pop()
num1 = stack.pop()
if num1 % num2 == 0:
stack.append(num1 // num2)
else:
stack.append(num1 / num2)
print(stack[-1])
|
abe21d85d69621041f41f2124725c45a2e8e3c52 | 702criticcal/1Day1Commit | /Baekjoon/2941.py | 272 | 3.65625 | 4 | str = input()
str = str.replace("c=","1")
str = str.replace("c-","1")
str = str.replace("dz=","1")
str = str.replace("d-","1")
str = str.replace("lj","1")
str = str.replace("nj","1")
str = str.replace("s=","1")
str = str.replace("z=","1")
count = len(str)
print(count)
|
452845da256217de1bb1cde425dc1103ff25a97b | 702criticcal/1Day1Commit | /Baekjoon/1427.py | 119 | 3.59375 | 4 | n = input()
n_list = sorted(list(map(int, n)))
n_list.reverse()
n_list = list(map(str, n_list))
print(''.join(n_list))
|
905f2b287938bbb3d80cdce951ac736a26b15871 | 702criticcal/1Day1Commit | /Baekjoon/1193.py | 162 | 3.671875 | 4 | x = int(input())
line = 1
while x > line:
x -= line
line += 1
if line % 2 == 0:
print(f'{x}/{line - x + 1}')
else:
print(f'{line - x + 1}/{x}')
|
51f082d3dde89a5467ca199d24e848e3ee3aafe4 | 702criticcal/1Day1Commit | /Baekjoon/1225.py | 376 | 3.6875 | 4 | # 1차 시도. 시간 초과 실패.
A, B = input().split()
result = 0
for a in A:
for b in B:
result += int(a) * int(b)
print(result)
# 2차 시도. 성공. 형변환이 반복문 안에 있는 것이 문제였던 것 같다.
A, B = input().split()
A = list(map(int, A))
B = list(map(int, B))
result = 0
b = sum(B)
for a in A:
result += a * b
print(result)
|
0791b5afa28e707de3ddac9947e2aa0df5ab962f | 702criticcal/1Day1Commit | /Baekjoon/10988.py | 109 | 3.90625 | 4 | S = input()
reversedS = ''.join(list(reversed(list(S))))
if S == reversedS:
print(1)
else:
print(0)
|
deab3ceba37a0c163e0dcfa73c78fcfdd58dc32f | 702criticcal/1Day1Commit | /Baekjoon/14916.py | 158 | 3.84375 | 4 | n = int(input())
if n == 1 or n == 3:
print(-1)
elif (n % 5) % 2 == 0:
print(n // 5 + (n % 5) // 2)
else:
print((n // 5) - 1 + (n % 5 + 5) // 2)
|
adfa64097aeb927cd37d57f18b9570658350cc95 | 702criticcal/1Day1Commit | /Baekjoon/1343.py | 281 | 3.59375 | 4 | board = list(input())
for i in range(len(board)):
if board[i:i + 4] == ['X', 'X', 'X', 'X']:
board[i:i + 4] = ['A', 'A', 'A', 'A']
if board[i:i + 2] == ['X', 'X']:
board[i:i + 2] = ['B', 'B']
if 'X' in board:
print(-1)
else:
print(''.join(board))
|
98eb446e51c509fd9f82721cd874474d7738880d | 702criticcal/1Day1Commit | /Programmers/stringIWanted.py | 275 | 3.5625 | 4 | import string
def solution(strings, n):
answer = []
for j in string.ascii_lowercase:
for i in sorted(strings):
if i[n] == j:
print(i[n])
answer.append(i)
return answer
# print(solution(["sun","bed","car"], 1)) |
bf4e9fe092735101ec7d741d73d40e54d60b9a44 | allysonja/hangman_steps | /3/maingame.py | 855 | 3.53125 | 4 | import random
import pygame
import sys
from pygame import *
pygame.init()
fps = pygame.time.Clock()
# CONSTANTS #
# DIMENSIONS #
WIDTH = 600
HEIGHT = 400
# COLORS #
WHITE = (255, 255, 255)
BLACK = (0 ,0, 0)
# GAME VARIABLES #
word_file = "dictionary.txt"
WORDS = open(word_file).read().splitlines()
word = random.choice(WORDS).upper()[1:-1]
word_display = ""
for char in word:
word_display += "_ "
window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('Hangman')
def draw(canvas):
global word, word_display
canvas.fill(WHITE)
# create labels for gameplay #
# word display label #
myfont2 = pygame.font.SysFont(None, 20)
label2 = myfont2.render(word_display, 1, BLACK)
canvas.blit(label2, (WIDTH // 2 - WIDTH // 8, HEIGHT // 2 + HEIGHT // 8))
while True:
draw(window)
pygame.display.update()
fps.tick(60) |
1ef246ae4f95f6727d38c8e55dfbe69cc8ba1385 | susoooo/IFCT06092019C3 | /PedroL/ejercicios/multi/python/ejercicios/4/Respuestas.nonexec.py | 2,155 | 4.09375 | 4 | #1
words = []
n = int(input("palabras a incluir"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
#2
words = []
n = int(input("palabras a incluir:"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
q = input("palabra a contar:")
print(q, "aparece ", words.count(q), "veces")
#3
words = []
n = int(input("palabras a incluir:"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
q = input("palabra a reemplazar:")
r = input("palabra de reemplazo:")
while not(q in words):
words[words.index(q)] = r
#4
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
for i in range(n1):
names1 += input("nombre:")
print("lista 1: ", names1)
n2 = int(input("numero de nombres en lista 2:"))
names2 = []
for i in range(n2):
names2 += input("nombre:")
print("lista 2:", names2)
print("eliminando elementos en lista 2 de lista 1")
for i in names1:
for j in names2:
names1.remove(names2)
print("lista 1:", names1)
#5
l = list(range(132, 139, 2))
#6
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
names2 = []
for i in range(n1):
names1 += input("nombre:")
for i in range(n1, 0, -1):
names2 += [names1[i]]
print("lista 1:", names1)
print("lista 2:", names2)
#7
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
for i in range(n1):
names1 += input("nombre:")
print("lista 1: ", names1)
n2 = int(input("numero de nombres en lista 2:"))
names2 = []
for i in range(n2):
names2 += input("nombre:")
print("lista 2:", names2)
res1 = []
res2 = []
res3 = []
for i in names1:
if i in names2:
res3 += i
else:
res1 += i
for i in names2:
if not(i in names1):
res2 += i
print("res1:", res1)
print("res2:", res2)
print("res3:", res3)
#8
x = int(input("numero hasta donde buscar primos:"))
p = []
for i in range(x + 1, 1, -1):
if (i % 2) and (i % 3) and (i % 5) and (i % 7):
p += [i]
print(p)
#9
w = input("palabra a evaluar:")
l = [['a', 0], ['e', 0], ['i', 0], ['o', 0], ['u', 0]]
for i in word:
for j in len(l):
if i == [j][0]:
l[j][1] += 1
print(l) |
b673338a1fd0bc8bd15fbc1993d06ff520150693 | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_1/Ejercicio1.py | 162 | 3.84375 | 4 | numero1=int(input("Introduzca el primer numero: "))
numero2=int(input("Introduzca el segundo numero: "))
media=(numero1 + numero2) / 2
print("La media es ",media) |
3c749b7db4951b609149529c15e025b2bc059383 | susoooo/IFCT06092019C3 | /Riker/python/05.py | 283 | 3.625 | 4 | # 5-Escriba un programa que pida una temperatura en grados Fahrenheit y que escriba esa temperatura en grados Celsius. La relación entre grados Celsius (C) y grados Fahrenheit (F) es la siguiente: C = (F - 32) / 1,8
f = int(input("Fahrenheit? "))
print("Celsius: ", (f - 32) /1.8)
|
6d540eb2495904a59fdf91444ce77d2a11e7fc94 | susoooo/IFCT06092019C3 | /Riker/python/11.py | 481 | 3.890625 | 4 | # 4-Escriba un programa que pida el año actual y un año cualquiera y que escriba cuántos años han pasado desde ese año o cuántos años faltan para llegar a ese año.
import datetime
year = int(input("Year? "))
current_year = datetime.datetime.now().year
if (year < current_year):
print("Years since ", year, ", ", current_year - year)
else:
if(year > current_year):
print("Years to ", year,", ", year - current_year)
else:
print("Same year.")
|
a6183dcb8aba1708c72862fd23d82a50147e946d | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio4.py | 442 | 4.09375 | 4 | # Escriba un programa que pregunte cuántos
# números se van a introducir, pida esos
# números y escriba cuántos negativos ha introducido.
iteracion=int(input("¿Cuantos números va a introducir?: "))
negativo=0
for i in range(iteracion):
numero=int(input("Introduzca el numero: "))
if numero < 0 :
negativo+=1
if negativo!=1:
cadena="negativos"
else :
cadena="negativo"
print("Se ha introducido",negativo,cadena) |
cfd6225160256d38046ffa0d99ac9863945a553c | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e7.py | 294 | 3.71875 | 4 | #7-Escriba un programa que pida una cantidad de segundos y que escriba cuántas horas, minutos y segundos son.
print("Segundos:")
sgd=int(input())
min=0
horas=0
while sgd>3600:
horas+=1
sgd-=3600
while sgd>60:
min+=1
sgd-=60
print("Horas: ", horas, "Minutos: ", min, " Segundos: ",sgd)
|
9ec0866daee52c1def3a8a9fed5299154dd92f64 | susoooo/IFCT06092019C3 | /Riker/python/14.py | 429 | 3.90625 | 4 |
# 8-Escriba un programa que pida tres números y que escriba si son los tres iguales, si hay dos iguales o si son los tres distintos.
n1 = int(input("n1 ? "))
n2 = int(input("n2 ? "))
n3 = int(input("n3 ? "))
if ((n1 == n2) and (n2 == n3)):
print("They are equal.")
else:
if ((n1 == n2) or (n1 == n3) or (n2 == n3)):
print("There are two equal numbers")
else:
print("They are all different")
|
babcf1bc7df6069a229344b05e97d97acfddca39 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/while4.py | 522 | 4.0625 | 4 | #4-Escriba un programa que pida primero dos números enteros (mínimo y máximo) y que después pida números enteros situados entre ellos. El programa terminará cuando se escriba un número que no esté comprendido entre los dos valores iniciales. El programa termina escribiendo la cantidad de números escritos.
print("Número entero mínimo:")
n1=int(input())
print("Número entero máximo:")
n2=int(input())
n3=n1
nums=0
while n1<=n3<=n2:
print("Número entero:")
n3=int(input())
nums+=1
print("Numeros: ",nums)
|
e08d5430b054d56ae0ac12b818ad476158cfa51f | susoooo/IFCT06092019C3 | /elvis/python/bucle5.py | 645 | 4.125 | 4 | # Escriba un programa que pregunte cuántos números se van a introducir, pida esos números
# y escriba cuántos negativos ha introducido.
print("NÚMEROS NEGATIVOS")
numero = int(input("¿Cuántos valores va a introducir? "))
if numero < 0:
print("¡Imposible!")
else:
contador = 0
for i in range(1, numero + 1):
valor = float(input(f"Escriba el número {i}: "))
if valor < 0:
contador = contador + 1
if contador == 0:
print("No ha escrito ningún número negativo.")
elif contador == 1:
print("Ha escrito 1 número negativo.")
else:
print(f"Ha escrito {contador} números negativos.")
|
14ddefb42599d0209461b9d3c7be587fdec95dab | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e2.py | 324 | 3.984375 | 4 | #2-Escriba un programa que pida el peso (en kilogramos) y la altura (en metros) de una persona y que calcule su índice de masa corporal (imc). El imc se calcula con la fórmula imc = peso / altura 2
print("Peso: (kg)")
peso = float(input())
print("Altura: (m)")
altura = float(input())
print("imc: ",peso/(altura*altura))
|
cedf8afaea566b52bc6e58b2162e4f8884244155 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/listas2.py | 410 | 4.0625 | 4 | #2-Amplia el programa anterior, para que una vez creada la lista, se pida por pantalla una palabra y se diga cuantas veces aparece dicha palabra en la lista.
palabras = []
print("Número de palabras?:")
num=int(input())
for n in range(num):
print("Palabra ", n+1, ": ")
palabras=palabras+[input()]
print(palabras)
print("Buscar palabra: ")
search=input()
print("Concurrencia: ", palabras.count(search))
|
37a04841bddbb99f65213075c1c8524b62fb4494 | susoooo/IFCT06092019C3 | /Riker/python/10.py | 303 | 3.828125 | 4 | # 3-Escriba un programa que pida dos números y que conteste cuál es el menor y cuál el mayor o que escriba que son iguales.
n1 = int(input("n1? "));
n2 = int(input("n2? "));
if(n1 > n2):
print(n1, ">", n2)
else:
if (n2 > n1):
print(n2, ">", n1)
else:
print(n2, "=", n1)
|
aea888ce79f3f38a5347cd8208531a8978cb1a01 | susoooo/IFCT06092019C3 | /Tere/python/ejercicio7.py | 345 | 3.828125 | 4 | #7-Escriba un programa que pida una cantidad de segundos y
#que escriba cuántas horas, minutos y segundos son.
print("Escribe unos segundos: ")
segundos= input()
horas= int(segundos)/3600
minutos = (int(segundos) - int (horas)*3600)/60
seg = int(segundos) % 60
print (int(horas),"horas,",int(minutos), "minutos y", int(seg), "segundos")
|
16ec073e55924a91de34557320e539c750f377a3 | susoooo/IFCT06092019C3 | /jesusp/phyton/Divisor.py | 215 | 4.125 | 4 | print("Introduzca un número")
num = int(input())
if(num > 0):
for num1 in range(1, num+1):
if(num % num1 == 0):
print("Divisible por: ", num1)
else:
print("Distinto de cero o positivo")
|
6a1f6dfefe46fd0ff31c1b967046182d90e61d9a | susoooo/IFCT06092019C3 | /Riker/python/13.py | 427 | 3.90625 | 4 | # 6-Escriba un programa que pida dos números enteros y que escriba si el mayor es múltiplo del menor.
n1 = int(input("n1 ?"))
n2 = int(input("n2 ? "))
if (n1 == n2):
print("Numbers are equal")
else:
if (n1 > n2):
max = n1
min = n2
else:
max = n2
min = n1
if(max%min == 0):
print(max, " is multiple of ", min)
else:
print(max, " isn't multiple of ", min)
|
b2ba8e45c360ae96a08209172ba05811dd3a3b96 | susoooo/IFCT06092019C3 | /jesusp/phyton/Decimal.py | 201 | 4.15625 | 4 | print("Introduzca un número")
num = int(input())
print("Introduzca otro número")
num1 = int(input())
while(num > num1):
print("Introduzca un numero decimal: ")
num1= float(input())
|
6e848cdacf2855debfa5adb7ee6164758a53f8e7 | susoooo/IFCT06092019C3 | /Riker/python/08.py | 232 | 3.609375 | 4 | # 1-Escriba un programa que pida dos números enteros y que calcule su división, escribiendo si la división es exacta o no.
n1 = int(input("n1? "))
n2 = int(input("n2? "))
if (n1%n2 == 0):
print("yes")
else:
print("no")
|
52cc76a4a00bb9d8b7cb7aa335b7060a434dc29c | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio2.py | 344 | 4 | 4 | # Escriba un programa que pida un número entero mayor que cero y que escriba sus divisores.
numero=int(input("Introduzca un número entero mayor que cero: "))
while numero<=0 :
numero=int(input("Error.Introduzca un número entero mayor que cero: "))
for i in range(1,numero+1) :
if numero%i==0 :
print(i,"es divisor de",numero) |
22bac0fd997d87e501d018b3af30dc76fd60f2c7 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e3.py | 322 | 4 | 4 | #3-Escriba un programa que pida una distancia en pies y pulgadas y que escriba esa distancia en centímetros.Un pie son doce pulgadas y una pulgada son 2,54 cm.
print("Distancia en pies:")
pies = float(input())
print("Distancia en pulgadas:")
pulgadas = float(input())
print("Distancia en cm: ", (pies*12+pulgadas)*2.54)
|
b41ed3fc64e7a705c9be5060c0b034528f0a5f98 | chrisfoose/randomColor.py | /randomColor.py | 195 | 3.953125 | 4 | # Random Color Generator
# Chooses random color from out of four choices
# Christopher Foose
import random
colorList = ["Red", "Blue", "Green", "Yellow"]
print("Your color is: ", random.choice(colorList))
|
ff3e2b0d818421e8924334b9658d12560c3fa3fd | Bakley/literate-bassoon | /rename_files.py | 576 | 3.53125 | 4 | from __future__ import print_function
import os
def renaming_files():
# get the path to the files and the file names
file_list = os.listdir("/home/koin/Desktop/HackRush/Bakley/Python/Learning/Udacity/prank")
print(file_list)
# get the saved path of the directory
saved_path = os.getcwd()
print("The saved path is,", saved_path)
os.chdir("/home/koin/Desktop/HackRush/Bakley/Python/Learning/Udacity/prank")
# rename files
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
renaming_files()
|
08f116b143a9b8e78849c29f1df7a810ebd78352 | devangsharmadj/Python_Workbook_Course | /palindrome.py | 360 | 4.0625 | 4 | verifier = input('String to be checked: ')
split_verifier = verifier.split()
str_verifier = ''
for char in split_verifier:
str_verifier += f'{char}'
j = len(str_verifier)
for i in range(len(str_verifier)):
if str_verifier[i] == str_verifier[j - 1 - i]:
continue
else:
print('Not a palindrome!')
exit(1)
print('Palindrome!')
|
63092169b0fbdedc99931c707dd8248feb413c5e | Chelton-dev/ICTPRG-Python | /loopinf01.py | 79 | 3.75 | 4 | # Infinite loop
j=0
k = 0
while j <= 5:
#while k <= 5:
print(k)
k = k+1 |
4885f7041431e60298e6655303696a9120fe272e | Chelton-dev/ICTPRG-Python | /setex01.py | 400 | 3.921875 | 4 | # Example of a set
# unique elements
# https://www.w3schools.com/python/python_sets.asp
# https://pythontic.com/containers/set/construction_using_braces
# Disadvantage that cannot be empty
# https://stackoverflow.com/questions/17373161/use-curly-braces-to-initialize-a-set-in-python
carmakers = { 'Nissan', 'Toyota', 'Ford', 'Mercedes' }
carmakers.add('Kia')
for comp in carmakers:
print(comp) |
0b67e25ac38cfb32a6fe9a217f59a394a832ffa7 | Chelton-dev/ICTPRG-Python | /func03main2.py | 128 | 3.734375 | 4 | def main():
nm = get_name()
print("Hello "+nm)
def get_name():
name = input("Enter name: ")
return name
main() |
a8e222aca3153a0085ddf66b482b335c594042c9 | Chelton-dev/ICTPRG-Python | /format05printf.py | 326 | 3.984375 | 4 | # printing a string.
mystring = "abc"
print("%s" % mystring)
# printing a integer
days = 31
print("%d" % days)
# printing a float number
cost = 189.95
print("%f" % cost)
# printf apdaptions with concatenation (adding strings)
print("%s-" % "def" + "%f" % 2.71828)
# 2021-05-25
print("%d-" % 2021 + "0%d-" % 5 + "%d" % 25 ) |
19bfe557a5e0d351be9215b2f8ea501587337fda | Chelton-dev/ICTPRG-Python | /except_div_zero.py | 242 | 4.1875 | 4 | num1 = int (input("Enter num1: "))
num2 = int (input("Enter num2: "))
# Problem:
# num3 = 0/0
try:
result = num1/num2
print(num1,"divided by", num2, "is ", result)
except ZeroDivisionError:
print("division by zero has occured") |
6b5ac6244d890d1b5dcb135f22563bb8dc825abf | sorozcov/Digital-Sign-RSA | /digitalSign.py | 2,814 | 3.703125 | 4 | # Universidad del Valle de Guatemala
# Cifrado de información 2020 2
# Grupo 7
# Implementation Digital Sign.py
#We import pycryptodome library and will use hashlib to sha512
from Crypto.PublicKey import RSA
from hashlib import sha512
#Example taken from https://cryptobook.nakov.com/digital-signatures/rsa-sign-verify-examples
#We'll do an example of Digital Sign using RSA
print("This is an example OF Digital Signing using pycryptodome python library.")
message = b'My Secret Message'
print("The message Alice wants to send Bob is: ", message)
# First of all, Alice needs to generate a Public Key to give to Bob and a Private Key to keep secret.
# We'll do this using RSA Algorythm
#Alice Keys for signing
aliceKeys = RSA.generate(bits=1024)
nAlice=aliceKeys.n
publicKeyAlice=aliceKeys.e
privateKeyAlice=aliceKeys.d
#Bob Keys for encrypting and decrypting using RSA
bobKeys = RSA.generate(bits=1024)
nBob=bobKeys.n
publicKeyBob=bobKeys.e
privateKeyBob=bobKeys.d
#Cipher RSA
#c=m^{e}mod {n}}
#Decipher RSA
#m=c^{d}mod {n}}
print("Alice public key is: ", hex(publicKeyAlice))
print("Alice private key is: ", hex(privateKeyAlice))
print("Both keys will need the value of n: ", hex(nAlice))
print("Bob public key is: ", hex(publicKeyBob))
print("Bob private key is: ", hex(privateKeyBob))
print("Both keys will need the value of n: ", hex(nBob))
#Alice Part
#We generate a hash from our message and make a digest
hash = int.from_bytes(sha512(message).digest(), byteorder='big')
#After that we sign it using our privateKeyAlice
signature = pow(hash, privateKeyAlice,nAlice)
print("Signature of message:", hex(signature))
#If signature was altered
# signature=signature+1
#Now we encrypt our message and send it to Bob using Bobs public key
intMessage = int.from_bytes(message, byteorder='big')
encryptedMessage = pow(intMessage, publicKeyBob,nBob)
print("Message in Int: ",intMessage)
print("Encrypted message:", hex(encryptedMessage))
#Bobs Part
#Now we decrypt our message that was send from Alice using Public Key of Bob. Now Bob uses his privateKey
intDecryptedMessage = pow(encryptedMessage, privateKeyBob,nBob)
# If message was altered
# intDecryptedMessage=intDecryptedMessage+1
print("Decrypted Message in Int: ",intDecryptedMessage)
decryptedMessage = intDecryptedMessage.to_bytes((intDecryptedMessage.bit_length()+7)//8,byteorder="big")
print("Decrypted Message: ",decryptedMessage)
#Now we verify if the signature is valid
#For that we first decrypt the message
#Then we do the same verifying the hash from the message and the hash from the signature that was send
# If they match the signature is valid
hash = int.from_bytes(sha512(decryptedMessage).digest(), byteorder='big')
hashFromSignature = pow(signature, publicKeyAlice, nAlice)
print("Signature valid:", hash == hashFromSignature) |
c32ecd30c2fabc11127d5081d029a6c6271f3d2a | wtnb-msr/codeforces | /problem/118/A/solver.py | 233 | 3.609375 | 4 | #!/usr/bin/env python
import sys
origin = sys.stdin.readline().rstrip()
vowels = set(['a', 'A', 'o', 'O', 'y', 'Y', 'e', 'E', 'u', 'U', 'i', 'I'])
ans = [ '.' + c.lower() for c in origin if c not in vowels ]
print ''.join(ans)
|
1da02181c7de871672ec58d0ca79e721a0232367 | kunalkishore/Reinforcement-Learning | /Dynamic Programing /grid_world.py | 2,506 | 3.640625 | 4 | import numpy as np
class Grid():
def __init__(self,height,width,state):
self.height=height
self.width = width
self.i = state[0]
self.j = state[1]
def set_actions_and_rewards(self,actions, rewards):
'''Assuming actions consists of states other than terminal states and walls.
Rewards consists of only terminal states and in other states we assume reward to be 0'''
self.actions=actions
self.rewards = rewards
def set_current_state(self,state):
self.i=state[0]
self.j=state[1]
def get_state(self):
return (self.i,self.j)
def is_terminal(self,state):
return state not in self.actions
def move(self,action):
if action in self.actions[(self.i,self.j)]:
if action=='U':
self.i-=1;
elif action=='D':
self.i+=1
elif action=='L':
self.j-=1
elif action == 'R':
self.j+=1
return self.rewards.get((self.i,self.j),0)
def game_over(self):
return (self.i,self.j) not in self.actions
def all_states(self):
return set(list(self.rewards.keys())+list(self.actions.keys()))
def draw_grid(self):
for i in range(self.height):
print("________________________")
s=""
for j in range(self.width):
if (i,j) in self.actions:
reward=0
if (i,j) in self.rewards:
reward=self.rewards[(i,j)]
else:
reward=' / '
s+=str(reward)+" |"
print(s)
print("________________________")
def make_grid():
'''
|__|__|__|+1|
|__|__|//|__|
|__|//|__|-1|
|S |__|__|__|
'''
grid = Grid(4,4,(3,0))
rewards = {
(0,3):+1,
(2,3):-1,
(0,0):-0.1,
(0,1):-0.1,
(0,2):-0.1,
(1,0):-0.1,
(1,1):-0.1,
(1,3):-0.1,
(2,0):-0.1,
(2,2):-0.1,
(3,0):-0.1,
(3,1):-0.1,
(3,2):-0.1,
(3,3):-0.1
}
actions = {
(0,0):['R','D'],
(0,1):['R','L','D'],
(0,2):['R','L'],
(1,0):['R','U','D'],
(1,1):['U','L'],
(1,3):['U','D'],
(2,0):['U','D'],
(2,2):['R','D'],
(3,0):['U','R'],
(3,1):['L','R'],
(3,2):['U','L','R'],
(3,3):['U','L']
}
grid.set_actions_and_rewards(actions,rewards)
grid.draw_grid()
return grid
if __name__=='__main__':
make_grid()
|
67817397c76aea7ecd61a6030af87a5990fedb11 | alejandroverita/python-courses | /python-pro/iterators.py | 1,148 | 3.890625 | 4 | import time
class FiboIter:
def __init__(self, nmax):
self.nmax = nmax
def __iter__(self):
self.n1 = 0
self.n2 = 1
self.counter = 0
return self
def __next__(self):
if self.counter == 0:
self.counter = +1
return self.n1
elif self.counter == 1:
self.counter += 1
return self.n2
else:
self.aux = self.n1 + self.n2
if self.counter == self.nmax:
print("Finished")
raise StopIteration
self.n1, self.n2 = self.n2, self.aux
self.counter += 1
return self.aux
def run():
try:
nmax = int(input("Escribe la cantidad de ciclos en el Fibonacci: "))
if nmax > 0:
fibonacci = FiboIter(nmax)
for element in fibonacci:
print(f"{element}")
time.sleep(1)
elif nmax == 0:
print(0)
else:
raise ValueError
except ValueError:
print("Ingresa un numero positivo")
run()
if __name__ == "__main__":
run()
|
7562ed11cc98623910e7d9cd183bebad7bc207c0 | alejandroverita/python-courses | /bucles.py | 321 | 3.859375 | 4 | def run(veces, numero):
if veces <= numero:
print(f"La potencia de {veces} es {veces**2}")
run(veces + 1, numero)
else:
print("Fin del programa")
if __name__ == "__main__":
numero = int(input("Cuantas veces quieres repetir la potenciacion?: "))
veces = 0
run(veces, numero)
|
3c2ad960ec48388d2ed06952c26d9e044c851387 | Jumaruba/LeetCode | /328.py | 795 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
node = head
firstE = head.next
lastE = head.next
firstO = head
lastO = head
while lastE != None and lastE.next != None:
lastO.next = lastE.next
lastO = lastO.next # advance the lastO
prevLastONext = lastO.next
lastO.next = firstE
lastE.next = prevLastONext
lastE = lastE.next
return firstO
|
8c81082771a896fe45aa9f868c19ae9f64d6736e | Jumaruba/LeetCode | /235.py | 1,437 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Implemented with a small improvement
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.p = p
self.q = q
if self.p.val < self.q.val:
self.lowest = self.p
self.highest = self.q
else:
self.lowest = self.q
self.highest = self.p
self.ansNode = None
self.traverse(root)
return self.ansNode
# acc = 1 => we have found the value of the node already. Don't any process.
# acc == -2 => the first node to receive this value is the common ancestor.
def traverse(self, root):
acc = 0
if root == None:
return acc
if root == self.p:
acc = -1
elif root == self.q:
acc = -1
acc_left = 0
acc_right = 0
if root.val > self.lowest.val:
acc_left = self.traverse(root.left)
if root.val < self.highest.val:
acc_right = self.traverse(root.right)
if acc_left + acc_right + acc == -2:
self.ansNode = root
return 1
return acc + acc_left + acc_right
|
b40e2dbb8f231e4f7056ded68a1e01f363f1ed7d | Jumaruba/LeetCode | /844.py | 402 | 3.578125 | 4 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s = self.filterString(s)
t = self.filterString(t)
return s == t
def filterString(self, s):
s_ = ""
for i,l in enumerate(s):
if l == "#":
s_ = s_[:-1]
else:
s_ += l
return s_
|
011363075fb0db01ec2c1e91509a1d298c739790 | Jumaruba/LeetCode | /028.py | 550 | 3.578125 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
needle_size = len(needle)
haystack_size = len(haystack)
# Case the size is not compatible
if needle_size == 0:
return 0
if needle_size > haystack_size:
return -1
# Brute force algorithm O(n*m)!
for i in range(haystack_size - needle_size + 1):
s = haystack[i: i+needle_size]
if s == needle:
return i
return -1
|
9b44ba0b5d7221bf80da5243b2a8a9a349f32f1e | Jumaruba/LeetCode | /019.py | 1,004 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
numberOfElements = self.countElements(head)
toRemovePos = numberOfElements - n # lenght = 1, n = 1, 0
startNode = ListNode(-1, head)
self.removeElement(startNode, None, toRemovePos, -1)
return startNode.next
def removeElement(self, node: Optional[ListNode], prevNode, n, currPos):
if node == None:
return
if n == currPos:
prevNode.next = node.next
return
self.removeElement(node.next, node, n, currPos+1)
def countElements(self, node: Optional[ListNode]):
if node == None:
return 0
return self.countElements(node.next) + 1
|
fb77723ea81b139766b51c2d7df89e2d5e20f8d0 | Ka1str/Python-GB- | /lesson-4/task-3-4.py | 73 | 3.640625 | 4 | print([num for num in range(20, 240) if num % 20 == 0 or num % 21 == 0])
|
22ebd991c03e65777566bc730ccd7d4dc7a304a3 | Ka1str/Python-GB- | /lesson-3/task-6-3.py | 1,243 | 4.03125 | 4 | def int_func(user_text):
"""
Проверяет на нижний регистр и на латинский алфавит
Делает str с прописной первой буквой
:param user_text: str/list
:return: print str
"""
if type(user_text) == list:
separator = ' '
user_text = separator.join(user_text)
latin_alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
not_latin = False
for letter in user_text:
if letter not in latin_alphabet:
not_latin = True
if user_text.islower() and not_latin == False:
user_text = user_text.title()
return print(user_text)
else:
return print('Ввели слово/слова не из маленьких латинских букв')
user_word = input('введите слово из маленьких латинских букв')
int_func(user_word)
user_split_text = input('введите строку из слов из латинских букв в нижнем регистре, разделенных пробелом').split()
int_func(user_split_text)
|
917c3cda891b29c1d1ed0471be3ec773332a7b93 | ritika-rao/Machine-Learning | /03 Categorical Data.py | 1,086 | 3.78125 | 4 | # Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1] #Take all the columns except last one
y = dataset.iloc[:, -1] #Take the last column as the result
# Taking care of missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X.iloc[:, 1:])
X.iloc[:, 1:] = imputer.transform(X.iloc[:, 1:])
# Encoding categorical data
# 1st approach: Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X.iloc[:, 0] = labelencoder_X.fit_transform(X.iloc[:, 0]) # 0 is col 1
# label encoder has converted France as 1, Germany 2 and spain as 3
# 2nd approach: Make dummy variables
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()
# Encoding the Dependent Variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y) |
3daa982b7c0f53c73325d26a82935d5568eae25c | rnjsrntkd95/piro12 | /PYTHON_week2/argorithm/bracket(9012).py | 548 | 3.703125 | 4 | number = int(input())
bracket = []
tmp = ''
for i in range(number):
bracket.append(input())
for target in bracket:
stack = []
target = list(target)
for check in target:
if check == '(':
stack.append(check)
else:
if not stack:
stack.append(check)
else:
tmp = stack.pop()
if tmp != '(':
stack.append(tmp)
stack.append(check)
if not stack:
print('YES')
else:
print('NO')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.