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
beaf525e63162d3622dc2a92539f5d9c06aa55cb
slamdunk0414/python
/3.字符串列表数组/9.for循环中的else.py
85
3.671875
4
nums = [11,22,33,44] for num in nums: print(num) else: print('循环完毕')
b7497c0e6ed896dbd94591d97ccbc2e3a91069a3
slamdunk0414/python
/4.元祖函数/5.函数的嵌套调用.py
301
3.6875
4
def test1(): print('test1') test2() def test2(): print('test2') test1() def input_num(): return int(input('请输入一个数字')) def add(): total = 0 num1 = input_num() num2 = input_num() num3 = input_num() total = num1 + num2 + num3 print(total) add()
db5eeb28857a086ed10ac3bbc93db809f18806d4
slamdunk0414/python
/7.面向对象/10.类属性.py
277
3.96875
4
class Tool(object): num = 0 def __init__(self,new_name): self.name = new_name Tool.num += 1 self.num2 = 0 self.num2 += 2 t1 = Tool('t1') t2 = Tool('t2') t3 = Tool('t3') print(Tool.num) print(t1.num2) print(t2.num2) print(t3.num2)
90d2b350864993b362c197cd6d13dc7b577a2f62
Arsher123/Wizualizacja-danych-BartoszN
/lab6/zad7.py
362
3.53125
4
import numpy as np def funkcja(n): macierz=np.zeros((n,n)) #tworzymy przekatne for i in range(n): macierz=macierz+np.diag(np.linspace(2*(i+1),2*(i+1),n-i),i) if (i!=0): macierz=macierz+np.diag(np.linspace(2*(i+1),2*(i+1),n-i),-i) return macierz n=input("podaj rozmiar tablicy:") n=int(n) print(funkcja(n))
3f2e50cc26a76b1ef4f4595b12ccecf4417960da
Arsher123/Wizualizacja-danych-BartoszN
/lab7/zadanie2.py
480
3.703125
4
import numpy as np a=np.array([9,5,1,4,6,2,7,3,5]).reshape(3,3) b=np.array([1,6,8,4,11,16,9,5,14,10,15,2,13,3,12,7]).reshape(4,4) print("Pierwsza tablica: ") print(a) print("Najmniejsze wartosci kazdego rzedu: ") print(a.min(axis=1)) print("Najmniejsza wartosc kazdej kolumy: ") print(a.min(axis=0)) print("Druga tablica: ") print(b) print("Najmniejsze wartosci kazdego rzedu: ") print(b.min(axis=1)) print("Najmniejsza wartosc kazdej kolumy: ") print(b.min(axis=0))
e7a9c53e005411ab69f183ea2fa4c448aa5afb40
Arsher123/Wizualizacja-danych-BartoszN
/Zadania cw3/zadanie 4.py
286
3.703125
4
import math print("funkcja y=ax+b") a=input("podaj liczbe a: ") a=int(a) if a > 0: print("a jest wieksze od 0 zatem funkcja jest rosnaca ") if a < 0: print("a jest mniejsze od 0 zatem funkcja jest malejaca") if a==0: print("a jest rowne 0 zatem funkcja jest stala")
9600558ef3ed872f6644678992de0fb77206298b
yookie-bui/Rock-Paper-Scissor-game
/rps-Gui.py
1,464
3.53125
4
from tkinter import* import random class rpsGui: def __init__(self, parent): self.name_label = Label(parent, text='Rock Paper Scissor') self.name_label.grid(row=0,column=0,columnspan=2, pady=10) self.user_entry = Entry(parent, width=12) self.user_entry.grid(row=1,column=0,padx=5) self.button = Button(parent,text='Enter',command=self.rps) self.button.grid(row=1,column=1,padx=3) self.result = Label(parent,text='') self.result.grid(row=2,column=0,columnspan=3,pady=10) def rps(self): result = '' choice = ['R','P','S'] computer = random.choice(choice) user = self.user_entry.get() if user == 'R': if computer == 'R': result = 'DRAW' elif computer =='P': result = 'LOST' else: result = 'WIN' elif user == 'P': if computer == 'P': result = 'DRAW' elif computer =='S': result = 'LOST' else: result = 'WIN' else: if computer == 'S': result = 'DRAW' elif computer =='P': result = 'LOST' else: result = 'WIN' self.result.config(text=result) def main(): window = Tk() gui = rpsGui(window) window.mainloop() if __name__ == "__main__": main()
ff1a9b191b3bf4ec35cefa1e2ef63485b684b4ef
danielcaballero88/dc_Multiscale-Nanofibers-2_gitlab-bu
/ejemplo_1d.py
2,150
3.65625
4
""" Este ejemplo es una simulacion de un caso de 1d resuelto aparte son dos barras de longitudes l1=5 y l2=7. La barra 1 esta anclada en x=0, en x=5 están conectadas (nodo) y el extremo de x=12 se lleva hasta x=20 Entonces se encuentra un nuevo punto de equilibrio El resultado es completamente acorde a la simulacion 1d hecha aparte y tambien concuerda con los calculos manuales de equilibrio para este caso sencillo . Quizas preocupa un poco que sean 43 las iteraciones para obtener el equilibrio Pero la tolerancia esta puesta bastante baja y la pseudoviscosidad quizas muy alta (de hecho con una pseudoviscosidad*0.1 son 15 iteraciones (+2 inestables)) (con pseudoviscosidad*0.01 son 10 iteraciones (+5 previas inestables), notar que esta es adaptiva) (con *0.001 son 6 iteraciones (+8 previas inestables)) tal parece que empezar con poca pseudoviscosidad es buen plan """ from Malla import Nodos, Subfibras, Malla, Iterador import numpy as np nod_coors = [ [0, 0], [5, 0], [12, 0], ] nod_tipos = [1,2,1] n = Nodos(nod_coors,nod_tipos) print "num nodos: ", n.num print "tipo nodos: ", n.tipos print "coordenadas: ", n.x print "mask fronteras: ", n.mask_fr print "mask intersecciones: ", n.mask_in print "num fron y num in: ", n.num_fr, n.num_in print "---" conec = [ [0,1], [1,2], ] parcon = [ [1.0], # subfibra 1 [2.0] # subfibra 2 ] s = Subfibras(conec, n.x0, parcon) print "ne: ", s.ne print "ie. ", s.ie print "je: ", s.je print "---" pseudovis = [2.0, 2.0, 2.0] m = Malla(n, s, pseudovis) #m.psv = m.psv*0.1 F = np.array( [ [20.0/12.0, 0.0], [0.0, 1.0] ], dtype=float ) m.mover_nodos_frontera(F) ref_pequeno = 0.1 ref_grande = 5.0 ref_diverge = 0.9 max_iter = 100 tolerancia = 0.00001 i = Iterador(len(nod_coors), m.nodos.x, m, ref_pequeno, ref_grande, ref_diverge, max_iter, tolerancia) i.iterar() ts = m.calcular_tracciones_de_subfibras() print m.calcular_tracciones_sobre_nodos(ts) print m.calcular_incremento() print "---" m.set_x(i.x) ts = m.calcular_tracciones_de_subfibras() print m.calcular_tracciones_sobre_nodos(ts) print m.calcular_incremento()
65dcc7f9b80d722f12c01381dbe6b5d4473c681c
kiukin/codewars-katas
/7_kyu/Reversing_fun.py
906
4.09375
4
# Kata: Reversing Fun # https://www.codewars.com/kata/566efcfbf521a3cfd2000056 # You are going to be given a string. # Your job is to return that string in a certain order that I will explain below: # Let's say you start with this: 012345 # The first thing you do is reverse it:543210 # Then you will take the string from the 1st position and reverse it again:501234 # Then you will take the string from the 2nd position and reverse it again:504321 # Then you will take the string from the 3rd position and reverse it again:504123 # Continue this pattern until you have done every single position, # and then you will return the string you have created. # For this particular number, you would return:504132 # #Input: A string of length 1 - 1000 # #Output: A correctly reordered string. def reverse_fun(n): for i in range(0, len(n)): n = n[:i] + n[i:][::-1] return n
7144bc7f17c0fd35a31e83a3bb8dd245a90ef61d
kiukin/codewars-katas
/7_kyu/Simple_string_characters.py
752
4.03125
4
# Kata: Simple string characters # https://www.codewars.com/kata/5a29a0898f27f2d9c9000058 # In this Kata, you will be given a string and your task will be to # return a list of ints detailing the count of uppercase letters, lowercase, # numbers and special characters, as follows. # solve("*'&ABCDabcde12345") = [4,5,5,3]. # --the order is: uppercase letters, lowercase, numbers and special characters. # More examples in the test cases. # Good luck! # Please also try Simple remove duplicates def solve(s): res= [0,0,0,0] for c in s: if c.isupper(): res[0] += 1 elif c.islower(): res[1] += 1 elif c.isdigit(): res[2] += 1 else: res[3] += 1 return res
7424e3d1c91b4052176e86aeedc9261a86490a14
kiukin/codewars-katas
/7_kyu/Descending_order.py
546
4.125
4
# Kata: Descending Order # https://www.codewars.com/kata/5467e4d82edf8bbf40000155/train/python # Your task is to make a function that can take any non-negative integer as a argument and # return it with its digits in descending order. Essentially, rearrange the digits to # create the highest possible number. # Examples: # Input: 21445 Output: 54421 # Input: 145263 Output: 654321 # Input: 123456789 Output: 987654321 def descending_order(num): sorted_num = sorted([d for d in str(num)],reverse=True) return int("".join(sorted_num))
61f43a56471e46893f9fe07227ea44161256a5d8
kiukin/codewars-katas
/7_kyu/Counting_array_elements.py
331
3.828125
4
# Kata: Counting Array Elements # https://www.codewars.com/kata/5569b10074fe4a6715000054 # Write a function that takes an array and counts the number of each unique element present. # count(['james', 'james', 'john']) # #=> { 'james' => 2, 'john' => 1} from collections import Counter def count(array): return Counter(array)
d2e683c7666f55bd51ca159822307bfc0136a253
aces8492/py_edu
/applications/vgood.py
514
3.515625
4
import sys vsize = int(input()) if (vsize % 2 == 0) or (vsize > 100): print("invalid") sys.exit() for i in range(vsize,0,-1): for j in range(1,vsize+1): if i == 1: if j == (vsize+1)/2: print("v",end="") else: print(".",end="") else: if (j == int(vsize/2) - int(i/2) + 1) or (j == vsize - (int(vsize/2) - int(i/2))): print("v",end="") else: print(".",end="") print()
79ce2fe95e1a8ccba8095daa0db9d57168192e71
aces8492/py_edu
/basics/slice.py
597
3.953125
4
score_lists = [40,50,60,70,100] score_tuple = (40,50,60,70,100) print("Value and this num") for i,score in enumerate(score_lists): print("{0}:{1}".format(i,score)) print("specify start and end point of value 1 to 4") print("list : {0}".format(score_lists[1:4])) print("tuple : {0}\n".format(score_tuple[1:4])) print("only specify end point") print("{0}\n".format(score_lists[:2])) print("only specify start point") print("{0}\n".format(score_lists[3:])) print("show 3 elements from tail of lists") print("{0}\n".format(score_lists[-3:])) #this can use string s = "Hello" print(s[2:4])
e4c63508ac697f87c6934b2520666027a15ee894
aces8492/py_edu
/basics/Comprehension_notation.py
815
3.9375
4
#comprehension notation (C_N) #range() is iterable print([i for i in range(10)]) #generate range object print(range(10)) #making list from iterable (range object) print(list(range(10))) #using C_N map like usage print([i*3 for i in range(10)]) #same processing using map print(list(map(lambda x:x*3,range(10)))) #using C_N filter like usage print([i*3 for i in range(10) if i % 2 == 0]) #same processing using map print(list(filter(lambda i:i%2==0,map(lambda x:x*3,range(10))))) #to try one-liner (it isn't readable ...) print([i if i % 2 == 0 else "skip 3" if i == 3 else "skip" for i in map(lambda x:x*3,range(10))]) print([i*3 if i % 2 == 0 else "skip 3" if i == 3 else "skip" for i in range(10)]) #C_N for list print({i*3 for i in range(10) if i % 2 == 0}) print(i*3 for i in range(10) if i % 2 == 0)
cd583aca69c3e7153884032017e2cb6a336f6e24
aces8492/py_edu
/basics/multi_inferitance.py
417
3.75
4
#class A,B -> C class A: def say_a(self): print("in A") def say_hi(self): print("hi A") class B: def say_b(self): print("in B") def say_hi(self): print("hi B") class C(B,A): pass instance_c = C() instance_c.say_a() instance_c.say_b() ''' if exist same instance name in multiple inheritance, a class that earier specified have priority ''' instance_c.say_hi()
8fd9dc373ee53a51250597f8d07b0075c868c011
kabirs/python
/99.py
200
3.84375
4
#!/usr/bin/env python3.3 basevalue=15 for a in range(1,basevalue): for b in range(1,basevalue) : if a>=b : print(repr(b).ljust(1)+"x"+repr(a).ljust(1)+"="+repr(b*a).ljust(3),end=' ') print('')
dc15053c612f0828e00738b1b5b22fcab47f8fab
MelanieArzola/AprendiendoPython
/Tabla.py
287
4.03125
4
# Melanie Arzola 16/09/2019 #Pides el numero que quieren tabla= int(input("Dame un numero del 1 al 9: ")) if tabla >9 or tabla <1: print("Este valor no es permitido") else: for i in range(1,11): salida= "{} x {} = {}" print(salida.format(tabla,i,i*tabla))
9059e5a2b1d99f12c4437e30cef9358a14fe4cf1
ersujalsharma/PythonPractice
/14_Swap_Two_Numbers_Common.py
81
3.5625
4
a= int(input()) b= int(input()) temp = a a = b b = temp print("a",a) print("b",b)
c78659011ed28a9d2c37a2e42214107ee317c31a
ersujalsharma/PythonPractice
/24_Quiz3.py
190
4.0625
4
while True: a = int(input("Enter a Number")) if a>100: print("COngrats You Have Enter Greater Than 100") break else: print("Wrong Input") continue
89c8905424a8b6d9f5d346b3f2fe82e1bf715636
ersujalsharma/PythonPractice
/47_args_and_kargs.py
301
4.03125
4
list = [] def function_add(*args): sum=0 for i in args: sum=sum+i return sum print("Enter numbers you want to add Enter c for REsult") while(1): number = input() if(number == 'c'): break list.append(int(number)) summation = function_add(*list) print(summation)
044c6ad5e47e02265d8c5af88460935dd4b80c5d
ersujalsharma/PythonPractice
/32_FileWritingOperation.py
109
3.53125
4
f = open("Hello.txt","w") f.write("HEy Pagla") print(f) f = open("Hello.txt","a") a = f.write("Sujal sharma") print(a)
33472ccb0008747c75097fd980344f2e7839f692
J100130098/Functional-Turtle-Art-Gallery
/FunctionalTurtleArtGallery.py
933
3.640625
4
import turtle Roger=turtle def hexagon(): for i in range(6): Roger.forward(150) Roger.right(60) def octagon(): for i in range(8): Roger.forward(50) Roger.left(45) def octagonLoop(): for i in range(80): octagon() Roger.right(5) def dodecagon(): for i in range(12): Roger.forward(100) Roger.right(30) def circleSpiral(): for i in range(40): Roger.circle(i*5) Roger.right(5) Roger.bgcolor("pink") Roger.speed(10000) octagonLoop() Roger.penup() Roger.goto(-300,100) Roger.pendown() Roger.color("Dark Green") Roger.begin_fill() hexagon() Roger.end_fill() Roger.penup() Roger.goto(300,-100) Roger.pendown() Roger.color("Light Coral") Roger.begin_fill() dodecagon() Roger.end_fill() Roger.penup() Roger.goto(500,200) Roger.pendown() Roger.color("Blue Violet") circleSpiral() Roger.exitonclick()
cbe5f99c9a95a4e3c2ed8ef05b7fbfff8a52380a
Yuhsuant1994/leetcode_history
/solutions/1_linkedlist.py
2,252
3.5625
4
class ListNode(object): def __init__(self, val=0, next=None): self.val=val self.next=next class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ level, current_max=0,0 check_later=list() if root: level+=1 #if it's not an empty tree else: return level #if (not root.left) & (not root.right) then stop #level==1 meaning only the first entrence #len(check_later)>0 meaning the loop to check is there if (not root.left) & ( not root.right ): return level #level 1 while (len(check_later)>0)|(level==1): if level!=1: #check loop check_ref=check_later.pop() level=check_ref[0] root=check_ref[1] while (root.left is not None) | (root.right is not None): level+=1 if not root.left: root=root.right elif not root.right: root=root.left else: check_later+=[[level,root.right]] root=root.left if level>current_max: current_max=level return current_max p5=ListNode(5) p4=ListNode(4,p5) p21=ListNode(2,p4) p22=ListNode(2,p4) headB=ListNode(1,p21) headA=ListNode(1,p22) #head # Second thought: store value if not headA or not headB: print( None) # Second thought: store value listA, listB, inter = list(), list(), list() pointA, pointB = headA, headB i = 1 while pointA: listA = listA + [pointA.val] pointA = pointA.next while pointB: listB = listB + [pointB.val] pointB = pointB.next while i < min(len(listA), len(listB)): if listA[-i:] == listB[-i:]: i = i + 1 else: i = i - 1 break if i == 0: print( None) skipA = len(listA) - i skipB = len(listB) - i pointA, pointB = headA, headB for s in range(skipA): pointA = pointA.next for s in range(skipB): pointB = pointB.next while pointA and pointB: if pointA == pointB: print( pointA) else: pointA = pointA.next pointB = pointB.next print( None)
1e3515ec7e6cda2d5edda61a283debeae79049fa
Yuhsuant1994/leetcode_history
/solutions/median_string_toint.py
2,719
3.828125
4
""" Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. Return the integer as the final result. """ #inital try good result """ Runtime: 12 ms, faster than 99.34% of Python online submissions for String to Integer (atoi). Memory Usage: 13.9 MB, less than 6.55% of Python online submissions for String to Integer (atoi). """ class Solution(object): def myAtoi(self, s): """ :type s: str :rtype: int """ result,i=0, 0 s=s.lstrip() if len(s)==0: return 0 mini, maxi=-2**31, 2**31-1 det= -1 if s[0]=='-' else 1 s=s[1:] if s[0] in ['-','+'] else s while i < len(s): if s[:i+1].isdigit(): i+=1 result=int(s[:i])*det else: i=len(s) result=mini if result<mini else result result=maxi if result>maxi else result return result """ Runtime: 16 ms, faster than 96.72% of Python online submissions for String to Integer (atoi). Memory Usage: 13.5 MB, less than 53.58% of Python online submissions for String to Integer (atoi). """ #try to optimize memory-> reduce variable class Solution(object): def myAtoi(self, s): """ :type s: str :rtype: int """ result=0 s=s.strip() if len(s)==0: return 0 start=1 if s[0] in ['-','+'] else 0 i=start while i < len(s): if s[start:i+1].isdigit(): i+=1 result=int(s[:i]) else: i=len(s) result=-2**31 if result<-2**31 else result result=2**31-1 if result>2**31-1 else result return result
781fb17c04ac87a118aca8853e7a58837a61942d
Yuhsuant1994/leetcode_history
/solutions/average_levels_in_binary_tree.py
1,428
4.03125
4
""" Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. """ # Recursive Create a dictionary for the tree values, then to everage the result. # note that we need to convert len to a float to get float division # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def createTreeDict(self, treeDict, i, node): if node: if i in treeDict: treeDict[i] = treeDict[i] + [node.val] else: treeDict[i] = [node.val] return self.createTreeDict(treeDict, i+1, node.left),\ self.createTreeDict(treeDict, i+1, node.right) else: return def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ result = list() treeDict = dict() self.createTreeDict(treeDict, 0, root) for l in range(len(treeDict)): result = result + [sum(treeDict[l]) / float(len(treeDict[l]))] return result
fd4e7f629a05d36875bbe8f3ee9e6d5ecab1d8e3
Asabeneh/Fundamentals-of-python-august-2021
/week5/list-comprehension.py
508
3.875
4
countries = ['Finland','Sweden','Denmark','Norway','Iceland'] nums = [1, 2, 3, 4, 5] # [1, 4, 9, 16, 25] new_nums = [n ** 2 for n in nums] print(new_nums) country_codes = [c.upper()[:3] for c in countries] print(country_codes) countries_with_land = [c for c in countries if 'land' in c] print(countries_with_land) countries_without_land = [c for c in countries if 'land' not in c] print(countries_without_land) countries_without_way = [c for c in countries if 'way' not in c] print(countries_without_way)
36a0cb1db271953430c191c321286014bc97ed6d
Asabeneh/Fundamentals-of-python-august-2021
/week-2/conditionals.py
997
4.40625
4
is_raining = False if is_raining: print('I have to have my umbrella with me') else: print('Go out freely') a = -5 if a > 0: print('The value is positive') elif a == 0: print('The value is zero') elif a < 0: print('This is a negative number') else: print('It is something else') # weather = input('What is the weather like today? ').lower() # if weather == 'rainy': # print('Go out with an umbrella') # elif weather == 'cloudy': # print('There is a possibility of rain.') # elif weather == 'sunny': # print('Go out freely and enjoy the sunny day.') # elif weather == 'snowy': # print('It may be slippery.') # else: # print('No one knows about today weather') a = 3 value = 'Positive' if a > 0 else 'Negative' print(value) if a > 0: if a % 2 == 0: print('It is a positive even number') else: print('It is a positive odd number') elif a == 0: print('The number is zero') else: print('The number is negaive')
27b0269da0ce0d4c3723623a4058f4f2bfa31fa7
Asabeneh/Fundamentals-of-python-august-2021
/week4/revision.py
1,146
3.703125
4
countries = ['Finland','Sweden','Denmark','Norway','Iceland'] print(len(countries)) print(countries[0]) print(countries[1]) print(countries[-1]) print(countries[-2]) # append, extend, pop, remove, del, insert etc nums = [1, 2, 3, 4, 5] # [1, 4, 9, 16, 25] new_nums = [] for i in nums: new_nums.append(i * i) print(new_nums) print(list(range(1, 11, 2))) # find the sum of all numbers from 0 to 100 all_nums = 0 for i in range(0, 101): all_nums = all_nums + i print(all_nums) # find the sum of all evens from 0 to 100 evens = 0 for i in range(0, 101, 2): evens = evens + i print(evens) # find the sum of all odds from 0 to 100 odds = 0 for i in range(1, 101, 2): odds = odds + i print(odds) new_countries = [] for country in countries: new_countries.append([country, country.upper(), country.upper()[:3], len(country)]) print(new_countries) hashes = '' for i in range(7): hashes = hashes + '#' print(hashes) for i in range(1, 8): print('#'*i, i) countries_with_land = [] for country in countries: if 'land' in country: countries_with_land.append(country) print(countries_with_land)
8d58e8c62c213af074d36c67a413cf4212f13eec
djdd01/CS50-2020
/pset6/credit/credit.py
2,221
3.984375
4
from sys import exit from cs50 import get_int # ok so first of all creating a long variable to get a card number as an input card = get_int("What is your credit card number? \n") temp = card # creating another variable temp to utilize instead of making changes in card alt = 0 # alternate digits adj = 0 # alt alternate digits (that are not muliplied by 2) ( dont know y i named it adj since they are not adjacent) while temp > 0: # now this loop is complicated since it does many mathematical operations in one line adj = adj + temp % 10 """ the next line is very messy but start from the innermost bracket and u will understand. i took the alternate digits, multiplied them by 2 then seperated the digits of the products and finally added them """ alt = alt + ((2 * ((temp % 100) // 10)) % 10) + ((2 * ((temp % 100) // 10)) // 10) temp = temp // 100 temp = card # replaces the value of temp with card again for further use total = alt + adj valid = False # created a variable to store if the card is valid if total % 10 == 0: valid = True else: print("INVALID\n") exit(1) # calculating the number of digits i = 0 digit = False if valid == True: while temp > 0: temp = temp // 10 i = i + 1 temp = card # checking the initial digits of the cards if i == 15: temp = temp // pow(10, 13) if temp == 34 or temp == 37: # since american express cards start with these print("AMEX\n") exit(0) else: print("INVALID\n") exit(1) temp = card if i == 16: temp = temp // pow(10, 14) if temp == 51 or temp == 52 or temp == 53 or temp == 54 or temp == 55: # since mastercards start with these print("MASTERCARD\n") exit(0) else: temp = temp // 10 if temp == 4: # nesting an if-else statement as master and visa both have 16 digit card numbers print("VISA\n") exit(0) else: print("INVALID\n") exit(1) temp = card if i == 13: temp = temp // pow(10, 12) if temp == 4: print("VISA\n") exit(0) else: print("INVALID\n") exit(1) else: print("INVALID\n") exit(1)
2e1146369916a05e2abed687a431935a3f7788e5
salehas222/Dataquest_Data_Analyst_In_Python
/Step_2_Intermediate_Python_and_Pandas/6_Data_Cleaning_Project_Walkthrough/Challenge_ Cleaning Data-102.py
1,839
3.671875
4
## 4. Filtering Out Bad Data ## import matplotlib.pyplot as plt true_avengers = pd.DataFrame() #avengers['Year'].hist() true_avengers = avengers[avengers["Year"] > 1960] true_avengers['Year'].hist() ## 5. Consolidating Deaths ## col_death = ["Death1","Death2","Death3","Death4","Death5"] #for col in col_death: # true_avengers[col] = true_avengers[col].fillna("NO") #print("----------------") #print(true_avengers[["Death1","Death2","Death3","Death4","Death5"]].head()) def convdeath(str): if str == "YES": return int(1) else: return int(0) #for col in col_death: # true_avengers[col] = true_avengers[col].apply(convdeath) #print("----------------") #print(true_avengers[["Death1","Death2","Death3","Death4","Death5"]].head()) def sumdeath(df): res = 0 for col in col_death: if df[col] == 'YES': res += 1 return res true_avengers["Deaths"] = true_avengers.apply(sumdeath,axis=1) print("----------------") print(true_avengers[["Deaths","Death1","Death2","Death3","Death4","Death5"]].head()) ## 6. Verifying Years Since Joining ## joined_accuracy_count = int() print("----------------") print(true_avengers.info()) print("----------------") print(true_avengers[["Year","Years since joining"]].head()) def testyearssincecol(df): if 2015 - df["Years since joining"] == df["Year"]: return 1 else: return 0 true_avengers["test"] = true_avengers.apply(testyearssincecol,axis=1) joined_accuracy_count = true_avengers["test"].sum() print(joined_accuracy_count) print(true_avengers[["Year","Years since joining","test"]].head()) # more simple ... joined_accuracy_count = int() correct_joined_years = true_avengers[true_avengers['Years since joining'] == (2015 - true_avengers['Year'])] joined_accuracy_count = len(correct_joined_years)
e765080b8821dd0cf37aee8298468cdaf08c320c
salehas222/Dataquest_Data_Analyst_In_Python
/step_5_Probability_and_Statistics/2_statistics_intermediate/Measures of Variability-308.py
5,705
3.8125
4
## 1. The Range ## import pandas as pd houses = pd.read_table('AmesHousing_1.txt') houses.head() def find_range(array): return max(array) - min(array) years = houses['Yr Sold'].unique() years range_by_year = {} for year in years: range_by_year[year] = find_range(houses[houses['Yr Sold'] == year]['SalePrice']) range_by_year two = True one = False ## 2. The Average Distance ## def avg_dist(array): mean = sum(array)/len(array) distances = [] for element in array: distance = element - mean distances.append(distance) return sum(distances)/len(distances) C = [1,1,1,1,1,1,1,1,1,21] C_average_distance = avg_dist(C) avg_distance = C_average_distance ## 3. Mean Absolute Deviation ## C = [1,1,1,1,1,1,1,1,1,21] def mean_abs_dist(array): mean = sum(array)/len(array) distances = [] for element in array: distance = abs(element-mean) distances.append(distance) return sum(distances)/len(distances) mad = mean_abs_dist(C) mad ## 4. Variance ## C = [1,1,1,1,1,1,1,1,1,21] def variance(array): mean = sum(array)/len(array) distances = [] for element in array: distance = (element-mean) ** 2 distances.append(distance) return sum(distances)/len(distances) variance_C = variance(C) variance_C ## 5. Standard Deviation ## from math import sqrt C = [1,1,1,1,1,1,1,1,1,21] def sd(array): mean = sum(array)/len(array) distances=[] for element in array: distance = (element-mean) ** 2 distances.append(distance) return sqrt(sum(distances)/len(distances)) standard_deviation_C = sd(C) standard_deviation_C ## 6. Average Variability Around the Mean ## def standard_deviation(array): reference_point = sum(array) / len(array) distances = [] for value in array: squared_distance = (value - reference_point)**2 distances.append(squared_distance) variance = sum(distances) / len(distances) return sqrt(variance) import matplotlib.pyplot as plt mean = houses['SalePrice'].mean() st_dev = sd(houses['SalePrice']) houses['SalePrice'].plot.hist() plt.axvline(mean, color = 'Black', label = 'Mean') plt.axvline(mean - st_dev, color = 'Red', label = 'Below') plt.axvline(mean + st_dev, color = 'Violet', label = 'Above') plt.legend() plt.show() years = {} for year in houses['Yr Sold'].unique(): years[year] = sd(houses[houses['Yr Sold'] == year]['SalePrice']) greatest_variability = max(years, key = years.get) greatest_variability lowest_variability = min(years, key = years.get) lowest_variability ## 7. A Measure of Spread ## sample1 = houses['Year Built'].sample(50, random_state = 1) sample2 = houses['Year Built'].sample(50, random_state = 2) def standard_deviation(array): reference_point = sum(array) / len(array) distances = [] for value in array: squared_distance = (value - reference_point)**2 distances.append(squared_distance) variance = sum(distances) / len(distances) return sqrt(variance) for i in range(1,5): sample = houses['SalePrice'].sample(50, random_state = i) st_dev = sd(sample) print('Sample ' + str(i) + ': ' + str(st_dev)) sample1 = houses['Year Built'].sample(50, random_state = 1) sample2 = houses['Year Built'].sample(50, random_state = 2) st_dev1 = sd(sample1) print(st_dev1) st_dev2 = sd(sample2) print(st_dev2) bigger_spread = 'sample 2' ## 8. The Sample Standard Deviation ## def standard_deviation(array): reference_point = sum(array) / len(array) distances = [] for value in array: squared_distance = (value - reference_point)**2 distances.append(squared_distance) variance = sum(distances) / len(distances) return sqrt(variance) import matplotlib.pyplot as plt s_d = [] for i in range(5000): s = houses['SalePrice'].sample(10,random_state=i) s_d.append(sd(s)) plt.hist(s_d) plt.axvline(sd(houses['SalePrice']), color = 'r') plt.show() sum(s_d) / 5000 sd(houses['SalePrice']) ## 9. Bessel's Correction ## from math import sqrt def standard_deviation(array): reference_point = sum(array) / len(array) distances = [] for value in array: squared_distance = (value - reference_point)**2 distances.append(squared_distance) variance = sum(distances)/(len(distances)-1) return sqrt(variance) import matplotlib.pyplot as plt st_devs = [] for i in range(5000): sample = houses['SalePrice'].sample(10, random_state = i) st_dev = standard_deviation(sample) st_devs.append(st_dev) plt.hist(st_devs) plt.axvline(pop_stdev) # pop_stdev is pre-saved from the last screen ## 10. Standard Notation ## from numpy import std, var sample = houses.sample(100, random_state = 1) from numpy import std, var pandas_std = sample['SalePrice'].std(ddof=1) numpy_std = std(sample['SalePrice'],ddof=1) equal_stdevs = (pandas_std == numpy_std) equal_stdevs pandas_var = sample['SalePrice'].var(ddof=1) numpy_var = var(sample['SalePrice'],ddof=1) equal_vars = pandas_var == numpy_var numpy_stdev = 76469.14464354333 pandas_stdev = 76469.14464354333 ## 11. Sample Variance — Unbiased Estimator ## population = [0, 3, 6] samples = [[0,3], [0,6], [3,0], [3,6], [6,0], [6,3] ] pop_var = var(population, ddof = 0) pop_std = std(population, ddof = 0) stds = [] variances = [] for s in samples: stds.append(std(s, ddof = 1)) variances.append(var(s, ddof = 1)) mean_std = sum(stds) / len(stds) mean_var = sum(variances) / len(variances) equal_stdev = (pop_std == mean_std) equal_var = (pop_var == mean_var)
313b4139cb12025d115123870bf769d8368091b9
verito-stanger/PythonPractice
/Conditions.py
1,357
3.84375
4
#----Conditions---- # Operators #Variables Integer = 0 Float = 0 String = "Mikey" Boolean = True Array = [1, 3, 4, 8, 76] Dictionary = {'Papagayo':'objeto', 'Patilla':'fruta'} Tuple = (12,25) Array2 =[] #validation = type(Tuple) """if (Integer <= 10): print("Si es menor a 10") if (Boolean): print("Boolean es VERDADERO!!") else: print("Esa Vaina es FALSA!!")""" """if(Float == 1): print("El Valor es muy bajo!!") elif (Float > 1 and Float < 5): #elif es un posible sustituto del switch case print("Todavia te falta mi ciela!") elif(Float > 4 and Float < 15): print("Pelo a pelo menol!") else: print("Esta vaina no aplica!") if (String is not None): #not None = No es Nulo print(String) if (len(Array2) != 0): print("No hay nada adentro!")""" """numero = 100 while Boolean: numero = numero * 10 print(numero) if (numero >= 100000): Boolean = False break """ Nombres = [] Documentos = [] while (Integer <= 2): Nombres.append(input ("Indroduzca su nombre:")) Documentos.append(input("Indroduzca su numero de DNI:")) print(f"se han registrado {Nombres[Integer]}") Integer = Integer +1 continue Integer = 0 for Nombre in Nombres: print(Nombre) print(Documentos[Integer]) Integer = Integer +1
d6e5435f634beb7a11f6095bb3f697fbeb426fb8
hossein-askari83/python-course
/28 = bult in functions.py
898
4.25
4
number = [0, 9, 6, 5, 4, 3, -7, 1, 2.6] print("-----------") # all , any print(any(number)) # if just one of values was true it show : true (1 and other numbers is true) print(all(number)) # if just one of values was false it show : false (0 is false) print("-----------") # min , max print(max(number)) # show maximum of numbers print(min(number)) # show minimum of numbers print("-----------") # sorted , reversed print(sorted(number)) # sort numbers from smallest to biggest print(list(reversed(number))) # show reversed list print("-----------") # len , abs print(len(number)) # show number of value in list print(abs(number[6])) # abs = absolute : show "قدر مطلق" print("-----------") # sum , round print(sum(number)) # show sum of list values # note : sum (varible , some sumber) if write a number after varible it show sum of "numbers + number" print(round(number[8]))
e1dbf5bf24acd79b8f81ee414ec7b9fd815285d3
hossein-askari83/python-course
/39 = decorator.py
912
3.828125
4
class user : def normalFunction(self): print("this is normal function") print(self) # print("--------------------------------------------------") @classmethod def functionWithDecorator(cls): print("this is function with decorator") print(cls) example = user() example.normalFunction() # it will return this : <__main__.user object at 0x0000022B189AAFA0> print("-------------------------------") example.functionWithDecorator() # it will return this : <class '__main__.user'> print("===================================") user.normalFunction() # it give us error cuze normal functions whant a instance and they dependent on that instance print("-------------------------------") user.functionWithDecorator() # it again print : <class '__main__.user'> cuz decorator do something to founction and they not dependent to # instance any more and it(function) return to class
f6380219eed1fb33a23997c9c6952693edf37a51
hossein-askari83/python-course
/38 = login example.py
1,099
3.890625
4
class users : activeUsersCount = 0 activeUsersList = [] allowedUsers = ["ali", "hossein" , "iman" , "javad" , "sara"] def __init__(self , userName , userFamily): self.name = userName self.family = userFamily def login(self): if self.name not in users.allowedUsers : raise ValueError("you cant login") print(f"{self.name} is logged in ") users.activeUsersCount += 1 print(f"{users.activeUsersCount} users is active ") users.activeUsersList.append(self.name) print(f"active users are : {users.activeUsersList}") def logout(self): print(f"{self.name} is log out ") users.activeUsersCount -= 1 print(f"{users.activeUsersCount} users is active ") users.activeUsersList.remove(self.name) print(f"active users are : {users.activeUsersList}") user1 = users("sara" , "ahamdi") user2 = users("ali" , "asghari") user3 = users("asghar" , "rahmati") user1.login() user2.login() # user3.login() # this give us erroe cuz "asghar" is not in allowed users user1.logout()
58ddeb4812eda53fd74c23fb258479449194869e
hossein-askari83/python-course
/9 = condision.py
314
4.03125
4
# condition logic = true or false # we whant giva medals to sporters print("please enter youre rank ") rank = int(input()) if rank == 1 : print("you got the GOLD medal ") elif rank == 2 : print("you got the SILVER madal ") elif rank == 3 : print("you got the BRONZE medal ") else : print("ridi")
6031ee42849ca64aafd9ae7829f83c207e0966af
ashleyjohnson590/CS162Python-Project7
/LinkedList1.py
6,229
4.25
4
#Author: Ashley Johnson #Date: 5/7/2021 #Description: Program adds and removes a node to the linked list, searches the linked list for a #value, inserts a node into the linked list at a specific value, reverses the linked list, and returns #the linked list as a regular python list, and returns the node object that is at tbe _head of # the linked list. #please grade the active submission that I submitted on 5/14/2021 and ignore the excercise #code. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data def set_data(self): data = self.data return data def get_next(self): return self.next def set_next(self): self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): """initializes head of linked list.""" self._head = None def add(self, val, current=None): """recursive version of add function""" if self.is_empty(): self.set_head(Node(val)) return if current is None: return self.add(val, self.get_head()) if current.next is None: current.next = Node(val) return else: self.add(val, current.next) def remove(self,val, current = None): """recursive version of remove function""" if self.is_empty(): # If the list is empty print("This is an empty list") return if current is None: head = self.get_head() head_data = head.get_data if head_data == val: print("Special case number is at the ead") self.set_head(head.next) return self.remove(val, self.get_head()) elif current.next is None: print("We are at the end of the list") return print("val = {}".format(val)) print("current.data = {}".format(current.data)) if current.next.data != val: print("Nope it doesn't matcvh") else: print("Yes it matches") print("My data = {}".format(current.data)) next_node = current.next print("My neighbors data {}".format(next_node.data)) next_next_node = next_node.next print("My next_next neight {}".format(next_next_node.data)) current.next = next_next_node self.remove(val, current.next) def contains(self, val, previous = None): """recursive version of contains function""" if self.is_empty(): # If the list is empty print("This is an empty list") return False if previous is None: if self.get_head().data == val: print("I found it at the head") return True else: return self.contains(val, self.get_head()) else: if previous.data == val: print("we found it in previous") return True else: if previous.next == None: print("im at the end of the list") return False else: return self.contains(val, previous.next) def insert(self,val, pos,index = 0, current=None): """recursive version of insert function""" if self.is_empty(): # If the list is empty print("list is empty") return if pos == 0: temp = self.get_head() self.set_head(Node(val)) self.get_head().next = temp return elif index == 0: if current is None: return self.insert(val, pos, 0, self.get_head()) if current is not None: if pos - 1 == index: next = current.next new_node = Node(val) new_node.next = next current.next = new_node return else: index += 1 return self.insert(val, pos, index, current.next) else: print("we got to the end of list. position is too long") def reverse(self, current = None, previous = None): """recursive version of reverse function.""" if self.is_empty(): return if current is None and previous is None: return self.reverse(self.get_head()) if current is not None: following = current.next current.next = previous previous = current current = following return self.reverse(current, previous) else: self.set_head(previous) return def to_plain_list(self, list = None, current = None): """recursive version of to_plain_list function""" if self.is_empty(): return [] if list is None: return self.to_plain_list([],self.get_head()) if current is not None: data = current.data list.append(data) return self.to_plain_list(list, current.next) else: return list ## def get_head(self): """function returns the node object that is at the _head of the linked list""" head = self._head return head def set_head(self, new_head): """function sets head""" self._head = new_head def is_empty(self): """ Returns True if the linked list is empty, returns False otherwise """ return self._head is None def main(): print("in main") ll = LinkedList() ll.add(3) ll.add(4) ll.add(5) if ll.contains(99): print("list contains 99") else: print("didn't find it") ll.insert(99, 0) list = ll.to_plain_list() print(list) ll.reverse() if __name__ == "__main__": main()
4b77591a779a29ea29cad5805a335ee7b5b9da5f
rintukutum/functional-gene-annotation
/fact_function.py
205
4.15625
4
def factorial (n): f = 1 while (n >0 ): f = f * n n = n - 1 return f print("Input your number") n= int(input()) print ("factorial of your input number:", factorial(n))
a0e243a830e5b91d7f4081784700dee2ed58289b
Victoria-DR/codecademy
/computer-science/veneer/script.py
2,340
3.578125
4
import datetime class Art: def __init__(self, artist, title, year, medium, owner): self.artist = artist self.title = title self.year = year self.medium = medium self.owner = owner def __repr__(self): return f"{self.artist}. \"{self.title}\". {self.year}, {self.medium}. {self.owner.name}, {self.owner.location}." class Marketplace: def __init__(self): self.listings = [] def add_listing(self, new_listing): self.listings.append(new_listing) def remove_listing(self, old_listing): self.listings.remove(old_listing) def show_listings(self): for listing in self.listings: if listing.expiration_date < datetime.date.today(): remove_listing(listing) else: print(listing) # veneer = Marketplace() class Client: def __init__(self, name, location, is_museum, wallet, wishlist): self.name = name self.location = location self.is_museum = is_museum self.wallet = wallet self.wishlist = wishlist def sell_artwork(self, artwork, price, expiration_date): if artwork.owner == self: veneer.add_listing(Listing(artwork, price, self, expiration_date)) def buy_artwork(self, artwork): if artwork.owner != self: for listing in veneer.listings: if artwork == listing.art: art_listing = artwork if listing.expiration_date < datetime.date.today(): veneer.remove_listing(listing) print("Listing unavailable.") break artwork.owner.wallet += listing.price self.wallet -= listing.price artwork.owner = self veneer.remove_listing(listing) break class Listing: def __init__(self, art, price, seller, expiration_date): self.art = art self.price = price self.seller = seller self.expiration_date = expiration_date def __repr__(self): return f"{self.art.title}, {self.price}." # edytta = Client("Edytta Halpirt", "Private Collection", False, 10000000, None) # moma = Client("The MOMA", "New York", True, 600000000, None) # girl_with_mandolin = Art("Picasso, Pablo", "Girl with a Mandolin (Fanny Tellier)", 1910, "oil on canvas", edytta) # edytta.sell_artwork(girl_with_mandolin, 6000000, datetime.date(2020, 12, 19)) # moma.buy_artwork(girl_with_mandolin) # print(girl_with_mandolin) # veneer.show_listings()
f7df70c87749177fdb0473207659ba0ee49741c0
beyzakilickol/week1Wednesaday
/palindrome.py
591
4.15625
4
word = input('Enter the word: ') arr = list(word) second_word = [] for index in range(len(arr)-1, -1 , -1): second_word.append(arr[index]) print(second_word) reversed = ''.join(second_word) print(reversed) def is_palindrome(): if(word == reversed): return True else: return False print(is_palindrome()) #-----------------------------------second way----------------------- #word = input('Enter the word: ') #reversed = word[::-1] #def is_palindrome(): # if(word == reversed): # return True # else: # return False #print(is_palindrome())
c86ab1fe4371066a37d70f6d5b4459325e54ed90
beepboop271/programming-contest-stuff
/CCC-03-J1.py
156
3.578125
4
t = input() s = input() h = input() for i in range(t): print '*'+(' '*s)+'*'+(' '*s)+'*' print '*'*(3+(2*s)) for i in range(h): print ' '*(s+1)+'*'
24f522cdedbbbe2c80fb94ba468f366102de7d06
beepboop271/programming-contest-stuff
/CCC-15-J1.py
248
4.125
4
month = input() day = input() if month < 2: output = "Before" elif month > 2: output = "After" else: if day < 18: output = "Before" elif day > 18: output = "After" else: output = "Special" print output
58da502d8cb88dd2e406c8715e1256977240583a
beepboop271/programming-contest-stuff
/CCC-13-S1.py
213
3.859375
4
year = input() valid = False while not valid: year += 1 yearList = list(str(year)) valid = True for letter in yearList: if yearList.count(letter) > 1: valid = False print year
1238f6ef46f90f7e0ad22ba5a1062f6a5a0d94fc
crashb/AoC-2017
/Solutions/Day17.py
1,014
3.90625
4
# solution to http://adventofcode.com/2017/day/17 # fills a buffer of length steps+1 with numbers according to part 1 # returns the buffer (list of int) def fillBuffer(stepLength, steps): buffer = [0] currentPos = 0 for i in range(1, steps + 1): currentPos = (currentPos + stepLength) % len(buffer) currentPos += 1 buffer.insert(currentPos, i) return buffer # finds the number after zero in a buffer of length steps+1 # returns the number after zero (int) def findAfterZero(stepLength, steps): currentPos = 0 lastChanged = 1 for i in range(1, steps + 1): currentPos = ((currentPos + stepLength) % i) + 1 if currentPos == 1: lastChanged = i return lastChanged if __name__ == "__main__": stepLength = 303 buffer = fillBuffer(stepLength, 2017) print("2017 location: " + str(buffer.index(2017))) print("Number in buffer after 2017: " + str(buffer[buffer.index(2017) + 1])) afterZero = findAfterZero(stepLength, 50000000) print("Number after 0 after 50000000 steps: " + str(afterZero))
0d6256b911b8e8dc665f2e52d1bd3ba3bdc83498
crashb/AoC-2017
/Solutions/Day11.py
2,151
4.09375
4
# solution to http://adventofcode.com/2017/day/11 # part 1: follow a path and find the shortest distance to its destination. # takes a list of directional strings: "n", "s", "ne", "sw", "nw", and "se". # the y-axis runs from n-s, while the x-axis runs from ne-sw. there is a third # axis, the z-axis, which runs from nw-se. interestingly, x + y + z = 0 for # the coordinates of any given tile. # very helpful: http://keekerdc.com/2011/03/hexagon-grids-coordinate-systems-and-distance-calculations/ # returns minimum distance (int) # rank: 297 def followPath(dirList): x = 0 y = 0 for dir in dirList: if dir == "n": y += 1 elif dir == "s": y -= 1 elif dir == "ne": x += 1 elif dir == "sw": x -= 1 elif dir == "nw": y += 1 x -= 1 elif dir == "se": y -= 1 x += 1 # now that we have x and y coordinates, get z coordinate using x + y + z = 0 property z = 0 - x - y # print("x, y, z: " + str(x) + "," + str(y) + "," + str(z)) # we might get negative values for x, y, z, so make sure to get absolute val of each d = max(abs(x), abs(y), abs(z)) return d # part 2: find the furthest distance a given path (list of strings) strays from the origin. # returns maximum distance (int) # rank: 281 def furthestDistance(dirList): x = 0 y = 0 maxDist = 0 for dir in dirList: if dir == "n": y += 1 elif dir == "s": y -= 1 elif dir == "ne": x += 1 elif dir == "sw": x -= 1 elif dir == "nw": y += 1 x -= 1 elif dir == "se": y -= 1 x += 1 else: print("Invalid direction: \"" + dir + "\"") return -1 # calculate z-coordinate of each traversed tile, and get shortest distance z = 0 - x - y d = max(abs(x), abs(y), abs(z)) # if we have a new furthest point, update maxDist if d > maxDist: maxDist = d return maxDist if __name__ == "__main__": # read input file into list of strings with open('Day11Input.txt', 'r') as myfile: dirList = myfile.read().strip().split(",") # print(str(dirList)) distance = followPath(dirList) print("Shortest distance: " + str(distance)) farDistance = furthestDistance(dirList) print("Furthest distance: " + str(farDistance))
7b3dce9551aa9acce445a765ca847dc956d1f375
rymo90/100DaysOfCodeChallenge
/numberfun.py
506
3.75
4
n= int(input()) svar="" for i in range(n): c= input() c= c.split() product= int(c[len(c)-1]) c = c[0:len(c)-1] c.sort(reverse = True, key= int) # print(c) if (int(c[0]) + int(c[1])) == product: svar="Possible" elif (int(c[0]) / int(c[1])) == product: svar="Possible" elif (int(c[0]) - int(c[1])) == product: svar="Possible" elif (int(c[0]) * int(c[1])) == product: svar="Possible" else: svar="Impossible" print(svar)
143cfbbbc0413e448fb78767e3876dda66cba6f7
iver56/it3105
/module1/base_node.py
1,321
3.625
4
class BaseNode(object): """ This class represents the state of a node along with its score (f, g, h) and expand function This is the class that should be replaced or subclassed to implement other A* problems """ ARC_COST_MULTIPLIER = 1 def __init__(self, **kwargs): self.parent = kwargs.get("parent", None) self.g = kwargs.get("g", None) self.h = kwargs.get("h", None) self.f = None def set_parent(self, parent): self.parent = parent def set_g(self, g): self.g = g def calculate_f(self): self.f = self.g + self.h def calculate_h(self): pass # must be implemented def generate_children(self): pass # must be implemented def is_solution(self): pass # must be implemented def get_ancestors(self): ancestors = [] current_node = self while True: if current_node.parent is None: return ancestors else: ancestors.append(current_node.parent) current_node = current_node.parent def __eq__(self, other_node): pass # must be implemented def __hash__(self): pass # must be implemented def get_arc_cost(self, other_node): return self.ARC_COST_MULTIPLIER
a826bd5b814dc947ed4a8ac67312654f46eef3a7
iver56/it3105
/module1/nav_node.py
1,551
3.84375
4
from point import Point from base_node import BaseNode class NavNode(BaseNode): """ This is a Node implementation that is specific to the "find shortest path" problem """ H_MULTIPLIER = 1 board = None def __init__(self, position, g=None, h=None, parent=None): super(NavNode, self).__init__(g=g, h=h, parent=parent) self.position = position def calculate_h(self): self.h = self.position.euclidean_distance_to(self.board.goal) * NavNode.H_MULTIPLIER def generate_children(self): children = set() candidate_positions = { Point(x=self.position.x, y=self.position.y + 1), Point(x=self.position.x, y=self.position.y - 1), Point(x=self.position.x + 1, y=self.position.y), Point(x=self.position.x - 1, y=self.position.y) } for position in candidate_positions: if self.board.is_tile_accessible(position): child = NavNode(position) children.add(child) return children def is_solution(self): return self.position.x == self.board.goal.x and self.position.y == self.board.goal.y def __eq__(self, other_node): return self.position.as_tuple() == other_node.position.as_tuple() def __hash__(self): return hash(self.position.as_tuple()) def get_arc_cost(self, other_node): return NavNode.ARC_COST_MULTIPLIER def __str__(self): return "x:" + str(self.position.x) + \ " y:" + str(self.position.y)
b004d77b2b1d156f22d74ce2cde2557dcec7055a
guohuahua2012/samples
/Test/CHEME_APP/get_csvfile.py
1,239
3.765625
4
#coding=utf-8 import os import csv ''' 读取文件夹下的csv文件 ''' def readAllFiles(filePath): file_list = [] fileList = os.listdir(filePath) for file in fileList: path = os.path.join(filePath, file) if os.path.isfile(path): file = open(path, 'r' , encoding='utf-8') file_list.append(path) else: continue return file_list tt = readAllFiles(r'D:\360MoveData\Users\ChunhuaGuo\Desktop\CM\kick\team\1681357\6') def get_csv_data(csv_path): csv_path_list = csv_path for i in csv_path_list: # print(i) with open(r'{0}'.format(i), 'r') as f: reader = csv.reader(f) # print(type(reader)) # for row in reader: # print(row) data_to_str = str(row) # print(data_to_str) # print(type(data_to_str)) data_str = data_to_str.strip('[]') data_str = data_str.strip("'") # print(data_str) with open(r'D:\360MoveData\Users\ChunhuaGuo\Desktop\CM\kick\team\1681357\6\del-6.csv', 'a') as data: print(data_str, file=data) # return data_list get_csv_data(tt)
b707c3f7f4ebc050b4f9b97502c8505a35acb690
guohuahua2012/samples
/OOP/study_class.py
1,305
4.15625
4
#coding=utf-8 ''' author:chunhua ''' ''' 对象的绑定方法 在类中,没有被任何装饰器的方法就是绑定的到对象到的方法,这类方法专门为对象定制 ''' class People1: country = 'China' def __init__(self, name): self.name = name def eat(self): print("%s is eating--1" %self.name) people1 = People1('nick') print(people1.eat()) ''' 类的绑定方法 @classmothod修饰的方法是绑定到类的方法。这类方法专门为类定制。通过类名调用绑定到类的方法时, 会将类本身当做参数传递给类方法的第一参数 ''' class People2: country = 'China' def __init__(self, name): self.name = name # 绑定到类的方法 @classmethod def eat(cls): print("chunhua is eating--2") # 通过类名调用,绑定到类的方法eat() People2.eat() ''' 非绑定方法 在类内部使用@staticmethod 修饰的方法,即为非绑定方法。这类方法和普通定义的函数没有区别, 不与类或对象绑定,谁都可以调用,且没有自动传值的效果。 ''' class People3: country = 'China' def __init__(self, name): self.name = name @staticmethod def eat(): print('s% is eating--3') People3.eat() People3('nick').eat()
7211b7d8835f37b292b93756a2deb5f64ee62d4b
andrew-kulikov/crypto
/el_gamal/crypto.py
827
3.65625
4
import random def encrypt_bit(number, p, g, y): k = random.randint(2, p - 2) a = pow(g, k, p) b = number * pow(y, k, p) % p return a, b # crypto pair def decrypt_bit(crypto_pair, public_key, private_key): p, _, _ = public_key x = private_key a, b = crypto_pair decrypted = (b * a ** (p - 1 - x)) % p # wiki формула для практических вычислений return decrypted def encrypt(text, public_key): p, g, y = public_key encrypted = [] for char in text: encrypted.append(encrypt_bit(ord(char), p, g, y)) return encrypted def decrypt(crypto_pairs, public_key, private_key): decrypted = [] for crypto_pair in crypto_pairs: decrypted.append(chr(decrypt_bit(crypto_pair, public_key, private_key))) return decrypted
e1695f2e4c4e00256d83d9c35091a628f04060a1
antonpols/Algorithms-Coursera
/Exercise_1.py
4,057
4
4
import math import random def karatsuba_multiplication(int1, int2): """Karatsuba implementation of integer multiplication.""" if isinstance(int1, int): int1 = str(int1) if isinstance(int2, int): int2 = str(int2) n_int1 = len(int1) n_int2 = len(int2) highest_pow_2 = max(2**math.ceil(math.log(n_int1, 2)), 2**math.ceil(math.log(n_int2, 2))) if not highest_pow_2 == n_int1: int1 = (highest_pow_2 - n_int1) * '0' + int1 if not highest_pow_2 == n_int2: int2 = (highest_pow_2 - n_int2) * '0' + int2 n = len(int1) if n == 1: return int(int1) * int(int2) else: int1_left_half = int1[:n // 2] int1_right_half = int1[n // 2:] int2_left_half = int2[:n // 2] int2_right_half = int2[n // 2:] sum_int1_left_right = int(int1_left_half) + int(int1_right_half) sum_int2_left_right = int(int2_left_half) + int(int2_right_half) res_ac = karatsuba_multiplication( int1_left_half, int2_left_half) res_ab_cd = karatsuba_multiplication( sum_int1_left_right, sum_int2_left_right) res_bd = karatsuba_multiplication( int1_right_half, int2_right_half) return 10**n * res_ac + 10**(n // 2) * (res_ab_cd - res_ac - res_bd) \ + res_bd def recursive_integer_multiplication(int1, int2): """Recursive implementation of integer multiplication.""" if isinstance(int1, int): int1 = str(int1) if isinstance(int2, int): int2 = str(int2) n_int1 = len(int1) n_int2 = len(int2) highest_pow_2 = max(2**math.ceil(math.log(n_int1, 2)), 2**math.ceil(math.log(n_int2, 2))) if not highest_pow_2 == n_int1: int1 = (highest_pow_2 - n_int1) * '0' + int1 if not highest_pow_2 == n_int2: int2 = (highest_pow_2 - n_int2) * '0' + int2 n = len(int1) if n == 1: return int(int1) * int(int2) else: int1_left_half = int1[:n // 2] int1_right_half = int1[n // 2:] int2_left_half = int2[:n // 2] int2_right_half = int2[n // 2:] res_ac = recursive_integer_multiplication( int1_left_half, int2_left_half) res_ad = recursive_integer_multiplication( int1_left_half, int2_right_half) res_bc = recursive_integer_multiplication( int1_right_half, int2_left_half) res_bd = recursive_integer_multiplication( int1_right_half, int2_right_half) return int(10**n * res_ac + 10**(n // 2) * (res_ad + res_bc) + res_bd) def grade_school_algorithmn(int1, int2): """Implementation of the Grade-School Algorithm for multiplying two integers.""" int1_str = str(int1) int2_str = str(int2) res = 0 for digit_pos, digit_int2 in enumerate(int2_str[::-1]): res_temp = '' carry = 0 for digit_int1 in int1_str[::-1]: res_pair_mult = str(int(digit_int1) * int(digit_int2) + carry) if len(res_pair_mult) == 1: res_pair_mult = '0' + res_pair_mult res_temp = res_pair_mult[1] + res_temp carry = int(res_pair_mult[0]) res_temp = str(carry) + res_temp res = res + int(res_temp + digit_pos * '0') return res if __name__ == '__main__': for i in range(10**3): int1 = random.randint(0, 10**128) int2 = random.randint(0, 10**128) assert(int1 * int2 == grade_school_algorithmn(int1, int2) ), ("Grade-School Algorithm for multiplying two integers is not " "implemented correctly.") assert(int1 * int2 == recursive_integer_multiplication(int1, int2) ), ("Recursive Algorithm for multiplying two integers is not " "implemented correctly.") assert(int1 * int2 == karatsuba_multiplication(int1, int2) ), ("Karatsuba Algorithm for multiplying two integers is not " "implemented correctly.")
dfcfc4edb4647d193e708b7dbaf99e5c04e7ce86
lyh71709/AS_Area_Perimeter
/08_calc_history_v1.py
6,017
4.15625
4
# Component 8 - Making a calculation history and print it at the end of the program # Only put in triangles and rectangles import math # number checker function goes here # Checks that it is not 0 and is a number def number_checker(question, error, num_type): valid = False while not valid: try: response = num_type(input(question)) if response <= 0: print(error) else: return response except ValueError: print(error) # string_checker function goes here # Ensures that an input is within the possible results def string_checker(choice, options, error): for var_list in options: # Blank case if choice == "": is_valid = "no" break # if the shape is in one of the lists, return the full list elif choice in var_list: # Get full name of shape and put it in title case # so it looks nice when out putted chosen = var_list[0].title() is_valid = "yes" break # if the chosen shape is not valid else: is_valid = "no" # If shape is not OK - ask question again if is_valid == "yes": return chosen else: print(error) return "invalid choice" # get_shape function goes here # get the desired shape def get_shape(): # Possible Shapes valid_shapes = [["square", "squ", "s"], ["rectangle", "rec", "r"], ["triangle", "tri", "t"], ["circle", "cir", "c"], ["parallelogram", "par", "p"], ["trapezium", "tra", "t"]] valid = False while not valid: # Find the shape desired_shape = input("What shape do you want? ").lower() check_shape = string_checker(desired_shape, valid_shapes, "Please enter a real shape") # When invalid choice if check_shape == "invalid choice": continue # t can be either triangle or trapezium so ask to specify elif desired_shape == "t": print("Can you specify either triangle or trapezium\n") continue else: break return check_shape # rectangle function goes here # Find the base and height then calculate area and perimeter def rectangle(): valid = False while not valid: # Get base and height base = number_checker("What is the base? ", "Please enter a number above 0", float) height = number_checker("What is the height? ", "Please enter a number above 0", float) # ------------- Calculations ------------- area = base * height perimeter = (2 * base) + (2 * height) # Check if it is a square if base == height: squ_or_rec = "square" else: squ_or_rec = "rectangle" # Print with appropriate shape name print("The area of your {} is {:.2f}".format(squ_or_rec, area)) print("The perimeter of your {} is {:.2f}".format(squ_or_rec, perimeter)) print() # return this until I put in a list for history return ["Rectangle", base, height, area, perimeter] # triangle function goes here # Figures out what the question gives and calculates the area and perimeter def triangle(): valid = False while not valid: # Find what the user is given info = input("What do you know about the triangle [Base and height(bh)] or [the side lengths(abc)]? ").lower() info_check = string_checker(info, [["bh"], ["abc"]], "Please say either 'bh' for base and height or 'abc' for side lengths") if info_check == "invalid choice": continue # ------------- Calculations ------------- # If base and height is given if info_check == "Bh": # Find Base and height base = number_checker("What is the base? ", "Please enter a number bigger than 0", float) height = number_checker("What is the height? ", "Please enter a number bigger than 0", float) area = 0.5 * base * height perimeter = "couldn't find" print("The area of your triangle is {:.2f}".format(area)) print("I can't find the perimeter with only base and height") # If triangle side lengths are given else: # Find triangle side lengths a = number_checker("What is the length of a? ", "Please enter a number bigger than 0", float) b = number_checker("What is the length of b? ", "Please enter a number bigger than 0", float) c = number_checker("What is the length of c? ", "Please enter a number bigger than 0", float) # Do Heron's Law and the sum of all the side lengths for perimeter s = (a + b + c) / 2 perimeter = a + b + c area = math.sqrt(s * (s-a) * (s-b) * (s-c)) print("The area of your triangle is {:.2f}".format(area)) print("The perimeter of your triangle is {:.2f}".format(perimeter)) # return this until I put in a list for history return "" # Main Routine history = [] calc_num = 0 # Keep going loop keep_going = "" while keep_going == "": what_shape = get_shape() # Just do rectangle and triangle for testing purposes if what_shape == "Rectangle": result = rectangle() else: result = triangle() # Append results to a history list for later printing history.append(result) keep_going = input("\nIf you want to continue press enter or any other key to quit: ") # Printing Area print("==================== History ====================\n") # History method is to just loop a print statement until it prints the whole history for item in history: calc_num += 1 print("{}| Shape: {} | Area: {} | Perimeter: {}".format(calc_num, item[0], item[3], item[4])) print()
0e4a586b1bfb3a97d3311b61d8653e0041c42eb0
sinceresiva/DSBC-Python4and5
/areaOfCone.py
499
4.3125
4
''' Write a python program which creates a class named Cone and write a function calculate_area which calculates the area of the Cone. ''' import math class ConeArea: def __init__(self): pass def getArea(self, r, h): #SA=πr(r+sqrt(h**2+r**2)) return math.pi*r*(r+math.sqrt(h**2+r**2)) coneArea=ConeArea() radius=input("Input the radius (numeric):") height=input("Input the height (numeric):") print("Area is {}".format(coneArea.getArea(float(radius),float(height))))
e484ba88e6d1587778d87a9831e30652ba9210ba
sinceresiva/DSBC-Python4and5
/replaceWordsWithLength.py
340
3.671875
4
class ReplaceWordsWithLength: def __init__(self): pass def getNewList(self, words): newList=[str(len(w)) for w in words] return newList replacer=ReplaceWordsWithLength() newList=replacer.getNewList(['A','Dark','Horse','Rode','Through','The','Mountain']) print("The new list is given below:") print(newList)
bf5b6d876ce86fa04d0c53ed77a221c087d63741
Introduction-to-Programming-OSOWSKI/1-2-wordsmash-Kaleb-Aguirre03
/main.py
329
3.828125
4
#Define Function wordSmash def wordSmash (a, b): #return two variables as one combined return a + b #print the function to create CatDog print (wordSmash ("Cat", "Dog")) #print the function to create Redblue print (wordSmash ("Red", "blue")) #print the function to create qqqqqwwwww print (wordSmash ("qqqqq", "wwwww"))
d1d9571a3ef48f6e25a8894baa0d5f4ad233a587
amir734jj/algorithm-practice
/regex/valid_number.py
534
3.703125
4
# https://leetcode.com/problems/valid-number/ import re def is_valid_number(token): return bool(re.fullmatch(r"\s*([+-]?((\d*\.)?\d+))(e[+-]?\d+)?\s*", token)) table = { "0": True, " 0.1 ": True, "abc": False, "1 a": False, "2e10": True, " -90e3 ": True, " 1e": False, "e3": False, " 6e-1": True, " 99e2.5 ": False, "53.5e93": True, " --6 ": False, "-+3": False, "95a54e53": False } print(list(filter(bool, [s for s, r in table.items() if is_valid_number(s) != r])))
b9d7374e9022ed8a3c3c5ceeef7999c88bb20596
tonytamsf/python-learning
/names.py
342
3.703125
4
def count_arara(n): names = ['anane', 'adak'] name = '' if n == 1: return names[0] if n == 2: return names[1] if n % 2 == 0: for i in range(1,n,2): name = name + ' ' + names[1] else: name = count_arara(n - 1) + ' ' + names[0] return name.lstrip() print count_arara(9)
a3367d1f2af874ec507fa053fc19cd65f0699522
tonytamsf/python-learning
/cracking-coding-interview/linklistnode.py
965
3.875
4
#!/usr/bin/env python from testy import test class linklistnode: def __init__(self, d): self.data = d self.next = None def insert(self, d): n = linklistnode(self.data) self.data = d n.next = self.next self.next = n def append(self, d): n = self new_node = linklistnode(d) while n: if not n.next: n.next = new_node break else: pass n = n.next def print_list(self): n = self; while n: print(n.data) n = n.next if __name__ == "__main__": l = linklistnode(154) test(l.data, 154) l.append(3) test(l.data, 154) test(l.next.data, 3) l.insert(7) print (l.data) test(l.data, 7) test(l.next.data, 154) test(l.next.next.data, 3) test(l.next.next.next, None) l.append(300) l.print_list()
8f6776c26746a6f291ba188d0402280ebd702cb0
beetee17/week_4_suffix_array
/kmp/kmp.py
1,216
3.96875
4
# python3 import sys def find_pattern_fast(pattern, text): """ Find all the occurrences of the pattern in the text and return a list of all positions in the text where the pattern starts in the text. """ s = pattern + '$' + text borders = prefix_function(s) matches = [] for i in range(len(pattern) + 1, len(s)): if borders[i] == len(pattern): matches.append(i - 2*len(pattern)) return matches def prefix_function(text): # see https://www.youtube.com/watch?v=GTJr8OvyEVQ for reference arr = [0] j = 0 i = 1 while i < len(text): if text[i] == text[j]: arr.append(j+1) i += 1 j += 1 elif j == 0: arr.append(0) i += 1 else: j = arr[i-1] while text[i] != text[j]: j = arr[j-1] flag = False if j == 0 and text[i] != text[j]: arr.append(0) i += 1 flag = True break if not flag: arr.append(j+1) i += 1 j += 1 return arr if __name__ == '__main__': pattern = sys.stdin.readline().strip() text = sys.stdin.readline().strip() result = find_pattern_fast(pattern, text) print(" ".join(map(str, result)))
41f15ccbd2a2d053731579db1caa8c2796d5e64f
mrvecka/Python-Projects
/ML tests/House_price_prediction.py
4,047
4
4
# # house price prediction.py # # this is very simple prediction of house prices based on house size, implemented in tensorflow. This code is part of Pluralsight's coourse # # import tensorflow as tf import numpy as np import math import matplotlib.pyplot as plt import matplotlib.animation as animation # generate house sizes between 1000 and 3500 square meters num_house = 160 np.random.seed(42) house_size = np.random.randint(low=1000, high = 3500, size= num_house) # generate house prices from house size with a random nooise added np.random.seed(42) house_price = house_size * 100.0 + np.random.randint(low = 20000,high = 70000,size = num_house) #plt.plot(house_size,house_price,"bx") # bx = blue x #plt.ylabel("Price") #plt.xlabel("Size") #plt.show() #you need to normalize values to prevent under/overflow def normalize(array): return (array - array.mean()) / array.std() # define number of training samles 0,7 = 70%. we can take first since the valueas are randomized num_train_samples = math.floor(num_house * 0.7) # define training data train_house_size = np.asarray(house_size[:num_train_samples]) train_price = np.asanyarray(house_price[:num_train_samples:]) train_house_size_norm = normalize(train_house_size) train_price_norm = normalize(train_price) # define test data test_house_size = np.array(house_size[num_train_samples:]) test_house_price = np.array(house_price[num_train_samples:]) test_house_size_norm = normalize(test_house_size) test_house_price_norm = normalize(test_house_price) # Set up Tensprflow placeholders that get updated as we descend down the gradient tf_house_size = tf.placeholder("float", name="house_size") tf_price = tf.placeholder("float",name="price") # Define the variables holding the size_factor and price_offset we set during training # We initialize them to some random values based on the normal distribution tf_size_factor = tf.Variable(np.random.randn(), name="size_factor") tf_price_offset = tf.Variable(np.random.randn(),name="price_offset") # Define the operation for the prediction values - predicted price = (size_factor * house_size) + price_offset # Notice the use of the tensorflow add and multiply function. These add the operations to the computation graph # AND the tensorflow methods understand how to deal with Tensors. Therefore do not try to use numpy or other library # methodes tf_price_pred = tf.add(tf.multiply(tf_size_factor,tf_house_size),tf_price_offset) # Define the loss Function (how much error) - mean square error tf_cost = tf.reduce_sum(tf.pow(tf_price_pred - tf_price,2)) / (2* num_train_samples) # optimizer learning rate. The size of the steps down the gradient learning_rate = 0.1 # Define a gradient descent optimizer that will minimize the loss defined in the opration optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(tf_cost) # At this point the tensorflow variables are uninitialized # Initializing the variables init = tf.global_variables_initializer() # Launch the graph in the session with tf.Session() as sess: sess.run(init) display_every = 2 num_training_iter = 50 #keep iterating the training data for iteration in range(num_training_iter): #fit all training data for(x,y) in zip(train_house_size_norm, train_price_norm): sess.run(optimizer, feed_dict={tf_house_size:x,tf_price: y}) # display current status if (iteration +1) % display_every == 0: c= sess.run(tf_cost, feed_dict={tf_house_size:train_house_size_norm,tf_price:train_price_norm}) print("iteration #:", '%04d' % (iteration +1), "cost=","{:.9f}".format(c),\ "size_factor=",sess.run(tf_size_factor), "price_offset=", sess.run(tf_price_offset)) print("Optimalization finished") training_cost = sess.run(tf_cost, feed_dict={tf_house_size:train_house_size_norm, tf_price:train_price_norm}) print("Trained cost=", training_cost, "size_factor=",sess.run(tf_size_factor),"price_offset=",sess.run(tf_price_offset),'\n')
432cace0d237b5a415897de321f3ef36d29c16d4
trevorgokey/drug-computing
/uci-pharmsci/assignments/solubility/tools.py
1,386
3.65625
4
from numpy import * def rmserr( set1, set2 ): """Compute and return RMS error for two sets of equal length involving the same set of samples.""" tot = 0. for i in range(len(set1)): tot+= (set1[i] - set2[i])**2 return sqrt(tot/float(len(set1))) def correl(x,y ): """For two data sets x and y of equal length, calculate and return r, the product moment correlation. """ if len(x)!=len(y): print("ERROR: Data sets have unequal length.\n") raise LengthError #Compute averages (try not to require numerical library) avgx=sum(x)/float(len(x)) avgy=sum(y)/float(len(y)) #Compute standard deviations sigmax_sq=0 for elem in x: sigmax_sq+=(elem-avgx)**2 sigmax_sq=sigmax_sq/float(len(x)) sigmay_sq=0 for elem in y: sigmay_sq+=(elem-avgy)**2 sigmay_sq=sigmay_sq/float(len(y)) sigmax=sqrt(sigmax_sq) sigmay=sqrt(sigmay_sq) #Compute numerator of r num=0 for i in range(len(x)): num+=(x[i]-avgx)*(y[i]-avgy) #Compute denominator of r denom=len(x)*sigmax*sigmay corr = num/denom return corr def percent_within_half( x, y): """Takes two sets, x and y, of equal length, and returns the percentage of values within 0.5 units.""" diff = x - y indices = where( abs(diff) < 0.5 ) return 100.*float(len(indices[0]) )/float(len(x))
405c0566fcd647b110e84736b9728303519cfd45
raymag/binary-search-tree-sketches
/py/node.py
1,894
3.9375
4
class Node(): def __init__(self, value): self.value = value self.left = None self.right = None def addNode(self, node): if node.value < self.value: if self.left == None: self.left = node else: self.left.addNode(node) elif node.value > self.value: if self.right == None: self.right = node else: self.right.addNode(node) def search(self, value): if self.value > value: if self.left != None: self.left.search(value) else: print(value, " não encontrado!") elif self.value < value: if self.right != None: self.right.search(value) else: print(value, " não encontrado!") else: print(value, "encontrado!") # def listify(self, nodes): # if self.left != None: # self.left.listify(nodes) # nodes.append(self.value) # if self.right != None: # self.right.listify(nodes) # return nodes def visit(self): if self.left != None: self.left.visit() print(self.value) if self.right != None: self.right.visit()
64f53a10971a8d012868cee0abbf380ff58dda59
palhiman/Lab-Practices
/python3/algorithms/sorting.py
542
3.59375
4
from random import randint from timeit import repeat def run_sorting_algorithm(algorithm, array): setup_code = f"from __main__ import {algorithm}" \ if algorithm != "sorted" else "" stmt = f"{algorithm}({array})" times = repeat(setup_code, stmt=stmt, repeat=3, number=10) print(f"Algorithm:{algorithm}. Minimum execution time :{min(times)}) ARRAY_LENGTH = 10000 if __name__ == "__main__": array = [randint(0, 1000) for i in range(ARRAY_LENGTH)] run_sorting_algorithm(algorithm="sorted", array=array)
45ffab46f36cc0fe42fd1d36eb72f2a94fb6730e
rbastardo13/ie_mbdbl2018_rbastardo_2
/__init__.py
1,168
3.890625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 30 09:45:16 2018 @author: Rafael Bastardo """ def linear_congruences_random_generator(X0=3,a=22695477,b=1,m=2**32,throws=1): """Function generates a list of random numbers using linear congruences equation X1=(a*X0+b) mod(m) Default values: a=22695477,b=1,m=2**32 and X0=3, throws=1""" if is_int(X0) == True and is_int(a) == True and is_int(b) == True and is_int(m) == True and is_int(m) == True and m>1: random=list() for i in range(1,throws+1): x=(a*X0+b)%m random.insert(i,x) X0=x return(random) else: print("All arguments must be positive integers and m greater than 1") return # function that verifies the input is an integer needed to run linear_congruences_random_generator() function def is_int(value): """Function to verify the input is an integer""" try: value = int(value) if value<0: print("Please enter a positive integer greater than 0") return (False) return (True) except ValueError: print("The input is not an integer!!!") return (False)
a6655d68d7d4d84709cea71f8e99229b86f05c0e
kostyafarber/info1110-scripts
/scripts/hailstones.py
343
3.90625
4
n = int(input("Starting Number: ")) num_list = [n] for i in num_list: if 1 in num_list: print("".join(str(num_list).strip("[]"))) elif i % 2 == 0: num_list.append(int(i / 2)) else: num_list.append(int(i * 3 + 1)) # Very useful function .strip to take the brackets out of a list if you want for printing.
009a177a0aea16ed8c9df0fa980e75d7412de480
kostyafarber/info1110-scripts
/scripts/integer.py
262
4.03125
4
while True: num = int(input("Integer: ")) if num == 0: print("Bye") break if num % 2 == 0 and num in range(20,201) or num % 2 != 0 and num < 0: print(num, "passes the test!") else: print(num, "fails the test :(")
928d5d403a69cd99e6c9ae579a6fc34b87965c1c
kostyafarber/info1110-scripts
/scripts/rain.py
468
4.125
4
rain = input("Is it currently raining? ") if rain == "Yes": print("You should take the bus.") elif rain == "No": travel = int(input("How far in km do you need to travel? ")) if travel > 10: print("You should take the bus.") elif travel in range(2, 11): print("You should ride your bike.") elif travel < 2: print("You should walk.") # if you use the range function with a if statement you use in not the equality operator
cfc8958512e750232c5441f55d7df0e79893053d
tschutter/skilz
/2010-12-06/compound_a.py
1,627
4.03125
4
#!/usr/bin/python # # Find all the two-word compound words in a dictionary. A two-word # compound word is a word in the dictionary that is the concatenation # of exactly two other words in the dictionary. Assume input will be a # number of lowercase words, one per line, in alphabetical order, # numbering around, say, 100K. Generate output consisting of all the # compound words, one per line, in alphabetical order. # import sys def main(): # Read the words into a list and sort the list. wordlist = [word.strip() for word in open(sys.argv[1]) if word != "\n"] nwords = len(wordlist) wordlist.sort() # Add the words to a dictionary. worddict = dict.fromkeys(wordlist) # Debug. maxscan = -1 ncompound = 0 # Loop through the words. for i, word in enumerate(wordlist): wordlen = len(word) # Find the following adjacent words that start with the same word. for j in xrange(i + 1, nwords): testword = wordlist[j] if not testword.startswith(word): if __debug__ and maxscan < j - i: maxscan = j - i break # See if the remaining part of the word is in the dictionary. suffix = testword[wordlen:] if suffix in worddict: print "%s + %s = %s" % (word, suffix, testword) if __debug__: ncompound += 1 if __debug__: print "DEBUG: nwords = %s" % nwords print "DEBUG: ncompound = %s" % ncompound print "DEBUG: maxscan = %s" % maxscan if __name__ == '__main__': main()
a2d0a7288f4fc9ce22f9f1447e1e70046b80b30b
tschutter/skilz
/2011-01-14/count_bits_a.py
733
4.125
4
#!/usr/bin/python # # Given an integer number (say, a 32 bit integer number), write code # to count the number of bits set (1s) that comprise the number. For # instance: 87338 (decimal) = 10101010100101010 (binary) in which # there are 8 bits set. No twists this time and as before, there is # no language restriction. # import sys def main(): number = int(sys.argv[1]) if number < 0: number = -number #import gmpy #print gmpy.digits(number, 2) nsetbits = 0 while number != 0: if number % 2 == 1: nsetbits += 1 number = number // 2 # // is integer division print "Number of bits set = %i" % nsetbits return 0 if __name__ == '__main__': sys.exit(main())
31d75fd3b23a68c0573b13b60ea7033b815e9661
tschutter/skilz
/2014-04-14/base_convert_b.py
3,101
4.09375
4
#!/usr/bin/env python3 """ Convert values from one base to another. Changed from original spec to specify output base in the input stream rather than the command line. This makes demonstration easier. """ import decimal import re import string import sys DEBUG = True def baseString(base): """Return a Unicode printable version of a base.""" (dig0, dig1) = divmod(base, 10) if dig0 == 0: printable = chr(0x2080 + base) else: printable = chr(0x2080 + dig0) + chr(0x2080 + dig1) return printable DIGITS = string.digits + string.ascii_uppercase def intBaseNToBase10(inputValue, inputBase): """ Given an input integer string and an input base, return a base10 integer. """ inputValue = inputValue.upper() sign = 1 result = 0 for digit in inputValue: if digit == "-": sign = -1 elif digit == "+": sign = 1 else: result = result * inputBase + DIGITS.index(digit) return sign * result # (?![-+]) allows E only if it is not followed by - or + RE_FLOAT = re.compile( "^([-+]?[0-9A-Z]+)(?:\.([0-9A-Z](?![-+]))+)?(?:[eE]([-+][0-9A-Z]+))?$" ) def floatBaseNToBase10(inputValue, inputBase): """Calculate a base10 decimal from an input value and an input base.""" match = RE_FLOAT.match(inputValue.upper()) whole = match.group(1) fraction = match.group(2) exponent = match.group(3) if exponent: exponent = intBaseNToBase10(exponent, inputBase) else: exponent = 0 if fraction: if DEBUG and False: print("\nexponent = {}, fraction = {}".format(exponent, fraction)) exponent -= len(fraction) value = whole + fraction if DEBUG and False: print("exponent = {}, value = {}".format(exponent, value)) else: value = whole value = decimal.Decimal(intBaseNToBase10(value, inputBase)) multiplier = decimal.Decimal(inputBase) ** decimal.Decimal(exponent) value = value * multiplier return value def base10ToOutput(value, outputBase): print(value, outputBase) """Given a base10 integer and an output base, return an output string.""" if value < 0: return "-" + base10ToOutput(-value, outputBase) result = "" while value != 0: value, remainder = divmod(value, outputBase) result = DIGITS[int(remainder)] + result return result def main(): """main""" for line in sys.stdin: if line.startswith("#"): continue (inputBase, inputValue, outputBase) = line.split() inputBase = int(inputBase) outputBase = int(outputBase) print("{}{}".format(inputValue, baseString(inputBase)), end=" = ") base10Value = floatBaseNToBase10(inputValue, inputBase) if DEBUG: print("{}{}".format(base10Value, baseString(10)), end=" = ") outputValue = base10ToOutput(base10Value, outputBase) print("{}{}".format(outputValue, baseString(outputBase))) return 0 if __name__ == "__main__": ret = main() sys.exit(ret)
31313ead59605c9aa557b4387d1a88284f22ce8e
taylorfio/pygames
/pizza hunt.py
17,857
3.734375
4
""" backstory: In this game you are papa john, the previous king of the major pizza corporation and have recently been dethroned by your own disciples to be replaced by shaquille o'neal. You need to fight your way through the hoards of pizza minions sent by shaq himself to confront him in a final battle to reclaim your honor and take back the throne. """ import pygame import random from os import path restart = True while restart: # loop for game img_dir = path.join(path.dirname(__file__), 'img') # path for images snd_dir = path.join(path.dirname(__file__), 'snd') # path for sounds WIDTH = 480 # sets size HEIGHT = 600 FPS = 60 # sets the frames per second POWERUP_TIME = 2000 # milliseconds, time for powerup # colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create window pygame.init() # loads pygame pygame.mixer.init() # loads the sounds screen = pygame.display.set_mode((WIDTH, HEIGHT)) # sets the screen dimensions pygame.display.set_caption("PAPA'S PIZZA HUNT") # window name clock = pygame.time.Clock() # sets game clock font_name = pygame.font.match_font('arial') # sets font """ this function makes it easy to display text by allowing you to call it and just set the parameter as what you want instead of doing something complicated every time """ def draw_text(surface, text, size, x, y): # function for drawing text on the screen font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) # True means that the text will be anti-aliased text_rect = text_surface.get_rect() text_rect.midtop = (x, y) # sets the texts position surface.blit(text_surface, text_rect) """this function displays the start screen and waits for the user input to go away""" def start_screen(): draw_text(screen, "PAPA'S PIZZA HUNT", 64, WIDTH / 2, HEIGHT / 4) # draws text draw_text(screen, "left and right arrow keys to move, up arrow key to fire", 22, WIDTH / 2, HEIGHT / 2) draw_text(screen, "Press a key to begin", 30, WIDTH / 2, HEIGHT * 3 / 4) draw_text(screen, "Press exit to quit", 18, WIDTH / 2, HEIGHT * 3 / 4 + 30) pygame.display.flip() waiting = True while waiting: # waits for input clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: # if exit is pressed it quits pygame.quit() elif event.type == pygame.KEYUP: # if any other key is pressed game starts waiting = False """this function displays the end screen with the score and high score and waits for the user input to go away""" def end_screen(score): draw_text(screen, "YOU LOST", 64, WIDTH / 2, HEIGHT / 4) # draws text end_text = "SCORE: " + str(score) # shows game score draw_text(screen, end_text, 35, WIDTH / 2, HEIGHT / 2 - 100) draw_text(screen, "HIGH SCORE", 35, WIDTH / 2, HEIGHT / 2 - 30) try: # trys to open the file that saves the high score file1 = open("save.txt", "r") # opens file to read line1 = file1.read() line1 = int(line1) # saves the number as a variable file1.close() # closes file file2 = open("save.txt", "w") # opens file to write if int(score) > int(line1): # if you get a better score file2.write(str(score)) # writes new score number = score # variable for printed score else: file2.write(str(line1)) # writes the old high score number = line1 # variable for printed score file2.close() # closes file except IOError: # error for file not found number = "ERROR SCORE NOT FOUND" draw_text(screen, str(number), 35, WIDTH / 2, HEIGHT / 2) # prints the high score number draw_text(screen, "Press a key to restart", 30, WIDTH / 2, HEIGHT * 3 / 4) draw_text(screen, "Press exit to quit", 18, WIDTH / 2, HEIGHT * 3 / 4 + 30) pygame.display.flip() waiting = True while waiting: # waits for input clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: # if exit is pressed it quits pygame.quit() elif event.type == pygame.KEYUP: # if any other key is pressed game starts waiting = False """ This class contains everything that is related to the player sprite. The update method shows the user movements on the screen and checks to see what power mode it is in. The shoot method tells the bullet when and where to spawn in which power mode. THe powe rup method tells the sprite when to change power modes. """ class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (90, 104)) # sets the sprite image and scales it down self.image.set_colorkey(BLACK) # eliminates the black filler colour from the png self.rect = self.image.get_rect() # sets the hit box for sprite self.rect.centerx = WIDTH / 2 # when the game starts and this function is called the position is set to the middle self.rect.bottom = HEIGHT - 10 # when the game starts and this function is called the position is set to just above the bottom # powerup self.power = 1 # sets base power level self.power_time = pygame.time.get_ticks() # timer to know when to go back to normal def update(self): # timeout for powerups # if howerver long its been since the getting the power up is greater then the amount of time if self.power >= 2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME: self.power -= 1 # brings you back to normal power self.power_time = pygame.time.get_ticks() # resets the timer self.speedx = 0 # sets the speed to nothing if nothing is being pressed keystate = pygame.key.get_pressed() # variable for what key is being pressed if keystate[pygame.K_LEFT]: # if left key pressed down self.speedx = -15 # moves left if keystate[pygame.K_RIGHT]: # if right key pressed down self.speedx = 15 # moves right self.rect.x += self.speedx # sets the sprite to move in what direction is pressed if self.rect.right > WIDTH: self.rect.right = WIDTH # stops it from moving of the screen right if self.rect.left < 0: self.rect.left = 0 # stops it from moving of the screen left def shoot(self): if self.power == 1: # normal state for shooting bullet = Bullet(self.rect.centerx, self.rect.top) # sets the bullet to the center of the sprite all_sprites.add(bullet) # whenever the bullet spawns it is added to the list so multiple can be on the screen bullets.add(bullet) shoot_sound.play() # plays the shooting sound if self.power == 2: # powered state for shooting bullet1 = Bullet(self.rect.left, self.rect.centery) # spawns three bullets in right, left and canter bullet2 = Bullet(self.rect.right, self.rect.centery) bullet3 = Bullet(self.rect.centerx, self.rect.centery) all_sprites.add(bullet1) all_sprites.add(bullet2) # adds three bullets to right, left and canter all_sprites.add(bullet3) bullets.add(bullet1) bullets.add(bullet2) bullets.add(bullet3) shoot_sound.play() # plays shooting sound def powerup(self): if self.power < 2: # stops the powers variable from getting more then 2 self.power += 1 # changes the power variable self.power_time = pygame.time.get_ticks() # sets timer """ This class contains everything for the enemy sprite and its stats are randomized. The update method shows the movements of the sprite and removes it if it goes off the bottom of the screen or bounces if it touches the side. """ class Enemy(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(enemy_img, (60, 69)) # sets the sprite image and scales it down self.image.set_colorkey(BLACK) # eliminates the black filler colour from the png self.rect = self.image.get_rect() # sets the hit box for sprite self.rect.x = random.randrange(0, WIDTH - self.rect.width) # spawns the sprite in a random spot on the top of the screen self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(5, 15) # random speed downwards self.speedx = random.randrange(-3, 3) # random speed sideways def update(self): self.rect.x += self.speedx # updates the position of the sprite by what it is moving by self.rect.y += self.speedy if self.rect.top > HEIGHT + 10: # if the top of the sprite is below the bottom it respawns at the top self.rect.x = random.randrange(0, WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) # respawns it self.speedy = random.randrange(4, 8) if self.rect.left < -25 or self.rect.right > WIDTH + 20: self.speedx = -self.speedx # bounces of the side """ This class contains everything for the bullet sprite like the image, size and speed. The update method shows the movement and removes it if it goes of the top of the screen. """ class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(bullet_img, (20, 35)) # sets the sprite image and scales it down self.image.set_colorkey(BLACK) # eliminates the black filler colour from the png self.rect = self.image.get_rect() # sets the hit box for sprite self.rect.bottom = y # sets y coordinates self.rect.centerx = x # sets x coordinates self.speedy = -30 # sets the rate at which it moves up def update(self): self.rect.y += self.speedy if self.rect.bottom < 0: # kills if it moves off the top of the screen self.kill() """ This class contains everything for the power up sprite like the image, size and speed. The update method shows the movement and removes it if it goes of the top of the screen. """ class Powerup(pygame.sprite.Sprite): def __init__(self, center): pygame.sprite.Sprite.__init__(self) self.image = powerup_img # sets the sprite image and scales it down self.image.set_colorkey(BLACK) # eliminates the black filler colour from the png self.rect = self.image.get_rect() # sets the hit box for sprite self.rect.center = center self.speedy = 20 def update(self): self.rect.y += self.speedy if self.rect.top > HEIGHT: # kill if it moves off the bottom of the screen self.kill() """ This class contains everything for the boss sprite like the image, size and speed. The update method shows the movements of the sprite and removes it if it goes off the bottom of the screen or bounces if it touches the side. """ class Boss(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(calzone_img, (200, 100)) # sets the sprite image and scales it down self.image.set_colorkey(BLACK) # eliminates the black filler colour from the png self.rect = self.image.get_rect() # sets the hit box for sprite self.rect.x = random.randrange(0, WIDTH - self.rect.width) # spawns the sprite in a random spot on the top of the screen self.rect.y = random.randrange(-100, -40) self.speedy = 20 # rate the sprite moves down def update(self): self.rect.y += self.speedy # moves the sprite at the given rate if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: # if the top of the sprite is below the bottom it respawns at the top self.rect.x = random.randrange(0, WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) # respawns it self.speedy = random.randrange(1, 8) # loads all the game graphics # .convert() converts the image to the same pixel format as the display background = pygame.image.load(path.join(img_dir, "dark restaurant.jpg")).convert() player_img = pygame.image.load(path.join(img_dir, 'pappa.png')).convert() enemy_img = pygame.image.load(path.join(img_dir, 'PizzaSlice.png')).convert() bullet_img = pygame.image.load(path.join(img_dir, 'lightninbolt.png')).convert() powerup_img = pygame.image.load(path.join(img_dir, 'bolt.png')).convert() calzone_img = pygame.image.load(path.join(img_dir, 'calzone.png')).convert() # loads all the game sounds pygame.mixer.music.set_volume(0.4) pygame.mixer.music.load(path.join(snd_dir, 'melody.mp3')) shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'pew.wav')) explosion_sounds = [] for sound in ['expl3.wav', 'expl6.wav']: # adds to sounds to list to randomly be selected explosion_sounds.append(pygame.mixer.Sound(path.join(snd_dir, sound))) # puts the sprites in groups to easily call them all_sprites = pygame.sprite.Group() player = Player() all_sprites.add(player) enemy = pygame.sprite.Group() bullets = pygame.sprite.Group() powerups = pygame.sprite.Group() boss = pygame.sprite.Group() for amount in range(8): # creates 10 sprites m = Enemy() all_sprites.add(m) enemy.add(m) score = 0 # sets score pygame.mixer.music.play(loops=-1) # tells pygame to loop music when it reaches the end start_screen() # runs the screen for when you begin the game # game loop running = True while running: clock.tick(FPS) # keeps loop running at the right frame rate # process the input (events) for event in pygame.event.get(): # checks for closing exit input if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: # filter for any keyboard input if event.key == pygame. K_UP: # if up key down player.shoot() # shoots bullet all_sprites.update() # updates the sprites # checks to see if a bullet hits a enemy hits = pygame.sprite.groupcollide(enemy, bullets, True, True) for hit in hits: # every time a bullet hits an enemy random.choice(explosion_sounds).play() # plays explosion sound score += 1 # increases score m = Enemy() all_sprites.add(m) # respawns the sprite enemy.add(m) # every time you hit an enemy there is a chance to spawn the boss boss_spawn = random.randint(1, 20) if boss_spawn == 1: # picks a random between 1 and 20 creating a 5% chance b = Boss() all_sprites.add(boss) # spawns sprite boss.add(b) # every time you hit an enemy there is a chance to spawn a power up if random.random() > 0.9: # picks a random decimal number between 0 and 1 creating a 10% chance powerup = Powerup(hit.rect.center) # spawns the sprite where the enemy was killed all_sprites.add(powerup) # spawns sprite powerups.add(powerup) # checks to see if a bullet hits the boss boss_hits = pygame.sprite.groupcollide(boss, bullets, True, True) for hit in boss_hits: # if boss is hit random.choice(explosion_sounds).play() # plays explosion sound score += 50 # increases score b = Boss() all_sprites.remove(boss) # removes the boss boss.remove(b) # checks to see if player hits a powerup hits = pygame.sprite.spritecollide(player, powerups, True) for hit in hits: # if powerup hits player player.powerup() # runs the powerup # checks to see if enemy hits player collision = pygame.sprite.spritecollide(player, enemy, False) if collision: # if enemy hits player running = False # ends game # checks to see if boss hits player collision = pygame.sprite.spritecollide(player, boss, False) if collision: # if boss hits player running = False # ends game # Draw / render screen.fill(BLACK) # fills the screen with black behind the image screen.blit(background, (0, 0)) # sets the background image to center all_sprites.draw(screen) # shows the sprites draw_text(screen, str(score), 50, WIDTH / 2, 10) # shows the current score pygame.display.flip() # after it draws everything flip the display end_screen(score) # plays the end screen pygame.quit()
1e00f9bada478a3c0643d3eb3ff11e3c6aa2ec38
tkmckenzie/pan
/PE/33.py
2,379
3.671875
4
import fractions def without(iterable, remove_indices): """ Returns an iterable for a collection or iterable, which returns all items except the specified indices. """ if not hasattr(remove_indices, '__iter__'): remove_indices = {remove_indices} else: remove_indices = set(remove_indices) for k, item in enumerate(iterable): if k in remove_indices: continue yield item class Fraction: def __init__(self, n, d): self.n = n self.d = d self.float = n / d def cancel_num(self): n_digits = [int(c) for c in list(str(self.n))] d_digits = [int(c) for c in list(str(self.d))] results = [] for n_i in range(len(n_digits)): n_digit = n_digits[n_i] for d_i in range(len(d_digits)): d_digit = d_digits[d_i] if n_digit == d_digit: n_omit = list(without(n_digits, n_i)) d_omit = list(without(d_digits, d_i)) results.append((int(''.join([str(e) for e in n_omit])), int(''.join([str(e) for e in d_omit])))) return list(set(results)) def cancel_equiv(self): cancellations = self.cancel_num() correct_cancellations = list(filter(lambda a: a[0] / a[1] == self.float, cancellations)) return(correct_cancellations) results = [] for n_1 in range(1, 10): for n_2 in range(1, 10): n = int(str(n_1) + str(n_2)) #First make first digit in denominator common for d_1 in list(set([n_1, n_2])): for d_2 in range(1, 10): d = int(str(d_1) + str(d_2)) f = Fraction(n, d) if len(f.cancel_equiv()) > 0: results.append((n, d)) #Now make second digit in denominator common for d_2 in list(set([n_1, n_2])): for d_1 in range(1, 10): d = int(str(d_1) + str(d_2)) f = Fraction(n, d) if len(f.cancel_equiv()) > 0: results.append((n, d)) results = list(filter(lambda a: a[0] / a[1] < 1, results)) print(sorted(set(results))) f_list = [fractions.Fraction(a[0], a[1]) for a in results] f_prod = f_list[0] for f in f_list[1:]: f_prod *= f print(f_prod)
fc3b101a2259c5fec7fde2b27a942244aaaa68dc
kimaya2/RSA
/RSA.py
1,037
3.8125
4
''' Created on Feb 24, 2020 @author: ccoew ''' p = input("Enter value of p:") q =input("Enter value of q:") mes = input("Enter message:") def computeGCD(x, y): while(y): x, y = y, x % y return x def findn(x,y): return x*y def findEulerQuotient(x,y): return (x-1)*(y-1) def finde(euler): for i in range(2,euler): if computeGCD(euler,i) == 1: return i def findd(euler,e): for i in range(1,euler): if (i*e)%(euler)==1: return i def encrypt(message,e,n): return((message**e)%n) def decrypt(message,d,n): return ((message**d)%n) n = findn(p, q) euler = findEulerQuotient(p, q) e =finde(euler) d = findd(euler, e) print "private key:",(e,n) print "private key:",(d,n) cipher = encrypt(mes, e, n) print "Encrypted Text:",cipher normal = decrypt(cipher, d, n) print "Decrypted Text:",normal ''' Enter value of p:11 Enter value of q:3 Enter message:7 private key: (3, 33) private key: (7, 33) Encrypted Text: 13 Decrypted Text: 7 '''
20d8e34261de4ea02a84699336eb618a3441c96d
WenHui-Zhou/weekly-code-STCA
/top100_frequency/top100/19.py
1,352
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode dummy = ListNode(-1) dummy.next = head last = dummy fast = dummy for i in range(n+1): fast = fast.next while fast != None: last = last.next fast = fast.next last.next = last.next.next return dummy.next if head == None: return None dummy = ListNode(-1) dummy.next = head first = dummy second =dummy for _ in range(n+1): first = first.next while first!=None: first = first.next second = second.next second.next = second.next.next return dummy.next""" if head == None: return head dummy = ListNode(-1) dummy.next = head first = dummy for i in range(n+1): first = first.next second = dummy while first: first = first.next second = second.next second.next = second.next.next return dummy.next
e691de9fd1594e0e684da46b8055f525d99a4a2c
WenHui-Zhou/weekly-code-STCA
/top100_frequency/thrid/98.py
1,214
3.8125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool if root == None: return True def dfs(root,low=-sys.maxsize,high=sys.maxsize): if root == None: return True val = root.val if not(low < val < high): return False if not dfs(root.left,low,val): return False if not dfs(root.right,val,high): return False return True return dfs(root) """ if root == None: return True def dfs(root,low=-sys.maxsize,high=sys.maxsize): if root == None: return True val = root.val if not low < val < high: return False if not dfs(root.left,low,val): return False if not dfs(root.right,val,high): return False return True return dfs(root)
2d0fe3fc1b1b688cc166b7674df3fac6cf9dd495
WenHui-Zhou/weekly-code-STCA
/week10-11/493.py
1,348
3.5625
4
class Solution(object): def reversePairs(self, nums): """ :type nums: List[int] :rtype: int """ def merge(nums,left,mid,right): res = [] start = left end = mid + 1 while start <=mid and end <= right: if nums[start] > nums[end]: res.append(nums[end]) end += 1 else: res.append(nums[start]) start += 1 while start <= mid: res.append(nums[start]) start += 1 while end <= right: res.append(nums[end]) end += 1 for idx,i in enumerate(range(left,right + 1)): nums[i] = res[idx] def merge_and_sort(nums,left,right): if left >= right: return 0 mid = (left + right) // 2 count = merge_and_sort(nums,left,mid) + merge_and_sort(nums,mid + 1,right) j = mid + 1 for i in range(left,mid+1): while j <= right and nums[i] > nums[j]*2: j += 1 count += j - (mid + 1) # return count merge(nums,left,mid,right) return count return merge_and_sort(nums,0,len(nums) - 1)
db5a8740b561ebf41daf9468ce6a1dd824a23f8e
WenHui-Zhou/weekly-code-STCA
/top100_frequency/fifth/baidu1.py
504
3.8125
4
# 输入两个整数 n 和 m,从数列1,2,3,.......,n 中随意取几个数, # 使其和等于 m ,要求将其中所有的可能组合列出来。 # 用动态规划的思想来做,对节点,从右到左遍历 n = 10 m = 8 def getList(n,m,lists,ans): if m == 0: ans.append(lists[::]) return if m < 0 or n <=0: return getList(n-1,m,lists,ans) lists.append(n) getList(n-1,m-n,lists,ans) lists.pop() ans = [] getList(n,m,[],ans) print(ans)
8741b37b87b2f0f7490c1297f6e8e2317f3f50aa
jw3030/git
/python/python_crawler/27_four_operation.py
374
3.734375
4
# plus minus multiple divide 을 return하는 함수 def getFourOperations(val1, val2): plusResult = val1 + val2 minusResult = val1 - val2 multipleResult = val1 * val2 divideResult = val1 / val2 return {"plus":plusResult, "minus":minusResult, "multiple":multipleResult, "divide":divideResult} result = getFourOperations(10,20) print(result)
33a159573bd04a0a6200561a6a33d3e8eac12c6e
Highcourtdurai/Deep-learning
/RNN.py
3,021
3.765625
4
#Google Stock Market Prediction #Importing Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #Importing the training set dataset_train=pd.read_csv("Google_Stock_Price_Train.csv") training_set=dataset_train.iloc[:,1:2].values #Feature Scaling from sklearn.preprocessing import MinMaxScaler sc=MinMaxScaler(feature_range=(0,1)) training_set_scaled=sc.fit_transform(training_set) #Creating a data structure with 60 timesteps and 1 output x_train=[] y_train=[] for i in range(60,1258): x_train.append(training_set_scaled[i-60:i,0])#0-column y_train.append(training_set_scaled[i,0]) x_train,y_train=np.array(x_train),np.array(y_train) #reshaping x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1)) #Part-2 Building the RNN #Importing keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout#It controls overfitting like regularization #Initializing the KNN regressor=Sequential() #Adding the first LSTM layer and some Dropout regularisation regressor.add(LSTM(units=50,return_sequences=True,input_shape=(x_train.shape[1],1))) regressor.add(Dropout(0.2)) #Adding a second LSTM layer and some Dropout regularisation regressor.add(LSTM(units=50,return_sequences=True)) regressor.add(Dropout(0.2)) #Adding a third LSTM layer and some Dropout regularisation regressor.add(LSTM(units=50,return_sequences=True)) regressor.add(Dropout(0.2)) #Adding a fourth LSTM layer and some Dropout regularisation regressor.add(LSTM(units=50)) regressor.add(Dropout(0.2)) #Adding the output layer regressor.add(Dense(units=1)) #Compiling the RNN regressor.compile(optimizer="adam",loss="mean_squared_error",metrics=("accuracy")) #fitting the RNN to the traning set regressor.fit(x_train,y_train,epochs=25,batch_size=32) regressor.summary() #part-3 -Making the predictions and visualising the results dataset_test=pd.read_csv("Google_Stock_Price_Train.csv") real_stock_price=dataset_test.iloc[:,1:2].values #Getting the predicted stock price of 2017 dataset_total=pd.concat((dataset_train["Open"],dataset_test["Open"]),axis=0) inputs=dataset_total[len(dataset_total)-len(dataset_test)-60:].values inputs=inputs.reshape(-1,1) inputs=sc.transform(inputs) x_test=[] for i in range(60,80): x_test.append(inputs[i-60:i,0]) x_test=np.array(x_test) x_test=np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1)) predicted_stock_price=regressor.predict(x_test) predicted_stock_price=sc.inverse_transform(predicted_stock_price) #Visualising the results plt.plot(real_stock_price,color="red",label="Real Google Stock Price") plt.plot(predicted_stock_price,color="blue",label="Predicted Google Stock Price") plt.title("Google Stock Price Prediction") plt.xlabel("Time") plt.ylabel("Google Stock Price") plt.legend() plt.show()
3984fed0a2026179870161f6c7d8edab7ec65f9e
spartakummaximus1/py_files
/union.py
90
4.03125
4
a=[1,3,4,2,4,5,4] b=[3,5,3,5,6,4,3] def union(a,b): return a+b or b+a print(union(a,b))
e382fdcfff2ad071794defd4b9baf013175b33aa
bencheng0904/python200817
/m&e.py
449
3.96875
4
E = int(input("輸入英文成績:")) M = int(input("輸入數學成績:")) if E >= 0 and M >= 0 and E <= 100 and M <= 100: if E >=90 and M >=90: print("幹的好,有獎品!") elif E <=60 and M <=60: print("幹的好,有處罰!!!") elif M <=60 or E <=60: print("幹的好,再加油!!") else: print("隨便啦,沒獎品喇") else: print("幹的好,輸入錯誤!!!!")
1d48da6a7114922b7e861afa93ddc03984815b0c
iZwag/IN1000
/oblig3/matplan.py
477
4.21875
4
# Food plan for three residents matplan = { "Kari Nordmann": ["brod", "egg", "polser"], "Magda Syversen": ["frokostblanding", "nudler", "burger"], "Marco Polo": ["oatmeal", "bacon", "taco"]} # Requests a name to check food plan for person = input("Inquire the food plan for a resident, by typing their name: ") # Prints feedback for the inquiry if person in matplan: print(matplan[person]) else: print("Sorry, that person doesn't seem to be a resident here.")
b3c5c76c0e7a77453da596bb4b615f00570b4ec9
iZwag/IN1000
/oblig4/reiseplan.py
1,385
4.03125
4
# Oppg 4.1 # Make an empty list called called "steder" elements = 5 steder = [] for i in range(0, elements): steder.append(input("Please enter a travel destination and hit ENTER: ")) # Oppg. 4.2 klesplagg = [] avreisedatoer = [] # NOTE: I am only making separate for-loops for the sake of the task. # I'd consider putting them in the same otherwise. for j in range(0, elements): klesplagg.append(input("Please enter a piece of clothing you're bringing: ")) for k in range(0, elements): avreisedatoer.append(input("Please enter a departure date: ")) # Oppg. 4.3 reiseplan = [steder, klesplagg, avreisedatoer] # Oppg. 4.4 for l in range(0, elements): print("Destination: %s \tClothing: %s \tDeparture: %s" % (reiseplan[0][l], reiseplan[1][l], reiseplan[2][l])) # Oppg. 4.5 # Prompts the user for input 1 i1 = int(input("Please enter which plan you want to view (integer 1-3): ")) # Checks if input 1 is within reasonable limits if i1 <= len(reiseplan) and i1 > 0: # Prompts the user for input 2 i2 = int(input("Please enter which item you want view (integer 1-%d): " % elements)) # Checks if input 2 is within limits # If it is, the print that element if i2 <= len(reiseplan[i1-1]) and i2 > 0: print("You wanted to know: %s" % reiseplan[i1-1][i2-1]) else: print("Ugyldig input!") else: print("Ugyldig input!")
914134c3475f4618fa39fbbde917a4ada837968f
iZwag/IN1000
/oblig5/regnefunksjoner.py
1,933
4.125
4
# 1.1 # Function that takes two parameters and returns the sum def addisjon(number1, number2): return number1 + number2 # 1.2 # Function that subtracts the second number from the first one def subtraksjon(number1, number2): return number1 - number2 # 1.2 # Function that divides the first argument by the second # Also added an assertion to test for 0 in denominator def divisjon(number1, number2): assert(number2 != 0),"Division by 0 is illegal" return number1/number2 # 1.3 # Converts inches to centimeter and tests for an input <= 0 def tommerTilCm(antallTommer): assert(antallTommer > 0), "Inches must be greater than 0" return antallTommer * 2.54 # 1.4 # User input is run through the above functions and tested def skrivBeregninger(): print("Utregninger:") number1 = float(input("Skriv inn tall 1: ")) number2 = float(input("Skriv inn tall 2: ")) print("") print("Resultat av summering: %.1f" % addisjon(number1, number2)) print("Resultat av subtraksjon: %.1f" % subtraksjon(number1, number2)) print("Resultat av divisjon: %.1f" % divisjon(number1, number2)) print("") print("Konvertering fra tommer til cm:") number3 = float(input("Skriv inn et tall: ")) print("Resultat: %.2f" % tommerTilCm(number3)) # 1.1 # Prints the results of addition print(addisjon(1,3)) # 1.2 # Testing all the other functions with assert assert(subtraksjon(5,7) == -2),"Subtraction didn't work!" assert(subtraksjon(1,-8) == 9),"Subtraction didn't work!" assert(subtraksjon(-5,-5) == 0), "Subtraction didn't work!" assert(divisjon(10,2) == 5),"Division didn't work!" assert(divisjon(-2,2) == -1),"Division didn't work!" assert(divisjon(-8,4) == -2),"Division didn't work!" # 1.3 # Tests the inches to cm function assert(tommerTilCm(3) > 0),"Converting from inches didn't work!" # 1.4 # Runs the user test without arguments skrivBeregninger()
08e71694bd2f54c8b3131912cab43b11156d41ae
keithkay/python
/python_crash_course/modulo.py
128
3.875
4
num_1 = input("First number: ") num_2 = input("Second number: ") result = int(num_1) % int(num_2) print("The result is", result)
67b284c3f8dcaed9bdde75429d81c7c96f31847c
keithkay/python
/python_crash_course/functions.py
2,432
4.78125
5
# Python Crash Course # # Chapter 8 Functions # functions are defined using 'def' def greeting(name): """Display a simple greeting""" # this is an example of a docstring print("Hello, " + name.title() + "!") user_name = input("What's your name?: ") greeting(user_name) # in addition to the normal positional arguements for a function, you can # pass 'keyword arguements' to a function, and provide a default for an # arguement, essentially making it optional (you can also just make it # optional without a default by using ='' def describe_pet(pet_name, animal_type='cat'): """Display information about a pet""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") # now when calling 'describe_pet' we either ensure they are in the correct # order, or we explictly assign them, illustrated here: describe_pet('harry', 'hamster') describe_pet(animal_type='dog', pet_name='willie') describe_pet('lois') # functions can also return a value, using, you guessed it 'return' def format_name(fname, lname, mname=''): """Return a full name, neatly formatted.""" if mname: full_name = fname + ' ' + mname + ' ' + lname else: full_name = fname + ' ' + lname return full_name.title() my_name = format_name('keith', 'kAy') print(my_name) print(format_name('J', 'Seymor', 'Thomas')) # functions can be set up to receive and arbitrary number of arguements # using '*' tells Python to create a tuple in which to store all the # arguements received def make_pizza(*toppings): """Print a list of the toppings requested""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') # you can also use '**' to pass a dictionary of unknown structure, but # the dictionary must be passed as keyword-value pairs def build_profile(fname, lname, **user_info): """ Build a dictionary containing everyting we know about a user. """ profile = {} profile['first_name'] = fname profile['last_name'] = lname for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print("") print(user_profile)
ef7d7c152439de6ccfcb9d3206f9d38fe14102b8
keithkay/python
/python_crash_course/test_name_function.py
729
3.921875
4
# Python Crash Course # # Chapter 11 - Testing # # This is the unit test to test name_function.py import unittest from name_function import format_this_name class NamesTestCase(unittest.TestCase): """Tests for 'name_function.py'.""" # each test must be named test_... def test_first_last_name(self): """Do names like 'Janis Joplin' work?""" formatted_name = format_this_name('janis', 'joplin') self.assertEqual(formatted_name, 'Janis Joplin') def test_first_middle_last_name(self): """Do names like 'Wolfgang Amedeus Mozart' work?""" formatted_name = format_this_name('wolfgang', 'mozart', 'amedeus') self.assertEqual(formatted_name, 'Wolfgang Amedeus Mozart') unittest.main()
d7b69396e0fd909f1db82de9606f6241d6499c4c
keithkay/python
/python_crash_course/scratch.py
196
3.59375
4
############################################################################### import kay_func as kf new_list = ['one', 'two', 'three'] print_list = kf.format_list(new_list) print(print_list)
03ec200798e7dfd44352b6997e3b6f2804648732
keithkay/python
/python_crash_course/classes.py
776
4.5
4
# Python Crash Course # # Chapter 9 OOP # In order to work with an object in Python, we first need to # define a class for that object class Dog(): """A simple class example""" def __init__(self, name, age): """Initializes name and age attributes.""" self.name = name self.age = age def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate rolling over in response to a command""" print(self.name.title() + " rolled over!") my_dog = Dog('rosey',11) print("My dog's name is " + my_dog.name.title() + ".") print(my_dog.name.title() + " is " + str(my_dog.age) + " years old.") my_dog.sit() my_dog.roll_over()
effe6b249e0b89c55a92a0d13b790fe0a87bd06c
keithkay/python
/sandbox/json_tests.py
1,522
3.609375
4
# json_tests.py # # This program works out how to handle different states you may encounter # loading a json file that contains a dictionary of settings. # # by: Keith Kay import json filename = 'testing.json' my_dict = {} # first open the the file and determine if it is empty try: with open(filename, 'r') as file_obj: if file_obj.read(): # The file is not empty print("I read something") # The seek(0) is need because the 'read()'above has moved the file # cursor to EOF, so we need to move it back file_obj.seek(0) my_dict = json.load(file_obj) test_value_1 = my_dict['test_value_1'] print(test_value_1) else: # The file exists, but has nothing in it print("I read nothing") with open(filename, 'w') as file_obj: my_dict = {'test_value_1': '0'} json.dump(my_dict, file_obj) except FileNotFoundError: print("File doesn't exist") # Create the file and write the dict with open(filename, 'w') as file_obj: my_dict = {'test_value_1': '0'} json.dump(my_dict, file_obj) except KeyError: print("File exists, but key not found") # File exists but the key was not in the dict with open(filename, 'r+') as file_obj: my_dict = json.load(file_obj) file_obj.seek(0) file_obj.truncate() my_dict['test_value_1'] = '0' json.dump(my_dict, file_obj)
165a331029d73afbe5e10d39bf1948d613d816fe
abhi1p/Undo_Redo
/Undo_Redo/__init__.py
1,237
3.515625
4
from collections import deque class UndoRedo: def __init__(self): self._stack = deque() self._index = -1 def append(self, num): self.pop() self._stack.append(num) self._index += 1 def pop(self): l = len(self._stack) for i in reversed(range(self._index + 1, l)): self._stack.pop() def undo(self): if self._index > 0: self._index -= 1 def undoText(self): i = self._index if i > 0: return self._stack[i - 1] else: return self._stack[0] def redo(self): indx = len(self._stack) if self._index < (indx - 1): self._index += 1 def redoText(self): indx = len(self._stack) i = self._index if i < (indx - 1): return self._stack[i + 1] else: return self._stack[indx - 1] def undoAvailable(self): if self._index > 0: return True else: return False def redoAvailable(self): l = len(self._stack) if self._index < l - 1: return True else: return False def out(self): return self._stack
d0fac3ca0f27e050d676c38ddc11f27afb017826
AeroX2/tree-distance-proof
/proof.py
3,081
3.5
4
from random import randint from collections import deque uuid = 0 class Node: def __init__(self, parent): global uuid uuid += 1 self.uuid = uuid self.parent = parent self.children = {} def drop(self): if (not self.parent): return self.add_child(self.parent) if (self in self.parent.children): del self.parent.children[self] self.parent.drop() def add_child(self,child): self.children[child] = None def __repr__(self): return "Node: %d" % (self.uuid) def __str__(self): return "Node: %d" % (self.uuid) def __eq__(self,other): return self.uuid == other.uuid def __hash__(self): return self.uuid RANDOM_CHILD = 5 RANDOM_HEIGHT_LOW = 8 RANDOM_HEIGHT_HIGH = 10 def make_random_tree(): root = Node(None) queue = deque([root]) for _ in range(randint(RANDOM_HEIGHT_LOW, RANDOM_HEIGHT_HIGH)): if (len(queue) == 0): break node = queue.popleft() for _ in range(randint(1,RANDOM_CHILD)): new_node = Node(node) queue.append(new_node) node.add_child(new_node) return root def print_tree(base, data): for i,node in enumerate(data): if (i == len(data)-1): print('%s└─%s' % (base, node.uuid)) else: print('%s├─%s' % (base, node.uuid)) if (not node.children): continue if (i == len(data)-1): print_tree(base + ' ', node.children)#+[None]) else: print_tree(base + '│ ', node.children)#+[None]) def method_one_helper(node, depth): max_depth = depth max_node = node for child in node.children: d,n = method_one_helper(child, depth+1) if (d > max_depth): max_depth = d max_node = n return (max_depth, max_node) def method_one(root): _,n1 = method_one_helper(root, 0) n1.drop() d1,_ = method_one_helper(n1, 0) return d1+1 def method_two_helper(node, depth): max_distance = 0 max_depths = [] if (len(node.children) == 0): return (0,depth) for child in node.children: mdi,mde = method_two_helper(child, depth+1) if (mdi > max_distance): max_distance = mdi max_depths.append(mde) max1 = 0 max2 = 0 for d in max_depths: if (d > max1): max2 = max1 max1 = d elif (d > max2): max2 = d #if (max1 != 0 and max2 != 0): distance = (max1+max2 - 2*depth)+1 max_distance = max(max_distance, distance) return (max_distance, max(max_depths)) def method_two(root): return method_two_helper(root, 0)[0] def main(): distance1 = 0 distance2 = 0 while (distance1 == distance2): global uuid uuid = 0 root = make_random_tree() print_tree("", [root]) distance2 = method_two(root) distance1 = method_one(root) print("DISCREPANCY FOUND") print(distance1, distance2) main()
7d287d26b6229506f59ac51080d93b0c4bb508c0
pala9999/python
/week1/zipCode.py
531
4.03125
4
# zipCode = "12345" # print(zipCode) zipCode=input("Enter zipCode:\n") #print(zipCode.isnumeric()) if len(zipCode) != 5: print("Invalid Zip: " + zipCode + "\t...expecting 5 digit zip") exit() elif (zipCode.isnumeric()) == False: print("Invalid zip: " + zipCode + "\t...expecting numbers only") exit() else: print(zipCode) print("The Zip Code is:", zipCode) print("zip code: %s" %(zipCode)) print(f"The zip code is {zipCode}") # Adding commet to test GIT from Visual Studio import sys
287f72721a917cd83e34efdd7856741b6c214565
pala9999/python
/week3/week3_utils.py
2,468
4.0625
4
## Q1. Create a function named custom_function . def custom_function(n): for i in range(1,11): #print(n,"*",i,"=",n*i) return n , i, n*i x,y,z = custom_function(5) ################################################################################ # Q2. Write the function call with 2 arguments fname, lname # that returns fname+lname, print returned value. def f_name (fname,lname): return fname+lname print(f_name("Prasanth","Ala")) ################################################################################ # Q3a. Create a function call with arguments def q3(*args): a1=args[0] a2=args[1] return a1+" "+a2 arg1=input("Q3a Enter fname value:\n") arg2=input("Q3a Entwe lname value:\n") print(q3(arg1,arg2)) ################################################################################ # Q3b. Create a function call with keyword arguments. def q3(**args): a1=args["fname"] a2=args["lname"] return a1+" "+a2 arg1=input("Q3b Enter fname value:\n") arg2=input("Q3b Enter lname value:\n") print(q3(fname=arg1, lname=arg2)) ################################################################################ # Q4. Create two functions where first function accepts a dictionary # as keyword argument and for each KEY in that dictionary # call the second function with argument as VALUE of that KEY. # The second function should validate if key is Alphabets only or # Alphanumeric or Numeric and print "VALUE, is of type Alphabets" # or "VALUE, is of type Alphanumeric" or "VALUE, is of type Numeric" respectively. def check_string(str1): if str1.isnumeric() == True: return "Input VALUE is Numeric" elif str1.isalpha() == True: return "Input VALUE is Alphabets" elif str1.isalnum() == True: return "Input VALUE is Alphanumeric" def read_srt(**args): d=dict() a1=args["string1"] a2=args["string2"] a3=args["string3"] d[a1]=check_string(a1) d[a2]=check_string(a2) d[a3]=check_string(a3) return d arg1=input("Enter 1st numbers or alpha or alphanumeric string:\n") arg2=input("Enter 2nd numbers or alpha or alphanumeric string:\n") arg3=input("Enter 3nd numbers or alpha or alphanumeric string:\n") print(read_srt(string1=arg1,string2=arg2,string3=arg3)) #### Q5. Find the factorial of an integer through recursion. def fact(n): if n == 1: return n else: return n*fact(n-1) print(fact(4))
d5f27265bbc922c31c7268b3395cde1f17d8bfb7
Kodamayuto2001/NumPyTest01
/test10.py
2,331
3.90625
4
import numpy as np from PIL import Image l_2d = [[0,1,2],[3,4,5]] print(l_2d) print(type(l_2d)) arr = np.array([[0,1,2],[3,4,5]]) print(arr) print(type(arr)) arr = np.arange(6) print(arr) arr = np.arange(6).reshape((2,3)) print(arr) print("-----Numpy Matrix-----") mat = np.matrix([[0,1,2],[3,4,5]]) print(mat) print(type(mat)) mat = np.matrix(arr) print(mat) print(type(mat)) mat_1d = np.matrix([0,1,2]) print(mat_1d) print(type(mat_1d)) print(mat_1d.shape) # コンストラクタの引数に一次元配列を渡すと二次元に拡張され、三次元以上の配列を渡すとエラーになる # Pythonリスト型の二次元配列の要素の値は、list[行番号][列番号]でアクセスできる。行番号・列番号は0始まり。値を取得することも、変更(代入)することもできる print(l_2d) print(l_2d[0][1]) l_2d[0][1] = 100 print(l_2d) # 転置行列 l_2d = [[0,1,2],[3,4,5]] print(l_2d) print([list(x) for x in list(zip(*l_2d))]) # numpy.ndarrayとnumpy.matrixは.Tで転置行列を取得できる。 arr = np.arange(6).reshape((2,3)) print(arr) print(arr.T) img = np.array(Image.open("JPG/lena.jpg")) print(type(img)) print(img.shape) print(img.T.shape) print(img.T[0].shape) Image.fromarray(np.uint8(img.T[0])).save("JPG/imgT0.jpg") Image.fromarray(np.uint8(img.T[0].T)).save("JPG/imgT0T.jpg") # 行列の和と差 print("-----行列の和と差-----") l_2d_1 = [[0,1,2],[3,4,5]] l_2d_2 = [[0,2,4],[6,8,10]] print(l_2d_1 + l_2d_2) arr1 = np.arange(6).reshape((2,3)) print(arr1) arr2 = np.arange(0,12,2).reshape((2,3)) print(arr2) print(arr1 + arr2) print(arr1 - arr2) # Pythonリスト型では、数値との*演算は配列の繰り返しとなり、リスト同士の*演算は定義されていないためerrorになる print(l_2d_1 * 2) # [[0, 1, 2], [3, 4, 5], [0, 1, 2], [3, 4, 5]] # numpy.ndarrayとnumpy.matrixでは、数値(スカラー値)との*演算は各要素のスカラー倍となる print(arr1 * 2) # [[ 0 2 4] # [ 6 8 10]] print(mat * 2) # [[ 0 2 4] # [ 6 8 10]] # 行列同士の要素ごとの積(アダマール積)を取得するには、numpy.multiply()を使う print(np.multiply(arr1,arr2)) # numpy.ndarrayでは、*演算子はnumpy.multiply()と等価で、要素ごとの積になる print(arr1 * arr2)
46206896c2b33cfa6d851e34c5a6938d27e306b5
minhhoangho/Machine-learning-algorithms
/Linear-regression/linear-regression_v2.py
1,064
3.578125
4
# Source: https://machinelearningcoban.com/2016/12/28/linearregression/ import numpy as np import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('data/Advertising.csv') # mẫu số liệu (x :Chiều cao, y: Cân nặng) # height (cm) X = np.array([[147, 150, 153, 158, 163, 165, 168, 170, 173, 175, 178, 180, 183]]).T # weight (kg) Y = np.array([[ 49, 50, 51, 54, 58, 59, 60, 62, 63, 64, 66, 67, 68]]).T # exit(0) # X = np.array([data.values[:, 2]]).T Y = np.array([data.values[:, 4]]).T one = np.ones((X.shape[0], 1)) X_train = np.concatenate((one, X), axis=1) # Calculating weights of the fitting line A = np.dot(X_train.T, X_train) b = np.dot(X_train.T, Y) weight = np.dot(np.linalg.inv(A), b) print("Ket qua: ") print(weight) # Preparing the fitting line w_0 = weight[0][0] w_1 = weight[1][0] print("Gia tri du doan cho X = 19 :") print(w_1*19 + w_0) x0 = np.linspace(0, 50, 100) y0 = w_0 + w_1*x0 # Drawing the fitting line plt.plot(X.T, Y.T, 'ro') # data plt.plot(x0, y0) # the fitting line plt.show()
06f48c859b796a65a874bb4a487dc29449bf0336
minhhoangho/Machine-learning-algorithms
/K-means/K-means2.py
2,497
3.59375
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np # Euclidian: (x1, y1) , (x2, y2) => (x1-x2) **2 + (y1-y2)**2 # # Manhattan: (x1, y1) , (x2, y2) => abs(x1-x2) + abs(y1-y2) # # trọng số, # # Minkowski: (x1, y1) , (x2, y2) => abs(x1-x2) + abs(y1-y2) def load_dataset(path): data = pd.read_csv(path, index_col=None) data = data.sample(frac=1) labels = list(set(data.values[:, 5])) X_train = data.values[:100, :] X_test = data.values[101:, :] class_1 = X_train[[i for i in range(X_train.shape[0]) if X_train[i][-1] == labels[0]], :] class_2 = X_train[[i for i in range(X_train.shape[0]) if X_train[i][-1] == labels[1]], :] class_3 = X_train[[i for i in range(X_train.shape[0]) if X_train[i][-1] == labels[2]], :] print("Labels:") print(labels) print("Train set: ", X_train.shape) print("Test set: ", X_test.shape) return X_train, X_test k def get_neighbors(trainning_set, test_instance, k): distances = [] print(test_instance) length = len(test_instance) - 1 # phải trừ 1 do label for i in range(len(trainning_set)): dis = euclidean_distance(trainning_set[i], test_instance, length) distances.append((trainning_set[i], dis)) distances = sorted(distances, key=lambda x: x[1]) neighbors = [] for i in range(k): neighbors.append(distances[i][0]) return neighbors def response(neighbors): class_votes = {} for i in range(len(neighbors)): response = neighbors[i][-1] if response in class_votes: class_votes[response] += 1 else: class_votes[response] = 1 sorted_votes = sorted(class_votes.items(), key=lambda x: x[1], reverse=True) return sorted_votes[0][0] def check_accuracy(test_set, predictions): correct = 0 for i in range(len(test_set)): if test_set[i][-1] is predictions[i]: correct += 1 return (correct / float(len(test_set))) if __name__ == "__main__": print("OK") X_train, X_test = load_dataset('./data/Iris.csv') predictions = [] k = 5 for i in range(len(X_test)): neighbours = get_neighbors(trainning_set=X_train, test_instance=X_test[i], k=k) result = response(neighbours) predictions.append(result) print('> Predicted=%7s ----- Actual=%s' % (predictions[i], X_test[i][-1])) accuracy = check_accuracy(test_set=X_test, predictions=predictions) print("Accuracy= %7f " % accuracy)
8899317ae6c5039dcbe7698db43bdf048062ade3
nickmoop/Pool
/Board.py
1,199
3.546875
4
class Board: def __init__(self, canvas=None): self.wide = 355 self.height = 710 self.g = 9.809 self.item = None self.canvas = canvas self.loss = 0.55 def paint(self, root): if self.canvas is None: return board = self.canvas(root, bg='brown') board.place(x=85, y=85, width=384, height=742) self.item = self.canvas(root, bg='dark green') self.item.place(x=100, y=100, width=356, height=712) self.item.create_line(0, 565, 356, 565, fill='white') self.item.create_arc( 120, 507, 236, 623, start=180, extent=180, style='arc', outline='white' ) self.item.create_oval( 176, 563, 180, 567, fill='white', outline='white') self.item.create_oval(176, 63, 180, 67, fill='white', outline='white') self.item.create_oval( 176, 176, 180, 180, fill='white', outline='white') self.item.create_oval( 176, 354, 180, 358, fill='white', outline='white') def paint_balls(self, balls): for ball in balls: ball.update_guess_coordinates() ball.paint(self.item)