blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d429a3e7b34a32a6d5cfc1d142b3f42c28a1d072
Tr4shL0rd/mathScripts
/uligheder/støreEndMindreEnd_Minus_num.py
324
3.734375
4
try: def main(): while True: a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) b = b+c result = b/a print(f"\nx = {result}\n======") main() except KeyboardInterrupt: print("\nGoodBye!!")
c8c6a921a5ece023c24c0d87c02d8b9e90f138df
bosshentai/pythonLearning
/regular_Expressions/teste.py
328
3.515625
4
import re pattern = re.compile('this') string = 'search inside of this text please!' #print('search' in string) a = pattern.search(string) b = pattern.findall(string) c = pattern.fullmatch(string) d = pattern.match(string) # print(a.span()) # print(a.start()) # print(a.end()) # print(a.group()) print(b) print(c) print(d)
13aaa497401f0d871d728846d8c8dda7515cd151
hrssurt/lintcode
/leetcode/234. Palindrome Linked List.py
1,757
3.875
4
"""*************************** TITLE ****************************""" """234. Palindrome Linked List.py""" """*************************** DESCRIPTION ****************************""" """ Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? """ """*************************** CODE ****************************""" # Definition for singly-linked list. # class ListNode: #     def __init__(self, x): #         self.val = x #         self.next = None ​ class Solution:    def isPalindrome(self, head: ListNode) -> bool:        if not head:            return True                        def find_mid(head):            slow = fast = head            while fast and fast.next:                fast = fast.next.next                slow = slow.next            return slow                                def reverse(head):            new_head = None            while head:                rem = head.next                head.next = new_head                new_head = head                head = rem                            return new_head                        first, second = head, reverse(find_mid(head))   # first represents first half, second represents second half        while first and second:            if first.val != second.val:                return False                        first, second = first.next, second.next                    return True         ​
c1aae258433b14ea1f5cec822df0073b6e4cc1dd
pedrosimoes-programmer/exercicios-python
/exercicios-Python/aula13.py
559
3.859375
4
for c in range(1, 7): print(2 * c) print('') for c in range(6, 0, -1): #-1 é a forma que o for realizará a contagem, ou seja, contando de -1 em -1 print(c) print('') for c in range(0, 12, 2): # 2 é a forma que ele vai fazer a contagem, ou seja, de 2 em 2 print(c) print('') i = int(input('Início: ')) f = int(input('Fim: ')) p = int(input('Passo: ')) for c in range(i, f+1, p): print(c) print('') s = 0 for c in range(0, 4): n = int(input('Digite um valor: ')) s += n print('A soma de todos os valores foi: {}'.format(s))
1a7ad7284e9bd64e23cd44a9a2df2fabd9376456
jayventi/primes_n_e
/prime_pattern_engine/primes_sieve_generator.py
2,003
4.34375
4
""" generates a sieve list of prime numbers up to a maximum given as a parameter primes_sieve_generator based on ideas from: https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/ Jay Venti September 8th, 2016 """ import math import json def is_prime(number, primes_table): """ determines if a number is prime using primes_table which is updated by top level primes_sieve_generator """ if number > 1: if number == 2: return True if number % 2 == 0: return False max_test = int(math.sqrt(number) + 1) for current in primes_table: if current > max_test: return True if number % current == 0: return False return True return False def get_primes(number, primes_table): while True: if is_prime(number, primes_table): yield number number += 1 # <<<<<<<<<< yield resumes here def primes_sieve_generator(max_prime): """ builds and it returns list of prime numbers up to max_prime """ prime_count = 1 primes_table = [] for next_prime in get_primes(3, primes_table): primes_table.append(next_prime) prime_count += 1 if next_prime >= max_prime: print('prime count', prime_count) print('prime power', int(math.log(next_prime, 10))) return primes_table def write_primes_sieve_2_file(sieve, max_prime, work_dir): file_path_name = "{0}primes_sieve_{1}.json".format(work_dir, max_prime) with open(file_path_name, 'w') as outfile: json.dump(sieve, outfile) if __name__ == '__main__': # configuration parameters max_prime = 1000 work_dir = 'work_files/' sieve = primes_sieve_generator(max_prime) write_primes_sieve_2_file(sieve, max_prime, work_dir) """ for max_prime = 40000000 ('total', 47088408550139L) ('prime count', 2433655) ('prime power', 7) [Finished in 148.6s] """
28c0dbe5f7745522aebffff555079a66bc6376c0
pigmonchu/BZ5_k2_romanos
/cromanos.py
3,455
3.53125
4
class RomanNumber(): __symbols = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1, } def __init__(self, valor): if isinstance(valor, str): self.value = self.romano_a_entero(valor) if self.value == 'Error en formato': self.rvalue = self.value else: self.rvalue = valor else: self.value = valor self.rvalue = self.entero_a_romano() if self.rvalue == 'Overflow': self.value = self.rvalue def romano_a_entero(self, numero_romano): if numero_romano == '': return 'Error en formato' entero = 0 numRepes = 1 letraAnt = '' fueResta = False for letra in numero_romano: if letra in self.__symbols: if letraAnt == '' or self.__symbols[letraAnt] >= self.__symbols[letra]: entero += self.__symbols[letra] fueResta = False else: if letraAnt + letra in self.__symbols.keys() and numRepes < 2 and not fueResta: entero = entero - self.__symbols[letraAnt] * 2 + self.__symbols[letra] fueResta = True else: return 'Error en formato' else: return 'Error en formato' if letra == letraAnt and numRepes == 3: return 'Error en formato' elif letra == letraAnt : numRepes += 1 else: numRepes = 1 letraAnt = letra return entero def entero_a_romano(self): if self.value > 3999 or self.value < 1: return 'Overflow' componentes = self.__descomponer(self.value) res = '' for valor in componentes: while valor > 0: k, v = self.__busca_valor_menor_o_igual(valor) valor -= v res += k return res def __busca_valor_menor_o_igual(self, v): for key, value in self.__symbols.items(): if value <= v: return key, value def __descomponer(self, numero): res = [] for orden in range(3, 0, -1): resto = numero % 10 ** orden res.append(numero - resto) numero = resto res.append(numero) return res def __str__(self): return self.rvalue def __repr__(self): return self.rvalue def __add__(self, other): # I, III if isinstance(other, int): suma = self.value + other else: suma = self.value + other.value resultado = RomanNumber(suma) return resultado def __radd__(self, other): return self.__add__(other) def __sub__(self, other): if isinstance(other, int): resta = self.value + other else: resta = self.value + other.value resultado = RomanNumber(resta) return resultado def __rsub__(self, other): return self.sub(other) def __eq__(self, other): return self.value == other.value
2dee56e2231536b6e501cad14177ba342459aa54
Danilo282/python-port
/Leitores_for_while/aposentadoria.py
217
3.78125
4
id = int(input('Digite a sua idade: ')) ts = int(input('Digite o tempo de serviço: ')) idts = id + ts if idts >= 85 or id >= 65 or ts >= 30: print('Pode se aposentar.') else: print('Não pode se aposentar.')
d9f47cb1a99b9089135c49c947a3c55609dbbdad
Mehvix/competitive-programming
/Codeforces/Individual Problems/P_118A.py
199
3.515625
4
fin = list(input().strip()) vowels = ["a", "e", "i", "o", "u"] for pos in range(len(fin)): if [s for s in fin if str(fin[pos]).lower() in s]: del fin[pos] # TODO NOT DONE print(fin)
902465ed5dbc2d9f9d028e8a0525d723b8b948a9
teja463/python
/oops.py
892
3.84375
4
class Employee(): #name = "Teja" company = "Mindtree" mail = "teja463@gmail.com" __sal = 22000 def __init__(self): self.name = "Pramod" def getSal(self): return self.__sal obj1 = Employee() #print (Employee.name) print (obj1.name) print (obj1.getSal()) print (obj1._Employee__sal) # Inheritance class Parent(): def __init__(self): print ("In parent") class Child1(Parent): def __init__(self): print ("In child1") class Child2(Parent): def __init__(self): print ("In child2") class GrandChild(Child2, Child1): pass """def __init__(self): print ("In grandchild")""" grand_child = GrandChild() child1 = Child1() # Documentation class Sample(): """ This is the documentation in multiple lines """ "" pass sample = Sample() print (sample.__doc__)
ccc12beab6b025ab7cd2afeccb3219f5f3fbe69e
daniele-canavese/fingerprinting
/classification/ml/classification.py
848
3.59375
4
""" Classification functions. """ from typing import Any from typing import Dict from typing import Tuple from pandas import DataFrame from pandas import Series def classify(model: Dict[str, Any], x: DataFrame, classes: Dict[int, str]) -> Tuple[Series, DataFrame]: """ Classifies some data. :param model: the model to use :param x: the input data :param classes: the dict for decoding the outputs :return: a tuple where the first element is the class and the second the probabilities. """ scaler = model["scaler"] numbers = model["numbers"] classifier = model["classifier"] x = scaler.transform(x) yy = Series(classifier.predict(x)) p = DataFrame(data=classifier.predict_proba(x), columns=classes.values()) if numbers: yy = yy.map(classes).astype("category") return yy, p
d112500b3f9e2121be7c98316b65f3ac4856c2c5
cristian341/First-Python-Programm
/Project.py
21,310
3.65625
4
import math from statistics import mode from graphics import * from bar_chart import * from pie_chart import * def area_of_square(x): return print(f"Area of square is {round(x**2, 3)}cm²") def perimeter_of_square(x): return print(f"Perimeter of square is {round(4*x, 3)}cm") def volume_of_cube(x): return print(f"Volume of cube is {round(x**3, 3)}cm³") def volume_of_cuboid(a,b,c): return print(f"Volume of cuboid is {round(a*b*c, 3)}cm³") def perimeter_of_rectangular(l,w): return print(f"Perimeter of rectangular is {round((l*2)+(w*2), 3)}cm") def area_of_rectangular(l,w): return print(f"Area of rectangular is {round(l*w, 3)}cm²") def area_of_triangle(b,h): return print(f"Area of triangle is {round((b*h)/2, 3)}cm²") def volume_of_triangle(b,h,H): return print(f"Volume of trinagle is {round(((b*h)/2)*H, 3)}cm³") def area_of_circle(r): return print(f"Area of circle is {round(math.pi*r**2, 3)}cm²") def diagonal_of_square(x): #new d = x*math.sqrt(2) return print(f"Diagonal of square is {round(d, 3)}cm") def diagonal_of_rectangular(l,w): #new d = math.sqrt((l**2)+(w**2)) return print(f"Diagonal of rectangular is {round(d, 3)}cm") def circumference_of_circle(r): return print(f"Circumference of circle is {round((math.pi*r)*2, 3)}cm") def area_of_kite(w,l): return print(f"Area of kite is {round(0.5*w*l, 3)}cm") def area_of_trapezium(a,b,h): return print(f"Area of trapezium is {round((h*(a+b))/2, 3)}cm2") def volume_of_cylinder(r,h): return print(f"Volume of cylinder is {round(math.pi*(r**2)*h, 3)}cm3") def volume_of_triangular_prism(b,h,l): return print(f"Volume of triangular prism is {round((b*h*l)/2, 3)}cm3") def vol_square_based_pyramid(x,h): return print(f"Volume of square based pyramid is {round(((x**2)*h)/3, 3)}cm3") def area_of_sphere(r): return print(f"Area of shpere is {round(4*math.pi*pow(r,2),3)}cm²") def volume_of_sphere(r): return print(f"Volume of shpere is {round(4/3*math.pi*pow(r,3),4) }cm³") def volume_of_cone(r,h): return print(f"Volume of Cone is {round(1/3*math.pi*pow(r,2)*h,4)}cm³") ####################################################################### Algebra def adding(x,y): return print(f"The sum of x and y is {x+y}") def subtract(x,y): return print(f"The subtract of x and y is {x-y}") def multiply(x,y): return print(f"The multiply of x and y is {x*y}") def division(x,y): return print(f"The division of x and y is {x/y}") def floor_div(x,y): return print(f"The floor division of x and y is {x//y}") def exponential(x,y): return print(f"The exponential of x and y is {x**y}") def modulus(x,y): return print(f"The rest of y in x is {x % y}") #############################################################Formulas def one(a,b): return print(f"The result of ({a}+{b})² is = {(a**2)+(b**2)+2*a*b}") def two(a,b): return print(f"The result of ({a}-{b})² is = {(a**2)+(b**2)-2*a*b}") def three(a,b): return print(f"The result of({a}²+{b}²) is = {((a+b)**2)-2*a*b}") def four(a,b): return print(f"The result of({a}²-{b}²) is = {(a+b)*(a-b)}") def five(a,b): return print(f"The result of({a}³+{b}³) is = {pow((a+b),3)-3*a*b*(a+b)}") def six(a,b): return print(f"The result of({a}³-{b}³) is = {pow((a-b),3)+3*a*b*(a-b)}") def seven(a,b): return print(f"The result of 2({a}²+{b}²) is = {pow((a+b), 2)+pow((a-b), 2)}") def eight(a,b): return print(f"The result of ({a}+{b})²-({a}-{b})² is = {4*a*b}") def nine(a,b): return print(f"The result of {a}^4+{b}^4 is = {pow(a, 4) + pow(b, 4)}") def ten(a,b,c): return print(f"({a}+{b}+{c})²= {pow(a,2)+pow(b,2)+pow(c,2)+2*a*b+2*b*c+2*c*a}") def eleven(a,b,c): return print(f"({a}+{b}-{c})²= {pow(a,2)+pow(b,2)+pow(c,2)+2*a*b-2*b*c-2*c*a}") def twelve(a,b,c): return print(f"({a}-{b}-{c})²= {pow(a,2)+pow(b,2)+pow(c,2)-2*a*b+2*b*c-2*c*a}") ##############################################################################Square Root def power(a,b): return print(f"{a} power {b} is {pow(a,b)}") #######################################################Percentage def found_the_procent(a,b): return print(f"{b}% from {a} is {(a*b/100)} ") def percentage_increase(a,b): return print(f"{a} increased by {b}% is {(a*b/100)+a}") def percentage_decrease(a,b): return print(f"{a} increased by {b}% is {a*(100-b)/100}") def percentage_difference(a,b): if a >= b: print(f"Difference between {a} and {b} in percentage is {100-((b*100)/a)}%") else: print(f"Difference between {a} and {b} in percentage is {((b*100)/a )-100}%") #def compound_interes(a,b,c): #part_one = 1 + b/100 #amound = a*pow(part_one,c) #print(amound) def compound_interes(a,b,c): for i in range(c): d= a*(b/100) a += d print(a) ##################################################################Convertor def mm(a): return print(f"{a}mm in is {a/10}cm,{a/100}dm,{a/1000}m,{a/pow(10,6)}km") def cm(a): return print(f"{a}cm in is {a*10}mm,{a/10}dm,{a/100}m,{a/pow(10,5)}km") def dm(a): return print(f"{a}dm in is {a*100}mm,{a*10}cm,{a/10}m,{a/pow(10,4)}km") def metre(a): return print(f"{a}m in is {a*1000}mm,{a*100}cm,{a*10}dm,{a/1000}km") def km(a): return print(f"{a}km in is {a*pow(10,6)}mm,{a*pow(10,5)}cm,{a*pow(10,3)}dm,{a*1000}m") ############################################################################################Mode def my_mode(): list_of_numbers = list(map(int, input("Enter the numbers separeted by space:").split())) print(f"The most often number is {mode(list_of_numbers)}") ##################################################################App function def project_app(): ###################################################################First UI print(""" Choose 0:Geometry 1:Algebra 2:Algebraic Formulas 3:Rounding 4:Mean 5:Range 6:Square Root 7:Percentage 8:Lenght convertor 9:Mode in a list of numbers 10:Graphs Type 101 to exit """) choose_first = int(input(":")) ###################################################################Second UI if choose_first == int(0): print(""" 0:Area of Square(x) 1:Perimeter of Square(x) 2:Diagonal of Square(x) 3:Volume of Cube(x) 4:Area of Rectangular(l,w) 5:Perimeter of Rectangular(l,w) 6:Diagonal of Rectangular(l,w) 7:Volume of Ruboid(a,b,c) 8:Area of Rriangle(b,h) 9:Volume of Rriangle(b,h,H) 10:Volume of Rriangular Prism(b,h,l) 11:Volume of Rquare Based Pyramid(x,h) 12:Area of Circle(r) 13:Circumference of Circle(r) 14:Volume of Clinder(r,h) 15:Area of Kite(w,l) 16:Area of Trapezium(a,b,h) 17:Area of Sphere(r) 18:Volume of Sphere(r) 19:Volume of Cone(r,H) Type 101 to exit """) ################################################################################# var = int(input("Enter the number of operation you want to do : ")) if var == int(0): #0:area_of_square(x) print("You're doing area of square") x = float(input("Press the number: ")) area_of_square(x) elif var == int(1): #1:perimeter_of_square(x) print("You're doing perimeter of square") x = float(input("Press the number: ")) perimeter_of_square(x) elif var == int(2): #2:Diagonal of square(x) print("You're doing the diagonal of square") x = float(input("Press the number: ")) diagonal_of_square(x) elif var == int(3): #2:volume_of_cube(x) print("You'are doing volume of cube") x = float(input("Press the number: ")) volume_of_cube(x) elif var == int(4): #5:area_of_rectangular(l,w) print("You'are doing area of rectangular") l = float(input("Press lenght: ")) w = float(input("Prees width: ")) area_of_rectangular(l,w) elif var == int(5): #4:perimeter_of_rectangular(l,w) print("You'are doing perimeter of rectangular") l = float(input("Press lenght: ")) w = float(input("Prees width: ")) perimeter_of_rectangular(l,w) elif var == int(6): #6:Diagonal of rectangular(l,w) print("You're doing diagonal of rectangular") l = float(input("Press lenght: ")) w = float(input("Press width: ")) diagonal_of_rectangular(l,w) elif var == int(7): #3:volume_of_cuboid(a,b,c) print("You'are doing volume of cuboid") a = float(input("Press a:")) b = float(input("Press b: ")) c = float(input("Press c: ")) volume_of_cuboid(a,b,c) elif var == int(8): #6:area_of_triangle(b,h) print("You'are doing area of triangle") b = float(input("Press base: ")) h = float(input("Press height: ")) area_of_triangle(b,h) elif var == int(9): #7:volume_of_triangle(b,h,H) print("You'are doing volume of triangle") b = float(input("Press base: ")) h = float(input("Press height: ")) H = float(input("Press Height: ")) volume_of_triangle(b,h,H) elif var == int(10): #Volume of triangular prism(b,h,l) print("You're doing volume of triangular prism") b = float(input("Press base: ")) h = float(input("Press h: ")) l = float(input("Press lenght: ")) volume_of_triangular_prism(b,h,l) elif var == int(11): #Volume of square based pyramid(x,h) print("You're doing volume of square based pyramid") x = float(input("Press x: ")) h = float(input("Press h: ")) vol_square_based_pyramid(x,h) elif var == int(12): #8:area_of_circle(r) print("You'are doing area of circle") r = float(input("Press radius: ")) area_of_circle(r) elif var == int(13): # :Circumference of circle(r) print("You're doing circumference of circle") r = float(input("Press radius: ")) circumference_of_circle(r) elif var == int(14): # Volume of cylinder(r,h) print("You're doing volume of cylinder") r = float(input("Press radius: ")) h = float(input("Press h:")) volume_of_cylinder(r,h) elif var == int(15): # Area of kite(w,l) print("You're doing area of kite") w = float(input("Press w: ")) l = float(input("Press l: ")) area_of_kite(w,l) elif var == int(16): print("You're doing area of trapezium") a = float(input("Press a:")) b = float(input("Press b: ")) h = float(input("Press h:")) area_of_trapezium(a,b,h) elif var == int(17): print("You are doing area of shpere") r = float(input("Enter the r:")) area_of_sphere(r) elif var == int(18): print("You are going volume of sphere") r = float(input("Enter the r:")) volume_of_sphere(r) elif var == int(19): print("Your are doing Volume of Cone") r = float(input("Enter the r:")) h = float(input("Press H:")) volume_of_cone(r,h) elif var == int(101): exit() ################################################Fhird UI elif choose_first == int(1): print("Operation available: \n0: + \n1: - \n2: * \n3: / \n4: // \n5: ** \n6:% \nType 101 to exit ") var_1 = int(input("Enter the number of operation you want to do : ")) if var_1 == int(0): print("You're doing addition") x = float(input("Press x: ")) y = float(input("Press y: ")) adding(x,y) elif var_1 == int(1): print("You're doing subtraction") x = float(input("Press x: ")) y = float(input("Press y: ")) subtract(x,y) elif var_1 == int(2): print("You're doing multiplication") x = float(input("Press x: ")) y = float(input("Press y: ")) multiply(x,y) elif var_1 == int(3): print("You're doing division") x = float(input("Press x: ")) y = float(input("Press y: ")) division(x,y) elif var_1 == int(4): print("You're doing floor division") x = float(input("Press x: ")) y = float(input("Press y: ")) floor_div(x,y) elif var_1 == int(5): print("You're doing exponential") x = float(input("Press x: ")) y = float(input("Press y: ")) exponential(x,y) elif var_1 == int(6): print("You're doing Modules of x") x = float(input("Press x: ")) y = float(input("Press y: ")) modulus(x,y) elif var_1 == int(101): exit() #####################################################Fourth UI elif choose_first == int(2): print(""" 0:(a+b)²=a²+b²+2ab 1:(a-b)²=a²+b²-2ab 2:a²+b²=(a+b)²-2ab 3:a²-b²=(a+b)*(a-b) 4:a³+b³=(a+b)*(a²-ab+b²)=(a+b)³-3ab*(a+b) 5:a³-b³=(a-b)*(a²+ab+b²)=(a-b)³+3ab*(a-b) 6:2(a²+b²)=(a+b)²+(a-b)² 7:(a+b)²-(a-b)²=4ab 8:a^4+b^4=(a+b)(a-b)[(a+b)²-2ab] 9:(a+b+c)²=a²+b²+c²+2ab+2bc+2ca 10:(a+b-c)²=a²+b²+c²+2ab-2bc-2ca 11:(a-b-c)²=a²+b²+c²-2ab-2bc-2ca Type 101 to exit """) var = int(input("Enter the number of operation you want to do : ")) if var == int(0): print("You're doing (a+b)²=a²+b²+2ab ") a = float(input("Press a: ")) b = float(input("Press b: ")) one(a,b) elif var == int(1): print("You're doing (a-b)²=a²+b²-2ab ") a = float(input("Press a: ")) b = float(input("Press b: ")) two(a,b) elif var == int(2): print("You're doing a²+b²=(a+b)²-2ab ") a = float(input("Press a: ")) b = float(input("Press b: ")) three(a,b) elif var == int(3): print("You're doing a²-b²=(a+b)*(a-b)") a = float(input("Press a: ")) b = float(input("Press b: ")) four(a,b) elif var == int(4): print("You're doing a³+b³=(a+b)*(a²-ab+b²)=(a+b)³-3ab*(a+b)") a = float(input("Press a: ")) b = float(input("Press b: ")) five(a,b) elif var == int(5): print("You're doing a³-b³=(a-b)*(a²+ab+b²)=(a-b)³+3ab*(a-b)") a = float(input("Press a: ")) b = float(input("Press b: ")) six(a,b) elif var == int(6): print("You're doing 2(a²+b²)=(a+b)²+(a-b)²") a = float(input("Press a: ")) b = float(input("Press b: ")) seven(a,b) elif var == int(7): print("You're doing (a+b)²-(a-b)²= 4ab") a = float(input("Press a: ")) b = float(input("Press b: ")) eight(a,b) elif var == int(8): print("You're doing a^4+b^4=(a+b)(a-b)[(a+b)²-2ab]") a = float(input("Press a: ")) b = float(input("Press b: ")) nine(a,b) elif var == int(9): print("You're doing (a+b+c)²=a²+b²+c²+2ab+2bc+2ca") a = float(input("Press a: ")) b = float(input("Press b: ")) c = float(input("Press c ")) ten(a,b,c) elif var == int(10): print("You're doing (a+b-c)²=a²+b²+c²+2ab-2bc-2ca") a = float(input("Press a: ")) b = float(input("Press b: ")) c = float(input("Press c ")) eleven(a,b,c) elif var == int(11): print("You're doing (a-b-c)²=a²+b²+c²-2ab-2bc-2ca") a = float(input("Press a: ")) b = float(input("Press b: ")) c = float(input("Press c ")) twelve(a,b,c) elif var == int(101): exit() ############################################################################### elif choose_first == int(3): print(""" 1:Round after 1 decimal places 2:Round after 2 decimal places 3:Round after 3 decimal places 4:Round to nearest 10 5:Round to nearest 100 6:round to nearest 1000 Type 101 to exit """) var = int(input("Enter the number of operation you want to do: ")) if var == int(1): a = float(input("Enter the number: ")) print(round(a, 1)) elif var == int(2): a = float(input("Enter the number: ")) print(round(a, 2)) elif var == int(3): a = float(input("Enter the number: ")) print(round(a, 3)) elif var == int(4): a = float(input("Enter the number: ")) print(round(a, -1)) elif var == int(5): a = float(input("Enter the number: ")) print(round(a, -2)) elif var == int(6): a = float(input("Enter the number: ")) print(round(a, -3)) elif var == int(101): exit() ################### elif choose_first == int(4): list_of_numbers = list(map(int, input("Type the numbers separetated by space:").split())) print(f"The mean of the numbers is {sum(list_of_numbers)/len(list_of_numbers)}") ################### elif choose_first == int(5): list_of_numbers = list(map(int, input("Enter the numbers separeted by space:").split())) m = max(list_of_numbers) l = min(list_of_numbers) print(f"The range is {m-l}") ################### elif choose_first == int(6): a = float(input("Enter the first number: ")) b = float(input("Enter the power number: ")) power(a,b) #################### elif choose_first == int(7): print(""" 1:Finding the percentage 2:Increase the percentage 3:Decrease the percentage 4:Find the difference between the numbers in % 5:Compound interest Type 101 to exit """) var = int(input("Enter the number of operation you want to do: ")) if var == int(1): a = float(input("Enter the number: ")) b = float(input("Enter the percentage: ")) found_the_procent(a,b) elif var == int(2): a = float(input("Enter the number: ")) b = float(input("Enter the percentage: ")) percentage_increase(a,b) elif var == int(3): a = float(input("Enter the number: ")) b = float(input("Enter the percentage: ")) percentage_decrease(a,b) elif var == int(4): a = float(input("Enter the first number: ")) b = float(input("Enter the last number: ")) percentage_difference(a,b) elif var == int(5): a = float(input("Enter future value of the investment/loan£: ")) b = float(input("Enter the annual interest rate%: ")) c = int(input("Enter the number of times that interest is compounded per year: ")) compound_interes(a,b,c) elif var == int(101): exit() ##################### elif choose_first == int(8): print(""" 1:mm to cm,dm,m,km 2:cm to mm,dm,m,km 3:dm to mm,cm,m,km 4:m to mm,cm,dm,km 5:km to mm,cm,dm,m Type 101 to exit """) var = int(input("Enter the number of operation you want to do:")) if var == int(1): a = float(input("Enter the number in mm: ")) mm(a) elif var == int(2): a = float(input("Enter the number in cm: ")) cm(a) elif var == int(3): a = float(input("Enter the number in dm: ")) dm(a) elif var == int(4): a = float(input("Enter the number in m: ")) metre(a) elif var == int(5): a = float(input("Enter the number in km: ")) km(a) elif var == int(101): exit() elif choose_first == int(9): my_mode() elif choose_first == int(10): print(""" 1:Line Graphs 2:Bar Chart 3:Pie Charts """) var = int(input("Enter the number of operation:")) if var == int(1): line_graphs() elif var == int(2): bar_chart() elif var == int(3): pie_chart() elif choose_first == int(101): exit() project_app()
df2d8489e45b603f514502f3d1d5b07e9ef912f4
shuixingzhou/learnpythonthehardway
/ex41.py
1,351
4.25
4
#!usr/bin/env python3 #-*- coding: utf-8 -*- class TheThing(object): def __init__(self): self.number = 0 def some_function(self): print('I got called.') def add_me_up(self,more): self.number += more return self.number #two different things a = TheThing() b = TheThing() a.some_function() b.some_function() print(a.add_me_up(20)) print(b.add_me_up(30)) print(a.number) print(b.number) #Study this. This is how you pass a variable #from one class to another. You will need this. class TheMultiplier(object): def __init__(self,base): self.base = base def do_it(self,m): return m * self.base x = TheMultiplier(a.number) print(x.do_it(b.number)) # Animal is a object (yes, sort of confusion) look at the extra credit class Animal(object): pass ##?? class Dog(Animal): def __init__(self,name): self.name = name class Cat(Animal): def __init__(self,name): self.name = name class Person(object): def __init__(self,name): self.name = name ## Person has a pet of some kind self.pet = None class Employee(Person): def __init__(self, name, salary): ## Hmm, what is this strange magic? super(Employee,self).__init__(name) self.salary = salary class Fish(object): pass class Salmon(Fish): pass class Halibut(Fish): pass ## rover is a Dog rover = Dog('Rover') satan = Cat('Satan') mary = Person('Mary')
cc1fb8c301c4f941c82b20ed8b7eeb652650be83
xCrypt0r/Baekjoon
/src/8/8712.py
398
3.515625
4
""" 8712. Wężyk 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 64 ms 해결 날짜: 2020년 9월 17일 """ def main(): n = int(input()) l = [] for i in range(n): l.append([j for j in range(n * i + 1, n * (i + 1) + 1)]) for i, v in enumerate(l): print(*(v[::-1] if i & 1 else v), sep=' ') if __name__ == '__main__': main()
fd8a06c8b32e1488ab3ff8b875a2d6a76f336a70
ExpertSeahorse/SimpleCode
/Same checker.py
492
3.75
4
def comp(array1, array2): if None in (array1, array2) or len(array1) != len(array2): return False newarray = [] for entry in array1: newarray.append(entry * entry) if ' '.join(map(str, sorted(newarray))) == ' '.join(map(str, sorted(array2))): return True else: return False def comp(a1, a2): try: return sorted([entry ** 2 for entry in a1]) == sorted(a2) except: return False print(comp([2, 2, 3], [4, 9, 9]))
bab4a15d231c8308dedb1d0856e6b005b06567d4
yifengjin89/bank_system
/atm.py
4,472
3.625
4
# 2/12/2020 # atm info from card import Card from user import User import random class Atm(object): def __init__(self): self.all_users = {} def atm_interface(self): print("***********************************************************************") print("* Welcome to Yj bank *") print("* *") print("* Please enter number to do the operation *") print("* *") print("* open account (1) balance info (2) *") print("* deposit (3) withdraw (4) *") print("* transfer (5) change password (6) *") print("* lock account (7) unlock account (8) *") print("* cancel account (9) remake a card (10) *") print("* exit (11) *") print("* *") print("***********************************************************************") def open_account(self): # press (1) print("Open account") name = str(input("Please Enter Your Name: ")) user_id_number = int(input("Please Enter Your ID Number, digit only: ")) phone = int(input("Please Enter Your Phone Number, digit only: ")) password = int(input("Please setting Your PassWord, digit only: ")) if not self.check_password(password): return -1 card_id = self.create_card() print("Your Card ID is: %s " % card_id) card_balance = 0 card_info = Card(card_id, password, card_balance) user_info = User(name, user_id_number, phone, card_info) self.all_users[card_id] = user_info print("Open Account Successfully !!! Please Remember Your Card ID !!!") def check_password(self, real_password): for i in range(3): re_password = int(input("Please Re-Enter Your PassWord, digit only: ")) if real_password == re_password: return True else: remain = 2 - i if remain < 1: break print("PassWord does not match!!! and You have %s" % remain + " chance") print("Your PassWord does not match!!!, operation failed !!!") return False def create_card(self): while True: str = "" for i in range(6): ch = chr(random.randrange(ord('0'), ord('9') + 1)) str += ch if not self.all_users.get(str): return str def balance_info(self): print("Balance info") card_id = input("Please Enter Card ID: ") user = self.all_users.get(card_id) if not user: print("Card Id does not exist!!") else: password = int(input("Please Enter Your PassWord, digit only: ")) self.check_password(user.card.card_password) print("Card Id: %s Balance: %s" % (user.card.card_id, user.card.card_balance)) def deposit(self): # press (3) print("Deposit") card_id = input("Please Enter Card ID: ") user = self.all_users.get(card_id) if not user: print("Card Id does not exist!!") else: password = int(input("Please Enter Your PassWord, digit only: ")) self.check_password(user.card.card_password) Deposit = int(input("Enter The Amount You want to Deposit: ")) if Deposit <= 0: print("You Deposit must be great than 0, Transaction cancelled !") return -1 user.card.card_balance += Deposit print("Deposit successful!") def withdraw(self): pass def transfer(self): pass def change_password(self): pass def lock_account(self): pass def unlock_account(self): pass def cancel_account(self): pass def remake_card(self): pass
451ed08b43cf35a88ae06fb9b94a0b4e43c83c98
Anz131/luminarpython
/polymorphism/method overriding.py
1,785
3.90625
4
#overriding - same method name same no of args # class Parent: # def properties(self): # print("abcd") # def marry(self): # print("abc") # class Child(Parent): # def marry(self): # print("abc") # c=Child() # c.marry() # class Person: # def properties(self,name): # self.name=name # print(self.name) # def ages(self,age): # self.age=age # print(self.age) # class Student(Person): # def ages(self,age): # self.age=age # print(self.age) # c=Student() # c.ages(22) # class Person: # def properties(self,name,age): # self.name=name # self.age=age # print(self.name) # print(self.age) # class Student(Person): # def properties(self,name,age): # self.name=name # self.age=age # print(self.name,self.age) # f=open("student","r") # for i in f: # data=i.rstrip("\n").split(",") # #print(data) # name=data[0] # age=data[1] # c=Student() # c.properties(name,age) # class Person: # def properties(self,name,std,dept,mark): # self.name=name # self.std=std # self.dept=dept # self.mark=mark # print(self.name) # print(self.std) # print(self.dept) # print(self.mark) # class Student(Person): # def properties(self,name,std,dept,mark): # self.name=name # self.std=std # self.dept=dept # self.mark=mark # print(self.name,self.std,self.dept,self.mark) # f=open("work","r") # for i in f: # data=i.rstrip("\n").split(",") # #print(data) # name=data[0] # std=data[1] # dept=data[2] # mark=data[3] # if(mark>"190"): # c=Student() # c.properties(name,std,dept,mark)
5053af671e27ca9b3094f57995f874f186d387e8
AstinCHOI/book_effective_python
/8_production/55_repr_for_debugging_output.py
796
3.5625
4
print('foo bar') print('%s' % 'foo bar') print(5) print('5') # >>> # foo bar # foo bar # 5 # 5 ## human readable, but type? a = '\x07' print(repr(a)) b = eval(repr(a)) assert a == b # >>> # '\x07' print(repr(5)) print(repr('5')) print('%r' % 5) print('%r' % '5') # >>> # 5 # '5' # 5 # '5' class OpaqueClass(object): def __init__(self, x, y): self.x = x self.y = y obj = OpaqueClass(1, 2) print(obj) # >>> # <__main__.OpaqueClass object at 0x1016b9cf8> class BetterClass(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return 'BetterClass(%d, %d)' % (self.x, self.y) obj = BetterClass(1, 2) print(obj) # >>> # BetterClass(1, 2) obj = OpaqueClass(4, 5) print(obj.__dict__) # >>> # {'y': 5, 'x': 4}
21cec749f446a0715e0e12a03d051833af552509
YANGYANTEST/Python-development
/stage one/day04/作业.py
1,236
4.1875
4
''' 第一题: num_list = [[1,2],[‘tom’,’jim’],(3,4),[‘ben’]] 1. 在’ben’后面添加’kity’ 2. 获取包含’ben’的list的元素 3. 把’jim’修改为’lucy’ 4. 尝试修改3为5,看看 5. 把[6,7]添加到[‘tom’,’jim’]中作为第三个元素 6.把num_list切片操作: num_list[-1::-1] 第二题: numbers = [1,3,5,7,8,25,4,20,29]; 1.对list所有的元素按从小到大的顺序排序 2.求list所有元素之和 3.将所有元素倒序排列 ''' num_list = [[1,2],['tom','jim'],(3,4),['ben']] num_list.append('kity')#在’ben’后面添加’kity’ print(num_list) print(num_list[3])#获取包含’ben’的list的元素 num_list[1][1]='lucy'#把’jim’修改为’lucy’ print(num_list) print(num_list) num_list[1].append([6,7]) print(num_list) num_list[-1::-1] print(num_list) ''' numbers = [1,3,5,7,8,25,4,20,29]; 1.对list所有的元素按从小到大的顺序排序 2.求list所有元素之和 3.将所有元素倒序排列 ''' numbers=[1,3,5,7,8,25,4,20,29] numbers.sort(reverse=False)#对list所有的元素按从小到大的顺序排序 print(numbers) print(sum(numbers))#求list所有元素之和 numbers.reverse()#将所有元素倒序排列 print(numbers)
fc38d0286381ac904103b33b8be811a376b79e2e
KenRishabh/BtechCSE
/function_in_function.py
575
4
4
def greater(a,b): if a>b: return a return b def greatest(a,b,c): if a>b and a>c: return a elif b>a and b>c: return b else: return c #function inside function #greater(a,b)--------> a or b #greater (a or b, c)------->greatest # # def new_greatest(a,b,c): # # bigger = greater(a,b) # # return greater(bigger, c) # # print(new_greatest(100,2000,400)) def new_greatest(a,b,c): return greater(greater(a,b), c) print(new_greatest(100,2000,400)) #kiss----> keep it simple stupid
ac7295fde7939e476733f7aa05ee1e7e67f90217
yameenjavaid/bigdata2019
/01. Jump to python/Chap05/174_class_calculator.py
689
4.09375
4
class Calculator : # 사용자 정의 클래스 def __init__(self): # 생성자(Constructor) : 객체 생성시 최초로 수행되는 함수 self로 인해 일반 함수와 비교 self.result = 0 # Class의 멤버 변수 def adder(self, num): # 멤버 함수(Member Function) print("[%d]값을 입력 받았습니다." %num) self.result += num+100 self.num1 = 100 # 멤버변수로 등록은 가능하나 가독성은 떨어진다. return self.result cal1 = Calculator() cal2 = Calculator() cal3 = Calculator() print(cal1.adder(3)) print(cal1.adder(4)) print(cal2.adder(3)) print(cal2.adder(7)) print(cal3.adder(2)) print(cal3.adder(6))
7f26fce622b7ec0bba23aa048797558ddfac6155
Terencetang11/Sudoku_Puzzle
/Sudoku_Algorithm.py
4,439
4
4
# Author: Terence Tang # Class: CS325 Analysis of Algorithms # Assignment: Portfolio Project - Sudoku Puzzle Game # Date: 3/8/2021 # Description: Algorithms for checking the validity of a sudoku solution / certificate and for deriving a solution for # a given instance of sudoku. Checking the validity of a provided certificate runs in O(n^2) and # algorithm for deriving a solution to the sudoku uses bruteforce backtracking. # # Resources used include the following: # https://en.wikipedia.org/wiki/Sudoku_solving_algorithms # https://arxiv.org/pdf/cs/0507053.pdf # https://stackoverflow.com/questions/65159024/why-this-sudoku-solver-return-same-board-without-solving-anything def check_solution(board): """ Method for verifying if a provided solution/certificate is a valid solution for the sudoku puzzle. """ # initialize data structures for checking rows, columns and segments row_check = [[0 for n in range(9)] for m in range(9)] column_check = [[0 for n in range(9)] for m in range(9)] segment_check = [[0 for n in range(9)] for m in range(9)] # scans by row and column for row in range(len(board)): for col in range(len(board[row])): num = board[row][col] - 1 segment = int(col / 3) + int(row / 3) * 3 # derives which segment current square resides in # updates counts for an instance of a number by it's row, column and segment if num >= 0: row_check[row][num] = row_check[row][num] + 1 column_check[col][num] = column_check[col][num] + 1 segment_check[segment][num] = segment_check[segment][num] + 1 # if the count of any number is greater than 1, it has been repeated; thus returning not solved if row_check[row][num] > 1 or column_check[col][num] > 1 or segment_check[segment][num] > 1: print(row, col) return "Not solved, try again!" # if no repeats encountered, returns solved return "Solved!" def solve_sudoku(board): """ Wrapper method for calling the recursive backtracking method to solve the sudoku puzzle. Also copies the puzzle board over to retain fidelity of the original puzzle. """ solution_board = [] for row in board: solution_board.append(row[:]) solve_sudoku_recursive(solution_board) return solution_board # returns solution def solve_sudoku_recursive(board): """ Bruteforce backtracking algorithm for deriving a solution to a sudoku puzzle. For each empty square, checks if any entry from 1 to 9 is valid, attempts that entry and then recursively checks the next square. If solution found to be invalid, back tracks up stack and removes original selection. """ # for each next empty square for row in range(9): for col in range(9): if board[row][col] == 0: # for each valid entry for input in range(1, 10): if check_valid_move(board, row, col, input): # try entry and recursively call down, if solution found, returns True back up stack board[row][col] = input if solve_sudoku_recursive(board): return True # if solution not valid, undoes current square input to allow backtracking to previous square board[row][col] = 0 # if no other valid entries available returns false and enables back tracking return False # if sudoku has been filled out, then return True return True def check_valid_move(board, row, col, input): """ Method for determining if a specific input is allowed at a specific square. Returns false if invalid input, returns True if valid input. """ # checks for duplicates in row and column for i in range(9): if board[row][i] == input or board[i][col] == input: return False # checks for duplicates in segment (3x3 square) seg_x = int(col / 3) * 3 seg_y = int(row / 3) * 3 for x in range(3): for y in range(3): if board[seg_y + y][seg_x + x] == input: return False # if no dupes encountered, returns True return True def main(): pass if __name__ == "__main__": main()
3a9eaf40139bfeecb7c286683c50c7874a2229c8
MarleneDraganov/teste
/ex048.py
148
3.828125
4
soma = 0 for n in range(1, 501, 2): if n % 3 == 0: soma = soma + n print('A soma de todos os valores solicitados foi {}'.format(soma))
82ad980798802ecf4c357da824a8989da1caa4fd
DomWeldon/SecretSanta
/nice.py
708
4.28125
4
"""The Nice Way This way simply shuffles the list of people and then treats them as a circle and produces a Hamiltonian path by assigning each person the next person in the cycle. Sequence approach means it works for an odd number of people. """ from itertools import cycle from random import sample # remember shuffle is in place from christmas import merry_christmas, EVERYONE, secret_santa # 🎅 num_people = len(EVERYONE) # 🎅 Santa Says Hello merry_christmas() secret_santa() # Let's make a graph... ss = cycle(list(sample(EVERYONE, k=num_people))) i, prev = 0, next(ss) while i < num_people: current = next(ss) print(f"{prev} gives a 🎁 to {current}") i, prev = i + 1, current
363f22244544473070d7807e6acdb01528d8d37f
Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne
/Exercises-for Teach Your Kids to Code by Bryson Payne/Color_spiral_input.py
706
4.65625
5
# Color spiral input import turtle t=turtle.Pen() turtle.bgcolor("black") # Set up a list of any 8 color names colors=["red", "green", "blue", "yellow", "orange", "pink", "white", "purple"] #Ask the user for the number of sides, betwen 1 and 8, with default of 4 sides=8 # Draw a colorful spiral with the user-specified number of sides for x in range(360): t.pencolor(colors[x%sides]) # Only use the right number of colors t.forward(x*3/sides+x) # Change the size to match the number of sides t.left(360/sides+1) # Turn 360 degrees / number of sides, plus 2 t.width(x*sides/200) # Make the pen larger as it goes outward
cabc250d21bdefbf18f1aaa5731c48e1191d7de4
Rasenku/LeetCodeProblems
/fifthLargest.py
244
4.15625
4
# In a list, return the fifth largest problem nums = [2, 3, 76, 1, 34, 98, 45, 2, 8] def fifthLargest(nums): """ Returns the fifth largest number in a array of n numbers """ nums.sort() return nums[-5] fifthLargest(nums)
f3ec8410aeaac7b85940c816d60b49de95bea011
jvaquino7/trabalho-extra
/dificil.py
406
3.8125
4
conta = float(input("INFORME SUA CONTA:")) senha = float(input("INFORME SUA SENHA:")) saque = float(input("INFORME SEU SAQUE:")) if conta == 999 and senha ==456: print("BEM VINDO") else: print("CONTA E/OU SENHA INCORRETAS") dinheiro = 100 - saque if saque > 100: print("SALDO INSUFICIENTE") else: print("SEU SALDO E DE:","R$", dinheiro,"REAIS") print("VOCE TIROU:","R$", saque, "REAIS")
0c3546a3fdcaa1da9ff8ff893aa24bb3cfa9d2c5
privateOmega/coding101
/geeksforgeeks/palindrome-count.py
427
3.828125
4
def palindromeCount(list_a): count = 0 for num in list_a: temp = num rev = 0 while temp > 0: rev = rev * 10 + temp % 10 temp = temp / 10 if num == rev: count = count + 1 print('Total number of palindromes in list', count) def main(): list_a = [10, 121, 133, 155, 141, 152] palindromeCount(list_a) if __name__ == '__main__': main()
bc88f18a5b0595012d81106e38ce5a9b39bea480
fyujn/project1ML
/scripts/ml_methods.py
8,377
3.8125
4
# Useful starting lines import numpy as np import matplotlib.pyplot as plt import importlib from proj1_helpers import * #initial_w is the initial weight vector #gamma is the step-size #max_iters is the number of steps to run #lambda_ is always the regularization parameter #from scripts.proj1_helpers import * def handleOutliers(tx): # think of mean or median meansPerColumn = np.mean(tx, axis=0) for i in range(30): for j in range(250000): if tx[j][i] == -999:5 tx[j][i] = meansPerColumn[i] return tx def linear_regresssion_GD_mse(y, tx, initial_w, max_itters, gamma): print("calc Linear regression using gradient descent") """Gradient descent algorithm.""" # Define parameters to store w and loss losses = [] w = initial_w for n_iter in range(max_itters): # *************************************************** # compute gradient and loss # *************************************************** loss = compute_loss_mse(y, tx, w) gradient = compute_gradient_mse(y, tx, w) print(gradient) # *************************************************** # update w by gradient # *************************************************** w = w + gamma*gradient print("Gradient Descent({bi}/{ti}): loss={l},w={w}".format( bi=n_iter, ti=max_itters - 1, l=loss, w=w)) return losses, w def least_squares_GD(y, tx, w, max_itters, gamma):#giving 0.745 acc print("calc Linear regression using gradient descent") """Gradient descent algorithm.""" # Define parameters to store w and loss for n_iter in range(max_itters): # *************************************************** # compute gradient and loss # *************************************************** gradient = least_squares(y,tx) # *************************************************** # update w by gradient # *************************************************** w = w + gamma*gradient print(compute_loss_rmse(y,tx,w)) print(compute_loss_mse(y,tx,w)) print("Gradient Descent({bi}/{ti}): w={w}".format(bi=n_iter, ti=max_itters - 1, w=w)) return w def least_squares_SGD(y,tx,w,max_iters,gamma): #giving 0.541 0.401 with 1000 iterations gamma = 0.2 print("Calc Linear regression using stochastic gradient descent") """Stochastic gradient descent algorithm.""" # *************************************************** # implement stochastic gradient descent. # *************************************************** for minibatch_y, minibatch_tx in batch_iter(y, tx, 32): # Define parameters to store w and loss for n_iter in range(max_iters): # *************************************************** # compute gradient # *************************************************** gradient = least_squares(minibatch_y, minibatch_tx) # *************************************************** # update w by gradient # *************************************************** w = w + gamma * gradient print("Gradient Descent({bi}/{ti}): w={w}".format(bi=n_iter, ti=max_iters - 1, w=w)) return w def least_squares(y,tx): #print("Calc Least squares regression using normal equations") return np.linalg.inv(np.transpose(tx)@tx)@np.transpose(tx)@y def ridge_regression(y,tx,lambda_): #print("Ridge regression using normal equations") """implement ridge regression.""" # *************************************************** # ridge regression # *************************************************** l_= lambda_*2*30 innerSum = np.linalg.inv(np.dot(np.transpose(tx), tx) + np.dot(l_, np.identity(30))) sumX = np.dot(innerSum,np.transpose(tx)) w = np.dot(sumX, y) return w def logistic_regression(y,tx,w, max_itters,gamma): print("Logistic regression using gradient descent or SGD") # "Logistic regression is the appropriate regression analysis to conduct when theession produces a logistic curve, which is limited to values between 0 and 1. Logistic regression is similar to a linear regression, but the curve is constructed using the natural logarithm of the “odds” of the target variable, rather than the probab dependent variable is dichotomous (binary)." - from the Internet # https://towardsdatascience.com/building-a-logistic-regression-in-python-301d27367c24 """ ypred = predict_labels(w,tx) sigmoid = 1/(1+np.exp(-ypred)) hoch = np.transpose(w)@np.transpose(tx) print(hoch) po = np.power(sigmoid,-hoch) print(po) mü = 1/(1+po) print("MÜ") print(mü) s = np.diag(mü) w = np.linalg.inv(np.transpose(tx)@s@tx)@np.transpose(tx)@(s@(tx@w+predict_labels(w,tx)-mü)) """ ypred = predict_labels(w,tx) sigmoid = 1/(1+np.exp(-y)) for n_iter in range(max_itters): # *************************************************** # compute gradient and loss # *************************************************** print("Step0") z = np.dot(tx,w) print("Step1") a = np.linalg.inv(np.dot(z, np.transpose(tx))) print("Step2") b = a@np.transpose(tx) print("Step3") c = b @ w print("Step 4") d = d@y gradient = d # *************************************************** # update w by gradient # *************************************************** w = w + gamma*gradient return w for i in range(max_itters): pediction = np.dot(w*tx) activationFunction = sigmoid(pediction) # make between 0-1 print(activationFunction) def reg_logisitc_regression(y,tx,lambda_,initial_w,max_iters,gamma): print("Regularized logistic regression using gradient descent or SGD") def run_ridge(y,tx): """ 1.0120632391308362 Lambda 32 1.0117232823257554 INDEX 6 (0.06) --> Best so far 1.0110984126186728 INDEX 11 (lambda = 0.55) --> new best 1.0110746757782039 INDEX 23 (lambda = 0.053) """ losses = [] ws = [] for i in np.arange(0.5,0.6,0.01): w_new = ridge_regression(y,tx,i) loss = compute_loss_rmse(y, tx, w_new) losses.append(loss) ws.append(w_new) print(losses) print(" LOSS RMSE ") print(compute_loss_rmse(y,tx,w_new)) minIndex = losses.index(min(losses)) print("WEIGHT MATRIX " + str(ws[minIndex])) print("INDEX " + str(minIndex)) plt.plot(losses) plt.show() return ws[minIndex] def run(): print("Load data ...") DATA_TRAIN_PATH = '../data/train.csv' y, tx, ids = load_csv_data(DATA_TRAIN_PATH) w = np.zeros(30) print("Handle Outliers per mean ...") handleOutliers(tx) print("Run Method ...") #w_new = least_squares_GD(y, tx, w, 200, 1) #w_new = least_squares_SGD(y, tx, w, 100000, 0.01) #w_new = logistic_regression(y,tx,w,1000,0.2) w_new = run_ridge(y, tx); DATA_TEST_PATH = '../data/test.csv' print("Output Data ...") #execute file y_test, tx_test, ids_test = load_csv_data(DATA_TEST_PATH) y_pred = predict_labels(w_new, tx_test) create_csv_submission(ids_test, y_pred, "fyujn") w_compare = [-2.80368247e+01,5.39471822e-01,-1.00522284e+01,1.13621369e+01,4.25777258e+02,5.05303694e+02,4.25229617e+02,-4.92012404e-01,3.50325763e+00,3.41860458e+01,2.13402302e-02,9.88750534e-02,4.25298113e+02,-5.73547481e+00,7.63626536e-03,1.38542432e-02,-1.44032246e+00,1.02196190e-02,-1.20750185e-02,3.44476629e+00,-3.26639200e-03,2.92616549e+01,5.18460080e-01,2.19436118e+02,2.03730018e+02,2.03732874e+02,4.43313020e+02,4.25186123e+02,4.25193362e+02,4.13618429e+01] w_0745 = [1.60583532e-03,-1.44064742e-01,-1.21068034e-01,-1.09519870e-02-3.87743154e-01,9.46936127e-03,-5.20717046e-01,6.50207171e+00-7.61470193e-04,-5.45449842e+01,-4.42440406e+00,1.90157268e+00,1.28065548e+00,5.47101777e+01,-6.63603993e-03,-1.90865700e-02,5.48053124e+01,-1.06832978e-02,1.94699716e-02,7.38450105e-02,7.08974899e-03,-1.08668920e-02,-6.60896070e+00,-2.81600995e-02,1.66286578e-02,2.04234543e-02,-3.36094832e-02,-1.16732964e-01-2.22175995e-01,5.45541828e+01] run()
a5dcb388425e44e4d981b9410d4ddcee8e57522a
ElliottBarbeau/Leetcode
/Problems/triplet sum.py
859
4
4
def search_triplets(arr): triplets = [] arr.sort() for i in range(len(arr) - 2): if arr[i] == arr[i+1]: continue left, right = i + 1, len(arr) - 1 while left < right: sum = arr[i] + arr[left] + arr[right] if sum == 0: triplets.append([arr[i], arr[left], arr[right]]) left += 1 right -= 1 else: if sum < 0: while arr[left] == arr[left+1]: left += 1 left += 1 else: while arr[right] == arr[right - 1]: right -= 1 right -= 1 return triplets def main(): print(search_triplets([-3, 0, 1, 2, -1, 1, -2])) print(search_triplets([-5, 2, -1, -2, 3])) main()
994f7083edc55bfc0b03405937f60cb028ed11f8
xvicxpx/Stat-535-Project
/Visualization.py
545
3.734375
4
#Visualization """ Takes a dictionary of lists Creates a new Dictionary with the same keys but values are the average of the lists of the original Then plots them in a bar plot After examination we will make graphs of the best and worst performances """ import matplotlib.pyplot as plt import Combinations as c rates_dict = {} testDict = c.combinations(N=100, n=10)[0] plt.bar(range(len(testDict)), list(testDict.values()), align='center') plt.xticks(range(len(testDict)), list(testDict.keys()), rotation = 'vertical') plt.ylim([0.4 , 0.6])
4025f531f13e511d2e8b49c857c084ffb28e3fca
huioo/SPEC-py2.7-tornado4.5
/utils/probability.py
1,188
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 概率方面的通用工具 """ import random def is_win_prize1(win=0.5): """ 按几率中奖,返回结果是否中奖 :param win: 中奖几率,取值范围0~1 :return: True / False """ result = False percent = random.random() if percent < win: result = True return result def is_win_prize2(win=0.5, percent=0.5): """ 克扣中奖 :param win: 中奖几率 :param percent: 中奖克扣百分比 :return: True / False """ result = False if is_win_prize1(win): return is_win_prize1(1-percent) return result def is_win_prize3(rule={}, precision=100): """ 多种奖品,按概率抽取其中一个 :param rule: 奖品中奖概率规则 prize_name/win_percent 字典映射 :param precision: 抽奖概率精度,配合中奖百分比,如0.01/100,0.281/1000 :return: prize_name 奖品名 """ pond = [] for k, v in rule.iteritems(): for _ in xrange(int(v * precision)): pond.append(k) return random.choice(pond) if __name__ == '__main__': print is_win_prize3({'a':0.3,'b':0.5,'c':0.2})
de93927a48d5b1ab4724615840c895b41b8737d5
Neocryan/Reinforcement_Learning
/Mountain-Car/agent.py
11,128
3.53125
4
__author__ = 'Xiaoyu' import numpy as np """ Contains the definition of the agent that will run in an environment. """ class r0: def __init__(self): self._w = np.random.random([2, 3]) self._olds = np.random.random([2, 1]) self._gamma = 0.05 self._alpha = 0.01 self._lambda = 0.01 self._z = np.random.random([2, 1]) self._s = np.random.random([2, 1]) self._oldr = -1 self._range = 150 def reset(self, x_range): # self._w /= 1e10000 self._range = abs(x_range[1] - x_range[0]) pass def act(self, observation): """Acts given an observation of the environment. Takes as argument an observation of the current state, and returns the chosen action. observation = (x, vx) """ self._s = np.array(observation).reshape(2, 1) qs = np.dot(self._s.T, self._w)[0] return np.argmax(qs) - 1 def reward(self, observation, action, reward): """Receive a reward for performing given action on given observation. This is where your agent can learn. """ self._s = np.array(observation).reshape(2, 1) self._z = self._gamma * self._lambda * self._z + self._olds theta = self._oldr + self._gamma * np.dot(self._s.T, self._w) - np.dot(self._olds.T, self._w) self._w += self._alpha * np.dot(self._z, theta) self._olds = self._s self._oldr = reward print(self._w) def kernel(s, kernel): phi = np.exp(-(s[0] - kernel[:, 0]) ** 2) * np.exp(-(s[1] - kernel[:, 1]) ** 2) return phi class SemiGradientTdLambda: def __init__(self): self.p = 2 self.k = 2 self._kernel = np.zeros([(self.p + 1) * (self.k + 1), 2]) self._phi = None self._w = np.zeros([3, (self.p + 1) * (self.k + 1)]) self._olds = None self._olda = 0 self._oldr = -1 self._oldphi = None self.z = 0 self._gamma = 0.5 self._lambda = 5 self._alpha = 0.5 self._dmin = 150 self.e = 0.05 self._t = 0 def reset(self, x_range): self._dmin = -x_range[0] for x in range((self.p + 1) * (self.k + 1)): i = x // (self.k + 1) j = x - (self.k + 1) * i self._kernel[x] = [i * (self._dmin / self.p) - self._dmin, j * (40 / self.k) - 20] # def kernel(self,s): # phi = np.exp(-(s[0] - self._kernel[:, 0]) ** 2) * np.exp(-(s[1] - self._kernel[:, 1]) ** 2) # return phi def act(self, observation): if np.random.uniform() > self.e: q = self._w.dot(kernel(observation, self._kernel)) return np.argmax(q) - 1 else: return np.random.choice([-1, 0, 1]) def reward(self, observation, action, reward): # print(action) if self._olds is not None: self.z = self._gamma * self._lambda * self.z + kernel(self._olds, self._kernel) theta = reward + self._gamma * self._w[self._olda + 1].dot(kernel(observation, self._kernel)) - self._w[ self._olda + 1].dot(kernel(self._olds, self._kernel)) # theta = reward + self._gamma * self._w[self._olda+1].dot(kernel(observation,self._kernel)) - self._w[self._olda+1].dot(kernel(self._olds,self._kernel)) self._w[self._olda] += self._alpha * theta * self.z else: self._t += 1 if self._t > 1: print(self._t) self._olda = action self._oldr = reward self._olds = observation class OnlineTdLambda: def __init__(self): self.p = 2 self.k = 2 self._kernel = np.zeros([(self.p + 1) * (self.k + 1), 2]) self._phi = None self._w = np.zeros([3, (self.p + 1) * (self.k + 1)]) self._olds = None self.olda = None self._oldr = -1 self._oldphi = None self.z = np.zeros((self.p + 1) * (self.k + 1)) self._gamma = 0.5 self._lambda = 4 self._alpha = 0.5 self._dmin = 150 self.e = 0.05 self._t = 0 self.oldv = None self.oldx = None def reset(self, x_range): self._dmin = -x_range[0] for x in range((self.p + 1) * (self.k + 1)): i = x // (self.k + 1) j = x - (self.k + 1) * i self._kernel[x] = [i * (self._dmin / self.p) - self._dmin, j * (40 / self.k) - 20] def act(self, observation): if np.random.uniform() > self.e: q = self._w.dot(kernel(observation, self._kernel)) print(q) return np.random.choice(np.where(q == q.max())[0]) - 1 else: return np.random.choice([-1, 0, 1]) def reward(self, observation, action, reward): # print(action) x_prime = kernel(observation, self._kernel) try: v_prime = self._w[self.olda + 1].dot(x_prime) except: v_prime = 0 if self.olda is not None: v = self._w[self.olda+1].dot(self.oldx) delta = reward + self._gamma *v_prime - v self.z = self._gamma * self._lambda * self.z + (1 - self._alpha * self._gamma *self._lambda * self.z.dot(self.oldx))*(self.oldx) self._w[self.olda+1] += self._alpha * (delta + v -self.oldv) * self.z - self._alpha* (v - self.oldv)* self.oldx else: self._t+=1 if self._t >1: print(self._t) print(self.oldv) self.olda = action self.oldv = v_prime self.oldx = x_prime class Qlearning: def __init__(self): self.p = 3 self.k = 3 self._kernel = np.zeros([(self.p + 1) * (self.k + 1), 2]) self._w0 = np.zeros((self.p + 1) * (self.k + 1)) self._w1 = np.zeros((self.p + 1) * (self.k + 1)) self._w2 = np.zeros((self.p + 1) * (self.k + 1)) self._olds = None self.olda = None self._oldr = -0.1 self._gamma = 0.5 self._lambda = 0.5 self._alpha = 0.001 self._dmin = 150 self.e = 0.05 self._t = 0 self.oldv = None self.thisKernel = None self.rbar = 0 self.s = None self.lastKernel = None def reset(self, x_range): self._dmin = -x_range[0] for x in range((self.p + 1) * (self.k + 1)): i = x // (self.k + 1) j = x - (self.k + 1) * i self._kernel[x] = [i * (self._dmin / self.p) - self._dmin, j * (40 / self.k) - 20] def act(self, observation): if np.random.uniform() > self.e: self.thisKernel = kernel(observation,self._kernel) q = np.array([self._w0.dot(self.thisKernel),self._w1.dot(self.thisKernel),self._w2.dot(self.thisKernel)]) # print(q) return np.random.choice(np.where(q == q.max())[0]) - 1 else: return np.random.choice([-1, 0, 1]) def reward(self, observation, action, reward): # print(action) if action == -1: self.s = self.thisKernel.dot(self._w0) if action == 0: self.s = self.thisKernel.dot(self._w1) if action == 1: self.s = self.thisKernel.dot(self._w2) if self.olda is not None: delta = self._oldr - self.rbar + self.s - self._olds self.rbar +=self._gamma * delta if self.olda == -1: self._w0 += self._alpha * delta *self.lastKernel if self.olda == 0: self._w1 += self._alpha * delta *self.lastKernel if self.olda == 1: self._w2 += self._alpha * delta *self.lastKernel self._olds = self.s self.olda = action self._oldr = reward self.lastKernel = self.thisKernel # pass class soso: def __init__(self): self.ds = {} self.alpha = 0.3 self.gamma = 0.3 self.olda = None self.olds = None self.oldr = None self.thiss = None def reset(self, x_range): self._dmin = -x_range[0] def act(self, observation): if abs(observation[0])> self._dmin/2: x = 1 else: x = 0 if observation[1]>0: v = 2 elif observation[1]<0: v = 1 else: v = 0 self.thiss = (x,v) # self.thiss = v if self.thiss in self.ds.keys(): return np.random.choice(np.where(self.ds[self.thiss] == self.ds[self.thiss].max())[0]) -1 else: return np.random.choice([-1,0,1]) def reward(self, observation, action, reward): if self.thiss not in self.ds.keys(): self.ds[self.thiss] = np.ones(3) if self.olda is not None: self.ds[self.olds][self.olda + 1] += self.alpha * ( self.oldr + self.gamma * self.ds[self.thiss].max() - self.ds[self.olds][self.olda + 1]) self.olda = action self.oldr = reward self.olds = self.thiss # print(self.ds) class TdLambda: def __init__(self): self.p = 149 #x self.k = 49 #v self._kernel = np.zeros([(self.p + 1) * (self.k + 1), 2]) self._w = np.zeros([3,(self.p + 1) * (self.k + 1)]) self._lastphi = None self._thisphi = None self._lasta = 0 self._lastr = -0.1 self._lastq = np.zeros(3) self._thisq = np.zeros(3) self._gamma = 0.9 self._lambda = 0.1 self._alpha = 0.1 self._dmin = 150 self.e = 0.0 self._t = 0 self.eg = np.zeros(self._w.shape) def reset(self, x_range,a=0.3,b=0.5,c=0.0): self._dmin = -x_range[0] self._alpha = a self._lambda = b self._gamma = c for x in range((self.p + 1) * (self.k + 1)): i = x // (self.k + 1) j = x - (self.k + 1) * i self._kernel[x] = [i * (self._dmin / self.p) - self._dmin, j * (40 / self.k) - 20] def act(self, observation): self._thisphi = kernel(observation, self._kernel) if np.random.uniform() > 0.01: self._thisq = self._w.dot(self._thisphi) return np.random.choice(np.where(self._thisq == self._thisq.max())[0]) - 1 else: return np.random.choice([-1, 0, 1]) def reward(self, observation, action, reward): if self._lastphi is not None: sigma = self._lastr +self._gamma * np.max(self._thisq) - self._lastq[self._lasta +1] eg = np.zeros(self._w.shape) eg[self._lasta+1] = self._lastphi eg[np.argmax(self._thisq)] -= self._gamma * self._thisphi if np.argmax(self._thisq) == self._lasta + 1: self.eg = self._gamma * self._lambda * self.eg + eg else: self.eg = eg self._w += self._alpha * sigma *self.eg self._lasta = action self._lastphi = self._thisphi self._lastq = self._thisq self._lastr = reward Agent = TdLambda
4efcf81ba322e6dad3356ad42fb7453b775841c9
hnzhangbinghui/selenium
/26、冒泡排序.py
2,315
4.125
4
''' 概念:冒泡排序(Bubble Sort),是一种计算机领域的较简单的排序算法。 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。''' '''算法原理: 冒泡排序算法的运作如下:(从后往前) >比较相邻的元素。如果第一个比第二个大,就交换他们两个。 >对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。 >针对所有的元素重复以上的步骤,除了最后一个。 >持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较''' #交=10 # 换两个数 #coding=utf-8 a=10 b=20 #设置一个临时变量c c=a a=b b=c #python里面交换还有更简单的 #a,b=b,a print('a=',a,'b=',b) #遍历比较相邻的数 #coding=utf-8 list=[1,333,10,7,54,78,9,24,67] s=range(len(list)-1) for i in s: for j in range(len(list)-1): #如果前面的数大就下沉 if list[j]>list[j+1]: list[j],list[j+1]=list[j+1],list[j] print(j) print(list) print(list) #在python里面的排序,可以通过sort()函数搞定 list1=[1,2,4,6,7,88,97,654,45657] list1.sort() print(list1) '''random() 方法返回随机生成的一个实数,它在[0,1)范围内。 注意:random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。 ''' import random print(random.random()) print(random.random()) for i in range(6): print(random.randint(1,33)) print(random.randint(1,16)) #生成1到16之间的整数型随机数 print(random.random()) #生成0到1之间的随机浮点数 print(random.uniform(1.1,5.6)) #生成他们之间的随机浮点数,区间可以不是整数 print(random.choice('zhangbinghui')) #从序列中随机选取一个元素 print(random.randrange(1,100,2)) #生成1到100的间隔为2的随机整数 a=[1,3,6,8,33,45] random.shuffle(a) #随机排序列表 print(a)
37278111378e572d1a2dc2c078efabe27cef97e3
Aaron1011/code_challenges
/keypad_2.py
1,435
3.6875
4
def load_words(): wordfile = open('/usr/share/dict/american-english', 'r') lines = wordfile.read().split('\n') wordfile.close() return lines def make_trie(words): root = dict() for word in words: curr_dict = root for letter in word: curr_dict = curr_dict.setdefault(letter, {}) return root def get_letters(number): numbers = {'2': ['a','b','c'], '3': ['d','e','f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} return numbers.get(number, []) count = 0 def keypad_words(number, trie, words=[""]): global count if type(number) == int: number = str(number) if number == "": return words words_2 = [] for w in words: for letter in get_letters(number[0]): curr_dict = trie for l in letter + w: try: curr_dict = curr_dict.get(l) except AttributeError: break if curr_dict != None: words_2.append(w + letter) count += 1 #words = [w + letter for w in words for letter in get_letters(number[0])] return keypad_words(number[1:], trie, words=words_2) def find_real_words(words, WORDLIST=load_words()): return [word for word in words if word in WORDLIST]
e47bc08a8b5ca8a0f6d67a0006baab297c8f8845
csuvis/MCGS
/utils/load_graph.py
1,057
3.921875
4
import csv import networkx as nx def loadGraph(graph_name): """Load the graph file and return the graph object. Parameters ---------- graph_name : string The name of the graph. Returns ------- G : Graph object The graph data object with nodes, edges and other graph attributes. Notes ----- The parameter graph_name is the name of graph, and it does not contain any suffix or extra information. For example, we can load the graph "Cpan" by using loadGraph("Cpan") instead of loadGraph("Cpan.csv"). """ with open('./dataset/{}_node.csv'.format(graph_name), 'r', encoding='utf-8') as fp: reader = csv.reader(fp) nodes = list(int(_[0]) for _ in reader) with open('./dataset/{}_edge.csv'.format(graph_name), 'r', encoding='utf-8') as fp: reader = csv.reader(fp) edges = list((int(_[0]), int(_[1])) for _ in reader if _[0] != _[1]) G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) return G
a49b2b65962fc5caf3518a89636d1b0d725837f3
SaiPranay-tula/DataStructures
/PY/ABS.py
338
3.640625
4
from abc import ABC,abstractmethod class Interface(ABC): @abstractmethod def abs_method(self): pass @staticmethod def absmethod(): print("abs in interface") class NEW_CLASS(Interface): @staticmethod def abs_method(): print("abs in class") a=NEW_CLASS() a.abs_method() a.absmethod()
bdc7784bdf069d1374fad0e7f8e8872f27a33893
luoshao23/Data_Structure_and_Algorithm_in_Python
/ch04_Recursion/bisearch.py
480
3.921875
4
def binary_search(data, target, low, high): if low > high: return False mid = (low + high) // 2 if target == data[mid]: return mid elif target < data[mid]: return binary_search(data, target, low, mid - 1) else: return binary_search(data, target, mid + 1, high) if __name__ == "__main__": lst = [3, 4, 8, 12, 42, 56, 88] print(binary_search(lst, 12, 0, len(lst) - 1)) print(binary_search(lst, 20, 0, len(lst) - 1))
48299963bcbd1aaed290c6b62a6d8a4a60c9bacc
TehyaStockman/TextMining
/text_processing.py
589
3.734375
4
def processing_file(filename): """processing initial file, stripping out guttenberg extra stuff""" fp = open(filename) all_text = fp.read() index_start = all_text.find('CONTENTS') index_end = all_text.find('End of Project Gutenberg') content = all_text[index_start: index_end] new_story = [] for line in content.split('\n'): if any_lowercase(line): new_story.append(line) story = ''.join(new_story) return story def any_lowercase(s): flag = False for c in s: flag = flag or c.islower() return flag processing_file('grimm_fairytales.txt')
67e0e47dd758dae04d8613916ad890c0d3e9b3cb
smartinsert/CodingProblem
/coin_change.py
626
3.859375
4
""" Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter. """ from typing import List def minimum_number_of_coins(coins: List[int], amount: int) -> int: dp = [amount + 1 for _ in range(amount + 1)] dp[0] = 0 for i in range(amount + 1): for j in range(len(coins)): if coins[j] <= i: dp[i] = min(dp[i], 1 + dp[i - coins[j]]) return dp[amount] if __name__ == '__main__': print(minimum_number_of_coins([1, 2, 5], 11))
0b398b593a907e3f8a190817e2ea83c8e1628ada
Sequd/python
/Examples/test.py
670
3.71875
4
import re def test_function(): """I print 'Hello, world!'""" print("Hello, world!") maxValue = 250 startPoint = maxValue / 4 for i in range(0, maxValue, 1): currentPoint = i / 2 + startPoint print('{0} = {1}'.format(i, currentPoint)) test_function() def t1(data: str) -> bool: if len(data) < 10: return False digital = 0 upper = 0 lower = 0 for c in data: if str.isdigit(c): digital += 1; if str.isupper(c): upper += 1; if str.islower(c): lower += 1; if digital > 0 and upper > 0 and lower > 0: return True return False
1c91f69ad179d216ead3812e4d604ab0c91487d5
jincheol5/2021_python
/8주차/8-2.py
166
4.09375
4
def multiply(n1,n2): s=n1*n2 return s def divide(n1,n2): s=n1/n2 return s n1 = int(input()) n2 = int(input()) print(multiply(n1, n2)) print(divide(n1, n2))
e6ee3652a054328f44c6c1b4dc352415ef1a792f
Sujan0rijal/LabOne
/LabTwo/four.py
452
4.34375
4
'''4. Given three integers, print the smallest one. (Three integers should be user input)''' integer1=int(input('enter first number:')) integer2=int(input('enter second number:')) integer3=int(input('enter third number:')) if integer1<integer3 and integer1<integer2: print(f'smallest number is {integer1}') elif integer2<integer3 and integer2<integer1: print(f'smallest number is {integer2}') else: print(f'smallest number is {integer3}')
9e7e503d01f89a0f5dd9bb45716fab9c7da2533e
KHWeng/pYthOn-Camp-Day1
/16條件判斷式 成績等第.py
371
3.859375
4
score = int(input("Enter your score Here:")) if 100>score and score>= 90:#標準寫法,通常這樣寫才過 print("Aaa") elif 90>score >= 80:#非標準寫法,可能只在蟒蛇限用 print("Bbb") elif 80>score >= 70: print("Ccc") elif 70>score >= 60: print("Ddd") elif 0<=score < 60: print("Eee") else: print("不要亂來")
5bdb2565e6376c63cf4ecda314b0730954b38ab5
juingzhou/Python
/递归.py
106
3.609375
4
def test(num): if num==1: return 1 else: return num * test(num-1) print(test(5))
25976aa1ce78f660b5ee97261b897816ff1bc408
henriqueconte/Challenges
/LeetCode/2.py
1,057
3.703125
4
# Definition for singly-linked list. from typing import final class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): firstNumberMultiplier = 1 l1Copy = l1.copy() while l1Copy.next: firstNumberMultiplier *= 10 l1Copy = l1Copy.next secondNumberMultiplier = 1 l2Copy = l2.copy() while l2Copy.next: secondNumberMultiplier *= 10 l2Copy = l2Copy.next finalValue = 0 while l1.next: finalValue += l1.val * firstNumberMultiplier l1 = l1.next firstNumberMultiplier /= 10 finalValue += l1.val while l2.next: finalValue += l2.val * secondNumberMultiplier l2 = l2.next secondNumberMultiplier /= 10 finalValue += l2.val print(finalValue) l1 = [2,4,3] l2 = [5,6,4] solution = Solution() solution.addTwoNumbers(l1, l2)
52065631b728642ef94759c67d1be84f76dbf19c
Susanta-Nayak/S
/code/main.py
837
3.71875
4
import parser import lexer def main(): # Variable to store the contents of the file content = "" with open('test.lang', 'r') as file: # reading and storing the contents of the file content = file.read() ############################ # Lexer # ############################ # Calling the lexer file Lexer class and initializing it with the source code in lex lex = lexer.Lexer(content) # Calling the tokenize method from inside the lexer instance tokens = lex.tokenize() ############################ # Parser # ############################ # Calling the parser file Parser class and initializing it with the source code parse = parser.Par(tokens) # Calling the parse method from inside the parse instance parse.parse() main()
0397fcacbc63f578e80b4eb32f740c4cef8a627c
AndreySperansky/TUITION
/_STRUCTURES/Set(Множество)/set_handle_III.py
953
4.09375
4
myset = {1.23} myset.add((1, 2, 3)) print(myset) # {1.23, (1, 2, 3)} # но с кортежем таких проблем нет print(myset | {(4, 5, 6), (1, 2, 3)}) # Объединение: то же, что и myset.union(...) #{1.23, (4, 5, 6), (1, 2, 3)} print((1, 2, 3) in myset) # Членство: выявляется по полным значениям #True print((1, 4, 3) in myset) #False L = [1, 2, 1, 3, 2, 4, 5] print(set(L)) #{1, 2, 3, 4, 5} L = list(set(L)) # Удаление повторяющихся значений print(L) #[1, 2, 3, 4, 5] T = (1, [2, 3], 4) # myset[1] = 'spam' # Ошибка: нельзя изменить сам кортеж # TypeError: object doesn’t support item assignment T[1][0] = 'spam' # Допустимо: вложенный изменяемый объект можно изменить print(T) #(1, ['spam', 3], 4)
5fa0c45670740edd31f25342cabd996a80ef1883
mryangxu/pythonPractice
/常用内建模块/itertools/practice_takewhile.py
175
3.78125
4
# 通过takewhile()可以根据条件判断截取一个有限的序列 import itertools x = itertools.count(1) y = itertools.takewhile(lambda x: x <= 10, x) print(list(y))
058a512a454014692dbaf9a5a35b9257d53d9fe7
TaiCobo/practice
/checkio/fight.py
1,049
3.84375
4
class Warrior: attack = 5 health = 50 is_alive = True class Knight(Warrior): attack = 7 def fight(unit_1, unit_2): term = 0 while unit_1.health > 0 and unit_2.health > 0: if term % 2 == 0: unit_2.health -= unit_1.attack else: unit_1.health -= unit_2.attack term += 1 if unit_1.health <= 0: unit_1.is_alive = False return False else: unit_2.is_alive = False return True if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() print(fight(chuck, bruce))# == True print(fight(dave, carl))# == False print(chuck.is_alive)# == True print(bruce.is_alive)# == False print(carl.is_alive)# == True print(dave.is_alive)# == False print(fight(carl, mark))# == False print(carl.is_alive)# == False print("Coding complete? Let's try tests!")
cb0d955fa9f2be5a83b4bb18bd0a8eb3e073b8e1
kenwilcox/compare
/compare2.7.py
1,276
3.71875
4
def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} same = set(o for o in intersect_keys if d1[o] == d2[o]) return added, removed, modified, same def what_we_care_about(modified, keys_we_care_about): keys = keys_we_care_about.split(',') return [x for x in keys if x in modified] x = dict(a=1, b=2, c="John", f="x", y=False, z=True) y = dict(a=2, b=2, c="Doe", d="y", y=True, z=True) keys_we_care_about = "a,b,c,z,q" added, removed, modified, same = dict_compare(x, y) # print "added:", added # print "removed:", removed # print "modified:", modified # print "same:", same # only keep the keys_we_care_about # print print "before", x print "after", y print print "keys we care about (even ones that don't exist)", keys_we_care_about print "keys that are different", [x for x in modified] care = what_we_care_about(modified, keys_we_care_about) print "keys we care about:", care print print "What really matters" for x in care: print x, ": was-", modified[x][0], "now-", modified[x][1] #HICCUP Isnt a Cool Client Update Program
7c8919bb63dbc49f6bec6c8e5b5a51f4670055be
fernandoeqc/calculadora_binaria
/main.py
2,816
3.671875
4
from prettytable import PrettyTable from prettytable import PLAIN_COLUMNS """ SAÍDA PARA CALCULOS SIMPLES: print("bin| 1100 + 0011 = 1111") print("dec| 12 + 3 = 15") print("hex| C + 3 = F") print("oct| 1100 + 0011 = 1111") print("asc| - + - = -") """ table = PrettyTable(["Bases", "Operador 1", "op", "Operador 2", "=", "Resultado"]) caracteres = ["+", "-", "*", "/", "|", "&"] def calculation(op1, op2, operation): result = None try: op1 = int(op1) op2 = int(op2) except ValueError: return f"Apenas operacoes com dois numeros inteiros positivos decimais" if operation == "+": result = op1 + op2 if operation == "-": result = op1 - op2 if operation == "*": result = op1 * op2 if operation == "/": if op2 == 0: return "Não é possível dividir por zero" else: result = op1 / op2 if operation == "|": result = op1 | op2 if operation == "&": result = op1 & op2 return result def findOperation(expression): global caracteres for caractere in caracteres: if caractere in expression: return caractere return False def formataBases(decimal): list_bases = [] list_bases.append("{:01x}".format(decimal)) list_bases.append("{:01d}".format(decimal)) list_bases.append("{:01o}".format(decimal)) list_bases.append("{:08b}".format(decimal)) if decimal > 32 and decimal < 126: #imprimivel list_bases.append("{:01c}".format(decimal)) else: list_bases.append("-") return list_bases while True: expression = input("Digite a expressão: \n") operation = findOperation(expression) if operation != False: hexadecimal = ['Hex'] decimal = ['Dec'] octal = ['Oct'] binary = ['Bin'] asc = ['Asc'] list_rows = [hexadecimal, decimal, octal, binary, asc] operators = expression.split(operation) result = calculation(operators[0], operators[1], operation) if type(result) == str: print(result) continue bases_op0 = formataBases(int(operators[0])) bases_op1 = formataBases(int(operators[1])) bases_res = formataBases(int(result)) for row in range(len(list_rows)): list_rows[row].append(bases_op0[row]) list_rows[row].append(operation) list_rows[row].append(bases_op1[row]) list_rows[row].append('=') list_rows[row].append(bases_res[row]) table.add_row(list_rows[row]) print(table) table.clear_rows() else: print("Não há operação a se fazer. tente uma das operações: [+ - * / | &]")
592fa886eef7bc1f231f8ec28a994091cc93a6d2
delroy2826/Programs_MasterBranch
/password_picker.py
588
3.921875
4
import random import string print("Password Picker") q =True while q: z=0 for i in range(3): common = random.choice(['a','b','c','e','z']) names = random.choice(['qa','we','as','rt']) special_char = random.choice(string.punctuation) num = str(random.randint(100,900)) a = random.choice(common) z+=1 print(z,")","PASSWORD: ",common+names+special_char+num+a) print("Do you want to exit (Yes/No)") q = input("") if q == 'yes': q == False print("Thank You") break else: q == True
3136edd16a91abcfef5a7dff23ca2d2558186f00
Yash-YC/Source-Code-Plagiarism-Detection
/gcj/gcj/188266/Simon.Rodgers/168107/0/extracted/a.py
966
3.5
4
def sum_of_squares( n, base, seen ): i = n; r = 0; while i > 0: r += (i % 10)**2; i /= 10; seen[n] = True; return convert_to_base( r, base ) def test_happy( n, base ): seen = dict(); i = convert_to_base(n, base); while i > 1 and (i not in seen): i = sum_of_squares( i, base, seen ); return (i == 1); def get_smallest( bases ): i = 2; d = False; while not d: d = True; for b in bases: d = d and test_happy( i, b ) if not d: i += 1 return i def convert_to_base( n, base ): r = 0; i = 0; while n > 0: r += (n % base) * 10**(i); n = n / base; i+=1; return r; def convert_from_base( n, base ): r = 0; i = 1; while n > 0: r += (n % 10) * base**(i-1); n = n / 10; i+=1; return r; raw = open("A-small-attempt0.in").readlines(); T = int(raw[0][:-1]); for i in xrange( T ): N = (raw[i+1][:-1]).split(" ") for x in xrange(len(N)): N[x] = int(N[x]) print "Case #" + str(i+1) + ": " + str(get_smallest( N ));
aff05634dd9df485e9c5f910ecbb09fce7475f83
MarRoar/Python-code
/05-OOP/07-property-.py
964
4.3125
4
''' property 方法的使用 ''' class Employee: def __init__(self, name, salary): self.__name = name self.__salary = salary # 如果用修饰器来写的话 # property 就相当于 getter 方法 @property def salary(self): return self.__salary # 给 salary 设置 setter 方法 @salary.setter def salary(self, salary): if 1000 < salary < 50000: self.__salary = salary else: print('请输入在1000--50000这个范围内') ''' def set_salary(self, salary): if 1000 < salary < 50000: self.__salary = salary else: print('请输入在1000--50000这个范围内') def get_salary(self): return self.__salary ''' e1 = Employee('mar', 400) ''' print(e1.get_salary()) e1.set_salary(20000) print(e1.get_salary()) ''' # 用装饰器的写法来实现 print(e1.salary) e1.salary = 2000 print(e1.salary)
286e354e9058cccf639085859bc1773bc164bdad
Elaech/Game-of-GO
/game_graphics.py
12,724
3.640625
4
import pygame import pygame.freetype """ This is the graphical module for the project Game-Of-GO It contains methods for initializing and drawing on the GUI The GUI for the project consists of mainly 3 parts: The Board for the game The Scores of the players A place to display game messages/errors """ # Variables that are used globally by this module board_size = None board_pixel_size = None line_color = None font = None score_pixel_size = None game_screen = None checker_pixel_size = None background_color = None player_colors = None upper_board_margin = None lower_board_margin = None line_thickness = None valid_color = None invalid_color = None last_hover = None checker_hover_pixel_radius = None checker_pixel_radius = None ko_pixel_length = None score_padding = None def initialise_game(options): """ Initialises all global variables that are needed for drawing anything on the user interface The values for initialisation are received from the controller It also creates the game screen on which all the elements are drawn :param options: information from the controller concerning pixels, sizes, fonts, colors given as a dictionary :return: None """ global game_screen global board_size global checker_pixel_size global board_pixel_size global line_color global font global score_pixel_size global background_color global player_colors global upper_board_margin global lower_board_margin global score_padding global line_thickness global valid_color global invalid_color global checker_hover_pixel_radius global checker_pixel_radius global ko_pixel_length board_size = options["board-size"] checker_pixel_size = options["checker-pixel-size"] board_pixel_size = (board_size + 1) * checker_pixel_size line_color = options["line-color"] invalid_color = options["invalid-color"] valid_color = options["valid-color"] score_pixel_size = options["score-pixel-size"] font = pygame.freetype.SysFont("Arial", score_pixel_size / 2) # Font will take only half of the vertical space of the score upper_board_margin = checker_pixel_size lower_board_margin = checker_pixel_size * board_size background_color = options["background-color"] player_colors = options["player-colors"] line_thickness = options["line-thickness"] score_padding = score_pixel_size / 8 # Padding used for distancing the score from other margins ko_pixel_length = checker_pixel_size / 3 # KO Checker length checker_hover_pixel_radius = checker_pixel_size / 3 checker_pixel_radius = checker_pixel_size / 2 - 2 # Checker Radius game_screen = pygame.display.set_mode((board_pixel_size, board_pixel_size + score_pixel_size)) # Initialize screen def draw_initial_board(): """ Draws the initial empty board according the already initialized piece/table/font colors and sizes :return: None """ game_screen.fill(background_color) for position in range(board_size): varying_position = (1 + position) * checker_pixel_size pygame.draw.line(game_screen, line_color, (varying_position, upper_board_margin), (varying_position, lower_board_margin), line_thickness) pygame.draw.line(game_screen, line_color, (upper_board_margin, varying_position), (lower_board_margin, varying_position), line_thickness) pygame.display.update() def draw_scores(player1_score, player2_score): """ Draws the score part of the user interface given the two player scores This part is visibile under the board and it consists in 3 parts: player1score, player2score, and error_msg :param player1_score: player1 score :param player2_score: player2 score :return: None """ # Deleting old scores pygame.draw.rect(game_screen, background_color, [0, board_pixel_size, board_pixel_size, board_pixel_size + score_pixel_size]) # Drawing the outer frames pygame.draw.rect(game_screen, player_colors[0], [score_padding, board_pixel_size - score_padding, score_pixel_size * 2.5, score_pixel_size - score_padding], line_thickness) pygame.draw.rect(game_screen, player_colors[1], [score_pixel_size * 2.5 + score_padding * 2, board_pixel_size - score_padding, score_pixel_size * 2.5, score_pixel_size - score_padding], line_thickness) # Drawing the text within the frames font.render_to(game_screen, (score_padding * 2, board_pixel_size + score_padding), "Player1: " + str(player1_score), player_colors[0]) font.render_to(game_screen, (score_pixel_size * 2.5 + score_padding * 4, board_pixel_size + score_padding), "Player2: " + str(player2_score), player_colors[1]) pygame.display.update() def draw_message(message, error=False): """ Draws message on the message part of the GUI with color depending of error parameter :param message: text to be drawn :param error: True - it is an error, False - it is not an error :return: None """ pygame.draw.rect(game_screen, background_color, [score_pixel_size * 5 + score_padding * 4, board_pixel_size + score_padding, board_pixel_size, board_pixel_size + score_pixel_size]) # Adapting text color color = valid_color if error: color = invalid_color # Drawing the text in its respective area font.render_to(game_screen, (score_pixel_size * 5 + score_padding * 4, board_pixel_size + score_padding), message, color) pygame.display.update() def draw_stone(turn, board_x, board_y): """ Given a player turn and a position on board it draws a player stone with corresponding color :param turn: current player turn :param board_x: x coordinate on board :param board_y: y coordinate on board :return: None """ # Getting player color color = player_colors[turn] # Transforming board coordinates to pixel coordinates x_pixel, y_pixel = get_pixel_pos_from_board_pos(board_x, board_y) # Drawing the stone pygame.draw.circle(game_screen, color, [x_pixel, y_pixel], checker_pixel_radius) pygame.display.update() def delete_stone(board_x, board_y): """ Given a board position it empties it by drawing an empty space :param board_x: x cooordinate on board :param board_y: y coordinate on board :return: None """ # Transforming coordinates to pixel coordinates pixel_x, pixel_y = get_pixel_pos_from_board_pos(board_x, board_y) # Draws empty space draw_empty_pixel_pos(pixel_x, pixel_y) def draw_empty_pixel_pos(x_pixel, y_pixel): """ Given a pair of pixel coordinates it draws an empty position corresponding to the Game-Of-GO: interior position: circle with background color with a cross formed with lines in its center exterior position: interior position but without one part of the cross :param x_pixel: x pixel coordinate :param y_pixel: y pixel coordinate :return: None """ # Emptying Space pygame.draw.circle(game_screen, background_color, [x_pixel, y_pixel], checker_pixel_radius) # Normalising the dimensions of the Cross based on pixel coordinates north = max(y_pixel - checker_pixel_radius, checker_pixel_size) south = min(y_pixel + checker_pixel_radius, board_pixel_size - checker_pixel_size) east = max(x_pixel - checker_pixel_radius, checker_pixel_size) west = min(x_pixel + checker_pixel_radius, board_pixel_size - checker_pixel_size) # Drawing the Cross pygame.draw.line(game_screen, line_color, [x_pixel, south], [x_pixel, north], line_thickness) pygame.draw.line(game_screen, line_color, [east, y_pixel], [west, y_pixel], line_thickness) pygame.display.update() def draw_ko_block(turn, board_x, board_y): """ Given a player turn for the color and a position on board it draw a KO block. A KO block represents a square centered on a position that has the color of the player that is being KO-ed :param turn: player turn :param board_x: x coordinate on board :param board_y: y coordinate on board :return: None """ # Getting correspondent color color = player_colors[turn] # Transforming coordinates to pixel coordinates x_pixel, y_pixel = get_pixel_pos_from_board_pos(board_x, board_y) # Drawing the KO Piece - Empty Centered Square pygame.draw.rect(game_screen, color, [x_pixel - ko_pixel_length, y_pixel - ko_pixel_length, 2 * ko_pixel_length, 2 * ko_pixel_length], line_thickness) pygame.display.update() def get_board_pos_from_pixel_pos(mouse_x, mouse_y): """ Given some pixel coordinates on the game board it returns the specific board coordinates :param mouse_x: x pixel coordinate :param mouse_y: y pixel coordinate :return: x board coordinate, y board coordinate """ x_pos = int((mouse_x - checker_pixel_size / 2) / checker_pixel_size) y_pos = int((mouse_y - checker_pixel_size / 2) / checker_pixel_size) return x_pos, y_pos def get_pixel_pos_from_board_pos(board_x, board_y): """ Given some board coordinates from the game board it returns the specific pixel coordinates :param board_x: x coordinate of board :param board_y: y coordinate of board :return: x pixel coordinate, y pixel coordinate """ x_pos = board_x * checker_pixel_size + checker_pixel_size y_pos = board_y * checker_pixel_size + checker_pixel_size return x_pos, y_pos def mouse_on_board(mouse_x, mouse_y): """ Given some pixel coordinates it returns whether the mouse is on the game board or not :param mouse_x: :param mouse_y: :return: True - mouse on board / False - mouse not on board """ # Checking the mouse coordinates against boarder margins return (board_pixel_size - checker_pixel_size / 2) > mouse_y > (checker_pixel_size / 2) \ and (checker_pixel_size / 2) < mouse_x < (board_pixel_size - checker_pixel_size / 2) def delete_last_hover(): """ Deletes the last drawn hover from the game board if it exists :return: None """ global last_hover if last_hover: draw_empty_pixel_pos(last_hover[0], last_hover[1]) last_hover = None def draw_mouse_hover(turn, board_x, board_y): """ Given a player turn and a position on the board it draws a smaller checker (hover checker) over the position the cursor is currently on :param turn: player turn :param board_x: x coordinate on board :param board_y: y coordinate on board :return: None """ global last_hover # Getting player color color = player_colors[turn] # Transforming board position to pixel position x_pixel, y_pixel = get_pixel_pos_from_board_pos(board_x, board_y) # Draw hover only if the position is different from last hover if not last_hover \ or last_hover[0] != x_pixel \ or last_hover[1] != y_pixel: # Empties last hovered position delete_last_hover() # Draws a smaller circle at current cursor position on board pygame.draw.circle(game_screen, color, [x_pixel, y_pixel], checker_hover_pixel_radius) last_hover = [x_pixel, y_pixel] pygame.display.update()
095c29d015955d1e84ae6ddf8ce33a47023d9ac4
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/815 Bus Routes.py
3,154
3.859375
4
#!/usr/bin/python3 """ We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible. Example: Input: routes = [[1, 2, 7], [3, 6, 7]] S = 1 T = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Note: 1 <= routes.length <= 500. 1 <= routes[i].length <= 500. 0 <= routes[i][j] < 10 ^ 6. """ ____ t___ _______ L.. ____ c.. _______ d.. c_ Solution: ___ numBusesToDestination routes: L..[L..[i..]], S: i.., T: i.. __ i.. """ BFS bus based nodes rather than stop based nodes BFS = O(|V| + |E|) = O(N + N^2), where N is number of routes Construction = O (N^2 * S), where S is number of stops """ __ S __ T: r.. 0 routes [s..(e) ___ e __ routes] G d..(s..) ___ i __ r..(l..(routes: ___ j __ r..(i + 1, l..(routes: stops_1, stops_2 routes[i], routes[j] # bus represented by stops ___ stop __ stops_1: # any(stop in stops_2 for stop in stops_1) __ stop __ stops_2: G[i].add(j) G[j].add(i) _____ q i ___ ?, stops __ e..(routes) __ S __ stops] target_set s..( i ___ ?, stops __ e..(routes) __ T __ stops]) visited d..(b..) ___ i __ q: visited[i] T.. step 1 w.... q: cur_q # list ___ e __ q: __ e __ target_set: r.. step ___ nbr __ G[e]: __ n.. visited[nbr]: visited[nbr] T.. cur_q.a..(nbr) step += 1 q cur_q r.. -1 ___ numBusesToDestination_TLE routes: L..[L..[i..]], S: i.., T: i.. __ i.. """ BFS Lest number of buses rather than bus stops Connect stops within in bus use one edge in G """ G d..(s..) ___ stops __ routes: ___ i __ r..(l..(stops: ___ j __ r..(i + 1, l..(stops: u, v stops[i], stops[j] G[u].add(v) G[v].add(u) q [S] step 0 visited d..(b..) visited[S] T.. # avoid add duplicate w.... q: cur_q # list ___ e __ q: __ e __ T: r.. step ___ nbr __ G[e]: __ n.. visited[nbr]: visited[nbr] T.. cur_q.a..(nbr) step += 1 q cur_q r.. -1 __ _______ __ _______ ... Solution().numBusesToDestination([[1, 2, 7], [3, 6, 7]], 1, 6) __ 2
1dfacfe675b336fbc2bb5521e7a37d65eff1fe65
joaocbjr/EXERCICIOS_curso_intensivo_de_python
/exe4.6.py
364
4.1875
4
print() print('4.6 – Números ímpares:\n Use o terceiro argumento da função range() para criar uma lista de números ímpares de 1 a 20. Utilize um laço for para exibir todos os números.') print() impar = list(range(1,21,2)) print('Os números ímpares da lista: ',impar) print('Todos os números da lista são: ') for todo in range(1,21): print(todo)
7f0d9776c13f464c603bbb48eb927691f989e6d1
jgoenawan407/Linear-Algebra
/matrix_arithmetic.py
1,968
3.875
4
# Jackson Goenawan, 8/23/21 import copy def scale(scalar, matrix): scaled = copy.deepcopy(matrix) for r in range(len(matrix)): #r starts at 0 and goes until end of matrix (exclusive of last index) for c in range(len(matrix[0])): scaled[r][c] = scalar * matrix[r][c] return(scaled) def add(m1, m2): r = len(m1) c = len(m1[0]) if len(m1) != len(m2) or len(m1[0]) != len(m2[0]): return("Matrix dimensions do not agree") else: M3 = copy.deepcopy(m1) # alr checked that this has same dimensions as m2 for i in range(r): for j in range(c): M3[i][j] = m1[i][j] + m2[i][j] return(M3) def mult(m1, m2): if len(m1[0]) != len(m2): return("Matrix dimensions do not agree") else: r = len(m1) c = len(m2[0]) m = [([0] * len(m2[0])) for i in range(len(m1))] for i in range(len(m)): for j in range(len(m[0])): numTerms = len(m1[0]) # how many products we need to sum for k in range(numTerms): m[i][j] += m1[i][k] * m2[k][j] # moving horizontally through m1, moving vertically through m2 return(m) def main(): m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[4, 6, 7], [9, 11, 2]] m3 = [[4, 7], [10, 3], [8, 2]] # can multiply m1m3 or m2m3 # m4 = input("enter matrix for determinant calculation"), tough to do matrix input, since we'd have to split by element and then cast each element to int print('Matrix 1: ' + str(m1)) print('Matrix 2: ' + str(m2)) print('Matrix 3: ' + str(m3)) print('Scaled matrix 1 by 6: ' + str(scale(6, m1))) print('Adding matrices 1 and 2: ' + str(add(m1, m2))) print('Adding matrices 1 and 3: ' + str(add(m1, m3))) # should return error print('Multiplying matrices 2 and 3: ' + str(mult(m2, m3))) print('Multiplying matrices 1 and 2: ' + str(mult(m1, m2))) # should return error if __name__ == '__main__': main()
5ab4759f7f7620b1b7bd331602b4f375b9cc339f
aussieyang/summer_python
/lesson2.py
678
4.09375
4
#Guessing the number game import random guessesTaken = 0 myName = raw_input("What's your name >>") number = random.randint(1, 10) print "I'm thinking of a number between 1 and 10." while guessesTaken < 3: guess = raw_input("Guess what number >>") guess = int(guess) guessesTaken += 1 #this means add one to guessesTaken if guess < number: print "Too low, go higher." if guess > number: print "Too high, go lower." if guess == number: break if guess == number: print "Good job, %s, you guessed correctly in %d turns!" % (myName, guessesTaken) else: print "Bad luck, I'm actually thinking of the number %d." % number
fec4b4867b0caff31535b287ed7883a8840b86c9
carines/ProjetOCR
/addition.py
232
3.78125
4
#!/usr/bin/python3 # -*- coding: utf8 -*- # message de bienvenue print ("Bonjour à tous") entierSaisi1 = int(input("Saisir un nombre :")) entierSaisi2 =int(input("Saisir un autre nombre :")) print(entierSaisi1+entierSaisi2)
e9f5ca62030ab0a8d99adec761567f61fdcd780e
SimoneNascivera/Avoid_obstacle_RL
/Avoid_obstacle/trained/avoidobstacle.py
5,246
3.609375
4
# This code is based on https://github.com/wh33ler/QNet_Pong/blob/master/pong.py # This code was by wh33ler. I changed it to be suitable for my scope and documented it. import pygame # simple library to develop simple python games import random # simple library to generate random numbers #size of our window WINDOW_WIDTH = 400 WINDOW_HEIGHT = 400 #size of our OBSTACLE OBSTACLE_WIDTH = 10 OBSTACLE_HEIGHT = 180 OBSTACLE_SPACE = 30 #size of our SHIP SHIP_WIDTH = 10 SHIP_HEIGHT = 10 #distance from the edge of the window SHIP_BUFFER = 10 SHIP_SPEED = 5 #RGB colors for our paddle and ball WHITE = (255, 255, 255) BLACK = (0, 0, 0) #initialize our screen using width and height vars screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) #draw the pipe def drawObstacle(center): obstacle = pygame.Rect(WINDOW_WIDTH/2, center + OBSTACLE_SPACE, OBSTACLE_WIDTH, WINDOW_HEIGHT-center-OBSTACLE_SPACE) obstacle1 = pygame.Rect(WINDOW_WIDTH/2, 0, OBSTACLE_WIDTH, center-OBSTACLE_SPACE) pygame.draw.rect(screen, WHITE, obstacle) pygame.draw.rect(screen, WHITE, obstacle1) #draw the little ship def drawShip(shipYPos, shipXPos): #create it paddle1 = pygame.Rect(shipXPos, shipYPos, SHIP_WIDTH, SHIP_HEIGHT) #draw it pygame.draw.rect(screen, WHITE, paddle1) def drawScore(score, neg): font = pygame.font.Font(None, 28) scorelabel = font.render("Score " + str(score), 1, WHITE) screen.blit(scorelabel, (30 , 10)) font = pygame.font.Font(None, 28) scorelabel = font.render("Failed " + str(neg), 1, WHITE) screen.blit(scorelabel, (30 , 50)) #draw infos on the top of the screen def drawInfos(infos, action): font = pygame.font.Font(None, 15) if(infos[3] != 'model only'): label = font.render("step " + str(infos[0]) + " ["+str(infos[3])+"]", 1, WHITE) screen.blit(label, (30 , 30)) label = font.render("epsilon " + str(infos[2]), 1, WHITE) screen.blit(label, (30 , 45)) label = font.render("q_max " + str(infos[1]), 1, WHITE) screen.blit(label, (30 , 60)) actionText = "--" if (action[1] == 1): actionText = "Up" if (action[2] == 1): actionText = "Down" label = font.render("action " + actionText, 1, WHITE) screen.blit(label, (30 , 75)) #update the paddle position def updateShip(action, shipYPos, shipXPos, center): #if move up if (action[1] == 1): shipYPos = shipYPos - SHIP_SPEED #if move down if (action[2] == 1): shipYPos = shipYPos + SHIP_SPEED #don't let it move off the screen if (shipYPos < 0): shipYPos = 0 if (shipYPos > WINDOW_HEIGHT - SHIP_HEIGHT): shipYPos = WINDOW_HEIGHT - SHIP_HEIGHT shipXPos = shipXPos + SHIP_SPEED score = 0 if((shipXPos >= WINDOW_WIDTH/2) and ((shipYPos> (center + OBSTACLE_SPACE-15)) or (shipYPos< (center -( OBSTACLE_SPACE-15))))): center = random.randint(0, 370) shipXPos = 0 shipYPos = WINDOW_HEIGHT / 2 - SHIP_HEIGHT / 2 score = -1 if((shipXPos >= WINDOW_WIDTH/2+50) and (shipYPos< (center + OBSTACLE_SPACE-15)) and (shipYPos> (center -( OBSTACLE_SPACE-15)))): center = random.randint(0, 370) shipXPos = 0 shipYPos = WINDOW_HEIGHT / 2 - SHIP_HEIGHT / 2 score = 1 return shipYPos, shipXPos, center, score #game class class AvoidObstacle: def __init__(self): pygame.font.init() #random number for initial direction of ball num = random.randint(0,9) #keep score self.neg = 0 self.tally = 0 #initialie positions of paddle self.shipYPos = WINDOW_HEIGHT / 2 - SHIP_HEIGHT / 2 # the initial frae def getPresentFrame(self): #for each frame, calls the event queue pygame.event.pump() #make the background black screen.fill(BLACK) #draw obstacles self.center = random.randint(0, 370) drawObstacle(self.center) #draw our ship self.shipXPos = SHIP_BUFFER drawShip(self.shipYPos, self.shipXPos) #draw our ball drawScore(self.tally, self.neg) #copies the pixels from our surface to a 3D array. we'll use this for RL image_data = pygame.surfarray.array3d(pygame.display.get_surface()) #updates the window pygame.display.flip() #return our surface data return image_data #update our screen def getNextFrame(self, action, infos): pygame.event.pump() score = 0 screen.fill(BLACK) #update our paddle self.shipYPos, self.shipXPos, self.center, score = updateShip(action, self.shipYPos, self.shipXPos, self.center) if(score == -1): self.neg = self.neg + 1 drawObstacle(self.center) if(self.shipXPos > WINDOW_WIDTH): self.shipXPos = SHIP_BUFFER drawShip(self.shipYPos, self.shipXPos) #get the surface data image_data = pygame.surfarray.array3d(pygame.display.get_surface()) drawScore(self.tally, self.neg) drawInfos(infos, action) #update the window pygame.display.flip() #record the total score self.tally = self.tally + score #return the score and the surface data return [score, image_data]
f9572e3e444d1349e9acce536d32b85a9766fba3
liseyko/CtCI
/leetcode/p0111 - Minimum Depth of Binary Tree.py
720
3.75
4
from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 lvl = 1 q = deque([root]) ql = 1 while len(q) > 0: n = q.popleft() ql -= 1 if n: if not n.left and not n.right: break q.extend([n.left, n.right]) if ql == 0: lvl += 1 ql = len(q) return lvl
ea6ede59600608798fd6cc4a2d6a3871de2c4a76
saenuruki/Codility
/Arrays/oddOccurrencesInArray.py
2,214
4.09375
4
#A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. # #For example, in array A such that: # # A[0] = 9 A[1] = 3 A[2] = 9 # A[3] = 3 A[4] = 9 A[5] = 7 # A[6] = 9 #the elements at indexes 0 and 2 have value 9, #the elements at indexes 1 and 3 have value 3, #the elements at indexes 4 and 6 have value 9, #the element at index 5 has value 7 and is unpaired. #Write a function: # #def solution(A) # #that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. # #For example, given array A such that: # # A[0] = 9 A[1] = 3 A[2] = 9 # A[3] = 3 A[4] = 9 A[5] = 7 # A[6] = 9 #the function should return 7, as explained in the example above. # #Write an efficient algorithm for the following assumptions: # #N is an odd integer within the range [1..1,000,000]; #each element of array A is an integer within the range [1..1,000,000,000]; #all but one of the values in A occur an even number of times. # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 # Aから先頭1つをPopしてstack_Aに格納する # Aの次の先頭1つをPopして、stack_Aに一致するか判定し、 # 一致する場合はstack_A内の一致した値をPopする # 一致しない場合はstack_Aに格納する # Aが空になるまで繰り返して、最後にstack_Aに残った値を返す stack_A = [] if len(A) <= 0 or len(A) >= 1000000: return 0 for element_A in A: if element_A <= 0 or element_A >= 1000000000: return 0 if len(stack_A) > 0: flag = 0 for stack_element_A in stack_A: if stack_element_A == element_A: stack_A.remove(stack_element_A) flag = 1 if flag == 0: stack_A.append(element_A) else: stack_A.append(element_A) return stack_A[0]
fe46d37c3d8c50513e86403eb3eb1adfd1c9a13b
Joffenmoses/Python-Assignment6
/Untitled2.py
202
3.890625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: list1=[1,2,3,4,5,6,7,8] list2=['a','b','c','d','e'] dict1={} len1=min(len(list1),len(list2)) print({list1[each]:list2[each] for each in range(len1)})
03e984c0d26fa168de16bf3b4e4f1a4a4e03f1d7
eszka/moje_programy
/cursera_list_8_4.py
1,272
3.9375
4
__author__ = 'Agnieszka' # C:\Users\Agnieszka\Desktop\ITC\Python Cursera\romeo.txt fname = raw_input("Enter file name: ") fh = open(fname) lst = list() for line in fh: li = line.rstrip().split() # li = a.split() for item in li: if item in lst: continue else: lst.append(item) print lst print line lst.sort() print lst # fname = raw_input("Enter file name: ") # fh = open(fname) # lst = list() # for line in fh: # line = line.rstrip() # words = line.split() # for word in words: # if word in words: continue # else: # lst.append(word) # # result = lst.sort() # print result # #initial code # #first for loop # #strip and split # Second for loop: #iterate for all the words in the lists # if word is already in list: # #do nothing and move to the start of the loop (hint: we've done this in prev lecs) # else: # #append to the list if it is not already present there # #sort the list # #print the list # Actually you shouldn't share code to graded assignments. # # You have two mistakes in your code: # # 1. You should create a new list to store result of line.split() # 2. append content of new list to word list(in your code newlist)
cd1766e5a04f43ad0702fd4e7ce899d333029112
MahbubHossainFaisal/Artificial-Intelligence
/new.py
581
3.921875
4
studentID=input("Give your student id:") if (studentID[2] == '-' and studentID[8]=='-' and len(studentID)==10 ): print("It is a valid ID") a=1 else: print("It is not a valid id") a=0 if a==1: if(studentID[0]=='2'): print("Student is in the 1st year") elif(studentID[0]=='1' and studentID[1]=='9'): print("Student is in the 2nd year") elif(studentID[0]=='1' and studentID[1]=='8'): print("Student is in the 3rd year") elif(studentID[0]=='1' and studentID[1]=='7'): print("Student is in the 4th year")
198276790ab7bbbe7db142f7780c986e2eaa0d0a
MD-Shibli-Mollah/pythonProject-geeksforgeeks
/hr_list.py
636
3.78125
4
if __name__ == '__main__': my_list = [] n = int(input()) for i in range(0, n): my_inp = input() my_val = my_inp.split() if my_val[0] == "insert": my_list.insert(int(my_val[1]), int(my_val[2])) if my_val[0] == "print": print(my_list) if my_val[0] == "remove": my_list.remove(int(my_val[1])) if my_val[0] == "append": my_list.append(int(my_val[1])) if my_val[0] == "sort": my_list.sort() if my_val[0] == "pop": my_list.pop() if my_val[0] == "reverse": my_list.reverse()
16ce1a6311c5a7468e8fab8a8ef54f7ddbad34e1
simpsons8370/cti110
/P4LAB2_OutOfRange_SimpsonShaunice.py
237
4.0625
4
first_num = int(input()) second_num = int(input()) if second_num < first_num: print('Second integer can\'t be less than the first.') while first_num <= second_num: print(first_num, end=' ') first_num += 5 print()
f0d1f8befb39c9b48607464c1e7da8c492c64c6b
seongbeenkim/Algorithm-python
/Programmers/Level2/올바른 괄호(correct parenthesis).py
359
3.5
4
# https://programmers.co.kr/learn/courses/30/lessons/12909 def solution(s): count = 0 for p in s: if p == "(": count += 1 else: count -= 1 if count < 0: return False return count == 0 print(solution("()()")) print(solution("(())()")) print(solution(")()(")) print(solution("(()("))
771d7e83254a85896bff71606cf89203f1f8bf2c
WesleyEspinoza/CS-PythonWork
/CS1.3/search.py
2,166
4.3125
4
#!python import math def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests #return linear_search_recursive(array, item) return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): if index > len(array) - 1: return None elif array[index] == item: return index else: return linear_search_recursive(array, item, index + 1) def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests #return binary_search_iterative(array, item) return binary_search_recursive(array, item) def binary_search_iterative(array, item): max = len(array)-1 min = 0 while min <= max: middle_index = (min + max) // 2 middle_item = array[middle_index] if item == middle_item: return middle_index elif item > middle_item: min = middle_index + 1 else: max = middle_index - 1 return None def binary_search_recursive(array, item, left=None, right=None): if left == None: left = 0 if right == None: right = len(array) - 1 middle_index = (left + right) // 2 middle_item = array[middle_index] if left <= right: if item == middle_item: return middle_index elif item > middle_item: return binary_search_recursive(array, item, middle_index +1, right ) elif item < middle_item: return binary_search_recursive(array, item, left, middle_index -1 ) else: return None
d06df4b39d4075752454d2349a611db8e966d61f
ron71/PythonLearning
/Input_Output(I_O)/BinaryI_OUsingShelve.py
4,683
4.34375
4
# Drawback of pickle is that, whenever we wanted any data we have to restore entire file in memory # via making their objects. So it is not good of very large files. # Therefore python has one more module called shelve, # this module is too recommended to not to be used with untrusted file sources like internet # It stores value in key object pairs just like dictionaries, # it stores using key value and values are pickled and then stored # IMPORTANT : SHELVE KEYS MUST BE STRINGS while dictionary can have any immutable object import shelve with shelve.open('shelveTest') as fruit: fruit['apple'] = 'An apple a day, keeps doctors away' fruit['grape'] = 'Larely used for making resins and alcohol' fruit['mango'] = 'They are king of fruit in Summer' fruit['watermelon'] = 'Greater in size more juice they have' fruit['orange'] = 'A citrus sweet source of vitamin C' print(fruit['apple']) print('*'*80) for key in fruit: print(key) # print(fruit['apple']) # O/P--> ValueError: invalid operation on closed shelf # AS shelve is closed we cannot access file # in dictionary we can create it using literals but shelve cannot be created by using literals # Note : Shelve files are persistent i.e. if we created a shelve file which contains a key value, # Howewer on second run we changes the value the value of key and run the file # We will observe that the old key value pairs are still there # that means when we ran the file second time it didn't erased the last entries rather it appended few more # Just like dictionary they are unordered # It too creates KeyError if we try to access key which is not present so it would be better using get() method # It returns None if key not found print('*'*80) while True: dict_key = input('Enter The key') if dict_key == 'quit': break print(fruit.get(dict_key, 'We don\'t have '+ dict_key )) print('line - 41\t'*20) fruit = shelve.open('shelveTest') for key in fruit: print('{0} - {1}'.format(key,fruit[key])) print() print("line - 47\t"*10) print(fruit.keys()) # NOTE : Instead of dict_keys object it returns KeysView print(fruit.items()) # NOTE : Instead of dict_items view it returns ItemsView print(fruit.values()) # NOTE : Instead of dict_values object it returns ValuesView # All three are view object i.e. we cant modify them fruit.close() # This line is must if we open a without 'with' # Updating data in shelves with shelve.open('shelveTest') as recipe: recipe['maaggi'] = ['water', 'Boiler', 'Maggi'] # now we try to update data with shelve.open('shelveTest') as recipe: recipe['maaggi'].append('veggies') with shelve.open('shelveTest') as recipe: print('Recipe for maggi : {}'. format(recipe['maaggi'])) # O/P--> Recipe for maggi : ['water', 'Boiler', 'Maggi'] # we can see the list didn't modified this is because # although we appended the list it was not triggered by shelve to save the modification in the file. # We just appended to a copy of list wich was loaded in the memory from file # So there are two ways to modify the content: # First way is to copy the list in a temporary list and then append the data in the temp. list # and finally copying the temp. list back to the shelve print() print(' Line No - 77\t********'*50) with shelve.open('shelveTest') as recipe: tempList = recipe['maaggi'] tempList.append('veggies') recipe['maaggi'] = tempList with shelve.open('shelveTest') as recipe: print('Recipe for maggi : {}'. format(recipe['maaggi'])) # Another way is to open the shelve file in 'writeback' mode = True and then append the content with shelve.open('shelveTest', writeback= True) as recipe: recipe['maaggi'].append("Taste Maker") with shelve.open('shelveTest') as recipe: print('Recipe for maggi : {}'. format(recipe['maaggi'])) # Python caches the data in memory and updates the data in the shelve at the time of closing the file # Actually a 'sync' method is called at the time of closing the file, so it loads the data in the disk # and clears the cache (Important) # So it can take a while to close the file if there are so many modification in the file # This is because all modification are to be written in disk/file # This becomes an disadvantage in case of huge amount of data # Using sync() method: # Note : It works under write back mode = True with shelve.open('shelveTest', writeback= True) as recipe: recipe['maaggi'].append('2 minutes') recipe.sync() print() print(' Line No - 108\t********'*50) with shelve.open('shelveTest') as recipe: print('Recipe for maggi : {}'. format(recipe['maaggi']))
d3eed8aa92cc1349d90a2357ceb5015ad8c8eb07
bingoshu/Python123
/二叉树.py
340
3.96875
4
import turtle as t def tree(length,level): #树的层次 if level <= 0: return t.forward(length) #前进方向画 length距离 t.left(45) tree(0.6*length,level-1) t.right(90) tree(0.6*length,level-1) t.left(45) t.backward(length) return t.pensize(3) t.color('green') t.left(90) tree(100,6)
ba1595173b666a2e8df43e7d98f8f1992e633586
youjiajia/learn-leetcode
/solution/295/solution.py
1,582
3.65625
4
import heapq class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.big_queue = [] self.small_queue = [] heapq.heapify(self.big_queue) heapq.heapify(self.small_queue) def addNum(self, num): """ :type num: int :rtype: void """ if not self.big_queue: heapq.heappush(self.big_queue, -num) return if len(self.big_queue) == len(self.small_queue): if num < -self.big_queue[0]: heapq.heappush(self.big_queue, -num) else: heapq.heappush(self.small_queue, num) elif len(self.big_queue) > len(self.small_queue): if num < -self.big_queue[0]: heapq.heappush(self.small_queue, -self.big_queue[0]) heapq.heapreplace(self.big_queue, -num) else: heapq.heappush(self.small_queue, num) else: if num > self.small_queue[0]: heapq.heappush(self.big_queue, -self.small_queue[0]) heapq.heapreplace(self.small_queue, num) else: heapq.heappush(self.big_queue, -num) def findMedian(self): """ :rtype: float """ if len(self.big_queue) == len(self.small_queue): return (self.small_queue[0]-self.big_queue[0])/2.0 elif len(self.big_queue) > len(self.small_queue): return -self.big_queue[0] else: return self.small_queue[0]
ce25a3fdcc94809df4534ba7cc57a49c9642e4c7
AlimyBreak/PythonStudy
/日常笔记/do_not_return_dict.py
680
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 24 14:00:35 2019 来源: B站UP主:哲的王 的稿件<<大兄弟,写Python请别返回Dict>> https://www.bilibili.com/video/av20963030/ @ File author: AlimyBreak """ # 方案一: def some_func(): d = dict() d['field_1'] = 1 d['field_2'] = 2 return d # 方案二: from collections import namedtuple someAPIDataModel = namedtuple('someAPIDataModel1',['field_1','field_2','field_3']); print(someAPIDataModel) model_data = someAPIDataModel(field_1 = 1,field_2 = 2,field_3 = 3) print(model_data) print(model_data.field_1) print(model_data[0]) #model_data[0] = 2; #tuple不能修改
377e9306e430bbec0410f82ae83be3c1a94fda8c
vagdevik/ML_DL
/My-Machine-Learning/100_Days_of_ML_code/Basic_Neural_net/nn.py
1,333
3.78125
4
import numpy as np def sigmoid(x): return 1/(1+np.exp(-x)) def derivative_sigmoid(x): return x*(1-x) np.random.seed(0) #input X = np.array([[1,0,0],[0,0,1],[0,1,0],[1,0,1],[1,1,1]]) Y = np.array([[1],[0],[0],[1],[1]]) #initialize neurons and learning rate input_neurons = X.shape[1] #number of features in data set first_hidden_neurons = 4 second_hidden_neurons = 1 alpha = 0.5 #initialize synapses weights and biases syn_w0 = np.random.rand(input_neurons,first_hidden_neurons) syn_w1 = np.random.rand(first_hidden_neurons,second_hidden_neurons) b0 = np.random.rand(1,first_hidden_neurons) b1 = np.random.rand(1,second_hidden_neurons) for i in range(2000): #forward propagation #activations net0 = np.dot(X,syn_w0) + b0 out0 = sigmoid(net0) net1 = np.dot(out0,syn_w1) + b1 out1 = sigmoid(net1) #total error E_total = (1/np.floor(2))*np.square(Y-out1) if(i%100==0): print "Error at epoch "+str(i)+" :" print np.sum(np.square((Y-E_total))) print "______________" #backward propagation E = -(Y-out1) delta_output = E*derivative_sigmoid(out1) delta_hidden = delta_output.dot(syn_w1.T)*derivative_sigmoid(out0) syn_w1 = syn_w1 - (out1.T.dot(delta_output)*alpha) syn_w0 = syn_w0 - X.T.dot(delta_hidden)*alpha b1 = b1 - np.sum(delta_output)*alpha b0 = b0 - np.sum(delta_hidden)*alpha print out1
03da43cd9836b7a76540e0f0c32087ed378ba108
Omarfos/Algorithms
/54.spiral-matrix.py
2,158
3.8125
4
# # @lc app=leetcode id=54 lang=python3 # # [54] Spiral Matrix # # https://leetcode.com/problems/spiral-matrix/description/ # # algorithms # Medium (33.55%) # Likes: 2205 # Dislikes: 556 # Total Accepted: 356.8K # Total Submissions: 1.1M # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' # # Given a matrix of m x n elements (m rows, n columns), return all elements of # the matrix in spiral order. # # Example 1: # # # Input: # [ # ⁠[ 1, 2, 3 ], # ⁠[ 4, 5, 6 ], # ⁠[ 7, 8, 9 ] # ] # Output: [1,2,3,6,9,8,7,4,5] # # # Example 2: # # Input: # [ # ⁠ [1, 2, 3, 4], # ⁠ [5, 6, 7, 8], # ⁠ [9,10,11,12] # ] # Output: [1,2,3,4,8,12,11,10,9,5,6,7] # # # @lc code=start class Solution: # def spiralOrder(self, matrix: List[List[int]]) -> List[int]: # if not matrix: # return [] # tr, br = 0, len(matrix) - 1 # lc, rc = 0, len(matrix[0]) - 1 # res = [] # while tr <= br and lc <= rc: # # right # for i in range(lc, rc + 1): # res.append(matrix[tr][i]) # tr += 1 # # down # for i in range(tr, br + 1): # res.append(matrix[i][rc]) # rc -= 1 # # left # if tr <= br: # for i in reversed(range(lc, rc + 1)): # res.append(matrix[br][i]) # br -= 1 # # up # if lc <= rc: # for i in reversed(range(tr, br + 1)): # res.append(matrix[i][lc]) # lc += 1 # return res def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] res = [] n = len(matrix) m = len(matrix[0]) di, dj = 0, 1 i, j = 0, 0 for _ in range(m * n): res.append(matrix[i][j]) matrix[i][j] = 'x' #seen if i + di < n and j + dj < m: if matrix[(i+di)%n][(j+dj)%m] == 'x': di, dj = dj, -di i += di j += dj return res # @lc code=end
97180e6aac0dff7e31f913d5f02027a26b7a63f4
jdowers20/2041-ass1
/demo03.py
292
3.75
4
#!/usr/bin/python3 # written by andrewt@cse.unsw.edu.au, adapted # retrive course codes import fileinput, re course_names = [] for line in open("course_codes"): m = re.match(r'(\S+)\s+(.*\S)', line) if m: course_names.append(m.group(2)) for course in course_names: print("%s"%(course))
b925648bfaad882235a27dce43e62d33ce852ffe
vilkoz/wolf3d
/res/gen_map.py
13,617
3.53125
4
#!/usr/bin/env python3 import random def randint(a, b): if a < b: return random.randint(a, b) return a MIN_SIZE = 6 class Node: def __init__(self, x1, x2, y1, y2): self.childs = [] self.border = ((x1, y1), (x2, y2)) self.room = None self.connected = False def split(self, iteration): w = self.border[1][0] - self.border[0][0] h = self.border[1][1] - self.border[0][1] if iteration <= 0: return if not (w > h and w / h >= 1.25) or (h > w and h / w >= 1.25) or \ randint(0, 1): if (h / 2) <= MIN_SIZE: return self.split_vert(iteration) else: if (w / 2) <= MIN_SIZE: return self.split_hor(iteration) def split_vert(self, iteration): percent = randint(40, 60) / 100 dist = self.border[1][1] - self.border[0][1] split_coord = self.border[0][1] + int(dist * percent) self.childs.append(Node(self.border[0][0], self.border[1][0], self.border[0][1], split_coord)) self.childs.append(Node(self.border[0][0], self.border[1][0], split_coord, self.border[1][1])) for elem in self.childs: elem.split(iteration - 1) def split_hor(self, iteration): percent = randint(40, 60) / 100 dist = self.border[1][0] - self.border[0][0] split_coord = self.border[0][0] + int(dist * percent) self.childs.append(Node(self.border[0][0], split_coord, self.border[0][1], self.border[1][1])) self.childs.append(Node(split_coord, self.border[1][0], self.border[0][1], self.border[1][1])) for elem in self.childs: elem.split(iteration - 1) def draw_border(self, m): for y in range(self.border[0][1], self.border[1][1] + 1): for x in range(self.border[0][0], self.border[1][0] + 1): if x == self.border[0][0] or x == self.border[1][0] or \ y == self.border[0][1] or y == self.border[1][1]: m[y][x] = '2' for child in self.childs: child.draw_border(m) def make_rooms(self): if (len(self.childs) != 0): for child in self.childs: child.make_rooms() else: w = self.border[1][0] - self.border[0][0] h = self.border[1][1] - self.border[0][1] gap_size = [0, 0] if w - w // 4 > MIN_SIZE: gap_size[0] = min([3, w // 4]) if h - h // 4 > MIN_SIZE: gap_size[1] = min([3, h // 4]) self.room = ( ( 1 + self.border[0][0] + randint(0, gap_size[0]), 1 + self.border[0][1] + randint(0, gap_size[1]) ), ( self.border[1][0] - 1 - randint(0, gap_size[0]), self.border[1][1] - 1 - randint(0, gap_size[1]) ) ) def draw_room(self, m): if (self.room): for y in range(self.room[0][1], self.room[1][1]+1): for x in range(self.room[0][0], self.room[1][0]+1): if y == self.room[0][1] or y == self.room[1][1] \ or x == self.room[0][0] or x == self.room[1][0]: m[y][x] = '*' else: m[y][x] = ' ' else: for child in self.childs: child.draw_room(m) def draw_room_walls(self, m): if (self.room): wall = "12345"[randint(0, 4)] for y in range(self.room[0][1], self.room[1][1]+1): for x in range(self.room[0][0], self.room[1][0]+1): if y == self.room[0][1] or y == self.room[1][1] \ or x == self.room[0][0] or x == self.room[1][0]: if m[y][x] not in ['D', 'd', '_']: m[y][x] = wall if randint(0, 1000) < 990 else '6' else: for child in self.childs: child.draw_room_walls(m) def get_center(self): w = self.border[1][0] - self.border[0][0] h = self.border[1][1] - self.border[0][1] return ( self.border[0][0] + w // 2, self.border[0][1] + h // 2 ) def connect_pair(self, a, b, m, doors=False): c_a = a.get_center() c_b = b.get_center() p1 = [min(c_a[0], c_b[0]), max(c_a[0], c_b[0])] p2 = [min(c_a[1], c_b[1]), max(c_a[1], c_b[1])] for y in range(p2[0], p2[1] + 1): for x in range(p1[0], p1[1] + 1): if doors and m[y][x] == '*' and p1[0] == p1[1]: m[y][x] = 'd' elif doors and m[y][x] == '*': m[y][x] = 'D' elif m[y][x] not in ['D', 'd']: m[y][x] = '_' for node in [a, b]: if len(node.childs) == 0: node.connected = True def get_child_pairs(self): for i in range(len(self.childs)): for j in range(len(self.childs)): if i != j: yield (self.childs[i], self.childs[j]) def dig_hall(self, m): if (len(self.childs) <= 1): return if (len(self.childs) == 2): a = self.childs[0] b = self.childs[1] if (len(self.childs) == 2) and len(a.childs) == 0 and len(b.childs) == 0: self.connect_pair(a, b, m, doors=True) else: for pair in self.get_child_pairs(): self.connect_pair(pair[0], pair[1], m) for c in self.childs: c.dig_hall(m) def get_first_child(self): if len(self.childs) == 0: return self return self.childs[0].get_first_child() def get_last_child(self): if len(self.childs) == 0: return self return self.childs[len(self.childs) - 1].get_first_child() def get_rooms(self): if self.room: return [self] rooms = [] for c in self.childs: rooms += c.get_rooms() return rooms def place_zombies(self, m): if randint(0, 5) > 1: size = max([self.room[1][0] - self.room[0][0], self.room[1][1] - self.room[0][1]]) num = randint(3, size) for _ in range(num): p = [ randint(self.room[0][0] + 1, self.room[1][0] - 1), randint(self.room[0][1] + 1, self.room[1][1] - 1) ] m[p[1]][p[0]] = 'z' def put_player(n, m): s = n.get_first_child() m[randint(s.room[0][1] + 2, s.room[1][1] - 2)][randint(s.room[0][0] + 2, s.room[1][0] - 2)] = 'P' def put_exit(n, m): s = n.get_last_child() if randint(0, 1): rand_1 = randint(s.room[0][1] + 1, s.room[1][1] - 1) rand_2 = randint(0, 1) while m[rand_1][s.room[rand_2][0]] == '_': rand_1 = randint(s.room[0][1] + 1, s.room[1][1] - 1) rand_2 = randint(0, 1) m[rand_1][s.room[rand_2][0]] = '8' else: rand_1 = randint(0, 1) rand_2 = randint(s.room[0][0] + 1, s.room[1][0] - 1) while m[s.room[rand_1][1]][rand_2] == '_': rand_1 = randint(0, 1) rand_2 = randint(s.room[0][0] + 1, s.room[1][0] - 1) m[s.room[rand_1][1]][rand_2] = '8' def replace_halls(m): for i, row in enumerate(m): for j, el in enumerate(row): if el == '_': m[i][j] = ' ' if el == '*': m[i][j] = '2' def count_zombies(m): z = 0 for row in m: for el in row: if el == 'z': z += 1 return z def place_sprites(m): for i, row in enumerate(m): for j, el in enumerate(row): if el == ' ': if i - 1 > 0 and m[i-1][j] not in ['d', 'D'] \ and i + 1 > 0 and m[i+1][j] not in ['d', 'D'] \ and j - 1 > 0 and m[i][j-1] not in ['d', 'D'] \ and j + 1 > 0 and m[i][j+1] not in ['d', 'D']: if randint(0, 100) > 95: m[i][j] = 'b' elif randint(0, 1000) > 999: m[i][j] = 'a' z_num = int(count_zombies(m) // 3) while z_num > 0: for i, row in enumerate(m): for j, el in enumerate(row): if z_num <= 0: break if el == ' ': if i - 1 > 0 and m[i-1][j] not in ['d', 'D'] \ and i + 1 > 0 and m[i+1][j] not in ['d', 'D'] \ and j - 1 > 0 and m[i][j-1] not in ['d', 'D'] \ and j + 1 > 0 and m[i][j+1] not in ['d', 'D']: if randint(0, 1000) > 999: m[i][j] = 's' z_num -= 1 elif randint(0, 1000) > 999: m[i][j] = 'h' z_num -= 1 if z_num <= 0: break if z_num <= 0: break def check_no_hall(p, size, m, index): if index in [1, 2]: size += 1 for x in range(p[0] + 1, p[0] + size - 1): for y in range(p[1] + 1, p[1] + size - 1): if m[y][x] == '_': return False return True def draw_secret_room(p, size, m, index): if index in [1, 2]: size += 1 for x in range(p[0] + 1, p[0] + size - 1): for y in range(p[1] + 1, p[1] + size - 1): if randint(0, 1): m[y][x] = 's' if randint(0, 5) > 3 else 'h' else: m[y][x] = ' ' def place_secret_door(p, index, m): deltas = [[0, 1], [-1, 0], [0, -1], [1, 0]] delta = deltas[index] p1 = [p[0] + 1, p[1] + 1] while m[p1[1]][p1[0]] in ['h', 's', ' ']: p1 = [x1 + x2 for x1, x2 in zip(delta, p1)] m[p1[1]][p1[0]] = '7' def place_secret_room(n, m): nodes = n.get_rooms() for r in nodes: gaps = [ r.room[0][1] - r.border[0][1] + 1, r.border[1][0] - r.room[1][0], r.border[1][1] - r.room[1][1], r.room[0][0] - r.border[0][0] + 1 ] w = r.border[1][0] - r.border[0][0] h = r.border[1][1] - r.border[0][1] is_enough_size = [x > 3 for x in gaps] if is_enough_size.count(True) >= 1 and True:#randint(0, 10) > 3: index = is_enough_size.index(True) if index == 0: p = [ randint(r.room[0][0] + 1, r.room[1][0] - 1 - gaps[index]), r.border[0][1] ] count = 0 while not check_no_hall(p, gaps[0], m, index): p = [ randint(r.room[0][0] + 1, r.room[1][0] - 1 - gaps[index]), r.border[0][1] ] count += 1 if count >= 10: return elif index == 2: p = [ randint(r.room[0][0] + 1, r.room[1][0] - 1 - gaps[index]), r.border[1][1] - gaps[index] ] count = 0 while not check_no_hall(p, gaps[index], m, index): p = [ randint(r.room[0][0] + 1, r.room[1][0] - 1 - gaps[index]), r.border[1][1] - gaps[index] ] count += 1 if count >= 10: return elif index == 1: p = [ r.border[1][0] - gaps[index], randint(r.room[0][1] + 1, r.room[1][1] - 1 - gaps[index]) ] count = 0 while not check_no_hall(p, gaps[index], m, index): p = [ r.border[1][0] - gaps[index], randint(r.room[0][1] + 1, r.room[1][1] - 1 - gaps[index]) ] count += 1 if count >= 10: return elif index == 3: p = [ r.border[0][0], randint(r.room[0][1] + 1, r.room[1][1] - 1 - gaps[index]) ] count = 0 while not check_no_hall(p, gaps[index], m, index): p = [ r.border[0][0], randint(r.room[0][1] + 1, r.room[1][1] - 1 - gaps[index]) ] count += 1 if count >= 10: return draw_secret_room(p, gaps[index], m, index) place_secret_door(p, index, m) size = 50 world = [] for _ in range(size): row = [] for __ in range(size): row.append(1) world.append(row) n = Node(0, size - 1, 0, size - 1) n.split(4) n.draw_border(world) n.make_rooms() n.draw_room(world) n.dig_hall(world) n.draw_room_walls(world) put_player(n, world) place_secret_room(n, world) replace_halls(world) rooms = n.get_rooms() for node in rooms[1:]: node.place_zombies(world) place_sprites(world) put_exit(n, world) for row in world: for el in row: print(el, end='') print("")
a4e4a1c1d36af978397f32679aee705f8aaa737a
bonicim/technical_interviews_exposed
/src/algorithms/blind_curated_75_leetcode_questions/longest_substring_without_repeating_characters.py
2,595
4.21875
4
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ """Commentary Although this problem hints at dynamic programming, a simpler way to think about this problem is to use a technique called the sliding window, in which you have two pointers that specify the range of a subset of items you are looking at within an array. In combination with using a collection to determine if you've seen a char before (i.e. to track history), the solution becomes fairly simple: if we've seen the character before, remove it from our seen list and move our left pointer. If we have not seen it, then we have increased our longest substring. Add that to our list of seen characters, update our maximum unique substring, and move the pointer to the right. A downside of this solution is that we don't move our right pointer continuously. When we encounter a duplicate, we revisit the right pointer again. """ def length_of_longest_substring(string): left = 0 right = 0 max_so_far = 0 unique_chars = set() substring = "" while right < len(string): char = string[right] if char not in unique_chars: unique_chars.add(char) if max_so_far < len(unique_chars): # we have found a new, longest substring max_so_far = len(unique_chars) substring = string[left : right + 1] right += 1 else: # we remove the duplicated char in the our set of seen unique chars, but we don't move the right pointer forward because we need to include that char, which was duplicated from an earlier same char. unique_chars.remove(string[left]) # instead of moving the right pointer, we simply move the left pointer forward # if the duplicated char was on the left pointer, then we have a new, albeit same length substring of left+1 to right # if not, then the duplicate must be somewhere in the middle of the current substring. on the next iteration, we'll eventually add the duplicated char back to the set left += 1 print(substring) return max_so_far
9894f39a43c008d523ac9f4ef4417d796a3b5845
ozan-san/AI-Homeworks
/03-search/heuristics.py
280
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 16:30:15 2020 @author: Ozan Şan """ from math import sqrt def heur(first, second): ''' Returns Euclidean distance between two points as tuples. ''' return sqrt((first[0] - second[0])**2 + (first[1] - second[1])**2)
8076fc2f60d0526ac5a1feed7941882ebdd72704
luizfranca/project-euler
/python/p09.py
302
4.09375
4
# Special Pythagorean triplet import math def pythagorean_Triplet(n): number = 0 for a in range(1, n): for b in range(1, n): c = math.sqrt(a ** 2 + b ** 2) if c % 1 == 0: number = a + b + int(c) c = int(c) if number == n: return a * b * c print pythagorean_Triplet(1000)
1a3a24db6f4c5c411f0c9564a49e696af941fb4a
ranjuinrush/excercise
/ex4/untitled6.py
215
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 17:13:38 2018 @author: user """ d={'A':10,'B':20,'C':30} print("Total sum of values in the dictionary:") s=1 for key in d: s=s*d[key] print(str(s))
322b61f918997a09b0311a6e8ec00883b26b4f50
coderwyc/leetcode-python
/sqrt_int.py
505
4.125
4
""" Implement int sqrt(int x). Compute and return the square root of x. """ class Solution: # @param x, an integer # @return an integer def sqrt(self, x): if x == 0: return 0 low = 1 high = x/2 + 1 while(low <= high): mid = (low + high) / 2 if mid**2 == x: return mid elif mid**2 > x: high = mid - 1 else: low = mid + 1 return high
236605132158eb24b70e6bd3bb3453f76e8c86f9
munkhtsogt/algorithms
/BackspaceStringCompare.py
658
3.71875
4
class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ s, t = [], [] for c in S: if c != '#': s.append(c) elif len(s) != 0: s.pop() for c in T: if c != '#': t.append(c) elif len(t) != 0: t.pop() return "".join(s) == "".join(t) sol = Solution() print sol.backspaceCompare("ab#c", "ad#c") print sol.backspaceCompare("ab##", "c#d#") print sol.backspaceCompare("a#c", "b") print sol.backspaceCompare("a##c", "#a#c") print sol.backspaceCompare("isfcow#", "isfco#w#")
b2c786750783bb2278b97fd5196c5c2c69e52835
tomhettinger/simplestone
/gameboard/Deck.py
467
3.53125
4
from random import shuffle as shuf class Deck(object): def __init__(self, side=None): self.side = side self.cards = [] self.size = len(self.cards) def add_card(self, card): self.cards.append(card) self.size += 1 def draw_card(self): if self.size <= 0: return None else: self.size -= 1 return self.cards.pop() def shuffle(self): shuf(self.cards)
074780e053d5a2d75a4a08f15de0430a06f49bdd
lemzoo/magic-mock
/tools.py
896
3.75
4
#!/usr/bin/env python def add(first_arg, second_arg): return first_arg + second_arg def sub(first_arg, second_arg): return first_arg - second_arg def mul(first_arg, second_arg): return first_arg * second_arg def div(first_arg, second_arg): return first_arg / second_arg class Calculette: def __init__(self): pass def add(self, first_arg, second_arg): return add(first_arg, second_arg) def sub(self, first_arg, second_arg): return sub(first_arg, second_arg) def mul(self, first_arg, second_arg): return mul(first_arg, second_arg) def div(self, first_arg, second_arg): return div(first_arg, second_arg) class CacluletteScientifique: def __init__(self, calculette): self.calculette = calculette def carre(self, value): carre = self.calculette.mul(value, value) return carre
db33940855cd12a6675db31ff4f779c1fa75d966
aman-singh7/training.computerscience.algorithms-datastructures
/09-problems/lc_461_hamming_distance.py
1,491
4.21875
4
class Solution_3: """ It optimized the previous solution It uses the trick: """ def hammingDistance(self, x: int, y: int) -> int: # 1. Find x's and y's bits that are different x ^= y # 2. Count the number of 1 bit_1_count = 0 while x != 0: bit_1_count += 1 x &= (x - 1) return bit_1_count class Solution_2: """ 1st. It finds all the different bits from x and y by using Xor operator on x and y 2nd. It computes the numbers of "1" in the resulted number """ def hammingDistance(self, x: int, y: int) -> int: # 1. Find x's and y's bits that are different x ^= y # 2. Count the number of 1 bit_1_count = 0 while x != 0: bit_1_count += (x & 1) x >>= 1 return bit_1_count class Solution_1: """ This solution checks every bit if they're equal or not by using the Xor operator Comment: we don't need to Xor for every bit """ # Time Analysis: O(1) # Space Analysis: O(1) def hammingDistance(self, x: int, y: int) -> int: different_bits_count = 0 for _ in range(32): different_bits_count += (x & 1) ^ (y & 1) x >>= 1 y >>= 1 return different_bits_count
499b753c4a9a6d2e519f5fd7b215fa55f144df09
mohitreddy1996/GenderFromName
/main.py
482
3.5625
4
from api_classifier import Genderize genderize = Genderize() while True: names = raw_input("Enter Names : (Break if you want to discontinue) ") names = names.split(' ') for name in names: flag, gender, prob = genderize.get_gender(name=name) if flag == 0: print "Name : " + name + " *** Gender : " + gender + " *** probabilty : " + str(prob) + " *** " else: print "Sorry couldn't find the gender for the name : " + name
15c7fc87068ec2232aaa3c0e541b57873433426a
vishnoiprem/pvdata
/lc-all-solutions-master/053.maximum-subarray/test.py
296
3.578125
4
class Solution: def maxSubArray(self,arr): print(arr) preSum=arr[0] maxSum=arr[0] for j in range(1,len(arr)): preSum=max(preSum+arr[j],arr[j]) maxSum=max(preSum,maxSum) return maxSum if __name__ == "__main__": print (Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
f8fe973133b7d30328007b33bcba57b351a92fbc
microprediction/pandemic
/pandemic/city.py
2,938
3.640625
4
import random, math import numpy as np def sprawl( geometry_params, num ): """ Chinese restaurant inspired sprawl model """ r = geometry_params['r'] s = geometry_params['s'] e = geometry_params['e'] b = geometry_params['b'] def bound(pos,b): return ( (pos[0]+b) % (2*b) - b , (pos[1]+b) % (2*b) - b ) def _neighbour(r, s, e, p, b ): """ Generate the next location, near to the position p :param r: float Typical distance to neighbour not including sprawl :param s: float Sprawl coef :param e: float Sprawl quadratic term :param p: (float,float) Neighbour :param b: float Bound :return: (float,float) """ return bound( ( r*np.random.randn()+(1+s)*p[0]+e*p[0]*abs(p[0]) , r*np.random.randn()+(1+s)*p[1]+e*p[1]*abs(p[1]) ),b=b) points = [ (0,0) ] for i in range(num-1): p = random.choice(points) points.append(_neighbour(r=r,s=s,e=e, p=p, b=b) ) return points def home_and_work_locations( geometry_params, num, centers=None ): def random_household_size(h): return 1 + np.random.binomial(n=6,p=(h-1)/8.0) if centers is None: b = geometry_params['b'] centers = [ (b/2*np.random.rand(),b/2*np.random.rand()),(0,-b*np.random.rand())] # Sprawl work locations around centers work_sprawls = list() for center in centers: work_sprawls.append( [ (pos[0]+center[0], pos[1]+center[1]) for pos in sprawl( geometry_params=geometry_params, num=num) ] ) work = [ random.choice(ws) for ws in zip( *work_sprawls ) ] # Sprawl homes away from centers also .. though further away geometry_params['r'] = 4 * geometry_params['r'] home_sprawls = list() for center in centers: home_sprawls.append( [(pos[0] + center[0], pos[1] + center[1]) for pos in sprawl(geometry_params=geometry_params, num=num)]) home_locations = [random.choice(hs) for hs in zip(*home_sprawls)] random.shuffle(home_locations) # Squeeze h people in each home. h = geometry_params['h'] # Avg number in household num_homes = int( math.ceil( num+500 / h ) ) home = [ hl for hl in home_locations[:num_homes] for _ in range(random_household_size(h)) ][:num] # Some stay home c = geometry_params['c'] work = [ w if np.random.rand()<c else h for w,h in zip(work,home) ] return home, work if __name__=="__main__": import matplotlib.pyplot as plt for _ in range(20): plt.close() import time from pandemic.example_parameters import LARGE_TOWN from pandemic.plotting import plot_points city = sprawl(geometry_params=LARGE_TOWN['geometry'], num=50000) plot_points(plt, city, status=None) plt.axis([-20,20,-20,20]) plt.show() plt.pause(0.001) time.sleep(1)
e10006587869a9420d9b7032f78472d52086d2db
venkyp1/Misc
/python_bits/dynamic_class_gen.py
1,331
4.25
4
###################################################### # Venky, Tue Aug 22 20:18:30 2017 # ###################################################### #This code to demonstrate ways of how a method can be added to a class instance dynamically (at run time). from types import MethodType class classA : pass def funA(self, data): print ("data = ", data) # Create an instance of classA ca = classA() # Add method to the instance (not to the class) using MethodType() # Syntax: instance.methodname = MethodType(methodName, instance, className) #ca.fun = MethodType(funA, ca, classA) # className is optional ca.fun = MethodType(funA, ca) # Note: Now, the method is available to the instance ONLY (not to the class). So another instance # of the class will not have the method available. ca.fun(100) # OTHER WAYS TO ADD A METHOD DYNAMICALLY ################################ # The following adds a method to the class so the new method will be available to all its instances. # including the objects created before adding the method. def dynaFun(self): # Make sure to pass 'self' as it will be a classMethod print ("dynaFun() called") classA.dynaFun = dynaFun new_ca = classA() new_ca.dynaFun() ca.dynaFun() # The instance was created before adding the method. How this works??
24b399829721b2b76f4b606a19368078a8c347e6
imran9217/oop_practice_M_IMRAN
/TASK/EVEN-ODD-NUMBER-WHILE-LAB-2-TASK.py
713
4.40625
4
#IMRAN LIAQAT #BAIM-S20-003 # EVEN ODD WITH WHILE LOOP ################################################################ Minimum = int(input(" Please Enter the Minimum Value : ")) Maximum = int(input(" Please Enter the Maximum Value : ")) number = 1 Minimum = number while number <= Maximum: if (number % 2 != 0): print(number,"IS ODD") number = number + 1 ################################################################ Minimum = int(input(" Please Enter the Minimum Value : ")) Maximum = int(input(" Please Enter the Maximum Value : ")) number = 1 Minimum = number while number <= Maximum: if (number % 2 == 0): print(number,"IS EVEN") number = number + 1
995a8e5f5ba43db1a0177b4e79512ddf2dd71e3a
piplani/doubly_linked_list
/add_after_given_node.py
1,082
4.25
4
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None def printlist(self): temp = self.head while temp: last = temp print temp.data, temp = temp.next print # if you want to print in reverse order """ while last: print last.data, last = last.prev """ def add(self, prev_node, new_data): new_node = Node(new_data) new_node.next = prev_node.next prev_node.next = new_node new_node.prev = prev_node.next if __name__ == '__main__': llist = DoublyLinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second second.next = third second.prev = llist.head third.prev = second print "before adding" llist.printlist() llist.add(llist.head, 1.5) llist.add(second, 2.5) print "after adding" llist.printlist()
18b7ebf4d30430b59406c6b3ec5ea1e6f856e19b
Mysyka/Skull
/Школа Х5/Урок 1/loops.py
591
4.15625
4
# Iterating over a single char in the string: for char in '123456789': print(char + '!') # Iterating over a single char in the string: for char in '123456789': if char == '2': continue print(char + '!') count = 10 while count > 0: print(count) count = count - 1 # Infinitive loop: while True: users_input = input('Please, input positive number: ') if float(users_input) > 0: print('Your number is: {0}'.format(users_input)) break else: print('{0} is a wrong number.'.format(users_input))
54401806a4486f133fb98f609246f3874ec9bc38
Maarten-vd-Sande/Rosalind-BioInformatics-Stronghold
/REVC/revc.py
310
3.703125
4
""" Solution to: http://rosalind.info/problems/revc/ """ with open("rosalind_revc.txt", 'r') as f: DNA = ''.join(f.readlines()) REV_COMPLEMENT = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} print(''.join([REV_COMPLEMENT[nuc] for nuc in reversed(DNA)]))
9a0b0db5c01ba78f224f2fe2ec9d189b00e798c4
Mohit-121/Arjuna_files
/Arjuna 25-8-19/DisneyPass.py
703
4.03125
4
def mincostPass(days,costs): ans=[0]*366 #ans is used to store ans for i in range(1,366): if (i not in days): ans[i] = ans[i - 1] #Non travel day cost is same as previous day #On travel day it is minimum of yesterday's cost plus single-day ticket, # or cost for 8 days ago plus 7-day pass, or cost 31 days ago plus 30-day pass else: ans[i] = min(ans[i - 1] + costs[0], ans[max(0, i - 7)] + costs[1], ans[max(0, i - 30)] + costs[2]) return ans[365] #Last day of the year gives the minimum cost days=list(map(int,input().split())) #Takes days array cost=list(map(int,input().split())) #Takes cost daily,weekly and monthly print(mincostPass(days,cost))
7c2d8ef6be8537af29d5493613dc72be77c14689
MohamedSafoury/Groking_Algorithms_exercises
/chapter4_QuickSorting/qsort.py
378
3.78125
4
def quickSort(array): #base case if len(array) < 2 : return array #recusive case else : pivot = array[0] less = [i for i in array[1:] if i <= pivot] greater = [i for i in array[1:] if i > pivot] return quickSort(less) + [pivot] + quickSort(greater) print(quickSort([1200,50,0.2,0.4,1,0,2000,10000,80,620,501,1000]))
c619c12e17c5a738e9c86059a0e82ad2918e53bf
ArjunChattoraj10/AChatt10
/Fun/Name Generator/Name Generator.py
2,950
4.15625
4
import string, random # Functions def length_asker(): """ This function is an i/o function that asks the user for a number that will be the length of the name, and returns the input. Any input that is not a positive integer is rejected and a sarcastic comment is printed, and the user is prompted for a different input. """ sarcastic = [ "And no, you are not funny.", "Stop being this way.", "Not funny btw.", "Ha. Hahaha. HAHAHAHAHAHAHAHHAHAHAHA. \n \n \n \t Stop.", "Omg you're like so funny like omg." ] length_input = input("\t Choose a length of the name: ") try: val = int(length_input) except ValueError: print("\t Input a positive integer in base 10 only. \n \t " + random.choice(sarcastic)) length_input = length_asker() if not (float(length_input) > 0 and float(length_input) % 1 == 0): print("\t Input a positive integer in base 10 only. \n \t " + random.choice(sarcastic)) length_input = length_asker() return(length_input) def letter_asker(): """ This function is an i/o function that the user for a choice of letter. Any input that is not a letter is rejected and a sarcastic comment is printed, with the user is prompted for a different input. """ sarcastic = [ "Wow. Such a genius.", "You think you're funny, don't ya.", "HEY CARL CHECK OUT THIS OUT. \n \t IT'S LIKE SO FUNNY. \n \t COMEDY. \n \t GOLD.", "Don't be a weirdo.", "This is why no one likes you." ] letter_in = input("\t Choose a letter CASE SENSITIVE: \n \t \t '1' for vowel -- a,e,i,o,u, \n \t \t '2' for consonants, \n \t \t '3' for any lowercase letter:, \n \t \t For a specific letter, simply type that letter: ") if len(letter_in) == 1 and letter_in in "123": return(letter_in) elif letter_in == "" or letter_in not in string.ascii_letters: print("\t Input 1,2,3 or a letter only. \n \t " + random.choice(sarcastic)) letter_in = letter_asker() def letter_generator(letter_input): """ This is a function to check what kind of letter should be used. Keyword arguments: letter_input -- an input from the user. If the input argument is "1", then the function returns a random vowel. If the input argument is "2", then the function returns a random consonant. If the input argument is "3", then the function returns a random lowercase letter. For any other letter input, the function simply returns the letter. """ vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstuvwxyz' if letter_input == "1": letter_out = random.choice(vowels) elif letter_input == "2": letter_out = random.choice(consonants) elif letter_input == "3": letter_out = random.choice(string.ascii_lowercase) else: # in the case user wants a specific letter letter_out = letter_input return(letter_out) # Function call length = length_asker() i = 0 name = [] while i < int(length): letter = letter_asker() name.append(letter_generator(letter)) i += 1 print("".join(name))
156ca024e6be1c7f02a133619583f34e79f7d703
NSMobileCS/pyfun
/pyfun10.py
432
3.625
4
from random import randrange def toss5K(): l = [randrange(2) for _ in range(5000)] headcount = 0 for idx, result in enumerate(l): sidename = 'tail' headcount += result if result: sidename = 'head' print("Attempt #{}: Throwing a coin... It's a {}... got {} heads and {} tails so far".format(idx+1, sidename, headcount, idx-headcount)) if __name__ == '__main__': toss5K()
f09129e5e714810d27c980fe29ef30eb8728ee85
Shiji-Shajahan/Python-Programs
/Creating course Report using Sets & Dictionaries.py
4,528
4.8125
5
#Lesson 6 Homework print('Lesson 6 Homework') course_name= "Introduction to Magic" print(f'The course name offered by ReDI School is {course_name}') print(f"This is a report about the \'{course_name}\' course.") print('\n') # Here, we define a list of students in the class. students = ['Michael', 'Kate', 'Scott', 'Lauren', 'Christopher'] print(f'The students in our class are: {students}') print('\n') # Here, we define a list of grades for a mid-term exam. grades = [100, 60, 55, 82, 90] print(f'The grades on the mid-term exam are: {grades}') print('\n') # 1. Using the function `max` on the `grades` list, define the variable # `best_grade` to be the max grade of the students. best_grade = max(grades) print(f'The best grade in the class is: {best_grade}') # 2. Using the function `min` on the `grades` list, define the variable # `worst_grade` to be the min grade of the students. worst_grade = min(grades) print(f'The worst grade in the class is: {worst_grade}') print('\n') # 3. Using the functions `sum` and `len` on the `grades` list as well as basic # math operations, define the variable `avg_grade` as the average grade of the students. student_strength= len(students) print(f'student_strength in the class is:{student_strength}') avg_grade = sum(grades)/student_strength print(f'The average grade in the class is: {avg_grade}') print('\n') # 4. Let's assume 'Alice' just joined the class. Add a line of code below, # which modifies the `students` list using the `append` operation in order to # add 'Alice' to the list of students. students.append('Alice') print(f'A new student, Alice, just joined the class!') print(f'The students in our class are now: {students}') print('\n') # Let's try a different data structure for storing the final exam grades. We'll # use a dictionary. final_grades = { 'Michael': 89, 'Kate': 100, 'Scott': 75, 'Lauren': 90, 'Christopher': 60, 'Alice': 84 } # 5. Fix the print statement to print Michael's final exam grade by using the # 'Michael' key to look up his grade in the `final_grades` dictionary print(f"Michael's final exam grade is {final_grades['Michael']}") # 6. Print the other students' final exam grades the same way you printed # Michael's. print(f"Kate's final exam grade is {final_grades['Kate']}") print(f"Scott's final exam grade is {final_grades['Scott']}") print(f"Lauren's final exam grade is {final_grades['Lauren']}") print(f"Christopher's final exam grade is {final_grades['Christopher']}") print(f"Alice's final exam grade is {final_grades['Alice']}") print('\n') # 7. One teacher realizes he made an error with Christopher's final exam # grade. Christopher actually got a 87. Fix his grade in the `final_grades` dictionary # by updating the value for the key 'Christopher' (not by recreating a new # dictionary). final_grades['Christopher']=87 print(f"Whoopsi, I made a mistake with Christopher's final exam grade. His grade is actually {final_grades['Christopher']}.") print('\n') # This `set` function creates a set from the list of students. all_students = set(students) passed = {'Michael', 'Lauren', 'Christopher', 'Alice'} print(f'The students who passed my class are: {passed}') # 8. Using the `difference` set operation, define variable `failed` as the set of # students who did not pass the class. failed = all_students.difference(passed) print(f'The students who failed my class are: {failed}') print('\n') women = {'Kate', 'Lauren', 'Alice'} # 9. Using the `intersection` set operation, define `passing_women` as the set of # women who passed the class. passing_women = passed.intersection(women) print(f'The women who passed my class are: {passing_women}') print('\n') teachers = {'Harry', 'Emma'} # 10. Using the `union` set operation, assign `all_people` the set of # all people, i.e. students and teachers, who are participating in this class. all_people =all_students.union(teachers) print(f'The students and teachers participating in this class are: ' f'{all_people}') # Optional BONUS: Create a few other report information. Feel free to be # creative by creating new sets or writing new statistics! print('\n') #Total men students in class men=all_students.difference(women) print(f'All men students in my class are:{men}') #men who passed the class passing_men= passed.difference(women) print(f' The men who passed my class are:{passing_men}') #failed men students in class failed_men=men.difference(passing_men) print(f'The men students failed in my class are:{failed_men}')