blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
3afc1ab7a0de2bb6dc837084dd461865a2c34089 | mirpulatov/racial_bias | /IMAN/utils.py | 651 | 4.15625 | 4 | def zip_longest(iterable1, iterable2):
"""
The .next() method continues until the longest iterable is exhausted.
Till then the shorter iterable starts over.
"""
iter1, iter2 = iter(iterable1), iter(iterable2)
iter1_exhausted = iter2_exhausted = False
while not (iter1_exhausted and iter2_exhausted):
try:
el1 = next(iter1)
except StopIteration:
iter1_exhausted = True
iter1 = iter(iterable1)
continue
try:
el2 = next(iter2)
except StopIteration:
iter2_exhausted = True
if iter1_exhausted:
break
iter2 = iter(iterable2)
el2 = next(iter2)
yield el1, el2
|
410c378f69b9d4b2ff43c1ec249bb2bf63d94589 | organisciak/programming-puzzles | /finished/euler/001-multiples-of-3-5.py | 336 | 3.859375 | 4 | # Find the sum of all the multiples of 3 or 5 below 1000.
x = 10
# Simple solution
print sum([n for n in range(0, x) if n % 3 == 0 or n % 5 == 0])
# Adding the sums of iterate by 3 and iterate by 5 ranges, then subtract
# the iterate by 15 range. No comparisons!
print sum(range(0, x, 3)) + sum(range(0, x, 5)) + sum(range(0, x, 15))
|
821e12b328bc80de48c097fd78617807d1430bdd | django/django-localflavor | /localflavor/uy/util.py | 324 | 3.921875 | 4 | def get_validation_digit(number):
"""Calculates the validation digit for the given number."""
weighted_sum = 0
dvs = [4, 3, 6, 7, 8, 9, 2]
number = str(number)
for i in range(0, len(number)):
weighted_sum = (int(number[-1 - i]) * dvs[i] + weighted_sum) % 10
return (10 - weighted_sum) % 10
|
1d5d793833094834c00371b46286e3057187a968 | vampire7414/bin_dec_hexa | /binary_to_hexa.py | 210 | 4.09375 | 4 | print('hello I can change the number from binary to hexa')
binary=input('enter a binary number:')
decimalsolution=int(binary,base=2)
hexasolution=hex(decimalsolution)
print('the answer is')
print(hexasolution)
|
c155a4b2a15f2934639592340350320d40367904 | shiny0510/DataStructure_Python | /Algorithm analysis/graph.py | 688 | 3.828125 | 4 | import matplotlib.pyplot as plt
import numpy as np
n = np.arange(1, 1000)
m = np.arange(1, 31)
plt.figure(figsize=(10, 6))
# set new range m, because 2^1000 is to big to show
plt.plot(n, np.log(n), label="$\log_{2} n$") # 수의 subscribt를 나타내는 LaTeX
plt.plot(n, n, label="n")
plt.plot(n, n*np.log(n), label="$n \log_{2} n$")
plt.plot(n, n**2, label="n**2")
plt.plot(n, n**3, label="n**3")
plt.plot(m, 2**m, label="2**m")
# for better looking graph
plt.xscale("log")
plt.yscale("log")
plt.xlim(3, 1000)
plt.ylim(1, 1000000)
plt.xlabel("size")
plt.ylabel("time")
# show legend and grid
plt.legend(loc="upper left")
plt.grid(True)
plt.show()
|
ea3fb234b041a3eabf8a459e23de7a777d34e109 | james122823/DivideAndConquer | /week03/local_min.py | 4,294 | 3.734375 | 4 | def local_min(matrix):
"""
Assume matrix as a list of lists containing integer or floating point
values with NxN values.
"""
if len(matrix) == 2:
a = matrix[0][0]
b = matrix[0][1]
c = matrix[1][0]
d = matrix[1][1]
sort = sorted([a, b, c, d])
return sort[0] != sort[3]
mid = int(len(matrix)/2.0)
min_window_val = float("inf")
min_window_index = (0,0)
top_row = matrix[0]
mid_row = matrix[mid]
bottom_row = matrix[len(matrix)-1]
for c in range(len(matrix[0])):
if top_row[c] < min_window_val:
min_window_val = top_row[c]
min_window_index = (0, c)
if mid_row[c] < min_window_val:
min_window_val = mid_row[c]
min_window_index = (mid, c)
if bottom_row[c] < min_window_val:
min_window_val = bottom_row[c]
min_window_index = (len(matrix)-1, c)
for r in range(1, mid-1):
if matrix[r][0] < min_window_val:
min_window_val = matrix[r][0]
min_window_index = (r, 0)
if matrix[r][mid] < min_window_val:
min_window_val = matrix[r][mid]
min_window_index = (r, mid)
if matrix[r][len(matrix[r])-1] < min_window_val:
min_window_val = matirx[r][len(matrix[r])-1]
min_window_index = (r, len(matrix[r])-1)
for r in matrix[mid+1:len(matrix)-1]:
if matrix[r][0] < min_window_val:
min_window_val = matrix[r][0]
min_window_index = (r, 0)
if matrix[r][mid] < min_window_val:
min_window_val = matrix[r][mid]
min_window_index = (r, mid)
if matrix[r][len(matrix[r])-1] < min_window_val:
min_window_val = matirx[r][len(matrix[r])-1]
min_window_index = (r, len(matrix[r])-1)
is_top = min_window_index[0] == 0
is_bottom = min_window_index[0] == (len(matrix[0])-1)
is_left = min_window_index[1] == 0
is_right = min_window_index[1] == (len(matrix)-1)
in_topleft = (min_window_index[0] <= mid) and (min_window_index[1] <= mid)
in_topright = (min_window_index[0] <= mid) and (min_window_index[1] >= mid)
in_bottomleft = (min_window_index[0] >= mid) and (min_window_index[1] <= mid)
in_bottomright = (min_window_index[0] >= mid) and (min_window_index[1] >= mid)
if not is_top and\
matrix[min_window_index[0]-1][min_window_index[1]] < min_window_val:
# Look at the value one row above minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_bottom and\
matrix[min_window_index[0]+1][min_window_index[1]] < min_window_val:
# Look at the value one row below minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_left and\
matrix[min_window_index[0]][min_window_index[1]-1] < min_window_val:
# Look at the value one column left of minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_right and\
matrix[min_window_index[0]][min_window_index[1]+1] < min_window_val:
# Look at the value one one column right of minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
else:
return True
def recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
in_bottomright, mid, rownums):
quadrants = [in_topleft, in_topright, in_bottomleft, in_bottomright]
row_splices = [(0, mid+1), (0, mid+1), (mid, rownums), (mid, rownums)]
col_splices = [(0, mid+1), (mid, rownums), (0, mid+1), (mid, rownums)]
for (quadrant, row_splice, col_splice) in\
zip(quadrants, row_splices, col_splices):
rec_matrix = []
if quadrant:
for row in matrix[row_splice[0]:row_splice[1]]:
rec_matrix.append(row[col_splice[0]:col_splice[1]])
if local_min(rec_matrix):
return True
return False
a = [[5, 4, 3, 4], [2, 1, 0, 1], [1, 2, 3, 4], [5, 6, 7, 8]]
print local_min(a)
b = [[0]*4]*4
print local_min(b)
|
cd73a1f2faa6aa7c4c7f39a12133b1a34f45ad81 | zhihao0040/CodingPractice | /sort/InsertionSort/insertionSort.py | 1,308 | 4.09375 | 4 | import sys # to get command line arguments
sys.path.append("C:/Users/61491/Desktop/Youtube/Code/CodingPractice/sort")
import sortAuxiliary
# print(sys.path)
# print(len(sys.path))
fileName = sys.argv[1]
fileDataTuple = sortAuxiliary.getFileData(fileName)
# print(fileDataTuple)
# Insertion Sort
j = 0
key = 0
for i in range(1, fileDataTuple[0]):
j = i - 1
key = fileDataTuple[1][i]
while (j >= 0 and fileDataTuple[1][j] > key):
fileDataTuple[1][j + 1] = fileDataTuple[1][j]
j -= 1
fileDataTuple[1][j + 1] = key
# insertion sort is basically saying
# "hey we have sorted the first x elements/cards, now looking at my x + 1th element/card
# ask myself, where should I put it between my first x elements.
# Imagine having a 1,2,5,7 in your hand and now you are dealt a 4, you will scan through your cards
# and realize, 2 is biggest number smaller than 4, that's where you will put it.
# Since it is already sorted, the first number you find that is smaller than the number you want to insert is the
# biggest number smaller than the 'key'"
sortAuxiliary.writeToFile("insertionSortPyOutput.txt", fileDataTuple)
# print(myTextList)
# f = open("selectionSortPyOutput.txt", "w")
# for i in range(numOfElems):
# f.write(myTextList[i] + "\n")
|
e95ce9ca229634753a9e4815b556d56b6d1e6d84 | joemac51/expense_tracker | /main.py | 597 | 3.78125 | 4 | import matplotlib.pyplot as plt
from random import randint
def main():
total = 1000
monthly_total = []
net_income = 0
months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
for i in range(12):
income = randint(800,1000)
bills = randint(800,1050)
net_income += (income - bills)
monthly_total.append(total + net_income)
plt.xticks([i for i in range(12)],months)
plt.plot([i for i in range(12)],monthly_total)
plt.show()
main() |
2ce9b6b91689544425656cf62e63a1db0fa6c804 | EkajaSowmya/SravanClass | /Oct5/PythonOperators/ArithmeticOperators.py | 482 | 4.0625 | 4 | a = 8
b = 2
add = a + b
sub = a - b
mul = a * b
div = a / b
mod = a % b
pow = a ** b
print("addition of {0} and {1} is {2}" .format(a, b, add))
print("subtraction of {0} and {1} is {2}" .format(a, b, sub))
print("multiplication of {0} and {1} is {2}" .format(a, b, mul))
print("division of {0} and {1} is {2}" .format(a, b, div))
print("modulus of {0} and {1} is {2}" .format(a, b, mod))
print("power of {0} and {1} is {2}" .format(a, b, pow))
#print(add, sub, mul, div, mod, pow)
|
3a1566cb54285e6f282a6e871ec37ff22caba743 | EkajaSowmya/SravanClass | /conditionalStatements/ifStatement.py | 295 | 4.25 | 4 | n1 = int(input("enter first number"))
n2 = int(input("enter second number"))
n3 = int(input("enter third number"))
if n1 > n2 and n1 > n3:
print("n1 is largest", n1)
if n2 > n3 and n2 > n3:
print("n2 is largest number", n2)
if n3 > n1 and n3 > n2:
print("n3 is largest number", n3)
|
84b07291c22afde33416f88cde4351fb0d601b97 | EkajaSowmya/SravanClass | /MyworkSpace/sqrtOfNumber.py | 662 | 3.984375 | 4 | import math # this function will import only to this file
x = math.sqrt(25)
print(x)
#math round up to nearest number..
# between 2.1 to 2.4 will be round upto to 2
# between 2.5 to 2.9 will be round upto to 3
print(math.floor(2.9)) #floor func will always rounds up to least value
print(math.ceil(2.2)) #ceil func will always rounds upto to highest value
print(math.pow(3, 2))
print(math.pi)
print(math.e)
#to print the value of entered expression 1+2+3-2=4
result = eval(input("enter the expression")) #using eval func
print(result)
"""command line argument not working for me
import sys
x = int(sys.argv[1])
y = int(sys.argv[2])
z = x + y
print(z)"""
|
b05456fa275f9e3df3f2d381607ee3efbd3d2fa8 | EkajaSowmya/SravanClass | /conditionalStatements/forLoopDemo/assign3.py | 321 | 4.0625 | 4 | """1.WAP to print the following pattern below by skipping even number rows
* * * * *
* * *
*
"""
rows = int(input("Enter the number of rows: "))
for i in reversed(range(0, rows+1)):
for j in range(0, i+1):
if i % 2 == 0:
print("*", end=' ')
else:
print(end=' ')
print() |
4cd5b2b9b4c6764e849cb01e653b9c7de4e23545 | fredcallaway/hci | /python/gui.py | 3,972 | 3.703125 | 4 | #!/usr/bin/python
"""Gui is a Tkinter Entry object cmd line interface coupled with a Tkinter Canvas object
for display and Text object for history. The cmd line accepts natural language input
and the Canvas serves as the graphical interface. """
from Tkinter import *
"""
class ObjInfo:
def __init__(self, id, name, color, width, height):
self.id = id
self.name = name
self.color = color
self.width = width
self.height = height
"""
class Gui:
def __init__(self, width=400, height=400):
self.canvasWidth = width
self.canvasHeight = height
self.Wcenter = self.canvasWidth/2
self.Hcenter = self.canvasHeight/2
self.window = Tk()
self.canvas = Canvas(self.window, width = self.canvasWidth, height = self.canvasHeight) #canvas widget
self.canvas.pack() #arranges window components in a certain way. Alternatively, can use grid
self.objectList = []
def oval(self,name,color="cyan",Xdiam=120,Ydiam=80):
halfX=Xdiam/2
halfY=Ydiam/2
ovalId = self.canvas.create_oval(self.Wcenter-halfX,self.Hcenter-halfY,self.Wcenter+halfX,self.Hcenter+halfY,fill=color,tag=name)
self.objectList.append(ovalId)
self.canvas.update()
def circle(self, name, color="green", diameter=80):
radius = diameter/2
circleId = self.canvas.create_oval(self.Wcenter - radius, self.Hcenter - radius, self.Wcenter+ radius, self.Hcenter + radius, fill=color, tag=name)
self.objectList.append(circleId)
self.canvas.update()
def rectangle(self,name,color="orange",sideX=120,sideY=80):
halfX=sideX/2
halfY=sideY/2
rectID = self.canvas.create_rectangle(self.Wcenter-halfX,self.Hcenter-halfY,self.Wcenter+halfX,self.Hcenter+halfY,fill=color,tag=name)
self.objectList.append(rectID)
self.canvas.update()
def square(self, name, color="red",side=80):
radius = side/2
squareID = self.canvas.create_rectangle(self.Wcenter - radius, self.Hcenter - radius, self.Wcenter + radius, self.Hcenter + radius, fill=color, tag=name)
self.objectList.append(squareID)
self.canvas.update()
def changeColor(self,name,color):
self.canvas.itemconfig(name,fill=color)
self.canvas.update()
#positions object A next to object B, on the right by default
def positionNextTo(self,nameA,nameB,where="right"):
acoord = self.canvas.coords(nameA)
bcoord = self.canvas.coords(nameB)
wha = (acoord[2]-acoord[0])/2 #half-width
hha = (acoord[3]-acoord[1])/2 #half-height
wcb = (bcoord[2]-bcoord[0])/2 + bcoord[0] #center width
hcb = (bcoord[3]-bcoord[1])/2 + bcoord[1] #center height
if where=='right':
self.canvas.coords(nameA,bcoord[2],hcb-hha,bcoord[2]+2*wha,hcb+hha)
elif where=='left':
self.canvas.coords(nameA,bcoord[0]-2*wha,hcb-hha,bcoord[0],hcb+hha)
elif where=='below':
self.canvas.coords(nameA,wcb-wha,bcoord[3],wcb+wha,bcoord[3]+2*hha)
elif where=='above':
self.canvas.coords(nameA,wcb-wha,bcoord[1]-2*hha,wcb+wha,bcoord[1])
else:
print "I don't know that position!"
self.canvas.update()
def moveExactly(self,name,dx,dy):
coord = self.canvas.move(name,dx,dy)
self.canvas.update()
#for moving abstractly
def move(self,name,dir):
dx = self.canvasWidth*0.1
dy = self.canvasHeight*0.1
if dir=='right':
self.canvas.move(name,dx,0)
elif dir=='left':
self.canvas.move(name,-dx,0)
elif dir=='up':
self.canvas.move(name,0,dy)
elif dir=='down':
self.canvas.move(name,0,-dy)
else:
print "I don't understand that direction!"
def hide(self,name):
self.canvas.itemconfig(name,state=HIDDEN)
self.canvas.update()
def unhide(self,name):
self.canvas.itemconfig(name,state=NORMAL)
#bring to top so the user can see it
#self.canvas.tag_raise(name) #?? do we want to do it this way
self.canvas.update()
def setBackground(self,color='white'):
self.canvas.config(background=color)
self.canvas.update()
def layer(self,name,upordown,of=None):
if of==None:
if upordown=='ab'
self.canvas.tag_raise(name)
self.canvas.update()
else:
print "I don't know how to do that yet."
|
9c8ff15b91ab3900f5007c33f615ccc06a50f740 | miljimo/pymvvm | /mvvm/argsvalidator.py | 796 | 3.703125 | 4 |
class ArgsValidator(object):
'''
@ArgValidator : this validate the argument given to make sure
that unexpected argument is given.
'''
def __init__(self,name, expected_args:list):
if(type(expected_args) != list):
raise TypeError("@ArgValidator: expecting a first object of the variable names expected.");
self.__expected_args = expected_args
self.__Name = name;
@property
def Name(self):
return self.__Name;
@property
def Args(self):
return self.__expected_args;
def Valid(self, **kwargs):
for key in kwargs:
if( key in self.__expected_args) is not True:
raise ValueError("{1} : Unknown '{0}' argument provided".format(key, self.Name))
return True;
|
86f5185710ab26a4789b844911a16e8399444ead | vivinraj/python4e | /ex_08/ex_08_05.py | 314 | 3.96875 | 4 | fname = input("Enter file name: ")
fh = open(fname)
count = 0
words=list()
for line in fh:
words=line.split()
if len(words)>1 :
if words[0] != 'From' :
continue
else:
word=words[1]
print(word)
count=count+1
print("There were", count, "lines in the file with From as the first word")
|
fe84ca931af6ee9ebce2b0d4013b01ea42275728 | crystal2001/U4Lesson5 | /problem5.py | 420 | 3.9375 | 4 | from turtle import *
bean = Turtle()
bean.color("black")
bean.pensize(5)
bean.speed(9)
bean.shape("turtle")
def drawStar():
for x in range(5):
bean.forward(50)
bean.left(144)
def row():
for x in range(3):
drawStar()
bean.penup()
bean.forward(70)
bean.pendown()
for y in range(4):
row()
bean.penup()
bean.backward(210)
bean.right(90)
bean.forward(60)
bean.left(90)
bean.pendown()
mainloop()
|
22377fd49f81c618e0d106af62e713383c03ac44 | soldierloko/Fiap | /Sprint1/Socket_IP.py | 218 | 3.8125 | 4 | import socket
resp ='S'
while (resp == 'S'):
url = input("DIgite um URL: ")
ip=socket.gethostbyname(url)
print("O IP referente à URL informada é: ", ip)
resp=input("Digite <S> para continuar: ").upper |
2d2deb268503beaefa09a399ea35fab09deaa86c | rahulremanan/akash_ganga | /src/create_video.py | 1,949 | 3.78125 | 4 | """
Dependencies:
pip install opencv - python
pngs_to_avi.py
Makes all the PNGs from one dir into a video .avi file
usage: pngs_to_avi.py [-h] [-d] png_dir
Author: Avi Vajpeyi and Rahul Remanan
"""
import sys
import argparse
import glob
import cv2
import os
def make_movie_from_png(png_dir, delete_pngs=False):
"""
Takes PNG image files from a dir and combines them to make a movie
:param png_dir: The dir with the PNG
:return:
"""
vid_filename = png_dir.split("/")[-1] + ".avi"
vid_filepath = os.path.join(png_dir, vid_filename)
images = glob.glob(os.path.join(png_dir, "*.png"))
if images:
frame = cv2.imread(images[0])
height, width, layers = frame.shape
video = cv2.VideoWriter(vid_filepath, -1, 25, (width, height))
for image in images:
video.write(cv2.imread(image))
video.release()
if delete_pngs:
for f in images:
os.remove(f)
return True
return False
def main():
"""
Takes command line arguments to combine all the PNGs in dir into a .avi
Positional parameters
[STRING] png_dir: the dir containing the png files
Optional parameters
[BOOL] delete: to delete the PNG files once converted into a video
:return: None
"""
parser = argparse.ArgumentParser(description='Process PNG files.')
# Positional parameters
parser.add_argument("png_dir", help="dir where png files located")
# Optional parameters
parser.add_argument("-d", "--delete",
help="delete PNG files after .avi creation",
action="store_true")
args = parser.parse_args()
if os.path.isdir(args.fits_dir):
make_movie_from_png(png_dir=args.png_dir,
delete_pngs=args.delete)
else:
print("Error: Invalid png dir")
sys.exit(1)
pass
if __name__ == "__main__":
main()
|
bb6d7d12aef583ea46f13c948dc52c61416225ac | yuyaxiong/interveiw_algorithm | /剑指offer/表示数值的字符串.py | 1,361 | 3.8125 | 4 | """
请实现一个函数用来判断字符串是否表示数值(包括:整数和小数)。
例如,字符串“+100”、“5e2”、“-123”,"3.1416"及“-1E-16”都
表示数值,但“12e”,"la3.14","1.2.3", '+-5'及’12e+5.4’
"""
class Solution(object):
def is_numeric(self, n):
num_str = [str(i) for i in range(1, 11)]
if len(n)<=0:
return False
if n[0] in ['+', '-']:
n = n[1:]
if n[0] == '.':
n = n[1:]
for num in n:
if num not in num_str:
return False
else:
if 'e' in n or 'E' in n:
n_list = n.split('e') if 'e' in n else n.split('E')
front, end = n_list[0], n_list[1]
for i in front:
if i not in num_str + ['.']:
return False
if len(end) == 0:
return False
if end[0] in ['+', '-']:
end = end[1:]
for i in end:
if i not in num_str:
return False
else:
for i in n:
if i not in num_str:
return False
return True
if __name__ == "__main__":
s = Solution()
print(s.is_numeric('12e+5.4')) |
f2f78e6d9900affeec2f38188471d95f25ed009a | yuyaxiong/interveiw_algorithm | /LeetCode/二叉树/652.py | 981 | 3.90625 | 4 | # Definition for a binary tree node.
# 652. 寻找重复的子树
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
if root is None:
return []
self.subtree_dict = dict()
self.result = []
self.traverse(root)
return self.result
def traverse(self, root):
if root is None:
return "#"
left, right = self.traverse(root.left), self.traverse(root.right)
subtree = left + "," + right + "," + str(root.val)
if self.subtree_dict.get(subtree) is None:
self.subtree_dict[subtree] = 1
else:
self.subtree_dict[subtree] += 1
if self.subtree_dict.get(subtree) == 2:
self.result.append(root)
return subtree |
d5b65c0ca0fc84a09f17f172404072d108c52afb | yuyaxiong/interveiw_algorithm | /剑指offer/和为S的连续正数序列.py | 849 | 3.546875 | 4 | """
输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
例如:输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以打印出3个连续
序列1-5,4-6和7-8。
"""
class Solution(object):
def find_continuous_sequence(self, sum):
small, bigger = 1, 2
while small < bigger:
if (small + bigger) * (bigger - small+1) / 2 == sum:
self.print_num(small, bigger)
bigger += 1
elif (small + bigger) * (bigger - small+1) / 2 > sum:
small += 1
else:
bigger += 1
def print_num(self, small, bigger):
strings = ''
for n in range(small, bigger+1):
strings += '%s, ' % n
print(strings)
if __name__ == '__main__':
s = Solution()
s.find_continuous_sequence(15) |
e9745a6d2620ea9d036316d094c55b46be30bbeb | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/234.py | 1,251 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 234.回文链表
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
n_list = []
while head is not None:
n_list.append(head.val)
head = head.next
print(n_list)
i, j = 0, len(n_list)-1
status = True
while i < j:
if n_list[i] != n_list[j]:
status = False
break
else:
i +=1
j -= 1
return status
class Solution1:
def isPalindrome(self, head: ListNode) -> bool:
p_head = head
pre_node = ListNode(p_head.val)
p_head = p_head.next
while p_head is not None:
node = ListNode(p_head.val)
node.next = pre_node
pre_node = node
p_head = p_head.next
status = True
while pre_node is not None and head is not None:
if pre_node.val == head.val:
pre_node = pre_node.next
head = head.next
else:
status = False
break
return status
|
7d2fd46534fca8d061e10b0ea73727c96631d14b | yuyaxiong/interveiw_algorithm | /剑指offer/第一个只出现一次的字符.py | 609 | 3.71875 | 4 | """
第一个只出现一次的字符。
在字符串中找出第一个只出现一次的字符。如输入:"abaccdeff",则输出"b"
"""
class Solution(object):
def first_not_repeating(self, pStrings):
if pStrings is None:
return None
s_count = {}
for s in pStrings:
if s_count.get(s) is None:
s_count[s] = 1
else:
s_count[s] += 1
for s in pStrings:
if s_count[s] == 1:
return s
if __name__ == '__main__':
s = Solution()
print(s.first_not_repeating("abaccdeff"))
|
79e0143f69a52b4379d644978551f76a90726e0c | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/141.py | 607 | 3.84375 | 4 | # Definition for singly-linked list.
from typing import Optional
# 141.环形链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
if __name__ == "__main__":
head_list = [-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5] |
6a9bab008e394d48679ea4ed304c4dbe8c42ef55 | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/21.py | 796 | 3.921875 | 4 | # Definition for singly-linked list.
# 21.合并两个有序链表
from typing import Optional
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]:
head = ListNode()
p_head = head
while list1 is not None and list2 is not None:
if list1.val < list2.val:
head.next = list1
list1 = list1.next
else:
head.next = list2
list2 = list2.next
head = head.next
if list1 is not None:
head.next = list1
if list2 is not None:
head.next = list2
return p_head.next |
9f74d1a7787bddd889b1abb1f786edca3b769d81 | yuyaxiong/interveiw_algorithm | /剑指offer/正则表达式匹配.py | 1,455 | 3.515625 | 4 | """
请实现一个函数用来匹配包含'.'和'*'的正则表达式。
模式中的字符'.'表示任意一个字符,而'*'表示它前面的
字符可以出现任意次(含0次)。在本题中,匹配是指字符串
的所有所有字符匹配整个模式。例如,字符串"aaa"与模式
"a.a"和"ab*ac*a"匹配,但与"aa.a"和"ab*a"均不匹配。
"""
class Solution(object):
def match(self, strings, pattern):
if strings is None or pattern is None:
return False
return self.match_core(strings, pattern)
def match_core(self, strings, pattern):
if len(strings) == 0 and len(pattern) == 0:
return True
if len(strings) != 0 and len(pattern) == 0:
return False
if len(pattern) >= 2 and pattern[1] == '*':
if pattern[0] == strings[0] or (pattern[0] == '.' and len(strings) != 0):
# parttern[0] 在string[0]中出现1次, 出现N次
return self.match_core(strings[1:], pattern[2:]) or self.match_core(strings[1:], pattern)
else:
#pattern[0] 在string[0]中出现 出现0次
return self.match_core(strings, pattern[2:])
if (strings[0] == pattern[0]) or (pattern[0] == '.' and len(strings) != 0):
return self.match_core(strings[1:], pattern[1:])
return False
if __name__ == '__main__':
s = Solution()
print(s.match('aaa', 'ab*a'))
|
ef92a4e1ebdf637dc387c96ba210fcaa95b7ffde | yuyaxiong/interveiw_algorithm | /剑指offer/二叉树的深度.py | 1,525 | 4.15625 | 4 | """
输入一颗二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点(含根,叶节点)形成树的一条路径,
最长路径的长度为树的深度。
5
3 7
2 8
1
"""
class BinaryTree(object):
def __init__(self):
self.value = None
self.left = None
self.right = None
class Solution(object):
def tree_depth(self, pRoot):
depth = 0
current = 0
return self.depth_help(pRoot, depth, current)
def depth_help(self, pRoot, depth, current):
if pRoot is None:
return depth
current += 1
depth = max(depth, current)
depth = self.depth_help(pRoot.left, depth, current)
depth = self.depth_help(pRoot.right, depth, current)
return depth
class Solution1(object):
def tree_depth(self, pRoot):
if pRoot is None:
return 0
left = self.tree_depth(pRoot.left)
right = self.tree_depth(pRoot.right)
return max(left, right) + 1
if __name__ == '__main__':
pRoot = BinaryTree()
pRoot.value = 5
pRoot.left = BinaryTree()
pRoot.left.value = 3
pl = pRoot.left
pRoot.right = BinaryTree()
pRoot.right.value = 7
pr = pRoot.right
pl.left = BinaryTree()
pl.right = BinaryTree()
pr.left = BinaryTree()
pr.right = BinaryTree()
pl.left.value = 2
pl.right.value = 4
# pr.left.value =
pr.right.value = 8
s = Solution1()
print(s.tree_depth(pRoot)) |
effff8cdf0de849a58edd641191a5c94c2b24f45 | yuyaxiong/interveiw_algorithm | /LeetCode/二分搜索/35.py | 529 | 3.6875 | 4 |
# 35. 搜索插入位置
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return self.findN(nums, target, 0, len(nums)-1)
def findN(self, nums, target, s, e):
if s > e:
return s
mid = int((s + e)/2)
if nums[mid] == target:
return mid
elif nums[mid] > target:
return self.findN( nums,target, s, mid-1)
elif nums[mid] < target:
return self.findN(nums, target, mid+1, e)
|
3a4131cff2a2fa57137ffcdecb2b51d0bb884098 | yuyaxiong/interveiw_algorithm | /剑指offer/数组中数值和下表相等的元素.py | 1,590 | 3.796875 | 4 | """
数组中数值和下标相等的元素
假设一个单调递增的数组里的每个元素都是整数并且是唯一的。
请编程实现一个函数,找出数组中任意一个数值等于其下标的元素。
例如:在数组[-3, -1, 1, 3, 5]
"""
class Solution(object):
def get_num_same_as_index(self, num, length):
if num is None or length <= 0:
return -1
left = 0
right = length -1
while left <= right:
mid = (left + right) // 2
if num[mid] == mid:
return mid
if num[mid] > mid:
right = mid -1
else:
left = mid + 1
return -1
class Solution1(object):
def get_num_same_as_index(self, num, length, s, e):
if s > e:
return -1
mid = (s + e) //2
if nList1[mid] == mid:
return mid
elif num[mid] > mid:
e = mid -1
else:
s = mid + 1
return self.get_num_same_as_index(num , length, s, e)
class Solution3(object):
def get_idx(self, nList, n):
left, right = 0, len(nList)-1
while left < right:
mid = (left + right) // 2
if nList[mid] > n:
right = mid -1
elif nList[mid] < n:
left = mid + 1
else:
return mid
return left
if __name__ == '__main__':
nList1 = [-3, -1, 1, 3, 5]
s = Solution3()
# print(s.get_num_same_as_index(nList1, len(nList1), 0,len(nList1)-1))
print(s.get_idx(nList1, 2)) |
295269c2e2f17f0aa0dbd9e75ddbdd60e240128c | yuyaxiong/interveiw_algorithm | /剑指offer/合并两个排序的链表.py | 1,538 | 3.8125 | 4 | """
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
例如, 输入图3.11中的链表1和链表2,则合并之后的升序链表如链表3所示。
1->3->5->7
2->4->6->8
1->2->3->4->5->6->7->8
"""
class ListNode(object):
def __init__(self):
self.value = None
self.next = None
class Solution(object):
def merge_list(self, pHead1, pHead2):
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
pHead = ListNode()
pNode = pHead
while pHead1 is not None and pHead2 is not None:
if pHead1.value > pHead2.value:
pNode.next = pHead2
pNode = pNode.next
pHead2 = pHead.next
else:
pNode.next = pHead1
pNode = pNode.next
pHead1 = pHead1.next
if pHead1 is not None:
pNode.next = pHead1
if pHead2 is not None:
pNode.next = pHead2
return pHead.next
class Solution1(object):
def merge(self, pHead1, pHead2):
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
pMergeHead = None
if pHead1.value < pHead2.value:
pMergeHead = pHead1
pMergeHead.next= self.merge(pHead1.next, pHead2)
else:
pMergeHead = pHead2
pMergeHead.next = self.merge(pHead1, pHead2.next)
return pMergeHead
|
6da2c66f141939606b9833e15c2a9628ee342864 | yuyaxiong/interveiw_algorithm | /LeetCode/二分搜索/1101.py | 1,177 | 3.546875 | 4 | from typing import List
# 1011. 在 D 天内送达包裹的能力
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
max_val = sum(weights)
min_val = max(weights)
return self.carrayWeight(weights, min_val, max_val, days)
def carrayWeight(self, weights, s, e, days):
if s == e:
return s
mid = (s + e) // 2
if self.carrayDays(weights, mid) > days:
return self.carrayWeight(weights, mid + 1, e, days)
else:
return self.carrayWeight(weights, s, mid, days)
def carrayDays(self, weights, limitWeight):
days = 0
cumWeight = 0
for w in weights:
if cumWeight + w > limitWeight:
days += 1
cumWeight = w
elif cumWeight + w == limitWeight:
days += 1
cumWeight = 0
else:
cumWeight += w
if cumWeight != 0:
days += 1
return days
if __name__ == "__main__":
s = Solution()
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
limitWeight = 11
print(s.carrayDays(weights, limitWeight)) |
a0c5d2ce5d084e464205eedc1e753fcb97dcc463 | yuyaxiong/interveiw_algorithm | /剑指offer/两个链表的第一个公共节点.py | 2,125 | 3.5625 | 4 | """
输入两个链表,找出它们的第一个公共节点。
1->2->3->6->7
4->5->6->7
"""
class ListNode(object):
def __init__(self):
self.value = None
self.next = None
class Solution(object):
def find_first_common_node(self, pHead1, pHead2):
pList1, pList2 = [], []
while pHead1.next is not None:
pList1.append(pHead1)
pHead1 = pHead1.next
while pHead2.next is not None:
pList2.append(pHead2)
pHead2 = pHead2.next
p1, p2 = pList1.pop(), pList2.pop()
last = None
while p1 == p2:
last = p1
p1 = pList1.pop()
p2 = pList2.pop()
return last
class Solution1(object):
def find_first_common_node(self, pHead1, pHead2):
p1, p2 = pHead1, pHead2
counter1 = 0
counter2 = 0
while pHead1.next is not None:
counter1 += 1
pHead1 = pHead1.next
while pHead2.next is not None:
counter2 += 1
pHead2 = pHead2.next
if counter1 > counter2:
while counter1 - counter2 > 0:
counter1 -= 1
p1 = p1.next
elif counter1 < counter2:
while counter2 - counter1 > 0:
counter2 -= 1
p2 = p2.next
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1
if __name__ == '__main__':
pHead1 = ListNode()
pHead1.value = 1
pHead1.next = ListNode()
pHead1.next.value = 2
pHead1.next.next = ListNode()
pHead1.next.next.value = 3
pHead1.next.next.next = ListNode()
pHead1.next.next.next.value = 6
pHead1.next.next.next.next = ListNode()
pHead1.next.next.next.next.value = 7
pHead2 = ListNode()
pHead2.value = 4
pHead2.next = ListNode()
pHead2.next.value = 5
pHead2.next.next = pHead1.next.next.next
s = Solution()
node = s.find_first_common_node(pHead1, pHead2)
s1 = Solution1()
node1 = s1.find_first_common_node(pHead1, pHead2)
print(node.value)
print(node1.value)
|
1e9fd34c7a9f795ae1b750675d98f51a72c448c9 | yuyaxiong/interveiw_algorithm | /LeetCode/回溯算法/698.py | 1,886 | 3.609375 | 4 | #698. 划分为k个相等的子集
# leetcode 暴力搜索会超时
from typing import List
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
if k > len(nums):
return False
sum_val = sum(nums)
if sum_val % k != 0:
return False
used_list = [False for _ in nums]
target = sum_val/k
return self.backtrack(k, 0, nums, 0, used_list, target)
def backtrack(self, k, bucket, nums, start, used_list, target):
status = False
if k == 0:
status = True
return status
if bucket == target:
return self.backtrack(k -1, 0, nums, 0, used_list, target)
for i in range(start, len(nums)):
if used_list[i]:
continue
if nums[i] + bucket > target:
continue
used_list[i] = True
bucket += nums[i]
if self.backtrack(k, bucket, nums, i+1, used_list, target):
status = True
return status
used_list[i] = False
bucket -= nums[i]
return False
def testCase():
nums = [3,9,4,5,8,8,7,9,3,6,2,10,10,4,10,2]
k = 10
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase1():
nums = [10,5,5,4,3,6,6,7,6,8,6,3,4,5,3,7]
k = 8
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase2():
nums = [4,3,2,3,5,2,1]
k = 4
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase3():
nums = [3522,181,521,515,304,123,2512,312,922,407,146,1932,4037,2646,3871,269]
k = 5
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
if __name__ == "__main__":
# testCase()
# testCase1()
# testCase2()
testCase3()
|
b9b1cb636e5e6168dbd58feb3f1266251d2abb7a | yuyaxiong/interveiw_algorithm | /剑指offer/二叉搜索树的后续遍历序列.py | 1,194 | 3.765625 | 4 | """
输入一个整数数组,判断该数组是否是某二叉搜索树的后续遍历结果。如果是则返回True,否则返回False。
假设输入的数组的任意两个数字都互不相同。例如,输入数组(5,7,6,9,11,10,8),则返回True,
因为这个整数序列是图4.9二叉搜索树的后续遍历结果。如果输入的数组是(7,4,6,5),则由于没有哪
颗二叉搜索树的后续遍历结果是这个序列,因此返回False。
8
6 10
5 7 9 11
"""
class Solution(object):
def verify_sequence_of_BST(self, nList):
if len(nList) == 0:
return True
root = nList[-1]
mid = 0
for idx, n in enumerate(nList):
if n >= root:
mid = idx
break
left, right = nList[:mid], nList[mid:-1]
for n in right:
if n < root:
return False
return self.verify_sequence_of_BST(left) and self.verify_sequence_of_BST(right)
if __name__ == '__main__':
s = Solution()
# nList = [5, 7, 6,9, 11, 10, 8]
nList = [7, 4, 6, 5]
print(s.verify_sequence_of_BST(nList))
|
accb77819a60ed86e64f5bf268f99662e8d40d48 | yuyaxiong/interveiw_algorithm | /剑指offer/之字形打印二叉树.py | 1,661 | 3.875 | 4 | """
请实现一个函数按照之字型顺序定二叉树,即第一行按照从左到右的顺序打印,
第二层按照从右到左的顺序打印,第三行按照从左到右的顺序打印,其他行依次类推。
例如,按之字形打印图4.8中二叉树的结构
8
| |
6 10
|| ||
5 7 9 11
"""
class BinaryTree(object):
def __init__(self):
self.value = None
self.left = None
self.right = None
class Solution(object):
# 需要NList是个栈
def print_bt(self, nList, depth):
if len(nList) == 0:
return
tmp = []
strings = ''
for node in nList:
strings += '%s\t' % node.value
if depth % 2 == 1:
if node.left is not None:
tmp.append(node.left)
if node.right is not None:
tmp.append(node.right)
else:
if node.right is not None:
tmp.append(node.right)
if node.left is not None:
tmp.append(node.left)
depth += 1
print(strings)
print('\n')
self.print_bt(tmp[::-1], depth)
if __name__ == '__main__':
pRoot = BinaryTree()
pRoot.value = 8
pRoot.left = BinaryTree()
pRoot.right = BinaryTree()
pRoot.left.value = 6
pRoot.right.value = 10
pl = pRoot.left
pr = pRoot.right
pl.left = BinaryTree()
pl.right = BinaryTree()
pr.left = BinaryTree()
pr.right = BinaryTree()
pl.left.value = 5
pl.right.value = 7
pr.left.value = 9
pr.right.value = 11
s = Solution()
s.print_bt([pRoot], 1) |
951af0dad234a397cadd2839c7695ee9397803ba | yuyaxiong/interveiw_algorithm | /LeetCode/数据结构设计/380.py | 1,412 | 3.828125 | 4 |
# 380. O(1) 时间插入、删除和获取随机元素
import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.valToIdx = dict()
def insert(self, val: int) -> bool:
if self.valToIdx.get(val) is not None:
return False
self.valToIdx[val] = len(self.nums)
self.nums.append(val)
return True
def remove(self, val: int) -> bool:
if self.valToIdx.get(val) is None:
return False
idx = self.valToIdx.get(val)
last_val = self.nums[-1]
self.valToIdx[last_val] = idx
self.nums[idx] = last_val
self.nums.pop()
del self.valToIdx[val]
return True
def getRandom(self) -> int:
return self.nums[random.randint(0, len(self.nums)-1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
def testCase():
rs_sol = RandomizedSet()
# ret = [rs_sol.insert(1), rs_sol.remove(2), rs_sol.insert(2), rs_sol.getRandom(), rs_sol.remove(1), rs_sol.insert(2), rs_sol.getRandom()]
ret = [rs_sol.insert(0), rs_sol.insert(1), rs_sol.remove(0), rs_sol.insert(2), rs_sol.remove(1), rs_sol.getRandom()]
# print(rs_sol.nums)
# print(rs_sol.valToIdx)
print(ret)
if __name__ == "__main__":
testCase()
|
0de9cbdec2ec0cb42e75376e9df8a989cfd4b405 | jougs/m4light | /espmpylight/animate.py | 850 | 3.9375 | 4 |
def map(val, in_min, in_max, out_min, out_max):
"""map a value val from one interval (in) to another (out)"""
return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def smoothstep(t, t_offs, duration, scale):
"""Function to fade smoothly from one value to another.
The canonical smoothstep equation is 3x^2-2x^3.
See https://en.wikipedia.org/wiki/Smoothstep for details.
Here, we use t - t_offs divided by duration as x to shift the
transition by t_offs into the future and stretch it to length
duration. We then multiply by it by scale to get the desired
height.
Please note that scale might be negative
"""
if t <= t_offs: return 0
if t >= t_offs + duration: return scale
t -= t_offs
t_div_d = t / duration
return (3 * t_div_d**2 - 2 * t_div_d**3) * scale
|
99f0223f2acdc0fba4a59939980b3f1e11781344 | MappingSystem/bonding | /Polygons.py | 4,144 | 4.3125 | 4 | import math
class Polygons:
""" This is the superclass."""
def number_of_sides(self):
return 0
def area(self):
return 0
def perimeter(self):
return 0
class Triangle(Polygons):
""" Models the properties of a triangle """
def number_of_sides(self):
return 3
def area(self, base, height):
return 1 / 2 * base * height
def perimeter(self, a, b, c):
if a + b > c:
return a + b + c
else:
return "Invalid input: make sure a + b > c"
def herons_formula(self, a, b, c):
""" Alternative to finding area of triangle. """
# s = semi perimeter
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
class Rhombus(Polygons):
"""" Models the properties of a Rhombus."""
def number_of_sides(self):
return 4
def area(self, p, q):
""" p is a Diagonal and q is a Diagonal.
The formula is A = p*q/2. """
return p * q / 2
def perimeter(self, a):
return 4 * a
class Pentagon(Polygons):
""" Models the properties of a regular Pentagon. """
def number_of_sides(self):
return 5
def area(self, a):
""" This is area of regular pentagon"""
return 1 / 4 * math.sqrt(5 * (5 + 2 * math.sqrt(5))) * a ** 2
def perimeter(self, a):
return 5 * a
class Hexagon(Polygons):
""" Models the properties of a regular Hexagon. """
def number_of_sides(self):
return 6
def area(self, a):
""" Models area of a regular hexagon."""
return (3 * math.sqrt(3) / 2) * a ** 2
def perimeter(self, a):
return 6 * a
class Heptagon(Polygons):
""" Models the properties of a regular Heptagon. """
def number_of_sides(self):
return 7
def area(self, a):
""" Area for regular heptagon. """
# convert degrees into radians.
deg = 180 * math.pi / 180
return (7 / 4 * a ** 2) * 1 / math.tan(deg / 7)
def perimeter(self, a):
return 7 * a
class Octagon(Polygons):
""" Models the properties of a regular Octagon. """
def number_of_sides(self):
return 8
"""" Area of regular Octagon. """
def area(self, a):
return 2 * (1 + math.sqrt(2)) * a ** 2
def perimeter(self, a):
return 8 * a
class Nonagon(Polygons):
"""" Models the properties of a regular Nonagon. """
def number_of_sides(self):
return 9
def area(self, a):
""" Models area of a regular Nonagon. """
# Python expects radians, so convert 180 to radians
deg = 180 * math.pi / 180
return 9 / 4 * a ** 2 * 1 / math.tan(deg / 9)
def perimeter(self, a):
return 9 * a
class Decagon(Polygons):
"""" Models the properties of a regular Decagon. """
def number_of_sides(self):
return 10
""" Area of a regular Decagon. """
def area(self, a):
return 5 / 2 * a ** 2 * math.sqrt(5 + 2 * math.sqrt(5))
def perimeter(self, a):
return 10 * a
# Below is some test cases.
tri = Triangle()
print("Triangle Area:", tri.area(5, 10))
print("Herons formula:", tri.herons_formula(5, 4, 3))
print("Perimeter:", tri.perimeter(20, 71, 90))
print("-----------------")
rho = Rhombus()
print("Rhombus Area:", rho.area(12.3, 83.9))
print("Perimeter:", rho.perimeter(5))
print("-----------------")
pent = Pentagon()
print("Pentagon Area:", pent.area(5))
print("Perimeter:", pent.perimeter(7.5))
print("-----------------")
hex = Hexagon()
print("Hexagon Area:", hex.area(5))
print("Perimeter:", hex.perimeter(11.25))
print("-----------------")
hep = Heptagon()
print("Heptagon Area:", hep.area(10))
print("Perimeter:", hep.perimeter(8))
print("-----------------")
oct = Octagon()
print("Octagon Area:", oct.area(10))
print("Perimeter:", oct.perimeter(7))
print("-----------------")
non = Nonagon()
print("Nonagon Area:", non.area(6))
print("Perimeter", non.perimeter(5))
print("-----------------")
dec = Decagon()
print("Decagon Area:", dec.area(10))
print(dec.perimeter(11.25))
|
48554cbfb4796689c3fd8410f975c4c3177b156c | marloncard/Terminal-trader | /sql_generic.py | 597 | 3.65625 | 4 | #!/usr/bin/env python3
def create_insert(table_name, columns):
columnlist = ", ".join(columns)
qmarks = ", ".join("?" for val in columns)
SQL = """ INSERT INTO {table_name} ({columnlist})
VALUES ({qumarks})
"""
return SQL.format(table_name=table_name,
columnlist=columnlist,
qmarks=qmarks)
if __name__ == '__main__':
print(create_insert("employees",
["first_name",
"last_name",
"employee_id",
"birth_date"])) |
894c5bd3426c7d33e4c4876940b788c490ad43e9 | CrocodileCroco/LPassGen | /LPassGen.py | 985 | 3.515625 | 4 | from tkinter import *
from functools import partial
import random
root = Tk()
genrated = ''
def passgen():
genrated = ''
charlimitset = 0
charlimitset = int(entry_chlimit.get())
charlimitloop = charlimitset
print(charlimitset)
path = 'passletters.txt'
letterlist = open(path,'r')
ltrlist = letterlist.read().splitlines()
print(ltrlist)
while charlimitloop > 0 :
genrated += random.choice(ltrlist)
charlimitloop = charlimitloop - 1
entry_name.delete('0',END)
entry_name.insert('0',genrated)
print(genrated)
text = genrated
label = Label(root, text='')
entry_name = Entry(root, textvariable=text)
longtext = Label(root, text='Character Limit:')
entry_chlimit = Entry(root)
button = Button(root, text='Generate', command=passgen)
entry_name.grid(column=0, row=1)
longtext.grid(column=0, row=3)
entry_chlimit.grid(column=0, row=4)
button.grid(column=0, row=5)
root.iconbitmap('iconefulltaille.ico')
root.mainloop() |
23093aeec021225ca268b13ff12cd6cb6fdc0f7d | task-master98/ReinforcementLearning | /Environments/Trial.py | 1,096 | 3.65625 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
pos = pygame.Vector2(100, 100)
clock = pygame.time.Clock()
# speed of your player
speed = 2
# key bindings
move_map = {pygame.K_LEFT: pygame.Vector2(-1, 0),
pygame.K_RIGHT: pygame.Vector2(1, 0),
pygame.K_UP: pygame.Vector2(0, -1),
pygame.K_DOWN: pygame.Vector2(0, 1)}
while run:
for e in pygame.event.get():
if e.type == pygame.QUIT: run = False
screen.fill((30, 30, 30))
# draw player, but convert position to integers first
pygame.draw.circle(screen, pygame.Color('dodgerblue'), [int(x) for x in pos], 10)
pygame.display.flip()
# determine movement vector
pressed = pygame.key.get_pressed()
move_vector = pygame.Vector2(0, 0)
for m in (move_map[key] for key in move_map if pressed[key]):
move_vector += m
# normalize movement vector if necessary
if move_vector.length() > 0:
move_vector.normalize_ip()
# apply speed to movement vector
move_vector *= speed
# update position of player
pos += move_vector
clock.tick(60) |
7d65a6e0fef25b6351e3b8add6fb79846520bf8c | task-master98/ReinforcementLearning | /DQN_models.py | 6,102 | 3.65625 | 4 | """
@Author: Ishaan Roy
#####################
Deep Q-Learning Algorithm
Framework: Pytorch
Task: Using Reinforcement Learning to play Space Invaders
File contains: Models required for Space Invaders game
#TODO
----------------------------------
=> Implement the Agent class: same file?
=> Write the main loop
=> Move helper function to utils.py
=> Add comments to explain the action space
----------------------------------
Change Log
-----------------------------------
=> Initial Commit: Built the model
-> Deep Convolution network: model tested
=> Implementation of RL agent
-> RL agent not tested yet; to be tested in the main loop
=> Helper function to plot rewards written
-----------------------------------
"""
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
class DeepQNetwork(nn.Module):
def __init__(self, lr, ):
super(DeepQNetwork, self).__init__()
self.lr = lr
self.conv_1 = nn.Conv2d(1, 32, kernel_size=8, stride=4, padding=1)
self.conv_2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv_3 = nn.Conv2d(64, 128, 3)
self.conv = nn.Sequential(
self.conv_1,
nn.ReLU(),
self.conv_2,
nn.ReLU(),
self.conv_3,
nn.ReLU(),
nn.Flatten()
)
self.fc_1 = nn.Linear(128*19*8, 512)
self.fc_2 = nn.Linear(512, 64)
self.fc_3 = nn.Linear(64, 6)
self.linear = nn.Sequential(
self.fc_1,
nn.ReLU(),
self.fc_2,
self.fc_3
)
self.optimizer = optim.RMSprop(self.parameters(), lr=self.lr)
self.loss = nn.MSELoss()
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.to(self.device)
def forward(self, observation):
observation = torch.Tensor(observation).to(self.device)
observation = observation.view(-1, 1, 185, 95)
feature_map = self.conv(observation)
actions = self.linear(feature_map)
return actions
class Agent:
def __init__(self, gamma, epsilon, lr,
maxMemsize, epsEnd=0.05,
replace=10000, action_space=list(range(6))):
## Parameters of Policy
self.GAMMA = gamma
self.EPSILON = epsilon
self.EPS_END = epsEnd
self.actionSpace = action_space
self.maxMemsize = maxMemsize
self.replace_target_cnt = replace
## RL tools
self.steps = 0
self.learn_step_counter = 0
self.memory = []
self.memCntr = 0
## Models
self.Q_eval = DeepQNetwork(lr=lr)
self.Q_target = DeepQNetwork(lr=lr)
def storeTransitions(self, old_state, action,
reward, new_state):
if self.memCntr < self.maxMemsize:
self.memory.append([old_state, action, reward, new_state])
else:
self.memory[self.memCntr%self.maxMemsize] = [old_state, action, reward, new_state]
self.memCntr += 1
def chooseAction(self, observation):
np.random.seed(42)
rand = np.random.random()
actions = self.Q_eval(observation)
if rand < 1 - self.EPSILON:
action = torch.argmax(actions[1]).item()
else:
action = np.random.choice(self.actionSpace)
self.steps += 1
return action
def learn(self, batch_size):
self.Q_eval.optimizer.zero_grad()
if (self.replace_target_cnt is not None and
self.learn_step_counter % self.replace_target_cnt == 0):
self.Q_target.load_state_dict(self.Q_eval.state_dict())
## Sampling from the memory bank (randomly)
if self.memCntr + batch_size < self.maxMemsize:
memStart = int(np.random.choice(range(self.memCntr)))
else:
memStart = int(np.random.choice(range(self.memCntr-batch_size-1)))
miniBatch = self.memory[memStart:memStart+batch_size]
memory = np.array(miniBatch)
Qpred = self.Q_eval.forward(list(memory[:, 0])).to(self.Q_eval.device)
Qnext = self.Q_target.forward(list(memory[:, 3])).to(self.Q_eval.device)
maxA = torch.argmax(Qnext, dim=1).to(self.Q_eval.device)
rewards = torch.Tensor(list(memory[:, 2])).to(self.Q_eval.device)
Qtargets = Qpred
Qtargets[:, maxA] = rewards + self.GAMMA*torch.max(Qnext[1])
if self.steps > 500:
if self.EPSILON - 1e-4 < self.EPS_END:
self.EPSILON -= 1e-4
else:
self.EPSILON = self.EPS_END
loss = self.Q_eval.loss(Qtargets, Qpred).to(self.Q_eval.device)
loss.backward()
self.Q_eval.optimizer.step()
self.learn_step_counter += 1
def plotLearning(x, scores, epsilons, filename=None, lines=None):
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.plot(x, epsilons, color="C0")
ax.set_xlabel("Game", color="C0")
ax.set_ylabel("Epsilon", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
N = len(scores)
running_avg = np.empty(N)
for t in range(N):
running_avg[t] = np.mean(scores[max(0, t-20):(t+1)])
ax2.scatter(x, running_avg, color="C1")
#ax2.xaxis.tick_top()
ax2.axes.get_xaxis().set_visible(False)
ax2.yaxis.tick_right()
#ax2.set_xlabel('x label 2', color="C1")
ax2.set_ylabel('Score', color="C1")
#ax2.xaxis.set_label_position('top')
ax2.yaxis.set_label_position('right')
#ax2.tick_params(axis='x', colors="C1")
ax2.tick_params(axis='y', colors="C1")
if lines is not None:
for line in lines:
plt.axvline(x=line)
return fig
def test_model():
img = torch.randn((185, 95))
model = DeepQNetwork(0.003)
print(model.forward(img).shape)
if __name__ == "__main__":
test_model()
|
2af2bc15f109cb2de4718386edc0f50162fd4f77 | TheReformedAlloy/py-class-examples | /clock.py | 2,077 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 11:50:38 2019
@author: Clint Mooney
"""
class Clock():
# Override Built-In Class Functions:
def __init__(self, hour=0, minutes=0, seconds=0):
self.hour = self.checkInput(hour, 0)
self.minutes = self.checkInput(minutes, 0)
self.seconds = self.checkInput(seconds, 0)
def __str__(self):
return "The time is {}:{}:{}".format(self.hour, self.minutes, self.seconds)
def __repr__(self):
return self.__str__()
# Override arithmetic operators:
def __add__(self, to_be_added):
if type(to_be_added) == Clock:
new_hour = self.hour + to_be_added.hour
new_mins = self.minutes + to_be_added.minutes
new_secs = self.seconds + to_be_added.seconds
return Clock(new_hour, new_mins, new_secs)
else:
new_hour = self.checkInput(to_be_added, 0)
return Clock(new_hour, self.minutes, self.seconds)
# Make addition communicative:
def __radd__(self, to_be_added):
return self.__add__(to_be_added)
# Function to streamline input management (Ensures input results in an int):
def checkInput(self, input_time, default):
if type(input_time) == int:
return input_time
elif type(input_time) == str:
if input_time.isdigit():
return int(input_time)
else:
print("Argument provided not a number. Setting affected input to '{}.'".format(default))
return default
elif type(input_time) == float:
return int(input_time)
else:
print("Argument provided not a number. Setting affected input to '{}.'".format(default))
return default
new_clock = Clock(5, 14, 30)
print(new_clock)
print(str(new_clock))
print(new_clock + Clock(1, 1, 10))
print(new_clock + 1)
print(new_clock + 1.0)
print(new_clock + "1")
print(new_clock + "Bop")
print(1 + new_clock)
print(1.0 + new_clock)
print("1" + new_clock)
print("Bop" + new_clock) |
ce6eceac86ea4bb06541e5fc214aed8a1aad6fa7 | amitrajhello/PythonEmcTraining1 | /inheritenceAndOverridding.py | 453 | 3.75 | 4 | from inheritence import Person
class Employee(Person):
"""Employee class extends to class Person"""
def __init__(self, eid, fn, ln):
self.eid = eid
super().__init__(fn, ln) # invoke the overridden method
def get_info(self):
print('employee id:', self.eid)
super().get_info()
if __name__ == '__main__': # calling main method
e = Employee('3242', 'Amit', 'Singh')
e.get_info()
|
3991d59a1de29307e9b9333585e679c7bd3e679b | amitrajhello/PythonEmcTraining1 | /listdemo.py | 135 | 3.6875 | 4 | # Defining a list
items = [2.2, 'pam', 3.4, 'allen', .98, 'nick', 1, 2, 3, 4]
print(items)
print(len(items))
print(type(items))
|
77c9f7f18798917cbee5e7fc4044c3a70d73bb33 | amitrajhello/PythonEmcTraining1 | /psguessme.py | 611 | 4.1875 | 4 | """The player will be given 10 chances to guess a number, and when player gives a input, then he should get a feedback
that his number was lesser or greater than the random number """
import random
key = random.randint(1, 1000)
x = 1
while x <= 10:
user_input = int(input('Give a random number to play the game: '))
if user_input > key:
print('your input is more than the number, please try again')
elif user_input < key:
print('your input is less than the number')
elif user_input == key:
print('Congratulations! you won!')
break
x += 1
|
fca48a33c99466a9c500454c2579590cd4390e5c | amitrajhello/PythonEmcTraining1 | /listRedundentEntries.py | 221 | 3.6875 | 4 | # eliminates duplicate entries
duplicates = [2.2, 3.3, 5.3, 2.2, 3.3, 5.3, 2.2, 3.3, 5.3]
print(set(duplicates)) # list type casted to set
uniq = list(set(duplicates)) # set type casted to list
print(uniq)
|
e1b50fc8a71d3bee42a9b8c02faf0128aa8e079e | amitrajhello/PythonEmcTraining1 | /iterator.py | 222 | 4 | 4 | s = 'root:x:0:0:root:/root>/root:/bin/bash'
for temp in s:
print(temp, '->', ord(temp)) # ord() is the function to print ASCII value of the character
for temp in reversed(s):
print(temp, '->', ord(temp))
|
9698a1b04749f46eb3735fe780e55880f48a2eab | amitrajhello/PythonEmcTraining1 | /inheritence.py | 419 | 3.953125 | 4 | class Person:
"""base class"""
def __init__(self, fn, ln): # self takes the reference of the current object
self.fn = fn # sets the first name of the current object
self.ln = ln
def get_info(self):
print('first name:', self.fn)
print('last name:', self.ln)
if __name__ == '__main__': # calling main method
p = Person('amit', 'raj')
p.get_info()
|
7095cca9d20fa2b15bb9afeb78cdc3af05164109 | Nosfer123/python_study | /HW_2_1.py | 494 | 4.09375 | 4 | def prepare_num(num):
while num <= 0:
print("Number should be more than zero")
num = prepare_num(int(input("Enter number: ")))
return num
def Fizz_Buzz(num):
if num % 3 == 0 and num % 5 == 0:
return "Fizz Buzz"
elif num % 3 == 0:
return "Fizz"
elif num % 5 == 0:
return "Buzz"
else:
return str(num)
def fizz_buzz_result():
num = prepare_num(int(input("Enter number: ")))
print(Fizz_Buzz(num))
fizz_buzz_result() |
84a2a5d8fd8de28f506ed71dc3634e5c815bdfbf | Nosfer123/python_study | /HW_4_1_2.py | 220 | 3.8125 | 4 | col = (input('Number of columns: '))
row = (input('Number of lines: '))
text = (input('What do you want to print? '))
def print_text():
for dummy_n in range (int(row)):
print (text*(int(col)))
print_text() |
9a9945bfd0b2e0998e4b25597fe15f6d93873245 | Nosfer123/python_study | /HW_8_1.py | 373 | 3.859375 | 4 | def is_concatenation(dictionary, key):
if not key:
return True
idx = 1
while idx <= len(key):
if key[0:idx] in dictionary and is_concatenation(dictionary, key[idx:]):
return True
idx += 1
return False
test_dict = ["world", "hello", "super"]
print(test_dict)
print("helloworld", is_concatenation(test_dict, 'helloworld')) |
0cfdbc8f80c62aa9c12efbdad639aef979675fb0 | Nosfer123/python_study | /HW_2_2.py | 212 | 3.875 | 4 | def number():
num = int(input("Enter number: "))
for number_in_list in range (num+1):
if number_in_list % 2 == 0 and number_in_list > 0:
print (number_in_list*number_in_list)
number() |
1d3bcad1638a46ff2e58a96439ed9d3a1d029510 | Nosfer123/python_study | /lesson3_9.py | 256 | 3.875 | 4 | def print_square(n):
for i in range(n):
for k in range(n):
print('*', end='')
print()
while True:
num = int(input('N: '))
print_square(num)
print()
is_done = input('One more?')
if is_done:
break |
5d0fbd2af9084c9b6b54c1b42b39dc144b0081ad | Nosfer123/python_study | /HW_3_1.py | 327 | 3.859375 | 4 | from random import randint
def dice_throw():
return randint(1,6)
def dice_sum():
counter = 0
while True:
dice1 = dice_throw()
dice2 = dice_throw()
counter += 1
if dice1+dice2 == 8:
print(dice1, dice2, counter)
break
for dummy_i in range(10):
dice_sum() |
2245707d7083ce60cbb00f9be02150a36806fba4 | SeptivianaSavitri/tugasakhir | /NER_Ika_Lib/WikiSplitType.py | 2,603 | 3.640625 | 4 | ####################################################################################
# WikiSplitType.py
# @Author: Septiviana Savitri
# @Last update: 8 Februari 2017
# Fasilkom Universitas Indonesia
#
# Objective: To filter the sentences so that meets certain criterias
# input:
# - a file contains all sentences --> output of Data3_SentencerNLTK.py
# output: a text file contains all selected sentences that meet certain criterias:
# - sentence has words > minimal number of words in a sentence
# - sentence has uppercase> minimal number of uppercase in a sentence
####################################################################################
import codecs
from function import writeListofStringToFile
##########################################################################
# M A I N
##########################################################################
#set the input and output file
folder = "dbpedia-new/original/"
#input = "dbpedia-new/cleansing/nyoba.txt"
input = "input.txt"
output1 = folder + "person.txt"
output2 = folder + "place.txt"
output3 = folder + "organization.txt"
######################### begin ################################
inputFile = codecs.open(input, 'r', errors='ignore')
flines = inputFile.readlines()
newListPerson = []
newListPlace = []
newListOrg = []
count = 1
for k in flines:
if k[0] == "<":
arrLine = k.split(" ")
arrType = arrLine[2].split("/")
arrValue = arrLine[0].split("/")
dataType = arrType[len(arrType) - 1]
dataValue = arrValue[len(arrValue) - 1]
if (dataType[:-1] == "Person") and (arrType[2]=="dbpedia.org"):
x = codecs.decode(dataValue[:-1], 'unicode_escape')
#x = dataValue[:-1]
# if count==90:
# print(x.replace('_',' '))
newListPerson.append(x.replace('_',' '))
elif (dataType[:-1] == "Place") and (arrType[2]=="dbpedia.org"):
x = codecs.decode(dataValue[:-1], 'unicode_escape')
newListPlace.append(x.replace('_',' '))
elif (dataType[:-1] == "Organisation") and (arrType[2]=="dbpedia.org") :
x = codecs.decode(dataValue[:-1], 'unicode_escape')
newListOrg.append(x.replace('_',' '))
count += 1
inputFile.close()
writeListofStringToFile(newListPerson, output1)
writeListofStringToFile(newListPlace, output2)
writeListofStringToFile(newListOrg, output3)
############################################################################
# End of file
############################################################################
|
e62ac4c465dacd0c5694a65ce2c3185c64e05419 | smritisingh26/AndrewNGPy | /LinearRegression.py | 1,064 | 3.625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
data = pd.read_csv('ex1data1.txt', header = None)
X = data.iloc[:,0]
y = data.iloc[:,1]
m = len(y)
print(data.head())
plt.scatter(X, y)
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
#plt.show()
X = X[:,np.newaxis]
y = y[:,np.newaxis]
theta = np.zeros([2,1])
iterations = 1500
alpha = 0.01
ones = np.ones((m,1))
X = np.hstack((ones, X))
def computeCost(X, y, theta):
temp = np.dot(X, theta) - y
return np.sum(np.power(temp, 2)) / (2*m)
J = computeCost(X, y, theta)
#print(J)
def gradientDescent(X, y, theta, alpha, iterations):
for _ in range(iterations):
temp = np.dot(X, theta) - y
temp = np.dot(X.T, temp)
theta = theta - (alpha/m) * temp
return theta
theta = gradientDescent(X, y, theta, alpha, iterations)
print(theta)
J = computeCost(X, y, theta)
print(J)
plt.scatter(X[:,1], y)
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.plot(X[:,1], np.dot(X, theta))
plt.show()
|
67e83fd9552337c410780198f08039044c925965 | Mickey248/ai-tensorflow-bootcamp | /pycharm/venv/list_cheat_sheet.py | 1,062 | 4.3125 | 4 | # Empty list
list1 = []
list1 = ['mouse', [2, 4, 6], ['a']]
print(list1)
# How to access elements in list
list2 = ['p','r','o','b','l','e','m']
print(list2[4])
print(list1[1][1])
# slicing in a list
list2 = ['p','r','o','b','l','e','m']
print(list2[:-5])
#List id mutable !!!!!
odd = [2, 4, 6, 8]
odd[0] = 1
print(odd)
odd[1:4] =[3 ,5 ,7]
print(odd)
#append and extend can be also done in list
odd.append(9)
print(odd)
odd.extend([11, 13])
print(odd)
# Insert an element into a list
odd = [1, 9]
odd.insert(1, 3)
print(odd)
odd[2:2] =[5,7]
print(odd)
# How to delete an element from a list?
del odd[0]
print(odd)
#remove and pop are the same as in array !!!
# Clear
odd.clear()
print(odd)
#Sort a list
numbers = [1, 5, 2, 3]
numbers.sort()
print(numbers)
# An elegant way to create a list
pow2 = [2 ** x for x in range(10)]
print(pow2)
pow2 = [2 ** x for x in range(10) if x > 5]
print(pow2)
# Membership in list
print(2 in pow2)
print(2 not in pow2)
# Iterate through in a list
for fruit in ['apple','banana','orange']:
print('i like', fruit) |
09c67af03e8d3a2219d072ac4e78b3bab4d19481 | BryanISC/b1 | /numeros primos recursivos.py | 350 | 3.875 | 4 | def numeroPrimoRecursivo(numero, c):
if(numero % c == 0 and numero > 2):
return False;
elif(c > numero / 2):
return True;
else:
return numeroPrimoRecursivo( numero, c+1 );
numero = int(input("\ningrese un numero: "))
if(numeroPrimoRecursivo(numero, 2) ):
print ("el numero es primo")
else:
print ("el numero no es primo") |
4eba19ae037e7b6ba9334c7c1d4099102c17ab5c | mycks45/DS | /Selection_sort.py | 405 | 3.734375 | 4 | def selection_sort(arr):
length = len(arr)
i = 0
while i < (length-1):
j = i+1
while j<length:
if arr[i]>arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
j +=1
i +=1
return arr
arr = [5,3,78,212,43,12,34,23,56,32,41,45,24,64,57,97,35]
print(arr)
result = selection_sort(arr)
print(result) |
c4f6294bcdffb315f9bb02e63810024ac79e97cf | mycks45/DS | /string encode.py | 429 | 3.59375 | 4 |
def encode(message, key):
new_message = ''
for i in range(len(message)):
ascii_val = ord(message[i])
val = ascii_val + key
if val >122:
k = (122-val)
k = k % 26
new_message += chr(96 + k)
else:
new_message += chr(val)
return new_message
message = 'hai'
key = 3
print(message)
mess = encode(message, key)
print(mess)
|
a744a47b4a4954fd8a718ca27e2bd3fcc799c084 | KMFleischer/PyEarthScience | /Transition_examples_NCL_to_PyNGL/xy/TRANS_bar_chart.py | 3,076 | 3.703125 | 4 | #
# File:
# TRANS_bar_chart.py
#
# Synopsis:
# Illustrates how to create a bar chart plot
#
# Categories:
# bar chart plots
# xy plot
#
# Author:
# Karin Meier-Fleischer, based on NCL example
#
# Date of initial publication:
# September 2018
#
# Description:
# This example shows how to create a bar chart plot.
#
# Effects illustrated:
# o Drawing a bar chart plot
# o Customizing a x-axis labels
#
# Output:
# A single visualization is produced.
#
# Notes: The data for this example can be downloaded from
# http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/
#
'''
Transition Guide Python Example: TRANS_bar_chart.py
- bar chart
- x-labels
18-09-03 kmf
'''
from __future__ import print_function
import numpy as np
import Ngl
#-- function get_bar returns coordinates of a bar
def get_bar(x,y,dx,ymin,bar_width_perc=0.6):
dxp = (dx * bar_width_perc)/2.
xbar = np.array([x-dxp, x+dxp, x+dxp, x-dxp, x-dxp])
ybar = np.array([ ymin, ymin, y, y, ymin])
return xbar,ybar
#--------------
# MAIN
#--------------
#-- create random x- and y-values
x = np.arange(1,13,1)
y = [8,5,11,6,9,9,6,2,4,1,3,3]
dx = min(x[1:-1]-x[0:-2]) #-- distance between x-values
#-- define color and x-axis labels
color = 'blue'
xlabels = ["Jan","Feb","Mar","Apr","May","Jun", \
"Jul","Aug","Sep","Oct","Nov","Dec"]#-- x-axis labels
#-- open a workstation
wkres = Ngl.Resources() #-- generate an resources object for workstation
wks_type = "png" #-- output type of workstation
wks = Ngl.open_wks(wks_type,"plot_TRANS_bar_chart_py",wkres)
#-- set resources
res = Ngl.Resources() #-- generate an res object for plot
res.nglFrame = False #-- don't advance frame
res.nglPointTickmarksOutward = True #-- point tickmarks outward
res.tiXAxisString = "x-values" #-- x-axis title
res.tiYAxisString = "y-values" #-- y-axis title
res.tmXBMode = "Explicit" #-- define bottom x-axis values and labels
res.tmXBValues = x #-- x-axis values
res.tmXBLabels = xlabels #-- x-axis labels
res.tmXBLabelFontHeightF = 0.012 #-- bottom x-axis font size
res.trXMinF = 0.0 #-- x-axis min value
res.trXMaxF = 13.0 #-- x-axis max value
res.trYMinF = 0.0 #-- y-axis min value
res.trYMaxF = 12.0 #-- y-axis max value
#-- bar resources
barres = Ngl.Resources() #-- resource list for bars
barres.gsFillColor = color #-- set bar color
#-- loop through each y point and create bar
for i in range(len(y)):
xbar,ybar = get_bar(x[i], y[i], dx, res.trXMinF, 0.3)
plot = Ngl.xy(wks, xbar, ybar, res)
Ngl.polygon(wks, plot, xbar, ybar, barres) #-- filled bar
Ngl.frame(wks) #-- advance frame
Ngl.end()
|
b5f7437fcb49452d5a9214af6a79e48cdb121b49 | minhnguyenphuonghoang/AlgorithmEveryday | /EverydayCoding/0019_validate_symbols.py | 2,114 | 3.78125 | 4 | from BenchmarkUtil import benchmark_util
"""Day 53: Validate Symbols
We're provided a string like the following that is inclusive of the following symbols:
parentheses '()'
brackets '[]', and
curly braces '{}'.
Can you write a function that will check if these symbol pairings in the string follow these below conditions?
They are correctly ordered
They contain the correct pairings
They are both of the same kind in a pair
For example, () is valid. (( is not. Similarly, {{[]}} is valid. [[}} is not.
"""
NO_OF_SOLUTION = 1
def solution_01(s):
hash_map = {
'parentheses': 0,
'brackets': 0,
'curly_braces': 0
}
for a_char in s:
if a_char == "{":
hash_map['curly_braces'] += 1
elif a_char == "}":
hash_map['curly_braces'] -= 1
if hash_map['curly_braces'] < 0:
return False
elif a_char == "(":
hash_map['parentheses'] += 1
elif a_char == ")":
hash_map['parentheses'] -= 1
if hash_map['parentheses'] < 0:
return False
elif a_char == "[":
hash_map['brackets'] += 1
else:
hash_map['brackets'] -= 1
if hash_map['parentheses'] < 0:
return False
for key in hash_map:
if hash_map[key] < 0:
return False
return True
def solution_02(s):
# Todo:
# the above solution is too bad. I must think another way to solve this problem
return s
tests = ["{{[]}}", "[[}}", "{()}[]()"]
results = [True, False, True]
for i in range(len(tests)):
for sln_idx in range(1, NO_OF_SOLUTION + 1):
curr_time = benchmark_util.get_current_time()
result = eval("solution_0{}".format(sln_idx))(tests[i])
elapse_time = benchmark_util.get_elapse_time(curr_time)
# debug:
print("SOLUTION: {} took {} nanoseconds to finish test.".format(sln_idx, elapse_time))
assert result == results[i], \
"Solution {} had wrong result {}, expecting {}".format("solution_0{}".format(sln_idx), result, results[i])
|
e1fcd85babfd1971ba7bdb4a9a733ad22b250438 | minhnguyenphuonghoang/AlgorithmEveryday | /EverydayCoding/0022_find_prime_number.py | 1,265 | 3.609375 | 4 | from BenchmarkUtil import benchmark_util
"""Write a function to find a prime number of a given number
Prime number is the number that can only divide by 1 and itself.
For example: 1, 2, 3, 5, 7, 13, etc are prime numbers.
"""
from math import sqrt
NO_OF_SOLUTION = 2
def solution_01(s):
if s < 1:
return False
for i in range(2, s):
if s % i == 0:
return False
return True
def solution_02(s):
if s < 1:
return False
for i in range(2, int(sqrt(s))+1):
if s % i == 0:
return False
return True
tests = [-3, 0, 1, 2, 13, 15, 89, 100, 100003, 111111113]
results = [False, False, True, True, True, False, True, False, True, True]
for i in range(len(tests)):
for sln_idx in range(1, NO_OF_SOLUTION + 1):
curr_time = benchmark_util.get_current_time()
result = eval("solution_0{}".format(sln_idx))(tests[i])
elapse_time = benchmark_util.get_elapse_time(curr_time)
# debug:
print("SOLUTION: {} took {} nanoseconds to finish test with input {}".format(sln_idx, elapse_time, tests[i]))
assert result == results[i], \
"Solution {} had wrong result {}, expecting {}".format("solution_0{}".format(sln_idx), result, results[i])
|
b7b283a77a4c9135f5cdd904dccb4594bc58eecb | minhnguyenphuonghoang/AlgorithmEveryday | /Algorithms/greatest_common_denominator.py | 160 | 3.5625 | 4 | def euclid_alg(num1, num2):
while num2 != 0:
temp = num1
num1 = num2
num2 = temp % num2
return num1
print(euclid_alg(20, 8))
|
c7bdf0cbdf287f5d15d4d229aa787e9f3e42523d | caramelmelmel/50.003-ESC_g_3_8 | /react-app/src/test/fuzzing/testFuzzInvalidPassword.py | 3,099 | 3.65625 | 4 | import random
import string
import re
# This test allows us to check if the passwords that we expect to fail will actually fail the regex
def fuzz(valid):
# Use various methods to fuzz randomly
for i in range(3):
trim_bool = random.randint(0, 1)
duplicate_bool = random.randint(0, 1)
swap_bool = random.randint(0, 1)
temp_valid = valid
if (trim_bool == 1):
valid = trim(valid)
if (len(valid) == 0):
choices = ["badskjabsdjk", "051288324969", "USABASKDAU", "&*!#*!^*@&"]
valid = random.choice(choices)
valid = duplicate(valid)
valid = swap(valid)
if (duplicate_bool == 1):
valid = duplicate(valid)
if (swap_bool == 1):
valid = swap(valid)
return valid
def trim(valid):
# Trim front or back of random length
length_valid = len(valid)
random_length = random.randint(1, int(length_valid/2)+1)
trim_bool = random.randint(0, 1)
if (trim_bool == 1):
output = valid[random_length:]
else:
output = valid[:random_length]
return output
def swap(valid):
# Swap characters at random
for i in range(len(valid)):
char = valid[i]
random_index = random.randint(0, len(valid)-1)
swap_char = valid[random_index]
if (random_index > i):
start = valid[0:i]
middle = valid[i+1:random_index]
end = valid[random_index+1:]
valid = start + swap_char + middle + char + end
elif (random_index < i):
start = valid[0:random_index]
middle = valid[random_index+1:i]
end = valid[i+1:]
valid = start + char + middle + swap_char + end
else:
continue
output = valid
return output
def duplicate(valid):
# Duplicate substrings in valid and add to the end of valid
first_index = random.randint(0, len(valid)-1)
if (first_index == len(valid)-1):
return valid
else:
second_index = random.randint(first_index, len(valid)-1)
if (first_index != second_index):
substring = valid[first_index:second_index]
valid = valid + substring
return valid
def verify_regex(input):
# Verify if the input passes the regex
regex = r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$"
regex_obj = re.compile(regex)
check = (regex_obj.search(input) != None)
return check
# This test allows us to check if the passwords that we expect to fail will actually fail the regex
check = False
while (check == False):
valid_passwords = ['abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'my spaced password', 'CapitalAndSmallButNoSymbol', 'C@PIT@L@NDSYMBOL!', '$mall$mbol@', '1234567890', 'CapitalAndSmallButNoSymbol123456789', 'C@PIT@L@NDSYMBOL!0987654321', '$mall$mbol@0192837465',
'abcde456fg213hijklmno987pqrst0uvwxyz', 'ABCD4EFGH583IJKLM62NOP1QRS70TUVW9XYZ']
valid = random.choice(valid_passwords)
output = fuzz(valid)
check = verify_regex(output)
print("Output:")
print(output) |
c9f325732c1a2732646deadb25c9132f3dcae649 | samir-0711/Area_of_a_circle | /Area.py | 734 | 4.5625 | 5 | import math
import turtle
# create screen
screen = turtle.Screen()
# take input from screen
r = float(screen.textinput("Area of Circle", "Enter the radius of the circle in meter: "))
# draw circle of radius r
t=turtle.Turtle()
t.fillcolor('orange')
t.begin_fill()
t.circle(r)
t.end_fill()
turtle.penup()
# calculate area
area = math.pi * r * r
# color,style and position of text
turtle.color('deep pink')
style = ('Courier', 10, 'italic')
turtle.setpos(-20,-20)
# display area of circle with radius r
turtle.write(f"Area of the circle with radius {r} meter is {area} meter^2", font=style, align='center')
# hide the turtle symbol
turtle.hideturtle()
# don't close the screen untill click on close
turtle.getscreen()._root.mainloop()
|
e1b281dbeb0452fa235c5bdfcd3827a44ebd4167 | Kristjan-O-Ragnarsson/FORR3RR05DU-verk2 | /sam.py | 155 | 3.625 | 4 | n = int(input())
m = int(input())
def funct(n, m):
if m == 0:
return n
else:
return funct(m, n % m)
print(funct(n, m))
|
933775bd8c8e1c702aa390bc16ba389db0287649 | Serpinex3/rx-anon | /anon/configuration/configuration_reader.py | 1,448 | 3.5625 | 4 | """Module containing corresponding code for reading a configuration file"""
import logging
from yaml import Loader, load
from .configuration import Configuration
logger = logging.getLogger(__name__)
class ConfigurationReader:
"""Class responsible for parsing a yaml config file and initializing a configuration"""
def read(self, yaml_resource):
"""
Reads a yaml config file and returns the corresponding configuration object
Parameters
----------
yaml_resource: (str, Path)
The configuration file.
Returns
-------
Configuration
The corresponding configuration object
"""
with open(yaml_resource, 'r') as file:
doc = load(file, Loader=Loader)
logger.info("Reading configuration from %s", yaml_resource)
config = Configuration()
# Make keys lower case to match columns in lower case
config.attributes = {attr.lower(): v for attr, v in doc['attributes'].items()}
if "entities" in doc: # Overwrite default
config.entities = doc['entities']
if "parameters" in doc: # Overwrite default
config.parameters = doc['parameters']
if "nlp" in doc: # Overwrite default
config.nlp = doc['nlp']
logger.debug("Using the following configuration:\n%s", config)
return config
|
c7ac2454578be3c3497759f156f7bb9f57415433 | dawid86/PythonLearning | /Ex7/ex7.py | 513 | 4.6875 | 5 | # Use words.txt as the file name
# Write a program that prompts for a file name,
# then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
fname = input("Enter file name: ")
fhand = open(fname)
# fread = fhand.read()
# print(fread.upper())
#for line in fread:
# line = line.rstrip()
# line = fread.upper()
# print(line)
for line in fhand:
line = line.rstrip()
line = line.upper()
print(line)
|
acc900f9c4e91d452dccec4c9220142fd32dbd9b | AndersonCamargo20/Exercicios_python | /ex012.py | 423 | 3.765625 | 4 | print('========== DESAFIO 012 ==========')
print('LEIA O VALOR DE UM PRODUTO E INFORME O VALOR FINAL COM DESCONTO APÓS LER A PORCENTAGEM')
valor = float(input('Informe o valor do produto: R$ '))
porcent = float(input('Informe o valor da porcentagem: '))
desconto = (valor * porcent) / 100
print('O produto custava R${}, na promoção com desconto de {}%, vai custar R${}'.format(valor, porcent, round(valor-desconto,2)))
|
e514f618a3ffe08a2610ea780cf7efff8314c1fa | AndersonCamargo20/Exercicios_python | /ex032.py | 548 | 4 | 4 | print('========== DESAFIO 032 ==========')
print('LEIA UM ANO E DIGA SE ELE É BISEXTO OU NÃO')
from calendar import isleap
from datetime import datetime
now = datetime.now()
ano = int(input('Informe um ano para o calculo (Caso queira o ano atual informe ->> 0 <<-): '))
if ano == 0:
if isleap(now.year):
print('O ano atual É BISEXTO')
else:
print('O ano atual NÃO é BISEXTO')
else:
if isleap(ano):
print('O ano {} É BISEXTO'.format(ano))
else:
print('O ano {} NÃO é BISEXTO'.format(ano))
|
d05af16be3b0e6715bdc528234604e6b515b641e | AndersonCamargo20/Exercicios_python | /ex007.py | 359 | 3.953125 | 4 | print('========== DESAFIO 007 ==========')
print('FAÇA UM PROGRAMA QUE FAÇA A MÉDIA ARITIMÉTICA ENTRE TRÊS NOTAS\n')
n1 = float(input("Informe a 1º nota: "))
n2 = float(input("Informe a 2º nota: "))
n3 = float(input("Informe a 3º nota: "))
soma = n1 + n2 + n3
media = soma / 3
print("A média das notas ({}, {} , {} ) é: {}".format(n1,n2,n3,media)) |
5373667470e39443ab1191f2f523e0dc43742638 | AndersonCamargo20/Exercicios_python | /ex013.py | 489 | 3.796875 | 4 | print('========== DESAFIO 013 ==========')
print('LEIA UM SALÁRIO E A PORCENTAGEM DE AUMENTA E CALCULA O VALOR DO SALÁRIO COM AUMENTO')
salario_old = float(input('Informe o salário do funcionário: R$ '))
porcent = float(input('Informe a porcentagem de aumento: '))
aumento = (salario_old * porcent) / 100
salario_new = salario_old + aumento
print('Um funcionário ganhava R${}, mas com {}% de aumento, o seu novo salário é R${}'.format(salario_old, porcent, round(salario_new, 2)))
|
aa7452cbe83e2b4f61db6f28d244f4f4b19cb481 | AndersonCamargo20/Exercicios_python | /ex019.py | 451 | 3.84375 | 4 | print('========== DESAFIO 019 ==========')
print('LENDO O NOME DE 4 ALUNOS SORTEI UM DELES DA CHAMADA PARA APAGAR O QUADRO')
import random
list_alunos = []
num_alunos = int(input('Quantos alunos deseja salvar: '))
random = random.randint(0,num_alunos - 1)
print(random)
for i in range(0, num_alunos):
list_alunos.append(input('Informe o nome do {}º Aluno: '.format(i + 1)))
print('\n\nO aluno escolhido foi {}.'.format(list_alunos[random]))
|
acd10df184f13bb7c54a6f4a5abac553127b27af | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_create_grade_calculator.py | 830 | 4.25 | 4 | #Python code for the Grade
#Calculate program in action
#Creating a dictionary which
#consists of the student name,
#assignment result test results
#And their respective lab results
def grade(student_grade):
name=student_grade['name']
assignment_marks=student_grade['assignment']
assignment_score=sum(assignment_marks)/len(assignment_marks)
test_marks=student_grade['test']
test_score=sum(test_marks)/len(test_marks)
lab_marks=student_grade['lab']
lab_score=sum(lab_marks)/len(lab_marks)
score=0.1*assignment_score+0.7*test_score+0.2*lab_score
if score>=90 :return 'A'
elif score>=80 :return 'B'
elif score>=70 :return 'C'
elif score>=60 :return 'D'
jack={"name":"Jack Frost","assignment":[80,50,40,20],"test":[75,75],"lab":[78,20,77,20]}
x=grade(jack)
print(x)
|
968829ff7ec07aabb3dedfb89e390334b9b9ee57 | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_check_if_a_string_is_palindrome_or_not.py | 450 | 4.3125 | 4 | print("This is python program to check if a string is palindrome or not")
string=input("Enter a string to check if it is palindrome or not")
l=len(string)
def isPalindrome(string):
for i in range(0,int(len(string)/2)):
if string[i]==string[l-i-1]:
flag=0
continue
else :
flag=1
return flag
ans=isPalindrome(string)
if ans==0:
print("Yes")
else:
print("No")
|
06132de9f0dd0dfbf3138ead23bd4a936ca4a70a | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_interchange_first_and_last_elements_in_a_list_using_pop.py | 277 | 4.125 | 4 | print("This is python program to swap first and last element using swap")
def swapList(newList):
first=newList.pop(0)
last=newList.pop(-1)
newList.insert(0,last)
newList.append(first)
return newList
newList=[12,35,9,56,24]
print(swapList(newList))
|
2f2fe636142d1859b49195d440d60e6641a45bc9 | inwk6312fall2018/programmingtask2-hanishreddy999 | /crime.py | 685 | 3.515625 | 4 |
from tabulate import tabulate #to print the output in table format
def crime_list(a): #function definition
file=open(a,"r") #open csv file in read mode
c1=dict()
c2=dict()
lst1=[]
lst2=[]
for line in file:
line.strip()
for lines in line.split(','):
lst1.append(lines[-1])
lst2.append(lines[-2])
for b in lst1:
if b not in c1:
c1[b]=1
else:
c1[b]=c1[b]+1
for c in lst2:
if c not in c2:
c2[c]=1
else:
c2[c]=c2[c]+1
print(tabulate(headers=['CrimeType', 'CrimeId', 'CrimeCount']))
for k1,v in c1.items():
for k2,v in c2.items():
x=[k1,k2,v] #tabular format
print(tabulate(x))
file_name="Crime.csv"
crime_list(file_name)
|
4c84102e21f49b710bd9bd292fc816700382f811 | basile-henry/projecteuler | /Python/problem60.py | 631 | 3.59375 | 4 | import primes2 as primes
def isPairPrime(a, b):
return primes.isPrime(int(str(a) + str(b))) and primes.isPrime(int(str(b) + str(a)))
def test(l, n):
return all([isPairPrime(a, n) for a in l])
def next(l, limit):
i = primes.getIndexOf(l[-1]) + 1
p = primes.getPrimeAt(i)
while not test(l, p):
i+=1
p = primes.getPrimeAt(i)
if p > limit:
return 0
return primes.getPrimeAt(i)
def buildList(start, limit):
ret = [start]
while ret[-1] > 0:
ret.append(next(ret, limit))
return ret[:-1]
i = 0
p = []
print primes.primes[-1]
while len(p) < 5:
p = buildList(primes.getPrimeAt(i), 10000)
print p, sum(p)
i+=1 |
509351177f6f9f41f47f5508a9da26c761202806 | jrihds/pdat | /code/generators.py | 265 | 4 | 4 | #!/usr/bin/env python3
"""Generator objects."""
colours = ['blue', 'red', 'green', 'yellow']
def e_count(_list):
"""Count how many e's in a string."""
for element in _list:
yield element.count('e')
for value in e_count(colours):
print(value)
|
10880d4e6f4462c7ae0af751dd4b68b5530680fe | Mitchell55/NumericalAnalysis | /Numerical_analysis/Forward_Euler.py | 673 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 20:19:09 2019
@author: Mitchell Krouss
Method: Forward Euler
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sc
a = 0
b = 1
h = 0.0001
n = int((b - a) / h)
def f(x,y):
return 998*x - 1998*y
def g(x,y):
return 1000*x - 2000*y
t = np.arange(a, b+h, h)
y = np.zeros(len(t))
x = np.zeros(len(t))
y[0] = 2
x[0] = 1
for i in range(1, len(t)):
y[i] = y[i-1] + h*f(x[i-1],y[i-1])
x[i] = x[i-1] + h*g(x[i-1],y[i-1])
print(x[1000])
print(y[1000])
print(t[1000])
plt.plot(t,y)
plt.plot(t,x)
plt.legend(['y(t)','x(t)'])
plt.xlabel('t')
plt.title('Forward Euler')
plt.show()
|
3067c55a4f898411564a58baff539cd41f94a4db | amiune/projecteuler | /Problem054.py | 4,338 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
cardValue = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':11,'Q':12,'K':13,'A':14}
# In[74]:
def getHighestCardValue(cards):
cards = sorted(cards, key=lambda card: cardValue[card[0]])
return cardValue[cards[-1][0]]
# In[86]:
def maxOfAKind(cards):
maxOfAKind = []
counter = 1
cards = sorted(cards, key=lambda card: cardValue[card[0]])
for i in range(1,5):
if int(cardValue[cards[i][0]]) == int(cardValue[cards[i-1][0]]): counter += 1
else:
maxOfAKind.append((counter, int(cardValue[cards[i-1][0]])))
counter = 1
maxOfAKind.append((counter, int(cardValue[cards[4][0]])))
maxOfAKind = sorted(maxOfAKind)
return maxOfAKind[-1], maxOfAKind[-2]
# In[87]:
def onePair(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 2 and max2[0] == 1: return True, max1, max2
return False, max1, max2
# In[88]:
def twoPairs(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 2 and max2[0] == 2: return True, max1, max2
return False, max1, max2
# In[89]:
def threeOfAKind(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 3: return True, max1, max2
return False, max1, max2
# In[90]:
def straight(cards):
cards = sorted(cards, key=lambda card: cardValue[card[0]])
for i in range(1,5):
if int(cardValue[cards[i][0]]) != int(cardValue[cards[i-1][0]]) + 1: return False
return True
# In[91]:
def flush(cards):
for i in range(1,5):
if cards[i][1] != cards[i-1][1]: return False
return True
# In[92]:
def fullHouse(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 3 and max2[0] == 2: return True, max1, max2
return False, max1, max2
# In[93]:
def fourOfAKind(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 4: return True, max1, max2
return False, max1, max2
# In[94]:
def straightFlush(cards):
if flush(cards) and straight(cards): return True
return False
# In[95]:
def getHandValue(cards):
if straightFlush(cards):
return 9_000_000 + getHighestCardValue(cards)
isFourOfAKind, max1, _ = fourOfAKind(cards)
if isFourOfAKind:
return 8_000_000 + max1[1]
isFullHouse, max1, max2 = fullHouse(cards)
if isFullHouse:
return 7_000_000 + max1[1]*100 + max2[1]
if flush(cards):
return 6_000_000 + getHighestCardValue(cards)
if straight(cards):
return 5_000_000 + getHighestCardValue(cards)
isThreeOfAKind, max1, max2 = threeOfAKind(cards)
if isThreeOfAKind:
return 4_000_000 + max1[1]*100 + max2[1]
isTwoPairs, max1, max2 = twoPairs(cards)
if isTwoPairs:
return 3_000_000 + max1[1]*100 + max2[1]
isOnePair, max1, max2 = onePair(cards)
if isOnePair:
return 2_000_000 + max1[1]*100 + max2[1]
return 1_000_000 + getHighestCardValue(cards)
# In[97]:
player1Wins = 0
with open("p054_poker.txt", "r") as f:
lineCounter = 0
for line in f:
hand1 = line[:14].split()
hand2 = line[15:29].split()
hand1Value = getHandValue(hand1)
hand2Value = getHandValue(hand2)
winner = 0
if hand1Value > hand2Value:
winner = 1
elif hand1Value < hand2Value:
winner = 2
else:
hand1 = sorted(hand1, key=lambda card: cardValue[card[0]])
hand2 = sorted(hand2, key=lambda card: cardValue[card[0]])
for i in range(5):
hand1Value = getHighestCardValue(hand1[:4-i])
hand2Value = getHighestCardValue(hand2[:4-i])
if hand1Value != hand2Value:
if hand1Value > hand2Value:
winner = 1
elif hand1Value < hand2Value:
winner = 2
break
print("{}vs{} -> Player {} wins: {} vs {}".format(sorted(hand1, key=lambda card: cardValue[card[0]]),
sorted(hand2, key=lambda card: cardValue[card[0]]), winner,
hand1Value, hand2Value))
if winner == 1:
player1Wins += 1
lineCounter += 1
print(player1Wins)
# In[ ]:
# In[ ]:
|
70db04c2a239741286b2ca8e14ad4aae7d6ed462 | amiune/projecteuler | /Problem049.py | 816 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
def isPrime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n % f == 0: return False
if n % (f+2) == 0: return False
f += 6
return True
# In[9]:
def isPermutation(a,b):
if len(a) == len(b):
return sorted(a) == sorted(b)
return False
# In[18]:
for n1 in range(1001,9999+1,2):
if isPrime(n1):
for diff in range(1,int(10000/3)):
if isPermutation(str(n1),str(n1+diff)) and isPermutation(str(n1),str(n1+2*diff)):
if isPrime(n1+diff) and isPrime(n1+2*diff):
print("{},{},{}".format(n1,n1+diff,n1+2*diff))
# In[ ]:
|
998cb8e31e2065edefca18de17d6d4062d3aa564 | amiune/projecteuler | /Problem009.py | 263 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import math
# In[8]:
n = 1000
for a in range(1,n-2):
for b in range(a+1, n-1):
c = math.sqrt(a*a + b*b)
if a + b + c == 1000:
print(int(a*b*c))
break
# In[ ]:
|
d57723a50878b71814f9ecdb6e7be14687e1aed9 | amiune/projecteuler | /Problem001.py | 168 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
answer = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
answer += i
print(answer)
# In[ ]:
|
0901c75662df3c0330deb4d25087868ba0693e94 | dipesh1011/NameAgeNumvalidation | /multiplicationtable.py | 360 | 4.1875 | 4 | num = input("Enter the number to calculate multiplication table:")
while(num.isdigit() == False):
print("Enter a integer number:")
num = input("Enter the number to calculate multiplication table:")
print("***************************")
print("Multiplication table of",num,"is:")
for i in range(1, 11):
res = int(num) * i
print(num,"*",i,"=",res) |
1533e4ed87eb8d3650b5bd6998224361c83f376f | fANZYo/FrenchTestPy | /frenchPhrases.py | 2,212 | 4 | 4 | # Keep your imports at the top. It's good practice as it tells anyone reading your code what the program relies on
from sys import argv, exit
from random import randint
import json
def play(data):
"""Start the game with the list of sentences provided
data -- list of sentences
"""
while True:
sentencePick = randint(0, len(data) - 1) # Pick a random sentence index
languages = list(data[sentencePick].keys()) # Dynamically pull out the list of languages for that sentence
langPick = languages[randint(0, len(languages) - 1)] # Picks a random language
languages.remove(langPick) # Remove langPick from the list of languages
for lang in languages: # Loop over the remaining languages
userAnswer = input('What is the ' + lang + ' translation of "' + data[sentencePick][langPick] + '"?\n> ')
if userAnswer == data[sentencePick][lang]:
print('Correct')
else:
print('Wrong, the answer was: "' + data[sentencePick][lang] + '"')
exit(1)
def addSentence(path):
"""Write a new sentence to a file
path -- file to amend
"""
f = open(path, 'r') # Open file in read mode
data = json.load(f) # Get the list of sentences
f.close() # Close the file
sentence = getSentence() # See function below
data.append(sentence) # Append the list of sentences with the new sentence dictionary returned by getSentence
f = open(path, 'w+') # Open and wipe the file
f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))) # Write the amended list of sentences to the file
f.close()
exit(0)
def getSentence():
"""Return a dictionary containing a sentence in different languages"""
sentence = {}
languageCount = int(input('How many languages?\n> '))
for i in range(0, languageCount):
language = input('Enter language nb ' + str(i + 1) + '\n> ')
sentence[language] = input('What is the sentence for that language?\n> ')
return sentence
if len(argv) > 2 and argv[1] == 'add': # If user entered 'python script add filename'
addSentence(argv[2])
elif len(argv) > 1: # If user entered 'python script filename'
data = json.load(open(argv[1])) # Assign the dictionary contained in the file to data
play(data)
else:
print('Syntax: [add] filename')
exit(1)
|
7b8fb7f4e7c0a339befa3619eefe77cfbb42a4f4 | Antn-Amlrc/Calendar_2020 | /day9.py | 1,707 | 3.921875 | 4 | file = open('input9.txt', "r")
lines = file.readlines()
file.close()
# PART 1
def is_the_sum_of_two_numbers(n, preambule):
for i in range(len(preambule)):
n1 = int(preambule[i])
for j in range(i+1,len(preambule)):
n2 = int(preambule[j])
if n1+n2==n:
preambule.remove(preambule[0]) # We remove the head of the list
preambule.append(n) # We add the last valid number found
return True
return False
preambule = [line[:-1] for line in lines[:25]]
invalid_number = 0
for line in lines[25:]:
invalid_number = int(line[:-1])
if not(is_the_sum_of_two_numbers(invalid_number, preambule)):
print("The following number does not have XMAS property", invalid_number)
break
# PART 2
contiguous_list = []
for index_to_start in range(len(lines)): # For each possible start
first_number = int(lines[index_to_start]) # Start number
contiguous_list.clear()
cpt_to_search = 0 # index to see following numbers
if not(first_number == invalid_number): # Will only give at least two number set
while sum(contiguous_list)<invalid_number and index_to_start+cpt_to_search<len(lines): # While sum lower than invalid number
new_number = int(lines[index_to_start+cpt_to_search])
contiguous_list.append(new_number)
cpt_to_search += 1 # We increment to go to next number
if invalid_number == sum(contiguous_list) and len(contiguous_list)>1:
encryption_weakness = min(contiguous_list)+max(contiguous_list)
print("The encryption weakness in my list is", encryption_weakness)
|
caaee5e916ac6fdee8d1cf40556b1168b1b266a5 | darsh10/HateXplain-Darsh | /Preprocess/attentionCal.py | 5,061 | 3.90625 | 4 | import numpy as np
from numpy import array, exp
###this file contain different attention mask calculation from the n masks from n annotators. In this code there are 3 annotators
#### Few helper functions to convert attention vectors in 0 to 1 scale. While softmax converts all the values such that their sum lies between 0 --> 1. Sigmoid converts each value in the vector in the range 0 -> 1.
##### We mostly use softmax
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0)
def neg_softmax(x):
"""Compute softmax values for each sets of scores in x. Here we convert the exponentials to 1/exponentials"""
e_x = np.exp(-(x - np.max(x)))
return e_x / e_x.sum(axis=0)
def sigmoid(z):
"""Compute sigmoid values"""
g = 1 / (1 + exp(-z))
return g
##### This function is used to aggregate the attentions vectors. This has a lot of options refer to the parameters explanation for understanding each parameter.
def aggregate_attention(at_mask,row,params):
"""input: attention vectors from 2/3 annotators (at_mask), row(dataframe row), params(parameters_dict)
function: aggregate attention from different annotators.
output: aggregated attention vector"""
#### If the final label is normal or non-toxic then each value is represented by 1/len(sentences)
if(row['final_label'] in ['normal','non-toxic']):
at_mask_fin=[1/len(at_mask[0]) for x in at_mask[0]]
else:
at_mask_fin=at_mask
#### Else it will choose one of the options, where variance is added, mean is calculated, finally the vector is normalised.
if(params['type_attention']=='sigmoid'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=sigmoid(at_mask_fin)
elif (params['type_attention']=='softmax'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=softmax(at_mask_fin)
elif (params['type_attention']=='neg_softmax'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=neg_softmax(at_mask_fin)
elif(params['type_attention'] in ['raw','individual']):
pass
if(params['decay']==True):
at_mask_fin=decay(at_mask_fin,params)
return at_mask_fin
##### Decay and distribution functions.To decay the attentions left and right of the attented word. This is done to decentralise the attention to a single word.
def distribute(old_distribution, new_distribution, index, left, right,params):
window = params['window']
alpha = params['alpha']
p_value = params['p_value']
method =params['method']
reserve = alpha * old_distribution[index]
# old_distribution[index] = old_distribution[index] - reserve
if method=='additive':
for temp in range(index - left, index):
new_distribution[temp] = new_distribution[temp] + reserve/(left+right)
for temp in range(index + 1, index+right):
new_distribution[temp] = new_distribution[temp] + reserve/(left+right)
if method == 'geometric':
# we first generate the geometric distributio for the left side
temp_sum = 0.0
newprob = []
for temp in range(left):
each_prob = p_value*((1.0-p_value)**temp)
newprob.append(each_prob)
temp_sum +=each_prob
newprob = [each/temp_sum for each in newprob]
for temp in range(index - left, index):
new_distribution[temp] = new_distribution[temp] + reserve*newprob[-(temp-(index-left))-1]
# do the same thing for right, but now the order is opposite
temp_sum = 0.0
newprob = []
for temp in range(right):
each_prob = p_value*((1.0-p_value)**temp)
newprob.append(each_prob)
temp_sum +=each_prob
newprob = [each/temp_sum for each in newprob]
for temp in range(index + 1, index+right):
new_distribution[temp] = new_distribution[temp] + reserve*newprob[temp-(index + 1)]
return new_distribution
def decay(old_distribution,params):
window=params['window']
new_distribution = [0.0]*len(old_distribution)
for index in range(len(old_distribution)):
right = min(window, len(old_distribution) - index)
left = min(window, index)
new_distribution = distribute(old_distribution, new_distribution, index, left, right, params)
if(params['normalized']):
norm_distribution = []
for index in range(len(old_distribution)):
norm_distribution.append(old_distribution[index] + new_distribution[index])
tempsum = sum(norm_distribution)
new_distrbution = [each/tempsum for each in norm_distribution]
return new_distribution
|
c7a6b2bca50c23c93ab645a0be278b4a2d7830b2 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex018.py | 500 | 4.03125 | 4 | from math import(pi , cos , sin , tan , radians)
an1 = float(input('Diga o angulo: '))
an2 = (an1 * pi) / 180
# Podemos usar tambem o math: an2 = radians(an1)
# sen = (sin(radians(an1)))
sen = sin(an2)
cos = cos(an2)
tg = tan(an2)
print('')
print('{:-^30}' .format(''))
print('O SENO do angulo {} é: {:.3f}' .format(an1 , sen))
print('O COSSENO do angulo {} é: {:.3f}' .format(an1 , cos))
print('A TANGENTE do angulo {} é: {:.3f}' .format(an1 , tg))
print('{:-^30}' .format(''))
|
bcbb9151b1274e5b0b852c1cfa1db212d322f84d | JoaolSoares/CursoEmVideo_python | /Exercicios/ex004.py | 624 | 4.09375 | 4 | n1 = input('digite algo:')
print('o tipo primitivo desse valor é:', type(n1))
print('só tem espaços?', n1.isspace())
print('pode ser um numero?', n1.isnumeric())
print('é maiusulo?', n1.islower())
print('é minusculo?', n1.isupper())
print('é alfabetico?', n1.isalpha())
print('é alfanumerico?', n1.isalnum())
print('esta capitalizada(com maiusculas e minusculas)?', n1.istitle())
# Outra forma agora com a quebra de linha /n
n1 = input('digite algo')
s = type(n1)
p = n1.isspace()
n = n1.isnumeric()
print('primitive type {} \n só tem espaços? {} \n pode ser um numero? {}' .format(s , p , n))
|
9d6b6a18e003e0c7c3fca4dd0d2712f323f7cf5c | JoaolSoares/CursoEmVideo_python | /Exercicios/ex012.py | 220 | 3.65625 | 4 | d1 = float(input('Diga o desconto aplicado: '))
p1 = float(input('Diga o preço do produto: '))
desconto = (p1 * d1) / 100
print('O preço do produto com {}% de descondo ficará: {:.2f}' .format(d1 , p1 - desconto))
|
befa116c3ae0d337ea4ce41f8732d55e0c0b105a | JoaolSoares/CursoEmVideo_python | /Exercicios/ex031.py | 253 | 3.640625 | 4 | n1 = float(input('Diga quantos KM tem a sua viagem: '))
if n1 <= 200:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.50))
else:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.45))
print('Tenha uma boa viagem!! ;D') |
4a6e58653632be4182d5b9183938e56ea69f376c | JoaolSoares/CursoEmVideo_python | /Exercicios/ex069.py | 720 | 3.59375 | 4 | r = 's'
id18cont = mcont = f20cont = 0
# Esta sem a validação de dados...
while True:
print('--' * 15)
print('Cadastro de pessoas')
print('--' * 15)
idade = int(input('Qual a idade? '))
sex = str(input('Qual o sexo? [M/F] ')).strip().upper()[0]
print('--' * 15)
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if idade > 18:
id18cont += 1
if sex in 'Mm':
mcont += 1
elif sex in 'Ff' and idade < 20:
f20cont += 1
if r in 'Nn':
break
print(f'{id18cont} pessoas tem mais de 18 anos')
print(f'{mcont} Homens foram cadastrados')
print(f'{f20cont} Mulheres com menos de 20 anos foram cadastradas')
|
93a6dccf6ecbe72702504cd62cfdc54f117ee363 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex085.py | 310 | 3.625 | 4 | lista = [[], []]
for c in range(1, 8):
n1 = int(input(f'Digite o {c}º Numero: '))
if n1 % 2 == 0:
lista[0].append(n1)
else:
lista[1].append(n1)
print('\033[1;35m-+\033[m' * 18)
print(f'Numeros pares: {sorted(lista[0])}')
print(f'Numeros impares: {sorted(lista[1])}')
|
512085f8ba8507522624dd8f0ae41c5825387ce7 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex062.py | 461 | 3.78125 | 4 | pt = int(input('Diga o primeiro termo da P.A: '))
rz = int(input('Diga a tazão dessa P.A: '))
cont = 1
termo = pt
mais = 1
while mais != 0:
while cont <= 9 + mais:
print(termo, end=' - ')
termo += + rz
cont += 1
print('Finish...')
print('--' * 25)
mais = int(input('Voce quer mostras mais quantos termos? '))
print('Finish...')
print('foi finalizado mostrando no final {} termos' .format(cont))
|
8bf302e5b3c3b91e868479e2119f49f77a2b3422 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex054.py | 364 | 3.8125 | 4 | from datetime import date
cont = 0
cont2 = 0
for c in range(1, 8):
nasc = int(input('Qual o ano de nascimento da {}º pessoa? ' .format(c)))
if date.today().year - nasc >= 18:
cont += 1
else:
cont2 += 1
print('--' * 20)
print('Existem {} pessoas MAIORES de idade.\nExistem {} pessoas MENORES de idade.' .format(cont, cont2))
|
bdbd784a551a48151d15b76bdb80a49210bee853 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex089.py | 1,138 | 3.984375 | 4 | aluno = []
lista = []
res = 'S'
print('\033[1;35m--' * 15)
print(f'{"Sistema Do Colegio":^30}')
print('--' * 15, '\033[m')
print('----')
# Coleta de dados
while res in 'Ss':
aluno.append(str((input('Nome do aluno: '))))
aluno.append(float(input('Nota 1: ')))
aluno.append(float(input('Nota 2: ')))
aluno.append((aluno[1] + aluno[2]) / 2)
lista.append(aluno[:])
aluno.clear()
res = str(input('Quer continuar? [S/N] '))
print('-=' * 25)
# Tabela
print('\033[1;35mNº ALUNO NOTA')
print('-' * 25, '\033[m')
for c, a in enumerate(lista):
print(f'{c} {a[0]:<12} {a[3]}')
print('\033[1;35m-' * 25, '\033[m')
# Notas separadas dos alunos
while res != 999:
res = int(input('Nº do aluno para saber sua nota separada [999 para finalizar]: '))
if res > (len(lista) - 1) and res != 999:
print('\033[1;31mNão encontrei este aluno... Tente novamente...\033[m')
elif res != 999:
print(f'As notas do aluno {lista[res][0]} foram {lista[res][1]} e {lista[res][2]}...')
print('-=' * 25)
print('Programa Finalizado com sucesso...')
|
546907fe45b06b4c4813f9f1d193f073b7520672 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex103.py | 411 | 3.671875 | 4 | def ficha(nome='<Desconhecido>', gols=0):
print(f'O jogador {nome} marcou {gols} gols no campeonato.')
n1 = input('Nome do jogador: ')
n2 = input('Gols no campeonato: ')
print('-=' * 20)
if n2.isnumeric():
n2 = int(n2)
if n1.strip() != '':
ficha(n1, n2)
else:
ficha(gols=n2)
else:
if n1.strip() != '':
ficha(nome=n1)
else:
ficha()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.