blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a7f8138fe5c089abddd4312a9cbd48f2f1622ccb | Sandeep-2511/Python-Practise | /prog8.py | 148 | 3.703125 | 4 | l = "This is umbrella"
count = 0
for i in l:
if i == 'e':
count = count + 1
print("the occurence of e and is are:",count, l.count('is')) |
b752fdc52354cfc9fd1892a48258f8fb8647cdcd | reshmanair4567/100daycodingchallenge | /Python/Fibonnaci.py | 529 | 4.0625 | 4 | #Iterative##
def Fibonnaci(n):
a=0
b=1
if n<0:
print("please enter valid input")
if n==0:
return a
if n==1:
return b
else:
for i in range(2,n+1):
c=a+b
a=b
b=c
return b
'''
#Recursion
def Fibonnaci(n):
if n<0:
print("Enter valid input")
elif n==0:
return 0
elif n==1:
return 1
else:
return(Fibonnaci(n-1)+Fibonnaci(n-2))'''
if __name__=="__main__":
n=9
print(Fibonnaci(n))
|
0ec5ed951d292eb62f32e310777f72f26fb78896 | davidhawkes11/PythonStdioGames | /src/gamesbyexample/chomp.py | 3,112 | 4.125 | 4 | """Chomp, by Al Sweigart al@inventwithpython.com
A dangerously delicious logic game.
Inspired by a Frederik Schuh and David Gale puzzle, published by
Martin Gardner in Scientific American (January 1973)
More info at: https://en.wikipedia.org/wiki/Chomp"""
__version__ = 1
import random, sys
print('''CHOMP
By Al Sweigart al@inventwithpython.com
Inspired by a Frederik Schuh and David Gale puzzle.
In this two player game, players take turns picking a piece from a
chocolate bar and eating that piece and all pieces below and to the right
of it. The upper left piece is poisonous, and the player to eat that
piece loses.
''')
# The chocolate bar is always a random size:
width = random.randint(2, 9)
height = random.randint(2, 9)
# Create a dictionary to represent the chocolate bar:
uneatenBar = {}
for x in 'ABCDEFGHI'[:width]:
for y in '123456789'[:height]:
uneatenBar[(x, y)] = True
turn = 'X'
while True: # Main game loop.
# Display the chocolate bar:
print(' ABCDEFGHI'[: width + 1]) # Print the horizontal labels.
for iy in range(height):
print(iy + 1, end='') # + 1 because the labels start at 1, not 0.
for ix in range(width):
x = 'ABCDEFGHI'[ix]
y = '123456789'[iy]
if x == 'A' and y == '1':
print('P', end='') # Display P for poison piece.
elif uneatenBar[(x, y)] == True:
print('#', end='') # Display # for a chocolate bar piece.
else:
print('.', end='') # Display . for an eaten piece.
print() # Print a newline.
# Get the player's move:
print('It is {}\'s turn.'.format(turn))
while True:
print()
print('Select the piece to eat (or QUIT):')
response = input().upper()
# Check if the player wants to stop playing:
if response == 'QUIT':
print('Thanks for playing!')
sys.exit()
if len(response) != 2:
print('Enter a piece like "B3" or "D5".')
continue
piecex = response[0]
piecey = response[1]
if (piecex, piecey) not in uneatenBar.keys():
print('That piece doesn\'t exist on this chocolate bar.')
if uneatenBar.get((piecex, piecey), False) == True:
break
print('Select a piece that hasn\'t already been eaten.')
# At this point, go back to the start of the loop.
# Determine the other player's mark.
if turn == 'X':
otherPlayer = 'O'
elif turn == 'O':
otherPlayer = 'X'
# Check if the player ate the poison piece:
if piecex == 'A' and piecey == '1':
print('{} has eaten the poison piece!'.format(turn))
print('{} wins!'.format(otherPlayer))
break # Break out of the main game loop.
# Eat the selected piece and all pieces below and to the right of it:
for x in 'ABCDEFGHI'['ABCDEFGHI'.index(piecex) :]:
for y in '123456789'[int(piecey) - 1 :]:
uneatenBar[(x, y)] = False
# Switch turns to the other player:
turn = otherPlayer
# At this point, go back to the start of the main game loop.
|
155984b2aa54cbea2aacaf60b57bf8fa4c6b7696 | NIDHISH99444/CodingNinjas | /recursionBacktracking/uniqueNumberCombination.py | 758 | 3.828125 | 4 |
def printArray(p, n):
for i in range(0, n):
print(p[i], end=" ")
print()
def printAllUniqueParts(n):
p = [0] * n # An array to store a partition
k = 0 # Index of last element in a partition
p[k] = n # Initialize first partition
# as number itself
while True:
printArray(p, k + 1)
rem_val = 0
while k >= 0 and p[k] == 1:
rem_val += p[k]
k -= 1
if k < 0:
print()
return
p[k] -= 1
rem_val += 1
while rem_val > p[k]:
p[k + 1] = p[k]
rem_val = rem_val - p[k]
k += 1
p[k + 1] = rem_val
k += 1
print('All Unique Partitions of 3')
printAllUniqueParts(3)
|
a9ba82a0c7dc5f6a859f17ac00e3d1e786349eaf | mishraabhi083/standard-algorithms | /smallest_09_num.py | 399 | 3.734375 | 4 | def solve(num, base=[]):
if base == []:
base = ['9' + '0' * (len(str(num)) - 1)]
while base != []:
# print(base[0])
if int(base[0]) % num == 0: return int(base.pop(0))
else:
last = base.pop(0)
base = (base + [last + '0'] + [last + '9'])
if __name__ == "__main__":
print(f'least num is {solve(int(input("Enter num to test: ")))}') |
f4e1b664751849880849d57b522313e4ce1a92b5 | macraiu/software_training | /leetcode/py/414_Third_Maximum_Number.py | 1,103 | 4.125 | 4 | """ Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). """
def thirdMax(nums):
a = sorted(set(nums))
if len(a) < 3:
return max(a)
else:
return a[-3]
import time
import random
A = []
for i in range(0,10000):
n = random.randint(-10000,10000)
A.append(n)
t0 = time.clock()
print(thirdMax(A))
t1 = time.clock() - t0
print("first ", t1)
def thirdMax2(nums):
# ONE SUBMISSIONS WITH GOOD TIME
# Make a Set with the input.
nums = set(nums)
# Find the maximum.
maximum = max(nums)
# Check whether or not this is a case where
# we need to return the *maximum*.
if len(nums) < 3:
return maximum
# Otherwise, continue on to finding the third maximum.
nums.remove(maximum)
second_maximum = max(nums)
nums.remove(second_maximum)
return max(nums)
t0 = time.clock()
print(thirdMax2(A))
t1 = time.clock() - t0
print("second ", t1)
# FOR HIGH VARIANCE IN THE DISTRIBUTION MINE PERFORMS BETTER |
eb06cb81e4c205e40e18f0723110c0f2374d2382 | Saifullahshaikh/Assignment-5-Practice-problem-4.4-4.5 | /P.P 4.5.py | 336 | 3.78125 | 4 | print('Saifullah, 18B-092-CS, A')
print('Assignment# 5, practice problem 4.5')
first = 'Saifullah'
last = 'Shaikh'
street = 'PIB Street '
number = 46
city = 'Karachi'
state = 'Pakistan'
zip_code = '12564'
mailing_label = ('{} {}\n{} {}\n{}, {} {}')
print(mailing_label.format(first,last,number,street,city,state,zip_code))
|
2b4e2fba18266e04218a9c47dba601f2c09a4f17 | Oleksandr015/Algorytmy | /data_structures/deque.py | 803 | 3.65625 | 4 | from collections import deque
if __name__ == '__main__':
# ---------------------------
# ---------- STACK ----------
# ---------------------------
stack_deque = deque()
stack_deque.append(1)
stack_deque.append(2)
stack_deque.append(3)
assert stack_deque.pop() == 3
assert stack_deque.pop() == 2
assert stack_deque.pop() == 1
assert stack_deque.__len__() == 0
# ---------------------------
# ---------- QUEUE ----------
# ---------------------------
queue_deque = deque()
queue_deque.appendleft(1)
queue_deque.appendleft(2)
queue_deque.appendleft(3)
assert queue_deque.pop() == 1
assert queue_deque.pop() == 2
assert queue_deque.pop() == 3
assert queue_deque.__len__() == 0
|
ad7d3128ff138ec687d26fb518a1668f9f84761d | kunweiTAN/techgym_ai | /Nk3Q.py | 1,031 | 3.953125 | 4 | #AI-TECHGYM-3-3-Q-1
#回帰問題と分類問題
#インポート
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
#データを作成
#0〜1までの乱数を100個つくる
#値の範囲を-2~2に調整
x1 = x1 * 4 - 2
x2 = x2 * 4 - 2
#yの値をつくる
#標準正規分布(平均0,標準偏差1)の乱数を加える
y += np.random.randn(100, 1)
#モデル
#[[x1_1, x2_1], [x1_2, x2_2], ..., [x1_100, x2_100]]という形に変換
x1_x2 =
model = linear_model.LinearRegression()
#係数、切片を表示、決定係数
print('係数', model.coef_)
print('切片', model.intercept_)
print('決定係数', model.score(x1_x2, y))
# 求めた回帰式で予測
y_p = model.predict(x1_x2)
#グラフ表示
plt.scatter(x1, y, marker='x')
plt.scatter(x1, y_p, marker='o')
plt.xlabel('x1')
plt.ylabel('y')
plt.scatter(x2, y, marker='x')
plt.scatter(x2, y_p, marker='o')
plt.xlabel('x2')
plt.ylabel('y')
plt.tight_layout()
plt.show()
|
05bb2ce9c36217ebbeeff655129e74edcda7b432 | ggorla/PathtoFAANG1 | /Leetcode/56Mergeinterval.py | 439 | 3.71875 | 4 | def insert1(intervals, newinterval):
result=[]
for interval in intervals:
if not result or result[-1][1]<interval[0]:
result.append(interval)
else:
result[-1][1] = max(result[-1][1],interval[1])
return result
if __name__ == "__main__":
intervals = [[1,4],[4,5]]
newInterval = [4,10]
#print(insert1(intervals,newInterval))
print(insert1(intervals,newInterval)) |
bf322c0d44f5f29d23512dd1541762d932636484 | Lukazovic/Learning-Python | /CursoEmVideo/exercicio072 - numeros por extenso.py | 472 | 4.0625 | 4 | numeroExtenso = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis',
'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze',
'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
numeroEscolhido = int(input('\nDigite um número entre 0 e 20: '))
while numeroEscolhido<0 and numeroEscolhido>20:
numeroEscolhido = int(input('ERRO: Digite um número entre 0 e 20: '))
print(f'\nVocê digitou o número {numeroExtenso[numeroEscolhido]}!\n') |
b0f85cf0b0e6bf55ad25c32314d95cbfc98fa054 | JGuymont/ift2015 | /5_dictionnary/5.3 arbres binaires de recherche/5.3.1 abr/Tree.py | 3,282 | 3.890625 | 4 | #!/usr/local/bin/python3
from ListQueue import ListQueue
class Tree:
"""ADT Tree"""
class Position:
"""inner class Position"""
def element(self):
"""Return the element stored at this Position."""
raise NotImplementedError('must be implemented by subclass')
def __eq__(self, other):
"""Return True if other Position represents the same location."""
raise NotImplementedError('must be implemented by subclass')
def __ne__(self, other):
"""Return True if other does not represent the same location."""
return not(self == other)
def root(self):
"""Return Position representing the tree's root (or None if empty)."""
raise NotImplementedError('must be implemented by subclass')
def parent(self, p):
"""Return Position representing p's parent (or None if p is root)."""
raise NotImplementedError('must be implemented by subclass')
def num_children(self, p):
"""Return the number of children of a Position p"""
raise NotImplementedError('must be implemented by subclass')
def children(self, p):
"""Return an iteration of Positions representing p's children"""
raise NotImplementedError('must be implemented by subclass')
def __len__(self):
"""Return the number of nodes in the tree"""
raise NotImplementedError('must be implemented by subclass')
def is_root(self, p):
return self.root() == p
def is_leaf(self, p):
return self.num_children(p) == 0
def is_empty(self):
return len(self) == 0
def depth(self, p):
"""Return the number of levels separating Position p from the root."""
if self.is_root(p):
return 0
else:
return 1 + self.depth(self.parent(p))
def height(self, p):
"""Return the height of the subtree rooted at Position p."""
if self.is_leaf(p):
return 0
else:
return 1 + max( self.height(c) for c in self.children(p))
# imprime le sous-arbre dont la racine est la Position p
# utilise un parcours préfixé
def preorder_print( self, p, indent = "" ):
# on traite le noeud courant
print( indent + str( p ) )
# et par la suite les enfants, récursivement
for c in self.children( p ):
self.preorder_print( c, indent + " " )
# imprime le sous-arbre dont la racine est la Position p
# utilise un parcours postfixé
def postorder_print( self, p ):
# on traite les enfants
for c in self.children( p ):
self.postorder_print( c )
# et par la suite le parent
print( p )
# imprime le sous-arbre dont la racine est la Position p
# utilise un parcours en largeur, utilisant une File
def breadth_first_print(self, p):
Q = ListQueue()
# on enqueue la Position p
Q.enqueue(p)
# tant qu'il y a des noeuds dans la File
while not Q.is_empty():
# prendre le suivant et le traiter
q = Q.dequeue()
print(q)
# enqueuer les enfants du noeud traité
for c in self.children( q ):
Q.enqueue(c) |
ee198bc3403a53a3e1bca9ee1d6fdf894c3b36bd | sginne/solidabis | /graph.py | 3,110 | 4.1875 | 4 | """
Class implementing graph
"""
class Graph(object):
def __init__(self, graph_dict=None):
"""
Initializing graph
"""
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
def vertices(self):
""" vertices of the graph """
return list(self.__graph_dict.keys())
def edges(self):
""" edges of a graph """
return self.__generate_edges()
def add_vertex(self, vertex):
"""
add vertex if not exist
"""
if vertex not in self.__graph_dict:
self.__graph_dict[vertex] = []
def add_edge(self, edge):
"""
multiple edges between edges possible
"""
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict:
self.__graph_dict[vertex1].append(vertex2)
else:
self.__graph_dict[vertex1] = [vertex2]
def __generate_edges(self):
"""
generating edges
"""
edges = []
for vertex in self.__graph_dict:
for neighbour in self.__graph_dict[vertex]:
if {neighbour, vertex} not in edges:
edges.append({vertex, neighbour})
return edges
def __str__(self):
'''to string'''
res = "vertices: "
for k in self.__graph_dict:
res += str(k) + " "
res += "\nedges: "
for edge in self.__generate_edges():
res += str(edge) + " "
return res
def find_isolated_nodes(self):
""" isolated nodes. stops without bus """
isolated = []
for node in graph:
if not graph[node]:
isolated += node
return isolated
def find_path(self, start_vertex, end_vertex, path=None):
""" one path """
if path == None:
path = []
graph = self.__graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
return path
if start_vertex not in graph:
return None
for vertex in graph[start_vertex]:
if vertex not in path:
extended_path = self.find_path(vertex,
end_vertex,
path)
if extended_path:
return extended_path
return None
def find_all_paths(self, start_vertex, end_vertex, path=[]):
""" all paths """
graph = self.__graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
return [path]
if start_vertex not in graph:
return []
paths = []
for vertex in graph[start_vertex]:
if vertex not in path:
extended_paths = self.find_all_paths(vertex,
end_vertex,
path)
for p in extended_paths:
paths.append(p)
return paths |
dcd7000d110e865b1fa9815d5cd985e5f5b7278e | PRaNenS/python | /ErrorOccur.py | 2,318 | 3.625 | 4 | # 임의 에러 발생
class BigNumberError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
# 예외 처리
try:
print("한자리 숫자 나누기")
num1 = int(input("숫자1 >"))
num2 = int(input("숫자2 >"))
if num1 >= 10 or num2 >= 10:
raise BigNumberError("입력값: {0}, {1}" .format(num1, num2))
print("{0} / {1} = {2}" .format(num1, num2, int(num1/num2)))
except ValueError:
print("잘못된 값 입력! 한 자리만 입력")
except BigNumberError as err:
print("예외 발생! 한자리만 입력할 것!")
print(err)
finally:
print("계산기 이용 종료")
# Quiz) 동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다
# 대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다
# 시스템 코드를 확인하고 적절한 예외처리를 구문을 넣으시오
# 조건1: 1보다 작거나 숫자가 아닌 입력값이 들어올 때는 ValueError 로 처리
# 출력 메세지: "잘못된 값을 입력하였습니다"
# 조건2: 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
# 치킨 소진 시 사용자 정의 에러[SoldOutError]를 발생시키고 프로그램 종료
# 출력 메세지: "재고가 소진되어 더 이상 주문을 받지 않습니다"
# [코드]
class SoldOutError(Exception):
pass
chicken = 10
waiting = 1 # 홀 안에는 현재 만석, 대기번호 1부터 시작
while(True):
try:
print("[남은 치킨 : {0}]" .format(chicken))
order = int(input("치킨 몇 마리 주문하시겠습니까?"))
if order > chicken: # 남은 치킨보다 주문량이 많을 때
print("재료가 부족합니다")
elif order <= 0:
raise ValueError
else:
print("[대기번호 {0}] {1}마리 주문이 완료되었습니다" .format(waiting, order))
waiting += 1
chicken -= order
if chicken == 0:
raise SoldOutError
except ValueError:
print("잘못된 값을 입력하였습니다")
except SoldOutError:
print("재고가 소진되어 더 이상 주문을 받지 않습니다")
break |
142d796c660b86ec3050fe942837286424a529d0 | kenan666/caseStudy | /pandas_exercise/SimpleITK_py/sitk_transform.py | 23,154 | 3.5625 | 4 | # SimpleITK transform
from __future__ import print_function
import SimpleITK as sitk
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact, fixed
OUTPUT_DIR = "Output"
print(sitk.Version())
'''
Points in SimpleITK
Utility functions
A number of functions that deal with point data in a uniform manner.
'''
import numpy as np
def point2str(point, precision=1):
"""
Format a point for printing, based on specified precision with trailing zeros. Uniform printing for vector-like data
(tuple, numpy array, list).
Args:
point (vector-like): nD point with floating point coordinates.
precision (int): Number of digits after the decimal point.
Return:
String represntation of the given point "xx.xxx yy.yyy zz.zzz...".
"""
return ' '.join(format(c, '.{0}f'.format(precision)) for c in point)
def uniform_random_points(bounds, num_points):
"""
Generate random (uniform withing bounds) nD point cloud. Dimension is based on the number of pairs in the bounds input.
Args:
bounds (list(tuple-like)): list where each tuple defines the coordinate bounds.
num_points (int): number of points to generate.
Returns:
list containing num_points numpy arrays whose coordinates are within the given bounds.
"""
internal_bounds = [sorted(b) for b in bounds]
# Generate rows for each of the coordinates according to the given bounds, stack into an array,
# and split into a list of points.
mat = np.vstack([np.random.uniform(b[0], b[1], num_points) for b in internal_bounds])
return list(mat[:len(bounds)].T)
def target_registration_errors(tx, point_list, reference_point_list):
"""
Distances between points transformed by the given transformation and their
location in another coordinate system. When the points are only used to evaluate
registration accuracy (not used in the registration) this is the target registration
error (TRE).
"""
return [np.linalg.norm(np.array(tx.TransformPoint(p)) - np.array(p_ref))
for p,p_ref in zip(point_list, reference_point_list)]
def print_transformation_differences(tx1, tx2):
"""
Check whether two transformations are "equivalent" in an arbitrary spatial region
either 3D or 2D, [x=(-10,10), y=(-100,100), z=(-1000,1000)]. This is just a sanity check,
as we are just looking at the effect of the transformations on a random set of points in
the region.
"""
if tx1.GetDimension()==2 and tx2.GetDimension()==2:
bounds = [(-10,10),(-100,100)]
elif tx1.GetDimension()==3 and tx2.GetDimension()==3:
bounds = [(-10,10),(-100,100), (-1000,1000)]
else:
raise ValueError('Transformation dimensions mismatch, or unsupported transformation dimensionality')
num_points = 10
point_list = uniform_random_points(bounds, num_points)
tx1_point_list = [ tx1.TransformPoint(p) for p in point_list]
differences = target_registration_errors(tx2, point_list, tx1_point_list)
print(tx1.GetName()+ '-' + tx2.GetName()+':\tminDifference: {:.2f} maxDifference: {:.2f}'.format(min(differences), max(differences)))
# SimpleITK points represented by vector-like data structures.
point_tuple = (9.0, 10.531, 11.8341)
point_np_array = np.array([9.0, 10.531, 11.8341])
point_list = [9.0, 10.531, 11.8341]
print(point_tuple)
print(point_np_array)
print(point_list)
# Uniform printing with specified precision.
precision = 2
print(point2str(point_tuple, precision))
print(point2str(point_np_array, precision))
print(point2str(point_list, precision))
# TranslationTransform
# A 3D translation. Note that you need to specify the dimensionality, as the sitk TranslationTransform
# represents both 2D and 3D translations.
dimension = 3
offset =(1,2,3) # offset can be any vector-like data
translation = sitk.TranslationTransform(dimension, offset)
print(translation)
# Transform a point and use the inverse transformation to get the original back.
point = [10, 11, 12]
transformed_point = translation.TransformPoint(point)
translation_inverse = translation.GetInverse()
print('original point: ' + point2str(point) + '\n'
'transformed point: ' + point2str(transformed_point) + '\n'
'back to original: ' + point2str(translation_inverse.TransformPoint(transformed_point)))
# Euler2DTransform
point = [10, 11]
rotation2D = sitk.Euler2DTransform()
rotation2D.SetTranslation((7.2, 8.4))
rotation2D.SetAngle(np.pi/2)
print('original point: ' + point2str(point) + '\n'
'transformed point: ' + point2str(rotation2D.TransformPoint(point)))
# Change the center of rotation so that it coincides with the point we want to
# transform, why is this a unique configuration?
rotation2D.SetCenter(point)
print('original point: ' + point2str(point) + '\n'
'transformed point: ' + point2str(rotation2D.TransformPoint(point)))
# VersorTransform
# Rotation only, parametrized by Versor (vector part of unit quaternion),
# quaternion defined by rotation of theta around axis n:
# q = [n*sin(theta/2), cos(theta/2)]
# 180 degree rotation around z axis
# Use a versor:
rotation1 = sitk.VersorTransform([0,0,1,0])
# Use axis-angle:
rotation2 = sitk.VersorTransform((0,0,1), np.pi)
# Use a matrix:
rotation3 = sitk.VersorTransform()
rotation3.SetMatrix([-1, 0, 0, 0, -1, 0, 0, 0, 1]);
point = (10, 100, 1000)
p1 = rotation1.TransformPoint(point)
p2 = rotation2.TransformPoint(point)
p3 = rotation3.TransformPoint(point)
print('Points after transformation:\np1=' + str(p1) +
'\np2='+ str(p2) + '\np3='+ str(p3))
# Translation to Rigid [3D]
dimension = 3
t =(1,2,3)
translation = sitk.TranslationTransform(dimension, t)
# Only need to copy the translational component.
rigid_euler = sitk.Euler3DTransform()
rigid_euler.SetTranslation(translation.GetOffset())
rigid_versor = sitk.VersorRigid3DTransform()
rigid_versor.SetTranslation(translation.GetOffset())
# Sanity check to make sure the transformations are equivalent.
bounds = [(-10,10),(-100,100), (-1000,1000)]
num_points = 10
point_list = uniform_random_points(bounds, num_points)
transformed_point_list = [translation.TransformPoint(p) for p in point_list]
# Draw the original and transformed points, include the label so that we
# can modify the plots without requiring explicit changes to the legend.
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
orig = ax.scatter(list(np.array(point_list).T)[0],
list(np.array(point_list).T)[1],
list(np.array(point_list).T)[2],
marker='o',
color='blue',
label='Original points')
transformed = ax.scatter(list(np.array(transformed_point_list).T)[0],
list(np.array(transformed_point_list).T)[1],
list(np.array(transformed_point_list).T)[2],
marker='^',
color='red',
label='Transformed points')
plt.legend(loc=(0.0,1.0))
euler_errors = target_registration_errors(rigid_euler, point_list, transformed_point_list)
versor_errors = target_registration_errors(rigid_versor, point_list, transformed_point_list)
print('Euler\tminError: {:.2f} maxError: {:.2f}'.format(min(euler_errors), max(euler_errors)))
print('Versor\tminError: {:.2f} maxError: {:.2f}'.format(min(versor_errors), max(versor_errors)))
# Rotation to Rigid [3D]
rotationCenter = (10, 10, 10)
rotation = sitk.VersorTransform([0,0,1,0], rotationCenter)
rigid_euler = sitk.Euler3DTransform()
rigid_euler.SetMatrix(rotation.GetMatrix())
rigid_euler.SetCenter(rotation.GetCenter())
rigid_versor = sitk.VersorRigid3DTransform()
rigid_versor.SetRotation(rotation.GetVersor())
#rigid_versor.SetCenter(rotation.GetCenter()) #intentional error
# Sanity check to make sure the transformations are equivalent.
bounds = [(-10,10),(-100,100), (-1000,1000)]
num_points = 10
point_list = uniform_random_points(bounds, num_points)
transformed_point_list = [ rotation.TransformPoint(p) for p in point_list]
euler_errors = target_registration_errors(rigid_euler, point_list, transformed_point_list)
versor_errors = target_registration_errors(rigid_versor, point_list, transformed_point_list)
# Draw the points transformed by the original transformation and after transformation
# using the incorrect transformation, illustrate the effect of center of rotation.
from mpl_toolkits.mplot3d import Axes3D
incorrect_transformed_point_list = [ rigid_versor.TransformPoint(p) for p in point_list]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
orig = ax.scatter(list(np.array(transformed_point_list).T)[0],
list(np.array(transformed_point_list).T)[1],
list(np.array(transformed_point_list).T)[2],
marker='o',
color='blue',
label='Rotation around specific center')
transformed = ax.scatter(list(np.array(incorrect_transformed_point_list).T)[0],
list(np.array(incorrect_transformed_point_list).T)[1],
list(np.array(incorrect_transformed_point_list).T)[2],
marker='^',
color='red',
label='Rotation around origin')
plt.legend(loc=(0.0,1.0))
print('Euler\tminError: {:.2f} maxError: {:.2f}'.format(min(euler_errors), max(euler_errors)))
print('Versor\tminError: {:.2f} maxError: {:.2f}'.format(min(versor_errors), max(versor_errors)))
# Similarity [2D]
def display_center_effect(x, y, tx, point_list, xlim, ylim):
tx.SetCenter((x,y))
transformed_point_list = [ tx.TransformPoint(p) for p in point_list]
plt.scatter(list(np.array(transformed_point_list).T)[0],
list(np.array(transformed_point_list).T)[1],
marker='^',
color='red', label='transformed points')
plt.scatter(list(np.array(point_list).T)[0],
list(np.array(point_list).T)[1],
marker='o',
color='blue', label='original points')
plt.xlim(xlim)
plt.ylim(ylim)
plt.legend(loc=(0.25,1.01))
# 2D square centered on (0,0)
points = [np.array((-1.0,-1.0)), np.array((-1.0,1.0)), np.array((1.0,1.0)), np.array((1.0,-1.0))]
# Scale by 2
similarity = sitk.Similarity2DTransform();
similarity.SetScale(2)
interact(display_center_effect, x=(-10,10), y=(-10,10),tx = fixed(similarity), point_list = fixed(points),
xlim = fixed((-10,10)),ylim = fixed((-10,10)));
# Rigid to Similarity [3D]
rotation_center = (100, 100, 100)
theta_x = 0.0
theta_y = 0.0
theta_z = np.pi/2.0
translation = (1,2,3)
rigid_euler = sitk.Euler3DTransform(rotation_center, theta_x, theta_y, theta_z, translation)
similarity = sitk.Similarity3DTransform()
similarity.SetMatrix(rigid_euler.GetMatrix())
similarity.SetTranslation(rigid_euler.GetTranslation())
similarity.SetCenter(rigid_euler.GetCenter())
# Apply the transformations to the same set of random points and compare the results
# (see utility functions at top of notebook).
print_transformation_differences(rigid_euler, similarity)
# Similarity to Affine [3D]
rotation_center = (100, 100, 100)
axis = (0,0,1)
angle = np.pi/2.0
translation = (1,2,3)
scale_factor = 2.0
similarity = sitk.Similarity3DTransform(scale_factor, axis, angle, translation, rotation_center)
affine = sitk.AffineTransform(3)
affine.SetMatrix(similarity.GetMatrix())
affine.SetTranslation(similarity.GetTranslation())
affine.SetCenter(similarity.GetCenter())
# Apply the transformations to the same set of random points and compare the results
# (see utility functions at top of notebook).
print_transformation_differences(similarity, affine)
# Scale Transform
# 2D square centered on (0,0).
points = [np.array((-1.0,-1.0)), np.array((-1.0,1.0)), np.array((1.0,1.0)), np.array((1.0,-1.0))]
# Scale by half in x and 2 in y.
scale = sitk.ScaleTransform(2, (0.5,2));
# Interactively change the location of the center.
interact(display_center_effect, x=(-10,10), y=(-10,10),tx = fixed(scale), point_list = fixed(points),
xlim = fixed((-10,10)),ylim = fixed((-10,10)));
# Scale Versor
scales = (0.5,0.7,0.9)
translation = (1,2,3)
axis = (0,0,1)
angle = 0.0
scale_versor = sitk.ScaleVersor3DTransform(scales, axis, angle, translation)
print(scale_versor)
# Scale Skew Versor
scale = (2,2.1,3)
skew = np.linspace(start=0.0, stop=1.0, num=6) #six equally spaced values in[0,1], an arbitrary choice
translation = (1,2,3)
versor = (0,0,0,1.0)
scale_skew_versor = sitk.ScaleSkewVersor3DTransform(scale, skew, versor, translation)
print(scale_skew_versor)
# Bounded Transformations
#
# This function displays the effects of the deformable transformation on a grid of points by scaling the
# initial displacements (either of control points for BSpline or the deformation field itself). It does
# assume that all points are contained in the range(-2.5,-2.5), (2.5,2.5).
#
def display_displacement_scaling_effect(s, original_x_mat, original_y_mat, tx, original_control_point_displacements):
if tx.GetDimension() !=2:
raise ValueError('display_displacement_scaling_effect only works in 2D')
plt.scatter(original_x_mat,
original_y_mat,
marker='o',
color='blue', label='original points')
pointsX = []
pointsY = []
tx.SetParameters(s*original_control_point_displacements)
for index, value in np.ndenumerate(original_x_mat):
px,py = tx.TransformPoint((value, original_y_mat[index]))
pointsX.append(px)
pointsY.append(py)
plt.scatter(pointsX,
pointsY,
marker='^',
color='red', label='transformed points')
plt.legend(loc=(0.25,1.01))
plt.xlim((-2.5,2.5))
plt.ylim((-2.5,2.5))
# BSpline
# Create the transformation (when working with images it is easier to use the BSplineTransformInitializer function
# or its object oriented counterpart BSplineTransformInitializerFilter).
dimension = 2
spline_order = 3
direction_matrix_row_major = [1.0,0.0,0.0,1.0] # identity, mesh is axis aligned
origin = [-1.0,-1.0]
domain_physical_dimensions = [2,2]
bspline = sitk.BSplineTransform(dimension, spline_order)
bspline.SetTransformDomainOrigin(origin)
bspline.SetTransformDomainDirection(direction_matrix_row_major)
bspline.SetTransformDomainPhysicalDimensions(domain_physical_dimensions)
bspline.SetTransformDomainMeshSize((4,3))
# Random displacement of the control points.
originalControlPointDisplacements = np.random.random(len(bspline.GetParameters()))
bspline.SetParameters(originalControlPointDisplacements)
# Apply the BSpline transformation to a grid of points
# starting the point set exactly at the origin of the BSpline mesh is problematic as
# these points are considered outside the transformation's domain,
# remove epsilon below and see what happens.
numSamplesX = 10
numSamplesY = 20
coordsX = np.linspace(origin[0]+np.finfo(float).eps, origin[0] + domain_physical_dimensions[0], numSamplesX)
coordsY = np.linspace(origin[1]+np.finfo(float).eps, origin[1] + domain_physical_dimensions[1], numSamplesY)
XX, YY = np.meshgrid(coordsX, coordsY)
interact(display_displacement_scaling_effect, s= (-1.5,1.5), original_x_mat = fixed(XX), original_y_mat = fixed(YY),
tx = fixed(bspline), original_control_point_displacements = fixed(originalControlPointDisplacements));
# DisplacementField
# Create the displacement field.
# When working with images the safer thing to do is use the image based constructor,
# sitk.DisplacementFieldTransform(my_image), all the fixed parameters will be set correctly and the displacement
# field is initialized using the vectors stored in the image. SimpleITK requires that the image's pixel type be
# sitk.sitkVectorFloat64.
displacement = sitk.DisplacementFieldTransform(2)
field_size = [10,20]
field_origin = [-1.0,-1.0]
field_spacing = [2.0/9.0,2.0/19.0]
field_direction = [1,0,0,1] # direction cosine matrix (row major order)
# Concatenate all the information into a single list
displacement.SetFixedParameters(field_size+field_origin+field_spacing+field_direction)
# Set the interpolator, either sitkLinear which is default or nearest neighbor
displacement.SetInterpolator(sitk.sitkNearestNeighbor)
originalDisplacements = np.random.random(len(displacement.GetParameters()))
displacement.SetParameters(originalDisplacements)
coordsX = np.linspace(field_origin[0], field_origin[0]+(field_size[0]-1)*field_spacing[0], field_size[0])
coordsY = np.linspace(field_origin[1], field_origin[1]+(field_size[1]-1)*field_spacing[1], field_size[1])
XX, YY = np.meshgrid(coordsX, coordsY)
interact(display_displacement_scaling_effect, s= (-1.5,1.5), original_x_mat = fixed(XX), original_y_mat = fixed(YY),
tx = fixed(displacement), original_control_point_displacements = fixed(originalDisplacements));
displacement_image = sitk.Image([64,64], sitk.sitkVectorFloat64)
# The only point that has any displacement is (0,0)
displacement = (0.5,0.5)
displacement_image[0,0] = displacement
print('Original displacement image size: ' + point2str(displacement_image.GetSize()))
displacement_field_transform = sitk.DisplacementFieldTransform(displacement_image)
print('After using the image to create a transform, displacement image size: ' + point2str(displacement_image.GetSize()))
# Check that the displacement field transform does what we expect.
print('Expected result: {0}\nActual result:{1}'.format(str(displacement), displacement_field_transform.TransformPoint((0,0))))
# Composite transform (Transform)
# Create a composite transformation: T_affine(T_rigid(x)).
rigid_center = (100,100,100)
theta_x = 0.0
theta_y = 0.0
theta_z = np.pi/2.0
rigid_translation = (1,2,3)
rigid_euler = sitk.Euler3DTransform(rigid_center, theta_x, theta_y, theta_z, rigid_translation)
affine_center = (20, 20, 20)
affine_translation = (5,6,7)
# Matrix is represented as a vector-like data in row major order.
affine_matrix = np.random.random(9)
affine = sitk.AffineTransform(affine_matrix, affine_translation, affine_center)
# Using the composite transformation we just add them in (stack based, first in - last applied).
composite_transform = sitk.Transform(affine)
composite_transform.AddTransform(rigid_euler)
# Create a single transform manually. this is a recipe for compositing any two global transformations
# into an affine transformation, T_0(T_1(x)):
# A = A=A0*A1
# c = c1
# t = A0*[t1+c1-c0] + t0+c0-c1
A0 = np.asarray(affine.GetMatrix()).reshape(3,3)
c0 = np.asarray(affine.GetCenter())
t0 = np.asarray(affine.GetTranslation())
A1 = np.asarray(rigid_euler.GetMatrix()).reshape(3,3)
c1 = np.asarray(rigid_euler.GetCenter())
t1 = np.asarray(rigid_euler.GetTranslation())
combined_mat = np.dot(A0,A1)
combined_center = c1
combined_translation = np.dot(A0, t1+c1-c0) + t0+c0-c1
combined_affine = sitk.AffineTransform(combined_mat.flatten(), combined_translation, combined_center)
# Check if the two transformations are equivalent.
print('Apply the two transformations to the same point cloud:')
print('\t', end='')
print_transformation_differences(composite_transform, combined_affine)
print('Transform parameters:')
print('\tComposite transform: ' + point2str(composite_transform.GetParameters(),2))
print('\tCombined affine: ' + point2str(combined_affine.GetParameters(),2))
print('Fixed parameters:')
print('\tComposite transform: ' + point2str(composite_transform.GetFixedParameters(),2))
print('\tCombined affine: ' + point2str(combined_affine.GetFixedParameters(),2))
# Global transformation.
translation = sitk.TranslationTransform(2,(1.0,0.0))
# Displacement in region 1.
displacement1 = sitk.DisplacementFieldTransform(2)
field_size = [10,20]
field_origin = [-1.0,-1.0]
field_spacing = [2.0/9.0,2.0/19.0]
field_direction = [1,0,0,1] # direction cosine matrix (row major order)
# Concatenate all the information into a single list.
displacement1.SetFixedParameters(field_size+field_origin+field_spacing+field_direction)
displacement1.SetParameters(np.ones(len(displacement1.GetParameters())))
# Displacement in region 2.
displacement2 = sitk.DisplacementFieldTransform(2)
field_size = [10,20]
field_origin = [1.0,-3]
field_spacing = [2.0/9.0,2.0/19.0]
field_direction = [1,0,0,1] #direction cosine matrix (row major order)
# Concatenate all the information into a single list.
displacement2.SetFixedParameters(field_size+field_origin+field_spacing+field_direction)
displacement2.SetParameters(-1.0*np.ones(len(displacement2.GetParameters())))
# Composite transform which applies the global and local transformations.
composite = sitk.Transform(translation)
composite.AddTransform(displacement1)
composite.AddTransform(displacement2)
# Apply the composite transformation to points in ([-1,-3],[3,1]) and
# display the deformation using a quiver plot.
# Generate points.
numSamplesX = 10
numSamplesY = 10
coordsX = np.linspace(-1.0, 3.0, numSamplesX)
coordsY = np.linspace(-3.0, 1.0, numSamplesY)
XX, YY = np.meshgrid(coordsX, coordsY)
# Transform points and compute deformation vectors.
pointsX = np.zeros(XX.shape)
pointsY = np.zeros(XX.shape)
for index, value in np.ndenumerate(XX):
px,py = composite.TransformPoint((value, YY[index]))
pointsX[index]=px - value
pointsY[index]=py - YY[index]
plt.quiver(XX, YY, pointsX, pointsY);
# Writing and Reading
import os
# Create a 2D rigid transformation, write it to disk and read it back.
basic_transform = sitk.Euler2DTransform()
basic_transform.SetTranslation((1,2))
basic_transform.SetAngle(np.pi/2)
full_file_name = os.path.join(OUTPUT_DIR, 'euler2D.tfm')
sitk.WriteTransform(basic_transform, full_file_name)
# The ReadTransform function returns an sitk.Transform no matter the type of the transform
# found in the file (global, bounded, composite).
read_result = sitk.ReadTransform(full_file_name)
print('Different types: '+ str(type(read_result) != type(basic_transform)))
print_transformation_differences(basic_transform, read_result)
# Create a composite transform then write and read.
displacement = sitk.DisplacementFieldTransform(2)
field_size = [10,20]
field_origin = [-10.0,-100.0]
field_spacing = [20.0/(field_size[0]-1),200.0/(field_size[1]-1)]
field_direction = [1,0,0,1] #direction cosine matrix (row major order)
# Concatenate all the information into a single list.
displacement.SetFixedParameters(field_size+field_origin+field_spacing+field_direction)
displacement.SetParameters(np.random.random(len(displacement.GetParameters())))
composite_transform = sitk.Transform(basic_transform)
composite_transform.AddTransform(displacement)
full_file_name = os.path.join(OUTPUT_DIR, 'composite.tfm')
sitk.WriteTransform(composite_transform, full_file_name)
read_result = sitk.ReadTransform(full_file_name)
print_transformation_differences(composite_transform, read_result) |
3fe8ff6ea8a307276a311b01f494c3e92175868d | corridda/Studies | /Articles/Python/pythonetc/year_2018/september/operator_and_slices.py | 2,069 | 4.5 | 4 | """Оператор [] и срезы"""
"""В Python можно переопределить оператор [], определив магический метод __getitem__.
Так, например, можно создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:"""
class Cycle:
def __init__(self, lst):
self._lst = lst
def __getitem__(self, index):
return self._lst[
index % len(self._lst)
]
print(Cycle(['a', 'b', 'c'])[100]) # 'b'
print(Cycle(['a', 'b', 'c'])[1000]) # 'b'
print(Cycle(['a', 'b', 'c'])[1001]) # 'c'
print(Cycle(['a', 'b', 'c'])[1002], '\n') # 'a'
"""Необычное здесь заключается в том, что оператор [] поддерживает уникальный синтаксис.
С его помощью можно получить не только [2], но и [2:10], [2:10:2], [2::2] и даже [:].
Семантика оператора такая: [start:stop:step], однако вы можете использовать его любым иным образом
для создания кастомных объектов.
Но если вызывать с помощью этого синтаксиса __getitem__, что он получит в качестве индексного параметра?
Именно для этого существуют slice-объекты."""
class Inspector:
def __getitem__(self, index):
print(index)
Inspector()[1]
Inspector()[1:2]
Inspector()[1:2:3]
Inspector()[:]
# Можно даже объединить синтаксисы кортежей и слайсов:
Inspector()[:, 0, :]
# slice ничего не делает, только хранит атрибуты start, stop и step.
s = slice(1, 2, 3)
print(f"type(s): {type(s)}")
print(f"s.start: {s.start}")
print(f"s.stop: {s.stop}")
print(f"s.step: {s.step}")
print(f"Inspector()[s]: {Inspector()[s]}")
|
02061e20918ea8b66aca91ee764917dcb2103c31 | blueprint515/ForPy04 | /ex3.py | 945 | 4.21875 | 4 | # print "I will now count my chickens:"
print "I will now count my chickens:"
# print "Hens", count "25 + 30 / 6"
print "Hens", 25 + 30 / 6
# print "Hens",count"100-25*3%4"
print "Roosters",100-25*3%4
# print "Now I will count the eggs."
print "Now I will count the eggs."
# count"3+2+1-5+4%2-1/4+6"
print 3+2+1-5+4%2-1/4+6
# print "Is it true that 3+2<5-7?"
print "Is it true that 3+2<5-7?"
# no double quotes, will display false
print 3+2<5-7
# print "What is 3+2?",count"3+2"
print "What is 3+2?",3+2
# print "What is 5-7?",count"5-7"
print "what is 5-7?", 5-7
# print "Oh, that's why it's False."
print "Oh, that's why it's False."
# print "How about some more."
print "How about some more."
# print "Is it greater?", count"5>-2"
print "Is it greater?",5>-2
# print "Is it greater or equal?",count"5 >= -2"
print "Is it greater or equal?", 5 >= -2
# print "Is it less or equal?",count"5 <= -2"
print "Is it less or equal?", 5 <= -2
|
cd55b8cfe9bb5bce3e8c7e443f93e8044bccecd8 | gkelty/Sorry | /gameLoop.py | 10,796 | 3.5625 | 4 | # this is starting the game
import mainTest
from Button import Button
from TextInputBox import TextInputBox
from dbConnection import dbConnection
from Board import Board
from boardButton import BoardButton
import mainMenu
import PossibleMoves
import pygame
import pygame.locals as pl
import sys
import os.path
pygame.init()
##pygame.font.init()
# Define additional button colors (beyond white, grey, black)
TRANSPARENT = (0, 0, 0, 0)
PURPLE = (255, 125, 255)
DARKPURPLE = (198, 0, 198)
GREEN = (50, 200, 20)
FORESTGREEN = (34,139,34)
DARKGREY = (127,127,127)
# setting user colors
yellow = 0
green = 90
red = 180
blue = 270
# create array to use for validation later on
behaviorChoices = ["mean","nice"]
intelligenceChoices = ["smart","dumb"]
# create dictionary that is used to orient board
colors= { "yellow": 0,
"green": 90,
"red": 180,
"blue": 270
}
#global validMoves and buttons list and activePawn - DO WE NEED TO FIX THIS?
activePawn = None
playState = 0
# this is the main function that will create a new game
def main(textObjects, numOfComps, userColor, username, mode):
buttons = []
validMoves = []
# takes care of sliding a pawn when they land on an arrow on the board
def slide(board, pawn, lengthOfSlide):
currentTile = pawn.tileName
for i in range(lengthOfSlide-1):
newTile = board.tiles[currentTile]['tileAhead']
for otherPawn in board.pawns:
if otherPawn.tileName == newTile:
if otherPawn.player == board.currentPlayer:
sorryPawn(board, otherPawn)
elif otherPawn.player != board.currentPlayer:
sorryPawn(board, otherPawn)
currentTile = newTile
deactivateAllTileButtons(buttons)
activePawn.tileName = currentTile
# displays the squares that are valid moves for a pawn
def displayValidMovesForPawn(validMoves, buttons, tileName):
global playState
global activePawn
deactivateAllTileButtons(buttons)
if (board.currentPlayer ==1 or mode ==2):
for move in validMoves:
pawn = move[0]
if pawn.tileName == tileName:
for button in buttons:
if button.name == move[2]:
button.active = True
activePawn = pawn
break
playState = 2
else:
activePawn = validMoves[0][0]
movePawnToPosition(buttons,validMoves[0][2])
return None
# deactivate all tile buttons. (resets so you cant click or see them)
def deactivateAllTileButtons(buttons):
for button in buttons:
if 0 < button.name < 89:
button.active = False
# displays pawns that can move
def displayPawnsWithValidMoves(validMoves, buttons):
global playState
deactivateAllTileButtons(buttons)
for move in validMoves:
pawn = move[0]
currentPosition = pawn.tileName
for button in buttons:
if button.name == currentPosition:
button.active = True
break
if pawn.player == board.currentPlayer:
currentPosition = pawn.tileName
for button in buttons:
if button.name == currentPosition:
button.active = True
break
playState = 1
return None
# Button handler
def tileButtonHandler(tileName):
if playState == 1:
#send to function that does logic for displaying moves
displayValidMovesForPawn(validMoves, buttons, tileName)
elif playState == 2:
#send to function that moves pawn to new space (including handling slides), discard card, increment player, next player's turn
movePawnToPosition(buttons, tileName)
# ends turn
def endTurn(board, numPlayers):
board.deck.discardCard()
board.currentPlayer = board.currentPlayer%numPlayers + 1
# moves pawn to the tileName that is specified
def movePawnToPosition(buttons, tileName):
global playState
global activePawn
deactivateAllTileButtons(buttons)
activePawn.tileName = tileName
for otherPawn in board.pawns:
if otherPawn.player != board.currentPlayer:
if otherPawn.tileName == tileName:
sorryPawn(board, otherPawn)
if board.tiles[activePawn.tileName]['specialType'] == 'slide4':
slide(board, activePawn, 4)
elif board.tiles[activePawn.tileName]['specialType'] == 'slide5':
slide(board, activePawn, 5)
activePawn = None
if board.deck.currentCard.value == '2':
board.deck.discardCard()
else:
endTurn(board, numOfComps+1)
playState = 0
return None
# is called when a player gets knocked off the board
def sorryPawn(board, pawn):
startNumbers = [61, 62, 63, 64]
for num in startNumbers:
if board.tiles[num]['side'] == pawn.player:
newTile = num
pawn.tileName = newTile
#################### END OF FUNCTIONS ###########################
behaviorArray = []
intelligenceArray = []
newTxtObject = []
# validate computer setting input
for txt in textObjects:
txt = txt.getText()
newTxtObject.append(txt.lower())
# put behavior and intelligence settings into seperate arrays
for i in range(0,len(newTxtObject)):
if i % 2 == 0:
behaviorArray.append(newTxtObject[i])
else:
intelligenceArray.append(newTxtObject[i])
# validate behaviors the user set
for b in behaviorArray:
if b not in behaviorChoices:
if mode == 1:
mode = "computer"
elif mode == 2:
mode = "player"
mainMenu.newGame2(username, numOfComps, userColor, False, mode)
# validate intelligence that user set
for i in intelligenceArray:
if i not in intelligenceChoices:
mainMenu.newGame2(username, numOfComps, userColor, False)
if mode == 1:
mode = "computer"
elif mode == 2:
mode = "player"
mainMenu.newGame2(username, numOfComps, userColor, False, mode)
# when you get here I am assuming input is valid and a new game is being played so
# I update gamesPlayed in tblStats by 1
dbConnection.incrementGamesPlayed(dbConnection.connectDB(), username)
# Create screen and initialize clock
screen = pygame.display.set_mode((1000, 600))
clock = pygame.time.Clock()
# Create new board and shuffled deck
if numOfComps == 3:
for c in colors:
color = colors[userColor]
board = Board(boardOrientation=color, boardLocation=(350, 0))
if numOfComps == 2:
for c in colors:
color = colors[userColor]
board = Board(boardOrientation=color, boardLocation=(350, 0), playersEnabled=[True, True, True, False] )
if numOfComps == 1:
for c in colors:
color = colors[userColor]
board = Board(boardOrientation=color, boardLocation=(350, 0), playersEnabled=[True, True, False, False] )
for i in range(0,numOfComps):
print(intelligenceArray[i])
board.setComputer(i+2,intelligenceArray[i],behaviorArray[i])
# Play state variable
#1: choose valid pawn
#2: choose valid move (new tile)
#3: wait for discard
# sets locations and names all buttons that go around board and adds to buttonsn array
for i in range(1, 89):
propLocX = board.tiles[i]['pos'][0]
propLocY = board.tiles[i]['pos'][1]
propLocX = propLocX + board.boardLocation[0]
propLocY = propLocY + board.boardLocation[1]
boardBut = BoardButton(i, propLocX, propLocY)
boardButt = Button("", boardBut.getLocation(), tileButtonHandler, actionArgs=[i], name=i, buttonColor=PURPLE, backgroundColor=DARKPURPLE,
buttonSize=(35, 35), active=False, boardButton=True, boardButtObj=boardBut)
buttons.append(boardButt)
# Create buttons
drawPile = Button("Draw Card", (650, 250), board.deck.drawCard,
buttonColor=TRANSPARENT, backgroundColor=TRANSPARENT, buttonSize = (75,45))
turnDone = Button("End Turn", (175, 575), endTurn, actionArgs=[board, numOfComps+1],
buttonColor=GREEN, buttonSize = (100,30), active=False)
backButton = Button("Main Menu", (100,50), mainMenu.startPage, actionArgs=[username], buttonColor = FORESTGREEN, buttonSize=(200,30))
instructionsButton = Button("Instructions", (100,100), mainMenu.instructions, actionArgs=[username], buttonSize=(200,30),buttonColor = DARKGREY)
buttons.append(drawPile)
buttons.append(turnDone)
buttons.append(backButton)
buttons.append(instructionsButton)
# start loop to create the board
while True:
screen.fill((225, 225, 225))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
for button in buttons:
button.mouseButtonDown()
pygame.event.clear()
else:
pygame.event.clear()
# Blit board and cards to screen
board.displayBoard(screen,board)
board.displayColor(screen, int(mode))
# Blit buttons on screen
for button in buttons:
button.draw(screen)
# Blit pawns on screen
board.displayPawns(screen)
# Activate or deactivate drawPile
if board.deck.currentCard != None:
drawPile.active = False
if playState == 0:
validMoves = PossibleMoves.getValidPossibleMoves(board, board.currentPlayer)
if validMoves != []:
displayPawnsWithValidMoves(validMoves, buttons)
else:
turnDone.active = True
elif playState == 1 or playState == 2:
turnDone.active = False
else:
drawPile.active = True
turnDone.active = False
board.displayInstructions(screen, validMoves, playState, int(mode))
pygame.display.flip()
clock.tick(60)
|
5e79f7addb7828d3d855994bd2af26d28f107b63 | Naman-Kansal/python | /interviewbit/maxNonNegativeArray.py | 410 | 3.578125 | 4 | def max_non_negative_arr(A):
t = []
s = []
for i in range(len(A)):
if A[i] < 0:
if t is not []:
s.append(t)
t = []
else:
t.append(A[i])
val = []
for i in range(len(s)):
val.append(sum(s[i]))
i = val.index(max(val))
print(s[i])
max_non_negative_arr([1, 2, 5, -7, 2, 3, -1, 0, 3, 5])
|
9d2f8ab2aaa881d94740b0960200d51dd2ff7a96 | awan1/cs91_final_project | /project/webpage/static/graph-test.py | 715 | 3.515625 | 4 | """
@author: Adrian Wan
graph-test.py: a test for generating a graph visualization
"""
import networkx as nx
from networkx.readwrite import json_graph
import json
from itertools import permutations
def main():
G = nx.Graph()
# List of nodes. Nodes are tuples of (node_name, attribute_dict)
node_list = [(i, {'rt':i*3}) for i in range(1,6)]
# Add the nodes with their attribute
for node_name, attribute_dict in node_list:
G.add_node(node_name, rt=attribute_dict['rt'])
for pair in [x for x in permutations([tup[0] for tup in node_list], 2)]:
G.add_edge(*pair)
data = json_graph.node_link_data(G)
with open("graph.json", 'w') as f:
json.dump(data, f)
if __name__ == '__main__':
main() |
9cb373c9b7f48a3aedf124d678960083c867c4a2 | aglia-iu/LocationNavigation | /ApplicTests.py | 5,172 | 3.75 | 4 |
# This is the test file that tests both the LocationNode class and the Program class
# It contains two vlasses: A NodeTest Class and a ProgramTest class.
import sys
import LocationNode
from LocationNavigation import LocationNavigation
from LocationNode import LocationNode
from PySide2 import QtCore, QtWidgets, QtGui
# Used to test the LocationNode class. Must test the following:
# 1. Creating a node - both correctly and incorrectly *
# 2. Adding neighbours to the node. *
# 3. Getting each of the variables of the node and testing them to be sure they have been set correctly*
# 4. Creates multiple nodes correctly.*
class NodeTest(object):
# Tests the ability to create a Node
def test1_createNode(self):
name = "Church"
value = 0
node = LocationNode(name, value)
if (node == None):
print("test1 failed: node was not correctly initialized.")
else:
print("test1 passed!")
# Tests the ability to add Neighbours
def test2_addNeighbs(self):
# Anna and Sarah are neighbours
name1 = "Anna"
name2 = "Sarah"
value = 0
# Set 2 location nodes to one another
node1 = LocationNode(name1, value)
value += 1
node2 = LocationNode(name2, value)
# Add Sarah as Anna's neighbour
node1.addNeighbour(node2)
# Setting up the neighbour checkers
neighbour = node1.getNeighbours()
neighboursize = len(neighbour)
neighbour2 = node2.getNeighbours()
neighbour2size = len(neighbour2)
# Getting data of Anna
if(neighboursize != 1) or (neighbour[0].getName() != name2):
print("test2_a failed: expected size = 1; obtained size = "
+ str(neighboursize) + "; expected neighb = Sarah")
else:
print("test2_a passed!")
# Getting data of Sarah
if(neighbour2size != 1) or (neighbour2[0].getName() != name1):
print("test2_b failed: expected size = 1; obtained size = "
+ str(neighbour2size) + "; expected neighb = Sarah")
else:
print("test2_b passed!")
# Tests the ability to make getters and setters, and making multiple nodes successfully
def test3_GettersNSetters(self):
# There is a library next to the Diner
name1 = "Library"
name2 = "Joe's Diner"
value = 0
# We make two locationNodes out of this
node4 = LocationNode(name1, value)
value += 1
node5 = LocationNode(name2, value)
# We add the Library and the Diner as neighbours
node4.addNeighbour(node5)
# Getting data of Library
name4test = node4.getName()
neighbour4test = node4.getNeighbours()
value4test = node4.getValue()
# Getting Data of Diner
name5test = node5.getName()
neighbour5test = node5.getNeighbours()
value5test = node5.getValue()
# Get the tests for Library
if (name4test != name1) or (len(neighbour4test) != 1)or (neighbour4test[0].getName() != name2) or (value4test != 1):
print("test3_a failed: expected value = 1; obtained value = "
+ str(value4test) + "; expected neighb = Joe's Diner, obtained neighb = " + neighbour4test[0].getName() +"; expected name = Library, obtained name: "
+ name4test + "; expected length = 1, obtained length = " + str(len(neighbour4test)))
else:
print("test3_a passed!")
# Get the tests for Diner
if (name5test != name2) or (len(neighbour5test) != 1) or (neighbour5test[0].getName() != name1) or (value5test != 2):
print("test3_b failed: expected value = 2; obtained value = "
+ str(value5test) + "; expected neighb = Library, obtained neighb = " + neighbour5test[0].getName() + "obtained name: "
+ name5test+ "; expected length = 1, obtained length = " + str(len(neighbour5test)))
else:
print("test3_b passed!")
class NavigTests():
def test1_createLocation(self):
return None
def test2_removelocation(self):
return None
#def testE_testLoop(self):
# self.box = QtWidgets.QDialogButtonBox() # Adds the buttons to this box
# self.checklist = list()
# self.checkbut = QtWidgets.QCheckBox()
# neighbName = ""
# # For-Loop to create neighbouring buttons
# for x in LocationNavigation.locations:
# neighbName = str(LocationNavigation.locations[x].getName())
# self.checkbut = QtWidgets.QCheckBox(neighbName)
# self.checklist.append(self.checkbut)
# self.box.addButton(self.checkbut)
# testbut = self.checklist[len(self.checklist)-1]
# if(testbut != self.checkbut):
# print("TestEa_Failed: These two buttons aren't the same.")
if __name__ == '__main__':
NodeTest().test1_createNode()
NodeTest().test2_addNeighbs()
NodeTest().test3_GettersNSetters()
|
c0f74771800d5e1f2418aff8c0a00ea33c2ada4c | cho0op/python_databases | /movi_list_app/database.py | 2,035 | 3.6875 | 4 | import sqlite3, datetime
connection = sqlite3.connect('data.db')
def create_tables():
with connection:
connection.execute(
"CREATE TABLE IF NOT EXISTS movies ("
"id INTEGER PRIMARY KEY,"
" title TEXT,"
" release_timestamp REAL)")
connection.execute(
"CREATE TABLE IF NOT EXISTS users ("
"username TEXT PRIMARY KEY )")
connection.execute(
"CREATE TABLE IF NOT EXISTS watched ("
"user_username TEXT,"
" movie_id INTEGER,"
" FOREIGN KEY (user_username) REFERENCES users(username),"
" FOREIGN KEY (movie_id) REFERENCES movies(id)) ")
def add_movie(title, release_timestamp):
with connection:
connection.execute("INSERT INTO movies (title, release_timestamp) VALUES (?,?);", (title,
release_timestamp))
def add_user(username):
with connection:
connection.execute("INSERT INTO users VALUES (?)", (username,))
def get_movies(upcoming=False):
cursor = connection.cursor()
if upcoming:
today_timestamp = datetime.datetime.today().timestamp()
cursor.execute("SELECT * FROM movies WHERE release_timestamp>?;", (today_timestamp,))
else:
cursor.execute("SELECT * FROM movies;")
return cursor.fetchall()
def get_watched_movies(watcher_name, upcoming=False):
cursor = connection.cursor()
cursor.execute(
"SELECT movies.* FROM movies JOIN watched ON movies.id=watched.movie_id WHERE watched.user_username=?",
(watcher_name,))
return cursor.fetchall()
def watch_movie(username, movie_id):
with connection:
connection.execute("INSERT INTO watched (user_username, movie_id) VALUES (?,?)", (username, movie_id,))
def search_movie(title):
like_title = f"%{title}%"
cursor=connection.execute("SELECT * from movies WHERE title LIKE ?", (like_title,))
return cursor.fetchall() |
00ebff5e2473d63861d0cc16f78ce8e8b450509c | declau/python-beginner-projects | /madlibs/madlibs.py | 651 | 4.125 | 4 | # # String concatenation - (Como coocar strings juntas)
# # Vamos supor que você quira criar uma String que diga "Subscribe to ______"
youtuber = "Denis Claudiano" # Alguma variável string
# # Alguns modos de se fazer isso!
# print("Subscribe to " + youtuber)
# print("Subscribe to {}".format(youtuber))
# print(f"Subscribe to {youtuber}")
adj = input("Adjetivo: ")
verb1 = input("Verbo: ")
verb2 = input("Verbo: ")
pessoa_famosa = input("Pessoa famosa: ")
madlib = f"Desenvolvimento de software é tão {adj}! Isso me deixa animado o tempo todo porque eu \
amo muito {verb1}. Me manten Focado e {verb2} como se eu fosse {pessoa_famosa}!"
print(madlib)
|
707869713e87750ec6c1356f4defc3e68f9ea242 | karadisairam/Loops | /45.py | 259 | 4.21875 | 4 | for x in range(5):
print(x)
#To display numbers 0 to 10:
for x in range(11):
print(x)
#Odd numbers in 0 to 20 :
for x in range(21):
if x%2!=0:
print(x)
#Even numbers :
for i in range(10):
if i%2==0:
print(i) |
dbb6f5a0d9624b3f4e4e8b9f1e2e588bd33b2669 | OlhaHolysheva/Python_Cor_HW | /Are You Playing Banjo.py | 269 | 3.796875 | 4 | def areYouPlayingBanjo(name):
# Implement me!
#for i in name:
#name = str(name)
if name[0] == 'R' or name[0] == 'r':
return name + "plays banjo"
else:
return name + " does not play banjo"
print(areYouPlayingBanjo('olga')) |
d8ef635900411b6d943de59efa7ab0b038dd08eb | love-adela/algorithm-ps | /codeit/fibonacci.py | 160 | 3.84375 | 4 | # Time Complexity : O(2 ** n)
def fibo(n):
if n == 1 or n == 2:
return 1
return fibo(n-1) + fibo(n-2)
for i in range(1, 11):
print(fibo(i)) |
eb64ab2304d1c83b2b0c6471d6b578c525830102 | Ken2399/326-Group-Project | /final.py | 2,177 | 4.25 | 4 | class Account:
"""Create an account that will either be used to be a customer or an online retailer. """
def __init__(self, account_type, username, birthday, address, email, password):
def change_login_credentials():
""" Purpose: to edit login credentials (update email, chang username, etc. Args: login information. """
class Product:
"""Creates a product to be listed in the store with the vendor name, a description, and the price"""
def __init__(self, desc, price, reviews, inventory_size):
def set_product_information():
"""Sets the product object with the given name, description, price, and rating"""
class Inventory:
"""Provides a list of all the products in the store with the amount left available for each product"""
def __init__(self):
def add_inventory():
"""Purpose: Add products to inventory. Args: Product(a product object): product that’s being added to the inventory.Quantity(int): quantity of a product. Returns: List of products with newly added values. """
def change_inventory():
""" Removing or editing the inventory. Args: Product(a product object): product that’s being edited. Quantity(int: updated quantity of a product. Returns: An updated list of inventory. """
class Cart:
"""Calculate final checkout price of the order with the option to add or remove from cart and to add a discount code. """
def __init__(self):
def add_to_cart():
""""Adds products from shopping cart Returns: An updated shopping cart """
def remove_from_cart():
""""Removes products from shopping cart Returns: An updated shopping cart """
def cost(discount, shipping, tax):
"""Determines the checkout price for the order by including the shipping cost and discount Args: discount codes, Shipping cost. Returns: Float of the final checkout price"""
def currency_exchange(price):
""" Returns the final price of the item in the customer's currency. Args: Original Price, Final price in desired currency."""
|
769faf22bd9361a9ead99cddb22e211785112994 | vishal-asrani/tutorials | /python/itertools/chain.py | 332 | 3.609375 | 4 | from itertools import *
a = [0,1,2,3,4,5]
b = ['zero', 'one', 'two', 'three', 'four', 'five']
c = ['a', 'b', 'c', 'd', 'e', 'f']
print(list(chain(a,b,c)))
# [0, 1, 2, 3, 4, 5, 'zero', 'one', 'two', 'three', 'four', 'five', 'a', 'b', 'c', 'd', 'e', 'f']
print(list(chain(a[0:],b[:1],c[0:2])))
# [0, 1, 2, 3, 4, 5, 'zero', 'a', 'b'] |
5ba454ac6522ceb80956f78d5ae0cbeef708c46e | Vineet2000-dotcom/Competitive-Programming | /CODECHEF/June Starters/TOTCRT.py | 456 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 10:17:16 2021
@author: Vineet
"""
t=int(input())
for i in range(t):
n=int(input())
d1={}
list1=[]
for i in range(n*3):
x,y=map(str,input().split())
if x not in d1:
d1[x]=int(y)
else:
d1[x]=d1[x]+int(y)
x=list(d1.values())
x.sort()
print(*x)
|
384e0d96bfd3d7b0a43d0fcbd8d5a96ce7f9058c | Priyansh-Kedia/MLMastery | /24_feature_importance.py | 6,831 | 4.46875 | 4 | # Feature importance refers to a class of techniques for assigning scores
# to input features to a predictive model that indicates the relative
# importance of each feature when making a prediction.
# We will create test dataset with 5 important and 5 unimportant features
# Dataset would be created both for classification as well as regression
from math import perm
from sklearn import feature_selection
from sklearn.datasets import make_classification
# Create a classification dataset
seed = 32
X, Y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=seed)
# Create a regresion dataset
from sklearn.datasets import make_regression
X_reg, Y_reg = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=seed)
# Linear regression feature importance
# We can fit a linear regression model on the data, and then get the coefficient values for the
# input features. This assumes that the input features had the same scale before training
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt
model = LinearRegression()
model.fit(X_reg, Y_reg)
importance = model.coef_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Logistic Regresion feature importance
# The same process of retrieval of coefficients after the model is fit can be applied
# on Logistic Regression. This also assumes that the input features had the same scale before training
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X, Y)
importance = model.coef_[0]
# In case of Logistic Regression, coef_ returns a 2D array, this can be checked by print(model.coef_)
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# We will be able to see that there a negative coefficients too, which does not mean,
# that they are of less importance. A positive coefficient indicates the weight of the
# features towards 1, and negative coefficient indicates towards 0, in a problem where
# 0 and 1 are classes
# Decision Tree Feature Importance
# CART Feature Importance
# Regression
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Random forest feature importance
# Regression
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
for i,v in enumerate(importance):
print("Feature: %0d, Score: %.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classfication
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i,v in enumerate(importance):
print("Feature: %0d, Score: %.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# XGBoost feature importance
# XGBoost is a library that provides an efficient and effective implementation of
# the stochastic gradient boosting algorithm.
# Regression
from xgboost import XGBRegressor
model = XGBRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
print(importance)
for i,v in enumerate(importance):
print("Feature: %0d, Score: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from xgboost import XGBClassifier
model = XGBClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i, v in enumerate(importance):
print("Feature: %0d, Score: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Permuation feature importance
# First, a model is fit on the dataset, such as a model that does not support native feature
# importance scores. Then the model is used to make predictions on a dataset, although the
# values of a feature (column) in the dataset are scrambled. This is repeated for each feature
# in the dataset. Then this whole process is repeated 3, 5, 10 or more times. The result is a
# mean importance score for each input feature (and distribution of scores given the repeats).
from sklearn.neighbors import KNeighborsRegressor
from sklearn.inspection import permutation_importance
# Regression
model = KNeighborsRegressor()
model.fit(X_reg, Y_reg)
results = permutation_importance(model, X_reg, Y_reg, scoring='neg_mean_squared_error')
importance = results.importances_mean
for i, v in enumerate(importance):
print("Feature %0d, Scoring: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
model.fit(X,Y)
result = permutation_importance(model,X,Y, scoring='accuracy')
importance = result.importances_mean
for i,v in enumerate(importance):
print("Feature: %0d, Scoring: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Feature selection with importance
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
model = LogisticRegression(solver='liblinear')
model.fit(X_train, Y_train)
yhat = model.predict(X_test)
accuracy = accuracy_score(Y_test, yhat)
print('Accuracy: %.2f' % (accuracy*100))
from sklearn.feature_selection import SelectFromModel
# The first parameter is the model we wish to use
# The second parameter is the maximum number of features to be chosen
feature_selection = SelectFromModel(RandomForestClassifier(n_estimators=200), max_features=5)
# Learn the relationship between input and output
feature_selection.fit(X_train, Y_train)
X_train_fs = feature_selection.transform(X_train)
X_test_fs = feature_selection.transform(X_test)
model = LogisticRegression(solver='liblinear')
model.fit(X_train_fs, Y_train)
# evaluate the model
yhat = model.predict(X_test_fs)
# evaluate predictions
accuracy = accuracy_score(Y_test, yhat)
print('Accuracy: %.2f' % (accuracy*100)) |
0c9537118e144859a65068d1923ded156e4f0cae | alexandraback/datacollection | /solutions_5738606668808192_0/Python/pilagod/3.py | 1,150 | 3.5625 | 4 | class Solution(object):
def getJamcoins(self, n, j):
maxJamcoins = (1 << n) - 1
curJamcoins = (1 << (n - 1)) + 1
result = ""
count = 0
while count < j and curJamcoins < (maxJamcoins - 1):
curJamcoins += 2
binaryJamcoins = "{0:b}".format(curJamcoins)
isPrimeFlag = False
for base in range(2, 11):
if int(binaryJamcoins, base) % (base + 1) != 0:
isPrimeFlag = True
if not isPrimeFlag:
result += "{0} {1}\n".format(binaryJamcoins, ' '.join([str(i) for i in range(3, 12)]))
count += 1
return result
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(input()) # read a line with a single integer
test = Solution()
for i in range(1, t + 1):
testCase = input().split(' ')
n = int(testCase[0])
j = int(testCase[1])
print("Case #{}:\n{}".format(i, test.getJamcoins(n, j)), end="")
# check out .format's specification for more formatting options
|
9bff0918f45312c8657a2fd45baf034daa32995d | maksik228/info11 | /Урок 2/задание 6 стр 18.py | 99 | 3.71875 | 4 | n=int(input())
if n%2==0 or n%3==0:
print("истина")
else:
print("ложь")
|
f86b8c3612bd32446def10008bec3a6d76e34fc8 | Tabish596/Data-Structure-Algo | /stack.py | 977 | 4.0625 | 4 | class node:
def __init__(self,value):
self.value = value
self.next = None
class stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def peek(self):
if self.top is not None:
print(self.top)
return
def push(self,data):
new = node(data)
if self.length == 0:
self.bottom = new
self.top = new
self.length+=1
return
new.next = self.top
self.top = new
self.length+=1
def pop(self):
temp = self.top
self.top = temp.next
temp = None
self.length-=1
def printst(self):
temp = self.top
while(temp):
print(temp.value)
temp = temp.next
if __name__ == '__main__':
nstack = stack()
nstack.push(15)
nstack.push(6)
nstack.push(1)
nstack.push(8)
nstack.pop()
nstack.printst()
|
8030283a380430ff1fd340385caac318be4b5ece | joymajumder1998/Coding-By-Joy-Majumder | /dummy python code templates/linkedlist.py | 871 | 3.671875 | 4 | class Node:
def __init__(self,value):
self.value=value
self.link=None
class List:
def __init__(self):
self.header=None
def insert(self,value):
new=Node(value)
if(self.header==None):
self.header=new
return
ptr=self.header
while(ptr.link!=None):
ptr=ptr.link
ptr.link=new
def display(self):
ptr=self.header
while(ptr):
print(ptr.value,end=" ")
ptr=ptr.link
def Reverse(self,ptr):
if(ptr.link==None):
return ptr[]
if(ptr.link.link==None):
ptr.link.link=ptr
self.Reverse(ptr.link)
def reverse(self):
self.Reverse(self.header)
|
384b416b41f73235fa6531980575dd43a509da68 | seetwobyte/news | /aiden-4advance.py | 236 | 3.953125 | 4 | import turtle
fred = turtle.Pen()
fred.speed(0)
fred.color("purple")
fred.width(5)
for i in range(100):
fred.forward(i * 2)
fred.circle(i * 2, 90)
fred.right(20)
# then hit the enter key and watch the magic
# purple spiral
|
5e30c802ff80c9718cb7f11de62e97195567adad | zarev/interview-bootcamp | /arrays.py | 3,017 | 3.5625 | 4 | def rev_slice(string):
if(type(string) == str): print(string[::-1])
def rev_for(string):
for char in range(len(string), 0, -1):
print(string[char-1])
def mergeSorted(arr1, arr2):
# check input
if(len(arr1) == 0): return arr2
if(len(arr2) == 0): return arr1
merged = []
i, j = 0, 0
len1, len2 = len(arr1), len(arr2)
# while there are 2 arrays
while(i<len1 and j<len2):
if(arr1[i] < arr2[j]):
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# if only arr1 left
t1,t2=0,0
while(i < len1):
merged.append(arr1[i])
i += 1
# if only arr2 left
while(j < len2):
merged.append(arr2[j])
j += 1
return merged
def max_sub_sum(arr):
if(not arr): raise ValueError('Array must not be empty.')
running_max = arr[0]
maxses = [running_max]
for i in range(len(arr)-1):
nxt = arr[i+1]
running_max = max(nxt, running_max + nxt)
maxses.append(running_max)
return max(maxses)
# maxSum = [arr[0]]*len(arr)
# for i in range(len(arr)-1):
# maxSum[i] = max( arr[i], arr[i] + maxSum[i - 1] )
# return max(maxSum)
def moveZeroes(arr):
# input: [0,1,0,3,12]
# output: [1,3,12,0,0]
# edge cases:
# asumptions: in-line, w/o array copy
count = arr.count(0)
# [arr.remove(i) for i in arr if i==0]
arr = [i for i in arr if i!=0]
arr+= [0]*count
return arr
def containtsDuplicates(arr):
return len(arr) > len(set(arr))
def rotate(arr, k):
"""
Do not return anything, modify nums in-place instead.
[-1, -100, 3, 99], k=2
"""
def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
lenn = len(arr)
k = k % lenn
# reverse the whole list
# then each side of k
reverse(arr, 0, lenn-1)
reverse(arr, 0, k - 1)
reverse(arr, k, lenn-1)
def first_reccuring(arr):
hash = {}
for n in arr:
if n in hash: return n
# if not found add to hash
else: hash[n] = n
def main():
# rev_for('my name is')
# rev_slice('hi my name is')
# arr = [0,1,2,3]
# k = 3
# for i in range(len(arr)):
# new_i = (i+k) % len(arr)
# sorted1 = [0,3,4,31,32]
# sorted2 = [4,6,30]
# two_sum_arr = [2,7,11,15]
# max_sub_arr = [-2,1,-3,4,-1,2,1,-5,4]
# in_line_arr = [0,1,0,3,12]
# arr_rotate = [-1, -100, 3, 99]
first_reccur = [3,1,4,2,3]
# target = 9
# print(mergeSorted(arr1, arr2))
# print(two_sum(two_sum_arr, target))
# print(max_sub_sum(max_sub_arr))
# print(moveZeroes(in_line_arr))
# print(containtsDuplicates([3,3]))
# print(len(sorted1) > len(set([1,1])))
# print(rotate(arr_rotate,2))
print(first_reccuring(first_reccur))
# [start:stop:step]
main()
|
0c9274cb5d5edfc9edda48f2061f1e4d0b27d501 | Piersoncode11/Python-Project-PM | /Area of Circle Challenge PM.py | 435 | 4.09375 | 4 | print("What is the radius of the circle?")
radius = float(raw_input())
area = radius * radius * 3.14
print(area)
print("What is the radius of the sphere")
radius = float(raw_input())
volume = 4.71 * int(radius) ** 3
print(volume)
print("What is the value for x?")
x = float(raw_input())
x = int(x)
print("What is the value for y?")
y = float(raw_input())
y = int(y)
xy = x + y
xy = int(xy)
print(xy * xy)
|
67707d50f2c85e05ece4153e1d7d085c8e4a83c3 | lanestevens/aoc2017 | /day03/d3-2.py | 1,661 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import sys
def next_coordinate(xy):
#special case for origin
if xy == (0, 0):
return (1, 0)
#Bottom right - move out to the right
if xy[0] > 0 and xy[0] == -xy[1]:
return (xy[0] + 1, xy[1])
#Top right - move to the left
if xy[0] > 0 and xy[0] == xy[1]:
return (xy[0] - 1, xy[1])
#Top left - move down
if xy[0] < 0 and xy[0] == -xy[1]:
return (xy[0], xy[1] - 1)
#Bottom left - move right
if xy[0] < 0 and xy[0] == xy[1]:
return (xy[0] + 1, xy[1])
#Mid right - move up
if xy[0] > 0 and abs(xy[0]) > abs(xy[1]):
return (xy[0], xy[1] + 1)
#Mid top - move left
if xy[1] > 0 and xy[1] > abs(xy[0]):
return (xy[0] - 1, xy[1])
#Mid left - move down
if xy[0] < 0 and abs(xy[0]) > abs(xy[1]):
return (xy[0], xy[1] - 1)
#Bottom - move right:
if xy[1] < 0 and abs(xy[0]) < abs(xy[1]):
return (xy[0] + 1, xy[1])
target = int(sys.stdin.readline().strip())
ram = {}
for i in range(1, target + 1):
if i == 1:
xy = (0, 0)
ram[xy] = 1
else:
xy = next_coordinate(xy)
ram[xy] = ram.get((xy[0] + 1, xy[1]), 0)\
+ ram.get((xy[0] - 1, xy[1]), 0)\
+ ram.get((xy[0], xy[1] + 1), 0)\
+ ram.get((xy[0], xy[1] - 1), 0)\
+ ram.get((xy[0] + 1, xy[1] + 1), 0)\
+ ram.get((xy[0] + 1, xy[1] - 1), 0)\
+ ram.get((xy[0] - 1, xy[1] + 1), 0)\
+ ram.get((xy[0] - 1, xy[1] - 1), 0)
if ram[xy] > target:
print ram[xy]
break
|
ab4bf0a513379c8f7494182f4c12dab293ea7c21 | hzwangchaochen/red-bull | /leetcode/python/reverse_linked_list.py | 613 | 4.125 | 4 | class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
def reverse_linked_list(self,root):
dummy_node=None
while root:
next = root.next
root.next = dummy_node
dummy_node = root
root = next
return dummy_node
if __name__ == '__main__':
solution = Solution()
node=ListNode(2,ListNode(3,ListNode(4,ListNode(5,ListNode(6,None)))))
new_node=solution.reverse_linked_list(node)
while new_node:
print(new_node.val)
new_node=new_node.next
|
8d4dcb6368819ce68d842ac0ab223ac0bc91e5cb | Journalisme-UQAM/devoir-1-NoemieLaurendeau | /devoir1JHR.py | 251 | 3.546875 | 4 | #coding: utf-8
for annee in range(1930,2018) :
for numero in range (0,1000) :
print(str(annee)[2:] + format(numero,"03d"));
# Excellent! Ça fonctionne super bien!
# Tes deux scripts sont identiques, alors je ne commente que celui-ci :) |
fadb0e01793da124749b6a705a2dbb1c85e10ce4 | guogenjuan/python | /pythonScipt/mutiPlus.py | 239 | 3.734375 | 4 | def mutiPlus():
s=''
for j in range(9):
for i in range(9):
if j>=i:
s = (i+1)*(j+1)
print(str(i+1)+'*'+str(j+1)+'='+str(s)+' ',end='')
print()
mutiPlus()
|
b5eb4a320f463ff2b911cc78b2a2b274cb1a40f6 | yurijvolkov/mmb | /algo.py | 4,526 | 4.03125 | 4 | import time
import math
import numpy as np
def straightway(A, B):
"""
Simplest way to multiply matrices.
(By rowXcolumns rule)
Time complexity: O(N^3)
:param A: np.ndarray
:param B: np.ndarray
:return: np.ndarray
"""
if A.shape[1] != B.shape[0]:
raise ValueError('Shapes are incorrect {A.shape[1] != B.shape[0]}')
C = np.ndarray( (A.shape[0], B.shape[1]) )
for i in range(A.shape[0]):
for j in range(B.shape[1]):
C_ij = 0
for k in range(A.shape[1]):
C_ij += A[i, k] * B[k, j]
C[i, j] = C_ij
return C
def strassen(A, B):
"""
Strassen algorithm implented as it described in
Matrix analysis and linear algebra ( by E. E. Tyrtyshnikov )
Time complexity: ~O(N^2.8)
:param A: np.ndarray
:param B: np.ndarray
:return: np.ndarray
"""
init_shape_A = A.shape
init_shape_B = B.shape
def _wrap_matrix_(M, n):
if M.shape[0] != n:
diff = n - M.shape[0]
M = np.append(M, [[0] * M.shape[1]] * diff, axis=0)
if M.shape[1] != n:
diff = n - M.shape[1]
M = np.append(M, [[0] * diff] * M.shape[0], axis=1)
return M
if ( not( A.shape[0] == A.shape[1] == B.shape[1] )
or( np.log2(A.shape[0]) % 1 != 0) ):
n = max(A.shape[0], A.shape[1], B.shape[1])
n = 2 ** math.ceil(np.log2(n))
A = _wrap_matrix_(A, n)
B = _wrap_matrix_(B, n)
C = _strassen_rec(A, B)
return C[:init_shape_A[0], :init_shape_B[1]]
def _strassen_rec(A, B):
"""
Recursive part of Strassen algo.
(MUST NOT BE USED DIRECTLY)
"""
if A.shape[0] <= 16:
return straightway(A, B)
else:
n = A.shape[0]
a11 = A[:n//2, :n//2]
a12 = A[:n//2, n//2:]
a21 = A[n//2:, :n//2]
a22 = A[n//2:, n//2:]
b11 = B[:n//2, :n//2]
b12 = B[:n//2, n//2:]
b21 = B[n//2:, :n//2]
b22 = B[n//2:, n//2:]
k1 = _strassen_rec(a11 + a22, b11 + b22)
k2 = _strassen_rec(a21 + a22, b11)
k3 = _strassen_rec(a11, b12 - b22)
k4 = _strassen_rec(a22, b21 - b11)
k5 = _strassen_rec(a11 + a12, b22)
k6 = _strassen_rec(a21 - a11, b11 + b12)
k7 = _strassen_rec(a12 - a22, b21 + b22)
c11 = k1 + k4 - k5 + k7
c12 = k3 + k5
c21 = k2 + k4
c22 = k1 + k3 - k2 + k6
C = np.block([ [c11, c12],
[c21, c22] ])
return C
def winograd(A, B):
"""
Winograd algorithm implented as it described in
Matrix analysis and linear algebra ( by E. E. Tyrtyshnikov )
It does less multiplications than 'Straight way' algo.
Time complexity: O(N^3)
:param A: np.ndarray
:param B: np.ndarray
:return: np.ndarray
"""
init_shape_A = A.shape
init_shape_B = B.shape
if A.shape[1] % 2 == 1:
A = np.append(A, [[0]] * A.shape[0], axis=1)
B = np.append(B, [[0] * A.shape[0]], axis=0)
m = A.shape[1] // 2
a_term = np.sum( [ [A[i, 2*k - 1] * A[i, 2*k] for k in range(m) ]
for i in range(A.shape[0]) ],
axis=1)
b_term = np.sum( [ [B[2*k, j] * B[2*k - 1, j] for k in range(m) ]
for j in range(B.shape[1]) ],
axis=1)
C = np.ndarray((A.shape[0], B.shape[1]))
for i in range(A.shape[0]):
for j in range(B.shape[1]):
C_ij = 0
for k in range(0, m):
C_ij += (A[i, 2*k - 1] + B[2*k, j]) * (B[2*k-1, j] + A[i, 2*k])
C_ij -= a_term[i] + b_term[j]
C[i,j] = C_ij
return C[:init_shape_A[0], :init_shape_B[1]]
def check_multiplication(func):
"""
Compares implemented algorithm with algo
implemented in numpy
:param func: function
:return: bool
"""
A = np.random.rand(121, 100)
B = np.random.rand(100, 119)
C_numpy = A @ B
C_custom = func(A, B)
error = abs(C_numpy - C_custom)
if np.mean(error, (0, 1)) > 1e-5:
return False
return True
if __name__ == "__main__":
print(f"Straightway correct: {check_multiplication(straightway)}")
print(f"Strassen correct: {check_multiplication(strassen)}")
print(f"Winograd correct: {check_multiplication(winograd)}")
|
0ff661aeac659a56163cd8c0f3aa1aa68fae6246 | romariick/python_learning | /controlflow/controlflow.py | 121 | 3.75 | 4 |
x = int(raw_input("Please entrer un number"))
if x > 0 :
print "Superieur zero "
else:
print "Inferieur zero" |
f7e6f8981704180874b965a671be4bfe5c75630f | junwon-0313/PythonBasic | /python/Input,Output/2.py | 294 | 3.71875 | 4 | in_str = input("2자리 숫자의 암호를 대시오! \n")
#print(type(in_str))
#change data type , match is neccessary
real_junwon = '11'
real_lee = "22"
if real_junwon == in_str:
print("Hello Junwon")
elif real_lee == in_str:
print("Hello lee")
else:
print("로그인 실패!")
|
44f97e7ecbaeb7464604e020cd665ae6db72796d | cmurphy/netsec | /lab2/p3_tcp_server.py | 460 | 3.53125 | 4 | # Problem 3: Follow the example code at python.org to write a TCP server. Listen on TCP port 2003 for a message containing the flag.
import socket
TCP_IP = '192.168.14.149'
TCP_PORT = 2003
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.bind((TCP_IP, TCP_PORT))
sock.listen(1)
conn, addr = sock.accept()
#conn.send("GET FLAG")
while True:
data = conn.recv(1024)
if not data: break
print "received data: ", data
conn.close()
|
50f40f5809746916dad0992e7f2a0f4bca7cb77b | formigaVie/SNWD_Works_201711 | /Class08/example.py | 548 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# define variable name
creator = "FormigaVIE"
# print welcome to user
print "=" *80
print "Welcome to {} example" .format(creator)
print "=" *80
# Put Make string lower case to a personal greeting
user=raw_input("\nPlease enter your name: ")
print "\n Hello {}, pleasure to have you here at example" .format(user.lower())
print "=" *80
DIGITS = 2
# Round notwendig da er es nicht versteht nich 0.2 sondern 0.199999999*
if round(float(0.2 + 0.1),DIGITS) == 0.3:
print True
else:
print False
|
9e7d83dfb56184f30cb8fcd4adb48f43c6166a35 | caiosuzuki/exercicios-python | /ex036.py | 373 | 3.9375 | 4 | casa = float(input('Digite o valor da casa: R$'))
salario = float(input('Informe seu salário: R$'))
anos = int(input('Em quantos anos quer pagar? '))
prestacao = casa / (anos * 12)
if prestacao > salario * 0.3:
print('Empréstimo negado! O valor da prestação (R${:.2f}) excede 30% do seu salário'.format(prestacao))
else:
print('Seu empréstimo foi aprovado!')
|
4f0b3ad0db4a5d1514059e6acd37edfb0f7060d9 | Stefan1502/Practice-Python | /exercise 29.py | 1,020 | 4.34375 | 4 | # This exercise is Part 1 of 3 of the Hangman exercise series. The other exercises are: Part 2 and Part 3.
# In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary. Download this file and save it in the same directory as your Python code. This file is Peter Norvig’s compilation of the dictionary of words used in professional Scrabble tournaments. Each line in the file contains a single word.
# Hint: use the Python random library for picking a random word.
# Aside: what is SOWPODS
# SOWPODS is a word list commonly used in word puzzles and games (like Scrabble for example). It is the combination of the Scrabble Player’s Dictionary and the Chamber’s Dictionary. (The history of SOWPODS is quite interesting, I highly recommend reading the Wikipedia article if you are curious.)
import random
with open('/home/stefan/Desktop/exercises/sowpods.txt', 'r') as f:
words = list(f)
word = random.choice(words).strip()
print(word)
|
e4a56364774f93b0418e4f01a70c6aba86ec328a | SaifullahKatpar/pyusgs | /test.py | 732 | 3.6875 | 4 | # using the requests library to access internet data
#import the requests library
import requests
def main():
# Use requests to issue a standard HTTP GET request
url = "https://waterservices.usgs.gov/nwis/site/?format=rdb&stateCd=ri"
result = requests.get(url)
printResults(result)
def printResults(resData):
print("Result code: {0}".format(resData.status_code))
print("\n")
print("Headers: ----------------------")
print(resData.headers)
print("\n")
print("Returned data: ----------------------")
#print(resData.text)
lines = resData.text.splitlines()
for l in lines:
if not l.startswith('#'):
print(l.split('\t'))
if __name__ == "__main__":
main()
|
2166230a514bb1845fb3b1e070008964163cde37 | sivagopi204/python | /day7-2.py | 1,468 | 3.828125 | 4 |
def getCofactor(mat, temp, p, q, n):
i = 0
j = 0
# Looping for each element
# of the matrix
for row in range(n):
for col in range(n):
# Copying into temporary matrix
# only those element which are
# not in given row and column
if (row != p and col != q) :
temp[i][j] = mat[row][col]
j += 1
# Row is filled, so increase
# row index and reset col index
if (j == n - 1):
j = 0
i += 1
# Recursive function for
# finding determinant of matrix.
# n is current dimension of mat[][].
def determinantOfMatrix(mat, n):
D = 0 # Initialize result
# Base case : if matrix
# contains single element
if (n == 1):
return mat[0][0]
# To store cofactors
temp = [[0 for x in range(N)]
for y in range(N)]
sign = 1 # To store sign multiplier
# Iterate for each
# element of first row
for f in range(n):
# Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n)
D += (sign * mat[0][f] *
determinantOfMatrix(temp, n - 1))
# terms are to be added
# with alternate sign
sign = -sign
return D
def isInvertible(mat, n):
if (determinantOfMatrix(mat, N) != 0):
return True
else:
return False
# Driver Code
mat = [[ 1, 0, 2, -1 ],
[ 3, 0, 0, 5 ],
[ 2, 1, 4, -3 ],
[ 1, 0, 5, 0 ]];
N = 4
if (isInvertible(mat, N)):
print("Yes")
else:
print("No")
|
2b8b6001e170c41c895569e44e4d3d871dd29a40 | krother/Python3_Package_Examples | /json/example_json.py | 232 | 3.921875 | 4 |
import json
# Convert a dictionary to a JSON-formatted string:
data = {'first': 1, 'second': 'two', 'third': [3,4,5]}
jj = json.dumps(data)
print(jj)
# Convert JSON string back to a Python dictionary:
d = json.loads(jj)
print(d)
|
f0b24e787e4fd3f49a662eca77dfd95821041256 | gsrini27/Books-BK-PythonCookbook3rd | /Chapter1-Data_Structures _and_Algorithms/p1.8.py | 386 | 3.875 | 4 | # Calculating with Dictionaries
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
print(prices.keys(), prices.values())
# zip() creates an items that can only be consumed once s
min_price = min(zip(prices.values(), prices.keys()))
print(min_price)
prices_sorted = sorted(zip(prices.values(), prices.keys()))
print(prices_sorted) |
38f19472dfa2d351e68d03a443f8686f28d16349 | ManishShah120/Python_Basics | /Day6/Dictionaries.py | 463 | 3.734375 | 4 | '''
Dictionaries in Python is similar to STRUCTURE in C
Dictionaries contains
Dictionary = {"KEY":"Values",}
'''
Customer = {
"Name":"Manish",
"Age":21,
"Gender":"Male",
"Is_Verified": True
}
#print(Customer.get("name"))#None is an object with no value
Customer["Name"] = "Kumar"
print(Customer.get("Birthdate","Oct 14 1999"))
print(Customer["Name"])
Customer["Country"] = "India"
print(Customer["Country"])
|
dfa481fbc92f0870556d21482296f476acc53230 | SubhoBasak/MachineLearning | /GradientDescent/gradient_descent.py | 1,107 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
x = [1, 3, 2, 5, 3, 4, 6, 2]
y = [2, 2, 1, 4, 3, 5, 6, 3]
m = b =0
lrn = 0.1
line = lambda X: m*X+b
#line = lambda X: model.coef_*X+model.intercept_
def graph(func, x_range):
x_points = np.array(x_range).reshape(-1, 1)
y_points = eval(func)
plt.scatter(x, y)
plt.plot(x_points, y_points)
plt.show()
def plot_line(func, x_points):
x_points = range(int(min(x_points))-1, int(max(x_points))+1)
y_points = [func(i) for i in x_points]
plt.scatter(x, y)
plt.plot(x_points, y_points)
plt.show()
def summetion(func, x_points, y_points):
t1 = t2 = 0
for i in range(len(x_points)):
t1 = func(x_points[i])- y_points[i]
t2 = t1*x_points[i]
return t1/len(x_points), t2/len(x_points)
model = LinearRegression()
model.fit(np.array(x).reshape(-1, 1), y)
#graph('model.coef_*x_points+model.intercept_', range(0, 8))
#plot_line(line, x)
for i in range(50):
s1, s2 = summetion(line, x, y)
m = m- lrn*s1
b = b- lrn*s2
plot_line(line, x)
|
8125f287d64e90d807a8ee7016e3709ee68ea41e | wsgan001/PyFPattern | /Data Set/bug-fixing-4/4b8aebca6a302429a90e5713afc635b1bc35edb1-<jaccard_distance>-fix.py | 569 | 3.65625 | 4 | def jaccard_distance(set1, set2):
'Calculate Jaccard distance between two sets\n\n Parameters\n ----------\n set1 : set\n Input set.\n set2 : set\n Input set.\n\n Returns\n -------\n float\n Jaccard distance between `set1` and `set2`.\n Value in range [0, 1], where 0 is min distance (max similarity) and 1 is max distance (min similarity).\n '
union_cardinality = len((set1 | set2))
if (union_cardinality == 0):
return 1.0
return (1.0 - (float(len((set1 & set2))) / float(union_cardinality))) |
785f696325670ebe70bebdb6f1115bde6e78e89a | matthewrmettler/project-euler | /Problems 1 through 50/problem48_self_powers.py | 279 | 3.59375 | 4 | '''
Author: Matthew Mettler
Project Euler, Problem 1
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
Status: Correct
'''
print(str(sum([int(str(value**value)[-10:]) for value in range(1, 1001)]))[-10:]) |
662d44fffc457d8140d5783f9b9021243b563b21 | Agusef22/Python | /CursoBasicoDePython/Listas.py | 2,601 | 4.65625 | 5 | """**append()**Este método agrega un elemento al final de una lista.
**count()**Este método recibe un elemento como argumento, y cuenta la cantidad de veces que aparece en la lista.
**extend()**Este método extiende una lista agregando un iterable al final.
**index()**Este método recibe un elemento como argumento, y devuelve el índice de su primera aparición en la lista.
**insert()**Este método inserta el elemento x en la lista, en el índice i.
**pop()**Este método devuelve el último elemento de la lista, y lo borra de la misma.
**remove()**Este método recibe como argumento un elemento, y borra su primera aparición en la lista.
**reverse()**Este método invierte el orden de los elementos de una lista.
**sort()**Este método ordena los elementos de una lista.
**Convertir a listas**Para convertir a tipos listas debe usar la función list() la cual esta integrada en el interprete Python."""
"""append()
Añade un ítem al final de la lista:
lista = [1,2,3,4,5]
lista.append(6)
print(lista)
# [1, 2, 3, 4, 5, 6]
clear()
Vacía todos los ítems de una lista:
lista = [1,2,3,4,5]
lista.clear()
#[]
extend()
Une una lista a otra:
l1 = [1,2,3]
l2 = [4,5,6]
l1.extend(l2)
#[1, 2, 3, 4, 5, 6]
count()
Cuenta el número de veces que aparece un ítem:
["Hola", "mundo", "mundo"].count("Hola")
#1
index()
Devuelve el índice en el que aparece un ítem (error si no aparece):
["Hola", "mundo", "mundo"].count("Hola")
#0
insert()
Agrega un ítem a la lista en un índice específico:
l = [1,2,3]
l.insert(0,0) #(index , element) first position 0, second last position -1
#last position len
# [ 0, 1 , 2 , 3 ]
pop()
Extrae un ítem de la lista y lo borra:
l = [10,20,30,40,50]
print(l.pop())
print(l)
#50
#[10, 20, 30, 40]
Podemos indicarle un índice con el elemento a sacar (0 es el primer ítem):
print(l.pop(0))
print(l)
#10
#[20, 30, 40]
remove()
Borra el primer ítem de la lista cuyo valor concuerde con el que indicamos:
l = [20,30,30,30,40]
l.remove(30)
print(l)
#[20, 30, 30, 40]
reverse()
Le da la vuelta a la lista actual:
l.reverse()
print(l)
#[40, 30, 30, 20]
Las cadenas no tienen el método .reverse() pero podemos simularlo haciendo unas conversiones:
lista = list("Hola mundo")
lista.reverse()
cadena = "".join(lista)
cadena
#'odnum aloH'
sort()
Ordena automáticamente los ítems de una lista por su valor de menor a mayor:
lista = [5,-10,35,0,-65,100]
lista.sort()
lista
#[-65, -10, 0, 5, 35, 100]
Podemos utilizar el argumento reverse=True para indicar que la ordene del revés:
lista.sort(reverse=True)
lista
#[100, 35, 5, 0, -10, -65]
""" |
0c291bf1d72c58c6430691a65c42eaef8072c79d | choiking/LeetCode | /linkedlist/sortList.py | 2,389 | 3.921875 | 4 | # Author: Yu Zhou
# 148. Sort List
# Sort a linked list in O(n log n) time using constant space complexity.
# 思路
# 用链表的方式切分,然后递归Split,之后Merge
# 这道题要注意是切分的时候,要写个Prev的函数用来储存Slow的原点
# Time: O(nlogn)
# Space: O(1)
# ****************
# Final Solution *
# ****************
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
prev = None
fast = slow = head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
mid = slow
prev.next = None #截断
l = self.sortList(head) #递归
r = self.sortList(mid)
return self.merge(l, r)
#这是一种类似于创建一个头的DummyNode,把Head设置成Prev,Cur设置成head.next
def merge(self, l, r):
guard = cur = ListNode(None)
while l and r:
if l.val <= r.val:
cur.next = l
l = l.next
else:
cur.next = r
r = r.next
cur = cur.next
cur.next = l or r
return guard.next
vhead = curr = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return vhead.next
# ***************************************
# The following code is an fail attempt *
# ***************************************
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
fast = slow = head
#这里错在没有设置一个prev来保存Slow的值
#每次while结束后,slow就会变成slow.next
#假如想在slow的地方切断,就必须设置一个Prev
#来保存slow的值,下方 mid = slow.next
#其实已经是在经历过while 后的slow.next的next了
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None #截断
l = self.sortList(head) #递归
r = self.sortList(mid)
return self.merge(l, r)
|
e68f9a57756f4f48be846ec673ae2dae8d23c6ed | Satish980/JNTUK_Python_Workshop | /Day_3/tuple_demo.py | 1,006 | 4.625 | 5 | #!/usr/bin/python
# tuples in python
atup = ('physics','chemistry',2010,2014)
btup = (80,82,73,64,85)
# to print complete tuple
print("atup :", atup)
print("btup :", btup)
# to print first element of the tuple
print("atup[0]:", atup[0])
# to print elements starting from 2nd till 3rd
print("btup[1:3] : ", btup[1:3])
print("Value available at index 2 :")
print(atup[2])
#Not valid action to the tuple
# atup[2] = 2011
# Instead of assign create a new variable
ctup = atup[0:1] + btup[1:3]
print("New tuple : ")
print(ctup)
# Removing individual tuple elements is not possible
# del atup[2]
del(atup)
print("Tuple Deleted")
# the total length of the tuple
print("Second tuple length : ", len(btup))
#return items from the tuple with max value
print("Max value element :", max(btup))
#return items from the tuple with min value
print("Min value element :", min(btup))
# to converts a tuple into list
tup = ( 2014,'chemistry',84,'Grade B')
listtup = list(tup)
print("List elements :", listtup) |
ffd9249c31c64b1a539b121fb7356195f1088916 | spsree4u/MySolvings | /strings/longest_prefix_string.py | 733 | 4.0625 | 4 | """
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
"""
def find_longest_prefix(strs):
if not strs:
return ""
# Time complexity is m*n where m = len(strs[0]) and n = len(strs)
# Space complexity is O(1)
for i in range(len(strs[0])):
for j in range(1, len(strs)):
if i >= len(strs[j]) or (strs[j][i] != strs[0][i]):
return strs[0][:i]
return strs[0]
l1 = ["flower", "flow", "flight"]
l2 = ["dog", "racecar", "car"]
l3 = ["dog", "dog2", "dog45"]
l4 = []
l5 = ["abc"]
print(find_longest_prefix(l1))
print(find_longest_prefix(l2))
print(find_longest_prefix(l3))
print(find_longest_prefix(l4))
print(find_longest_prefix(l5))
|
73c0a9d98ec5cb2eb8d9b1ff02a97a0ddce29ff7 | mubeen070/PythonLearning1 | /test.py | 235 | 4.125 | 4 | #msg="hello world"
#msg2="sony"
#print(msg2+": "+msg)
#val1="3"
#val2="4"
#print(val1+val2)
#fruits = ["apple", "banana", "cherry"]
#for x in fruits:
# print(x)
val1=8
val2=13
if 13 > 8 :
print( "13 is greater than 8" )
|
b0200c7317916b3352459cf65a62a24bab5227c6 | renjieliu/leetcode | /0001_0599/21.py | 1,692 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: 'Optional[ListNode]', list2: 'Optional[ListNode]') -> 'Optional[ListNode]':
start = ListNode() #dummy start node, return start.next
node = start
while list1 and list2: #check every node, and put the smaller one here
if list1.val<=list2.val:
node.next = list1
list1 = list1.next
else:
node.next = list2
list2 = list2.next
node = node.next
node.next = list1 or list2 #put the rest of list1 or list2
return start.next
# previous approach
# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# class Solution:
# def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# if l1 == None: return l2
# if l2 == None: return l1
# if l1.val <= l2.val:
# start = ListNode(l1.val)
# l1 = l1.next
# else:
# start = ListNode(l2.val)
# l2 = l2.next
# node = start
# while l1 and l2:
# if l1.val<=l2.val:
# node.next = ListNode(l1.val)
# node = node.next
# l1 = l1.next
# else:
# node.next = ListNode(l2.val)
# node = node.next
# l2 = l2.next
# node.next = l1 if l1 else l2
# return start
|
49a349d93ece3c264ccca1edd8c9ebde0003266e | dlstzd/FamilyTree | /Family.py | 5,236 | 3.546875 | 4 | from PersonID import *
import pickle
import tkinter as tk
#future issue each person needs a unique id
#or we list duplicate and allow the person to select the correct person --
peopleList = []
def update_file():
with open("list.pkl", "wb") as f:
f.write(pickle.dumps(peopleList))
def get_person(peopleList, name):
for p in peopleList:
if p.name == name:
#print("person already exists")
return p
else:
print(name + " does not currently exist, would you like to create this person?y/n")
uinput = input(">").lower()
if(uinput == 'y'):
person = Person(name)
add_person(peopleList, person)
return person
else:
return None
def print_people(peopleList):
#sorted(peopleList, Person.birthyear)
for p in peopleList:
print(" %s | children: %s | parents: %s, %s | spouse: %s | Birth Year: %s | Age: %s" % (p.name, p.children, p.parent1, p.parent2, p.spouse, p.birthyear, p.age))
print("-----------------------")
def add_person(peopleList, person):
peopleList.append(person)
update_file()
# issue person remains as parent
def remove_person(peopleList, person):
#if not get_person(peopleList, person.name):
# print("Person was not found")
#else:
for p in peopleList:
if p.name == person.name:
if p.spouse != '?':
spouse = get_person(peopleList, p.spouse)
spouse.spouse = '?'
if len(p.children) is not 0: # mark parent as removed
for c in p.children:
kid = get_person(peopleList, c)
if p.name == kid.parent1:
kid.parent1 = '?'
if p.name == kid.parent2:
kid.parent2 = '?'
peopleList.remove(p)
if person.name in p.children: #remove person from list of children
p.children.remove(person.name)
update_file()
else:
print("Person was not found")
# issue of changing attributes could have to do with get_person function
def modify_person(peopleList, person):
if get_person(peopleList, person.name):
print("Modify How?")
print("1) Modify Name\n2) Add Child\n3) Cancel") # should become window option
user_input = input(">")
if user_input == "1":
user_input2 = 'y'
while user_input2 != 'y' or user_input2 != 'n':
print("Modify Name?\n y/n")
user_input2 = input(">").lower()
if user_input2 == 'y':
new_name = input("Please enter the new first name: ")
#print(new_name)
person = person.set_name(new_name)
#peopleList.append(person1)
# person.set_name(new_name)
print(person)
# print(Joe.name)
break
elif user_input2 == 'n':
print("Returning...")
break
else:
print("Not valid: press y or n")
elif user_input == "2":
name = input("Enter child's name: ")
new_child = Person(name)
add_child(peopleList, person, new_child)
else:
print("Person was not found")
def add_spouse(peopleList, person1, person2):
persona = get_person(peopleList, person1.name)
personb = get_person(peopleList, person2.name)
if persona is not None and personb is not None:
persona.spouse = personb.name
personb.spouse = persona.name
# link any children previously set to parent to be children of spouse
for c in personb.children:
persona.children.add(c)
ch = get_person(peopleList, c)
add_parent(peopleList, persona, ch)
for c in persona.children:
personb.children.add(c)
ch = get_person(peopleList, c)
add_parent(peopleList, personb, ch)
update_file()
def add_parent(peopleList, parent, child):
p = get_person(peopleList, parent.name)
c = get_person(peopleList, child.name)
if p is not None and c is not None:
p.children.add(c.name)
if c.parent1 == '?':
c.parent1 = p.name
if p.spouse != '?':
c.parent2 = p.spouse
sp = get_person(peopleList, p.spouse)
sp.children.add(c.name)
elif c.parent2 == '?':
c.parent2 = p.name
update_file()
def add_child(peopleList, parent, child):
parent.children.add(child.get_name())
add_parent(peopleList, parent, child)
if parent.spouse != '?':
spouse = get_person(peopleList, parent.spouse)
add_parent(peopleList, spouse, child)
update_file()
def get_missing_parents(peopleList):
for p in peopleList:
if p.parent1 != '?':
par = get_person(peopleList, p.parent1)
if par.spouse != '?':
p.parent2 = par.spouse
update_file()
def set_birthyear(name, year):
p = get_person(peopleList, name)
p.birthyear = year
p.get_age(year)
update_file()
|
c9a6580bc8f648ade956a75359f07487782b1a60 | Irisviel-0/a1 | /find_my_neighbourhood.py | 489 | 3.671875 | 4 | def find_my_neighbourhood(x, y):
NameStr = 'ABCDEFGHIJ'
a = NameStr[int(y)]+str(int(x)+1)
return a
def find_all_restaurants_in_neighbourhood(x, y):
Neib = find_my_neighbourhood(x, y)
list1 = [str(Neib)+'CR', str(Neib)+'MR']
return list1
if __name__ == "__main__":
for i in range(1,100):
for j in range(1,100):
print(find_my_neighbourhood(i/10,j/10))
print(find_all_restaurants_in_neighbourhood(i/10,j/10))
|
2e8934c4d547826bde1d029a3d76d3abe8ad01d2 | ShreyanshNanda/CyberSecurity | /Assignment 03/almost_there.py | 222 | 3.890625 | 4 | print("True if n is within 10 of either 100 or 200")
def almost_there(n):
if(abs(100-n) <=10 or abs(200-n) <=10):
return True
else:
return False
n=int(input("Enter the number : "))
almost_there(n)
|
161f6016f1b6f7c7bbe11706184d3972b009643c | AdamMcCarthyCompSci/Programming-1-Practicals | /Practical 7/p13p2.py | 531 | 4.28125 | 4 | """
Define max function with two variables
If first is greater than second then
return first
else then
return second
prompt for first float
prompt for second float
print result
"""
def max(a,b):
"""Function that returns the largest of its two arguments"""
if a>b:
return a
else:
return b
number1=float(input('Enter a number: '))
number2=float(input('Enter a number: '))
print('The largest of',number1,'and',number2,'is',max(number1,number2))
print('Finished!') |
dcb48b749fa4c408be2cfe1a7ad3f3de912ae2c8 | RahatIbnRafiq/leetcodeProblems | /Tree/437. Path Sum III.py | 579 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self,root,origin,targets):
if root is None:return 0
hit = 0
for t in targets:
hit += ((t-root.val)==0)
targets = [t-root.val for t in targets]+[origin]
return hit+self.helper(root.left,origin,targets)+self.helper(root.right,origin,targets)
def pathSum(self, root, sum):
return self.helper(root,sum,[sum])
|
5a76f80621d9496f12a46b5ae466bf6ebb5dc796 | evercsing/flatiron | /Chung Soo Lee_API Project.py | 2,421 | 3.890625 | 4 | # Python program to find current
# weather details of any city
# using openweathermap api
# import required modules
import requests, json
import matplotlib.pyplot as plt
# Enter your API key here
api_key = "c4440a0676f79455da1890baf316cde9"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/forecast?"
print("Hoboken: 5099133 \nPalisades Park: 5102369")
# full API URL
#http://api.openweathermap.org/data/2.5/forecast?id=5098135&appid=c4440a0676f79455da1890baf316cde9
# Give city name
#city_id = input("Enter city ID : ")
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&id=5102369"
# get method of requests module
# return response object
response = requests.get(complete_url)
results = response.json()
results = results['list']
#print(len(results['list']))
file = open('temp.txt', 'w')
file.write('')
file = open('dt_txt.txt', 'w')
file.write('')
count = 0
# save in a filer
for data in results:
file1 = open('temp.txt', 'a')
file1.write(str(data['main']['temp']) +'\n')
#print(data['main']['temp'])
file2 = open('dt_txt.txt', 'a')
file2.write(str(data['dt_txt']) +'\n')
#print(data['dt_txt'])
count += 1
if count == 30:
break
temp_list = []
# Open file
temp_file = open('temp.txt', 'r')
# Count lines
# We can skip ruits_file.readlines()
for line in temp_file:
temp_list.append(float(line.rstrip('\n')))
converted_temp_list = []
for temp in temp_list:
converted_temp_list.append((temp - 273.15) * 9/5 + 32)
dt_txt_list = []
# Open file
dt_txt_file = open('dt_txt.txt', 'r')
for line in dt_txt_file:
dt_txt_list.append(line.rstrip('\n'))
#temp_file.close()
# Initialize data points
x = dt_txt_list
y = converted_temp_list
# Generate line graph
plt.plot(x,y)
# Add title
plt.title('Weather history in Palisades Park, NJ')
# Add labels
plt.xlabel('Time')
plt.ylabel('Temp')
# Specify x and y axes range
plt.xlim(xmin=0, xmax=len(converted_temp_list))
plt.ylim(ymin=min(converted_temp_list), ymax=max(converted_temp_list))
# Add grid
plt.grid(False)
# Display line graph
plt.show()
print()
print('Temp')
print(converted_temp_list)
print()
print('Time')
print(dt_txt_list) |
363d2410efc59f9dc5536bbd714290d87a1ad1fe | DouglasKosvoski/URI | /1001 - 1020/1008.py | 162 | 3.75 | 4 | NUMBER = int(input())
HOURS = int(input())
VALUE = float(input())
SALARY = HOURS * VALUE
print('NUMBER = %d'%(NUMBER))
print('SALARY = U$ %.2f'%(SALARY))
|
638f3cd1e20db07152aa793bd3775df6228666b4 | heden1/1nledande-programer1ng | /selfPractice/l5worIndex.py | 558 | 3.703125 | 4 | def word_index(text):
dict ={}
if len(text)==0:
return dict
text=text.split(' ')
for i in range(len(text)):
list1=[i]
if text[i] in dict:
list1=dict.get(text[i])
list1.append(i)
dict[text[i]]= dict.get(text[i],list1)
return(dict)
print(word_index('the spider indexes the spider web') )
print(word_index(''))
#{'the': [0,3],'spider': [1,4], 'indexes': [2], 'web': [5]} |
2737f7110d5b74283d1b76dc699ea1a1a966f01a | GeorgeVince/HackerRank | /Data Structures/Stack/balanced_brackets.py | 490 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 5 16:13:21 2017
@author: George
"""
def is_matched(expression):
stack = []
pairs = {'(':')', '[':']','{':'}'}
for x in expression:
if pairs.get(x):
stack.append(pairs[x])
else:
if len(stack) == 0 or x != stack[len(stack) - 1]:
return False
stack.pop()
return len(stack) == 0
expression = "{[]}{{}}"
print (is_matched(expression)) |
c798478cfb2a114b702284ae7607a9120e0f6b8f | shayansaha85/pypoint_QA | /set 5/20.py | 279 | 4.15625 | 4 | n = int(input("How many elements do you want? : "))
numbers = []
squares = []
for i in range(n):
el = int(input(f"Enter the element #{i+1}: "))
numbers.append(el)
for x in numbers:
squares.append(x**2)
print("Entered list :",numbers)
print("Square list :",squares) |
3152fc7a9d94bfb326066f962046b3ca38112082 | drewwestphal/aoc2016 | /3.py | 713 | 3.5625 | 4 | #!/usr/bin/python
import itertools
def checkTriangle(s1,s2,s3):
for perm in itertools.permutations([s1,s2,s3]):
if not perm[0]+perm[1]>perm[2]:
return False
return True
#valid = filter(checkTriangle, open('./3input.txt'))
trianglerows = [[int(x) for x in line.split()] for line in open('./3input.txt')]
validrows = filter(lambda row: checkTriangle(*row), trianglerows)
print 'valid rows: ', len(validrows)
trianglecolumn = [row[0] for row in trianglerows]+[row[1] for row in trianglerows]+[row[2] for row in trianglerows]
newrows = [trianglecolumn[i:i + 3] for i in xrange(0, len(trianglecolumn), 3)]
validcols = filter(lambda row: checkTriangle(*row), newrows)
print 'valid cols: ', len(validcols)
|
bb2d3ee1668b3248d74f489d975fd60e7afa1958 | SurinJeon/python_study | /chap04/dict/final_question.py | 870 | 3.71875 | 4 | # 3번
numbers = [1, 2, 3, 4, 7, 5, 8, 4, 2, 8, 5, 8, 4, 1, 8, 5, 6, 9, 3]
counter = {}
for number in numbers:
key = number
if key in counter:
counter[number] += 1
else:
counter[number] = 1
print(counter)
# 4번
character = {
"name":"기사",
"level":12,
"items":{
"sword":"불꽃의 검",
"armor":"풀플레이트"
},
"skill":["베기", "세게 베기", "아주 세게 베기"]
}
for key in character:
if type(character[key]) is str:
print(key, " : ", character[key])
elif type(character[key]) is int:
print(key, " : ", character[key])
elif type(character[key]) is dict:
for i in character[key]:
print(i, " : ", character[key][i])
elif type(character[key]) is list:
for j in character[key]:
print(key, " : ", j)
|
70547951ef91e624d5c6e2daff4f04aff3cd7f67 | kleinstadtkueken/adventOfCode2018 | /src/2018/day_13/exercice1.py | 4,970 | 3.5 | 4 | #!/usr/bin/python3
from enum import Enum, auto
class Turn(Enum):
LEFT = auto()
RIGHT = auto()
STRAIGT = auto()
# def next(self):
# if self.LEFT:
# return self.STRAIGT
# elif self.STRAIGT:
# return self.RIGHT
# elif self.RIGHT:
# return self.LEFT
# else:
# raise Exception('Falscher Turn')
class Direction(Enum):
UP = ('^')
DOWN = ('v')
RIGHT = ('>')
LEFT = ('<')
def __init__(self, symbol):
self.symbol = symbol
def move(self, currentPosition):
if self == self.UP:
return currentPosition[0], currentPosition[1] - 1
elif self == self.DOWN:
return currentPosition[0], currentPosition[1] + 1
elif self == self.RIGHT:
return currentPosition[0] + 1, currentPosition[1]
elif self == self.LEFT:
return currentPosition[0] - 1, currentPosition[1]
def turnLeft(self):
if self == self.UP:
return self.LEFT
elif self == self.DOWN:
return self.RIGHT
elif self == self.RIGHT:
return self.UP
elif self == self.LEFT:
return self.DOWN
def turnRight(self):
if self == self.UP:
return self.RIGHT
elif self == self.DOWN:
return self.LEFT
elif self == self.RIGHT:
return self.DOWN
elif self == self.LEFT:
return self.UP
def nextDirection(self, track, nextTurn: Turn):
if track == '-' or track == '|':
return self, nextTurn
elif track == '/':
if self == self.UP:
return self.RIGHT, nextTurn
elif self == self.DOWN:
return self.LEFT, nextTurn
elif self == self.LEFT:
return self.DOWN, nextTurn
elif self == self.RIGHT:
return self.UP, nextTurn
elif track == '\\':
if self == self.UP:
return self.LEFT, nextTurn
elif self == self.DOWN:
return self.RIGHT, nextTurn
elif self == self.LEFT:
return self.UP, nextTurn
elif self == self.RIGHT:
return self.DOWN, nextTurn
elif track == '+':
if nextTurn == Turn.STRAIGT:
return self, Turn.RIGHT
elif nextTurn == Turn.LEFT:
return self.turnLeft(), Turn.STRAIGT
elif nextTurn == Turn.RIGHT:
return self.turnRight(), Turn.LEFT
else:
raise Exception('cart is of the track')
class Cart:
def __init__(self, position, direction: Direction):
self.position = position
self.direction = direction
self.nextTurn = Turn.LEFT
# def __cmp__(self, other):
# if self.position[0] < other.position[0]:
# return -1
# elif self.position[0] > other.position[0]:
# return 1
# # the x coordinates are identical. Now the y coordinate is checked
# elif self.position[1] < other.position[1]:
# return -1
# elif self.position[1] > other.position[1]:
# return 1
# else:
# return 0
#
# def __lt__(self, other):
# if self.__cmp__(other) <= 1:
# return True
# else:
# return False
def move(self):
p = self.position
self.position = self.direction.move(self.position)
# print(f'Previous {p} {self.direction} current {self.position}')
self.direction, self.nextTurn = self.direction.nextDirection(grid[self.position[1]][self.position[0]], self.nextTurn)
grid = []
carts = []
# with open('testInput.txt', 'r') as file:
with open('input.txt', 'r') as file:
for y, line in enumerate(file):
line = line[:-1]
changes = dict()
for x, char in enumerate(line):
if char == '>':
carts.append(Cart((x, y), Direction.RIGHT))
changes[x] = '-'
if char == '<':
carts.append(Cart((x, y), Direction.LEFT))
changes[x] = '-'
if char == '^':
carts.append(Cart((x, y), Direction.UP))
changes[x] = '|'
if char == 'v':
carts.append(Cart((x, y), Direction.DOWN))
changes[x] = '|'
for x, change in changes.items():
line = line[:x] + change + line[x+1:]
grid.append(line)
def pickNewRecipe(position):
steps = scoreBoard[position] + 1
position += 1 + steps
if len(scoreBoard) <= position:
position %= len(scoreBoard)
return position
# inputRounds = 503761
inputRounds = 9
scoreBoard = [3, 7]
firstElve = 0
secondElve = 1
currentRound = 0
for _ in range(inputRounds + 10):
createNewRecipe()
pickNewRecipe()
print(scoreBoard)
|
28431b71e1179b8297bbee03b2d629c2fc381d23 | zazolla14/basic-python | /break_while.py | 139 | 3.875 | 4 | #CONTOH menggunakn while dengan memanfaatkan BREAK
while True:
data=input("Data : ")
if data == "x":
break
print(data) |
8a2a34c0a8970a8344ea1495c4ca22dd9c833962 | mattwelson/Archive | /COMP150/Lab06/div3.py | 180 | 4.25 | 4 | def is_divisible_by_3(n):
if n % 3 == 0:
print n, "is divisible by 3!"
else:
print n, "is not divisible by 3 :("
is_divisible_by_3(6)
is_divisible_by_3(7)
|
906c8ca96ab5fdeae29be5c60f0e8eaa3f1bdce3 | kasy1tu/Financial-Records-Election-Analysis- | /PyBank/main.py | 1,702 | 3.828125 | 4 | #Open csv as read file
import os
import csv
file_to_load = os.path.join("Resources", "budget_data.csv")
#Defined all variables
total_months = 0
total_net = 0
change_values = []
total_net_change = 0
greatest_increase = [" ", " "]
greatest_decrease = [" ", " "]
greatest_increase_month = []
greatest_decrease_month = []
with open(file_to_load) as financial_data:
reader = csv.reader(financial_data)
header = next(reader)
next_data = next(reader)
prev_data = int(next_data[1])
for row in reader:
total_months += 1
total_net += int(row[1])
net_change = int(row[1]) - int(prev_data)
prev_data = int(row[1])
change_values.append(net_change)
total_net_change += net_change
average_change = round((total_net_change/len(change_values)), 2)
greatest_increase[0] = row[0]
greatest_decrease[0] = row[0]
greatest_decrease[1] = min(change_values)
greatest_increase[1] = max(change_values)
#Find greatest increase and decrease months
# for row in greatest_increase:
# if greatest_increase[1] == 1926159:
# print(greatest_increase)
# for row in greatest_decrease:
# if greatest_decrease[1] == -2196167:
# print(greatest_decrease)
print("Financial Analysis")
print("---------------------------")
#added 1 to total_months because I stored the first line as prev_data so adding it back to total months
print(f"Total Months: {total_months + 1}")
print(f"Average Change: {average_change}")
print(f"Greatest Increase In Profits: Feb-2012 {greatest_increase[1]}")
print(f"Greatest Decrease In Profits: Sep-2013 {greatest_decrease[1]}")
|
c7a67c23b2aae88e039c045f3dae89fe6b372e5e | samarla/LearningPython | /factorial using function.py | 289 | 4.25 | 4 | number = int(input('enter any number: '))
def factorial(n):
if n == 1: # The termination condition
return 1 # The base case
else:
res = n * factorial(n-1) # The recursive call
return res
print('the factorial of given number is: ',factorial(number))
|
4f894f14232c1f4c87e772b7a8dc6e9ac11be3c1 | Crown0815/ESB-simulations | /polygon.py | 216 | 3.71875 | 4 | from math import *
small_radius = 1.3
side_length = 2 * small_radius
number_of_sides = 4
radius = side_length / (2*(sin(pi / number_of_sides)))
print(radius+small_radius)
print((radius+small_radius)/small_radius)
|
9048a804a00728b642a9f35790f5dad62d142740 | jackh08/Python-General | /python_week4 clus and reg.py | 4,634 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Exercise – Week IV
Data Programming With Python – Fall / 2017
Regression, Clustering
"""
import pandas as pd
import numpy as np
import numpy.polynomial.polynomial as nppp
import scipy.cluster.vq as spcv
import scipy.stats as sps
from pylab import plot, title, show, legend
from scipy import linspace, sqrt, randn
from scipy.cluster.vq import kmeans, vq
# Section I – Regression
# 1- Import the ‘Auto Insurance in Sweden’ dataset from the following url,
# and do a linear regression to fit the data. Plot the data and the regression line.
# url - https://www.math.muni.cz/~kolacek/docs/frvs/M7222/data/AutoInsurSweden.txt
### sps lin regression
DataFrame = pd.read_csv('/users/c_dredmond/Downloads/AutoInsurSweden.txt', header=None)
DataMatrix = DataFrame.as_matrix()
InputMatrix= np.array(DataMatrix[:,0])
OutMatrix = np.array(DataMatrix[:,1])
(gradient,intercept,rvalue,pvalue,stderr) = sps.linregress(InputMatrix, OutMatrix)
Regression_line = nppp.polyval(InputMatrix,[intercept,gradient])
print ("Gradient & Intercept", gradient, intercept)
plot(InputMatrix,OutMatrix, 'vr')
plot(InputMatrix,Regression_line ,'b.-')
show()
# Section II – Clustering
# 2 - Download the ‘IRIS’ dataset from the url below, import it to Python and
# do a 3-mean clustering based on the inputs (4-dimesnion).
# Plot the members of each cluster with different colour (Red, Blue & Green )
# in a 2-axis coordinate which the horizontal axis is the first input and the
# vertical one is second input.
# url - https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
### k means
DataFrame = pd.read_csv('/users/c_dredmond/Downloads/iris.csv', header=None)
DataMatrix = DataFrame.as_matrix()
InputMatrix = np.matrix(DataMatrix[:,:4])
centroids,_ = kmeans(InputMatrix,3)
id,_ = vq(InputMatrix,centroids)
print(centroids)
print(id)
plot(InputMatrix[id==0,0], InputMatrix[id==0,1],
'*b', InputMatrix[id==1,0], InputMatrix[id==1,1],
'vr', InputMatrix[id==2,0], InputMatrix[id==2,1],
'og', linewidth=5.5)
show()
# Linear Regression
x = [5.05, 6.75, 3.21, 2.66]
y = [1.65, 26.5, -5.93, 7.96]
(gradient, intercept, r_value, p_value, stderr) = sps.linregress(x,y)
print ("Gradient & Intercept", gradient, intercept)
print ("R-squared", r_value**2)
print ("p-value ", p_value)
### Polynomial Regression
# x : [-1, -0.96, ..., 0.96, 1]
x = np.linspace(-1,1,51)
# x^3 – x^2 + N(0,1)“Gaussian noise"
y = x**3 - x**2 + np.random.randn(len(x))
c, stats = nppp.polyfit(x,y,3,full=True)
Datasample = -0.77
result = nppp.polyval(Datasample,c)
print(result)
### Clustering
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a,b),)
Num_of_clusters = 2;
Centre,Var = spcv.kmeans(X, Num_of_clusters )
id,dist = spcv.vq(X,Centre)
print id, dist
#Sample data creation
#number of points
n = 50
t = linspace(-5, 5, n)
#parameters
a = 0.8
b = -4
x = nppp.polyval(t,[a, b])
#add some noise
xn= x+randn(n)
(ar,br) = nppp.polyfit(t,xn,1)
xr = nppp.polyval(t,[ar,br])
#compute the mean square error
err = sqrt(sum((xr-xn)**2)/n)
print('Linear regression using polyfit')
print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, ms error= %.3f' % (a,b,ar,br,err))
print('-----------------------------------------------------')
#Linear regression using stats.linregress
(a_s,b_s,r,tt,stderr) = sps.linregress(t,xn)
print('Linear regression using stats.linregress')
print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, std error= %.3f' % (a,b,a_s,b_s,stderr))
#matplotlib ploting
title('Linear Regression Example')
plot(t,x,'g.--')
plot(t,xn,'k.')
plot(t,xr,'r.-')
legend(['original','plus noise', 'regression'])
show()
#generate two clusters: a with 100 points, b with 50:
# for repeatability of this example
np.random.seed(4711)
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]],
size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]],
size=[50,])
X = np.concatenate((a,b),)
# 150 samples with 2 dimensions
print(X.shape)
# computing K-Means with K = 2
centroids,_ = kmeans(X,2)
# assign each sample to a cluster
id,_ = vq(X,centroids)
plot(X[id==0,0],X[id==0,1],'ob',X[id==1,0],X[id==1,1],'or')
plot(centroids[:,0],centroids[:,1],'sg', markersize=15)
show()
A,B = spcv.kmeans(X,2)
print(A)
print('----------------------------------------------')
print(B)
print('----------------------------------------------')
id,dist=spcv.vq(X,A)
print('----------------------------------------------')
print(id)
print(dist)
|
1ab59fe086485d9f4ef1966e7c18e0d8609c72b0 | ViktoriaCsink/AnnotatePdf | /segment_docx.py | 1,380 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This function will access URLs that point to word documents and get the text.
Word documents are converted into pdfs in order to break them down into pages.
The text will be broken down into pages to do analysis on each page later on.
Input: 'response' (the result of the requests.get method)
Output: a dictionary where keys are page numbers and values are text
Viktoria, June 2021
"""
import os
import pdfplumber
from docx2pdf import convert
import re
def segment_docx(title, response, download):
#Get the correct extension of the output file
if '.docx' in title:
title = re.sub(r'.docx', '', title)
if '.pdf' not in title:
title = title + '.pdf'
#Initiate empty dictionary which will be populated
content = {}
open('myfile.docx', 'wb').write(response.content)
#Convert to pdf
convert("myfile.docx", title)
#Segment into pages
with pdfplumber.open(title) as pdf:
pages = pdf.pages
for count,page in enumerate(pages):
content[count+1] = page.extract_text()
#If download was requested...
if download == 1:
#Only remove the word file
os.remove('myfile.docx')
else:
#Remove them both
os.remove('myfile.docx')
os.remove(title)
return content |
13fd0849e73a9208c1f0eae7b379ada53188565d | lucas-mascena/Numerical_Methods | /Interpol_1.py | 829 | 3.890625 | 4 | '''
Linear Interpolation Method
'''
'''
time = [0,20,40,60,80,100]
temp = [26.0,48.6,61.6,71.2,74.8,75.2]
#y = lambda xp, x1, x2, y1, y2: y1+((y2-y1)/(x2-x1))*(xp-x1)
#y(50,40,60,61.6,71.2)
def y(xp, x, y):
for i, xi in enumerate(x):
if xp < xi:
return y[i-1]+((y[i]-y[i-1])/(x[i]-x[i-1]))*(xp-x[i-1])
else:
print('Given x-value is out of range.')
temp50 = y(50, time, temp)
print('The temperature = ', temp50)
'''
'''
Lagrange's Method:
'''
x=[0,20,40,60,80,100]
y=[26.0,48.6,61.6,71.2,74.8,75.2]
m = len(x) #length of x list (or array)
xp = float(input('Enter x: '))
yp = 0
for i in range(m):
L = 1
for j in range(m):
if j != i:
L *= (xp-x[j])/(x[i]-x[j])
yp += y[i]*L
print('For x = %.1f, y = %.1f' % (xp,yp))
|
d03ca4a8f9f758821d3af8d7d5b382706e3f64f4 | iTrauco/list_exercises | /11_11_2019/string_exercises.py | 2,502 | 4.03125 | 4 | #uppercase a string
# string = 'strang'
# string2 = string.upper()
# string2 = 'yeet'.upper()
# print(string2)
#capitalize a string
# string = 'strang gang'
# string2 = list(string)
# cap = string2[0]
# string2.remove(cap)
# string2.insert(0, cap.upper())
# final = ''.join(string2)
# print(final)
# reverse a string
# string = 'strang gang'
# string2 = list(string)
# print(string2)
# string3 = []
# index = -1
# for i in string2:
# string3.append(string2[index])
# index -= 1
# string3 = ''.join(string3)
# print(string3)
# can you do better?
# def reverse_it(a):
# a = list(a)
# b = []
# c = ''
# index = -1
# for i in a:
# b.append(a[index])
# index -= 1
# c = ''.join(b)
# print(c)
# reverse_it('tweet')
#leetspeak
# def leetspeak(name):
# name = name.upper()
# name = name.replace("L", "1")
# name = name.replace("E", "3")
# name = name.replace("T", "7")
# name = name.replace("S", "5")
# name = name.replace("O", "0")
# name = name.replace("A", "4")
# name = name.replace("G", "6")
# return name
# strang = input('What would you like to translate? ')
# print(leetspeak(strang))
#long-long vowels
# def vowelize(string):
# if 'oo' in string:
# string = string.replace('oo', 'ooooo')
# elif 'ee' in string:
# string = string.replace('ee', 'eeeee')
# else:
# string = string
# return string
# talk = input('talk: ')
# print(vowelize(talk))
# def vowelize(string):
# no_vowels = []
# for x in string:
# if x not in 'aeiou':
# no_vowels.append(x)
# return ''.join(no_vowels)
# vowel_string = input('Let me take those vowels for you: ')
# print(vowelize(vowel_string))
# ceaser cipher
# string = 'ibh zhfg hayrnea jung lbh unir yrnearq'
# index = 0
# encrypted = ''
# alphabet = list('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ')
# while index < len(string):
# temp = string[index]
# index += 1
# if temp == ' ':
# encrypted += temp
# else:
# temp2 = alphabet[(alphabet.index(temp) + 13)]
# encrypted += temp2
# # print(temp2)
# print(encrypted)
# ibh zhfg hayrnea jung lbh unir yrnearq
# def cipher(string):
# for char in string:
# char =
# print(ord('a'))
# # print(ord('pat'[0]))
# print( chr(int(ord('pat'[0])) + 5) )
|
7c1f942760ae059db2b48de811baf973a8cd8be4 | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 003.py | 280 | 4.09375 | 4 | #Crie um programa que leia dois números e mostra a soma entre eles, utilizando os tipos primitivos
n1 = int(input('Digite um primeiro número: '))
n2 = int(input('Digite um segundo número: '))
s = n1 + n2
print('A soma entre {} e {} será {}'.format(n1, n2, s))
print(type(n1))
|
100680433b32392bf9c071e839a14eaa2cb3adbe | JeffVa1/MonteCarlo-AreaCalculator | /MonteCarlo_AreaCalculator.py | 2,056 | 3.6875 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
import random
#print("Monte Carlo integration method to compute the area of 2D donut")
#print("============INFORMATION============")
r_outer = 1
r_inner = 0.5
actual_area = (math.pi * r_outer * r_outer) - (math.pi * r_inner * r_inner)
'''
print("Outer Circle Radius: " , r_outer)
print("Inner Circle Radius: " , r_inner)
print("Number of points: " , n_points)
'''
ni = []
err = []
areas_calculated = []
for n in range(1,5000,2):
n_points = n
x = []
y = []
for j in range(n_points):
x.append(random.uniform(-1*r_outer, r_outer))
y.append(random.uniform(-1*r_outer, r_outer))
points_enclosed = 0
for i in range(len(x)):
if (x[i] <= -0.5 and x[i] >= -1.0) or (x[i] >= 0.5 and x[i] <= 1.0):
if (y[i] <= -0.5 and y[i] >= -1.0) or (y[i] >= 0.5 and y[i] <= 1.0):
points_enclosed += 1
calculated_area = ((r_outer*2)**2) * (points_enclosed / n_points)
error_num = abs(calculated_area - actual_area) / actual_area
areas_calculated.append(calculated_area)
ni.append(n_points)
err.append(error_num)
print("Area of donut: " , actual_area)
print("Average area calculated: ", np.mean(areas_calculated))
print("Average error calculated: ", np.mean(err))
plt.plot(ni, err,'b')
plt.title("Number of points vs. Difference in area")
plt.xlabel("Number of points (N)")
plt.ylabel("Error (area difference)")
plt.savefig('result_plot.png')
plt.show()
'''
#Used during testing
print("")
print("==============RESULTS==============")
print("Calculated Area:", calculated_area)
print(" Error:", error_num)
x_outer = np.linspace(-r_outer,r_outer,1000)
y_outer = np.sqrt(-x_outer**2+r_outer**2)
plt.plot(x_outer, y_outer,'b')
plt.plot(x_outer,-y_outer,'b')
x_inner = np.linspace(-r_inner,r_inner,1000)
y_inner = np.sqrt(-x_inner**2+r_inner**2)
plt.plot(x_inner, y_inner,'b')
plt.plot(x_inner,-y_inner,'b')
plt.plot(x, y, "ro")
plt.gca().set_aspect('equal')
plt.show()
'''
|
5fad73d783659f89d48a5ed3282e4368c33e67f1 | kantawat1156-github/allelab-procon | /Lab08PB_01.py | 508 | 4.5 | 4 | import math
r = float(input("Enter a radius: "))
def circle(r):
circle = math.pi * (r**2)
return circle
def circumference(r):
circumference = 2 * math.pi * r
return circumference
def sphere(r):
sphere = 4 / 3 * math.pi * (r ** 3)
return sphere
print("Area of a circle with radius %.2f is %.2f." %(r, circle(r)))
print("Circumference of a circle with radius %.2f is %.2f." % (r, circumference(r)))
print('Volume of sphere with radius %.2f is %.2f.' % (r, sphere(r)))
|
cb21a0306d30e2006f17975acd02bdc0c4a05c48 | ultimate010/codes_and_notes | /133_longest-words/longest-words.py | 577 | 3.671875 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/longest-words
@Language: Python
@Datetime: 16-06-18 10:28
'''
class Solution:
# @param dictionary: a list of strings
# @return: a list of strings
def longestWords(self, dictionary):
# write your code here
ret = []
if len(dictionary) == 0:
return ret
maxLen = max([len(i) for i in dictionary])
for d in dictionary:
if len(d) == maxLen:
ret.append(d)
return ret |
3176153befc5fc18cbc5215e36992b6e64e24bb7 | zonghui0228/rosalind-solutions | /code/rosalind_inod.py | 457 | 3.78125 | 4 | # ^_^ utf-8: ^_^
"""
Counting Phylogenetic Ancestors
url: http://rosalind.info/problems/inod/
Given: A positive integer n (3≤n≤10000).
Return: The number of internal nodes of any unrooted binary tree having n leaves.
"""
with open("../data/rosalind_inod.txt") as f:
n = int(f.readline().strip())
# n = 4
print("the number of internal nodes is:", n-2)
print("the total number of the tree nodes is:", 2*n-2)
print("the edges of the tree is:", n-1)
|
fb3318f64f23dc64daebdb37d4e1d56ff46148c7 | Silocean/Codewars | /7ku_fizz_buzz.py | 704 | 4.09375 | 4 | '''
Description:
Return an array containing the numbers from 1 to N, where N is the parametered value. N will never be less than 1.
Replace certain values however if any of the following conditions are met:
If the value is a multiple of 3: use the value 'Fizz' instead
If the value is a multiple of 5: use the value 'Buzz' instead
If the value is a multiple of 3 & 5: use the value 'FizzBuzz' instead
'''
def fizzbuzz(n):
# your code here
l = []
for i, x in enumerate(range(1,n+1), 1):
if i%15==0:
l.append('FizzBuzz')
elif i%5==0:
l.append('Buzz')
elif i%3==0:
l.append('Fizz')
else:
l.append(x)
return l |
197f71001b7130deecd20ee7f96116cbfdc5930b | emildi/QNLP | /modules/py/pkgs/QNLP/encoding/encoder_base.py | 322 | 3.546875 | 4 | from abc import ABC, abstractmethod #Abstract base class
class EncoderBase(ABC):
"""Base class for binary encoding bitstring data"""
def __init__(self):
super().__init__()
@abstractmethod
def encode(self, bin_val):
pass
@abstractmethod
def decode(self, bin_val):
pass |
1a705d414c859de168285260a9122b6fecf939bb | caaare-ctrl/google-auto-dino | /main.py | 1,028 | 3.921875 | 4 | # https://elgoog.im/t-rex/
# You goal today is to write a Python script to automate the playing of this game.
# Your program will look at the pixels on the screen to determine when it needs
# to hit the space bar and play the game automatically.
# You can see what it looks like when the game is automated with a bot:
# https://elgoog.im/t-rex/?bot
# You might want to look up these two packages:
# https://pypi.org/project/Pillow/
# https://pyautogui.readthedocs.io/en/latest/
# Size(width=1920, height=1080)
# The game window is on the left side, half of the size of the window
import pyautogui
# start the game
pyautogui.click(x=200, y=200)
pyautogui.press('up')
select_region = (183,489,160,100)
# region = left, top, width, and height
# pyautogui.screenshot(imageFilename="example.jpg",region=(5,250,1000,400))
pyautogui.screenshot(imageFilename="test.png",region=select_region)
while True:
if pyautogui.locateOnScreen("img_6.png", confidence=0.3, region=select_region, grayscale=True):
pyautogui.press('up')
|
1662dc0d3e6a78f2d4ee16bd5760c9e7e332d883 | Lokeshbalu/AttendanceMonitoringSystem | /mailserver/sendmail.py | 1,157 | 3.625 | 4 | import smtplib
import sqlite3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail(contacts):
tolist=[]
for data in contacts:
conn=sqlite3.connect("database/attendance")
c=conn.cursor()
c.execute("select email from contacts where id="+str(data))
k=c.fetchall()
l=k[0][0]
l=str(l)
print(l)
tolist.append(l)
conn.commit()
c.close()
conn.close()
for data in tolist:
print("connecting to smtp")
#for tls the port number is 587 and host for gmail is smtp.gmail.com
s = smtplib.SMTP(host="smtp.gmail.com", port=587)
print("ok")
s.starttls()
s.login("lokeshbalaji68@gmail.com", "RVLB@loke=family")
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message = "You bloody I am SITAMS. Why are absent today??"
# setup the parameters of the message
msg['From']="lokeshbalaji68@gmail.com"
print("sending mail to "+str(data))
msg['To']=data
msg['Subject']="This is TEST"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# send the message via the server set up earlier.
s.sendmail("lokeshbalaji68@gmail.com",data,msg.as_string())
|
a9e0a458f957bb5ef5c8d0116d824db152f0401e | ShanDeneen/lesson2 | /Adventure Game (Formative).py | 3,571 | 4.25 | 4 | vName=input("Please enter your name: ")
print("Hello",vName)
def tentacle():
print("You have been trapped inside a giant octopus's stomach.You can try and exit through any of the octopus's 8 tentacles.")
choice= input("Choose a number between 1 & 8: ")
if choice != "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8":
if choice== "1":
print("Sorry there was an ink malfunction, you died")
elif choice== "5":
print("You have entered a dark sea tunnel.")
print(seatunnel())
elif choice== "2":
print("Sorry there was an ink malfunction, you died")
elif choice== "6":
print("You have entered a dark sea tunnel.")
print(seatunnel())
elif choice== "3":
print("Sorry there was an ink malfunction, you died")
elif choice== "7":
print("You have entered a dark sea tunnel.")
print(seatunnel())
elif choice== "4":
print("Sorry there was an ink malfunction, you died")
elif choice== "8":
print("You have entered a dark sea tunnel.")
print(seatunnel())
else:
print("Sorry, that tentacle does not exist.")
def seatunnel():
print("You have arrived in a dark sea tunnel. There are two paths before you. You can either go right or left.")
direction= input("Choose right or left: ")
if direction !="right"or"left":
if direction=="right":
print("Sorry, you have run into a dead end and there is no air left. You died.")
elif direction=="left":
print("You find a mysterious satchel.")
print(satchel())
else:
print("Sorry, that was not an option. Try again.")
def satchel():
print("You have picked up the mysterious satchel. Inside you find a scuba mask and a potato gun.")
choice2= input("Do you want to pick up the scuba mask or the potato gun?: ")
if choice2 !="scuba mask" or "potato gun":
if choice2=="scuba mask":
print("You grab the scuba mask and put it on.")
print(scubamask())
elif choice2=="potato gun":
print("You take the potato gun and the potato bullets.")
print(potate())
else:
print("Sorry, that was not an option. Try again.")
def potate():
print("You are hungry. You have potatoes. You can choose to eat or keep the potatoes.")
hunger= input("Eat or keep?: ")
if hunger != "eat"or"keep":
if hunger== "eat":
print("Sorry, you are allergic to potatoes. You died.")
elif hunger== "keep":
print("You keep the potato gun and keep walking through the sea tunnel. Eventually you encounter a giant seahorse. You try and defend yourself, but cannot beat the seahorse. You die of exhaustion.")
else:
print("Sorry,that is not an option. Please try again.")
def scubamask():
print("After you put your mask on you approach a hole in the sea tunnel. You can use your mask and swim through it or stay and explore.")
swim=input("Swim or explore?: ")
if swim != "swim" or "explore":
if swim== "explore":
print("You decided to stay and eplore the tunnel. After 5 minutes your oxygen tank explodes and you died.")
elif swim== "swim":
print("After you exit the tunnel through the hole, you see the shore and swim to it. Congrats! You survived. ")
else:
print("Sorry,that is not an option. Please try again.")
print(tentacle())
|
bdd39c7b6668d21b1208af82da40c9acc2e94186 | ovchingus/optimization-methods | /linear-extremum-search-methods/1py/util.py | 472 | 3.515625 | 4 | from math import sqrt
def sign(x):
"""
Return 1 if arg larger then 0, -1 is smaller then 0
"""
return int(x > 0)
gr = (1 + sqrt(5)) / 2
def naive_fib(n):
if 0 <= n <= 1:
return n
else:
return naive_fib(n - 1) + naive_fib(n - 2)
def better_fib(n):
if 0 <= n <= 1:
return n
else:
fib = [0, 1]
for i in range(2, n + 1):
fib.append(fib[i - 1] + fib[i - 2])
return fib[n]
|
504dc6bfcaab29b603394fef88fb6746b3766eab | paweldabrowa1/automat_biletowy_mpk | /automat_biletowy_mpk/coins/coins_holder.py | 2,434 | 3.8125 | 4 | from automat_biletowy_mpk.coins import *
class WrongAppendAmountException(Exception):
"""Throw when user gives negative number at CoinsHolder.append"""
pass
class WrongRemoveAmountException(Exception):
"""Throw when user gives positive number at CoinsHolder.remove"""
pass
class CoinsHolder:
"""
Some kind dictionary for managing Coins with some useful helpers.
It's initialized with basic set of acceptable coins
"""
def __init__(self):
self.__coins = {}
for coin in acceptable_coins():
self.__coins[coin] = 0
def __str__(self) -> str:
s = ""
for key, value in self.__coins.items():
s += "%s: \t%d\n" % (key, value)
return s
def append(self, coin, amount):
"""Used to add certain amount of coins to holder. Can't be negative!"""
if amount <= 0:
raise WrongAppendAmountException()
self.__coins[coin] = self.__coins[coin] + amount
def remove(self, coin, amount):
"""Used to remove certain amount of coins to holder. Can't be positive"""
if amount >= 0:
raise WrongRemoveAmountException()
self.__coins[coin] = self.__coins[coin] + amount
def set(self, coin, amount):
"""Used to set amount of coins in holder. Minimum is 0."""
if amount < 0:
amount = 0
self.__coins[coin] = amount
def get_amount(self, coin):
"""Used to retrieve amount of coins in holder"""
return self.__coins[coin]
def get_coins_dict(self):
"""Returns dictionary of coins to their amount"""
return self.__coins
def sum_all_coins_value(self):
"""Returns total value of coins in holder"""
total = 0
for coin, amount in self.__coins.items():
total += amount * coin.value
return total
def append_all(self, coin_dict):
"""Used to adding dictionary of coins and their amount to holder"""
for coin, amount in coin_dict:
self.append(coin, amount)
def append_holder(self, holder):
"""Used to union holder coins amounts"""
for coin, amount in holder.get_coins_dict().items():
if amount == 0:
continue
self.append(coin, amount)
def reset(self):
"""Sets every coin amount to 0."""
for c in self.get_coins_dict():
self.set(c, 0)
|
19cc319eb936384cf4fb5bc90be19d8aa3110488 | Aasthaengg/IBMdataset | /Python_codes/p02699/s255579636.py | 132 | 3.515625 | 4 | val = input().split()
sheep = int(val[0])
wolf = int(val[1])
if (wolf - sheep) >= 0:
print("unsafe")
else:
print("safe") |
725bad04a3d28723d4c8a1bb8ae69a213c65d899 | dti-t-s/pythonScraping | /save_csv_join.py | 376 | 3.78125 | 4 | print('rank,city,population')
# 2行目以降を書き出す join()メソッドの引数に渡すlistの要素はstrでなければならないことに注意
print(','.join(['1', '上海', '123']))
print(','.join(['2', 'カラチ', '123']))
print(','.join(['3', '北京', '123']))
print(','.join(['4', '天津', '123']))
print(','.join(['5', 'イスタンブル', '123'])) |
0b5a0c79639242c229cdf5c222db42ef9815e95b | FrankGuo22/Codeforces | /A295.py | 348 | 3.5 | 4 | # A295.py
a = raw_input()
string = raw_input()
judge = 0
chk = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0,}
for ch in string:
if chk[ch.lower()] == 0:
chk[ch.lower()] = 1
judge += 1
if judge == 26:
print 'YES'
else:
print 'NO' |
5e711633fdf4e7f11140244fffb097ffd8754054 | rangerjo/python.casa | /examples/kap09-func/fibonacci.py | 933 | 3.734375 | 4 | #!/usr/bin/env python3
# herkömmliche Funktion, liefert die ersten n
# Fibonacci-Zahlen
def fiblst(n):
a, b = 0, 1
result = []
for _ in range(n):
result += [a]
a, b = b, a+b
return result
print(fiblst(10))
# Ausgabe [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Generator-Funktion
def fibgen(n):
cnt = 0
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a+b
cnt += 1
if cnt > n:
return
print(fibgen(10))
# Ausgabe <generator object fibgen at 0x109569af0>
print(list(fibgen(10)))
# Ausgabe [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Fibonacci-Zahlen < 1000 ausgeben
gen = fibgen(100)
fib = next(gen)
while fib<1000:
print(fib)
fib = next(gen)
# nochmals, aber Generator zu klein
gen = fibgen(10)
fib = next(gen)
while fib<1000:
print(fib)
fib = next(gen, None)
if fib == None:
print('Generator erschöpft')
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.