blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b45c396e6b80a33845f27583f96a22f385f7250d
jmishra01/Google_foobar_Challenge
/5/5_1 Expanding Nebula.py
5,858
3.515625
4
# Expanding Nebula # ================ # You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! - # one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You start monitoring the nebula, # but unfortunately, just a moment too late to find where the pod went. However, you do find that the gas of the steadily # expanding nebula follows a simple pattern, meaning that you should be able to determine the previous state of the gas and # narrow down where you might find the pod. # From the scans of the nebula, you have found that it is very flat and distributed in distinct patches, so you can model # it as a 2D grid. You find that the current existence of gas in a cell of the grid is determined exactly by its 4 nearby cells, # specifically, (1) that cell, (2) the cell below it, (3) the cell to the right of it, and (4) the cell below and to the right of it. # If, in the current state, exactly 1 of those 4 cells in the 2x2 block has gas, then it will also have gas in the next state. # Otherwise, the cell will be empty in the next state. # For example, let's say the previous state of the grid (p) was: # .O.. # ..O. # ...O # O... # To see how this grid will change to become the current grid (c) over the next time step, consider the 2x2 blocks of cells around # each cell. Of the 2x2 block of [p[0][0], p[0][1], p[1][0], p[1][1]], only p[0][1] has gas in it, which means this 2x2 block would # become cell c[0][0] with gas in the next time step: # .O -> O # .. # Likewise, in the next 2x2 block to the right consisting of [p[0][1], p[0][2], p[1][1], p[1][2]], two of the containing cells have # gas, so in the next state of the grid, c[0][1] will NOT have gas: # O. -> . # .O # Following this pattern to its conclusion, from the previous state p, the current state of the grid c will be: # O.O # .O. # O.O # Note that the resulting output will have 1 fewer row and column, since the bottom and rightmost cells do not have a cell below and to # the right of them, respectively. # Write a function answer(g) where g is an array of array of bools saying whether there is gas in each cell (the current scan of the nebula), # and return an int with the number of possible previous states that could have resulted in that grid after 1 time step. For instance, # if the function were given the current state c above, it would deduce that the possible previous states were p (given above) as well as # its horizontal and vertical reflections, and would return 4. The width of the grid will be between 3 and 50 inclusive, and the height of # the grid will be between 3 and 9 inclusive. The answer will always be less than one billion (10^9). # Languages # ========= # To provide a Python solution, edit solution.py # To provide a Java solution, edit solution.java # Test cases # ========== # Inputs: # (boolean) g = [[True, False, True], # [False, True, False], # [True, False, True]] # Output: # (int) 4 # Inputs: # (boolean) g = [[True, False, True, False, False, True, True, True], # [True, False, True, False, False, False, True, False], # [True, True, True, False, False, False, True, False], # [True, False, True, False, False, False, True, False], # [True, False, True, False, False, True, True, True]] # Output: # (int) 254 # Inputs: # (boolean) g = [[True, True, False, True, False, True, False, True, True, False], # [True, True, False, False, False, False, True, True, True, False], # [True, True, False, False, False, False, False, False, False, True], # [False, True, False, False, False, False, True, True, False, False]] # Output: # (int) 11567 # Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. from collections import defaultdict def gen_function(x, y, z): z = ~(2**z) a = x & z b = y & z c = x >> 1 d = y >> 1 return (a&~b&~c&~d) | (~a&b&~c&~d) | (~a&~b&c&~d) | (~a&~b&~c&d) def matrix(n, nums): dict_map = defaultdict(set) nums = set(nums) rn = 2**(n+1) for i in range(rn): for j in range(rn): generation = gen_function(i,j,n) if generation in nums: dict_map[(generation, i)].add(j) return dict_map def answer(g): g = list(zip(*g)) ncols = len(g[0]) nums = [sum([2**i if col else 0 for i, col in enumerate(row)]) for row in g] matrix_map = matrix(ncols, nums) pre_image = {i: 1 for i in range(2**(ncols+1))} for row in nums: next_row = defaultdict(int) for c1 in pre_image: for c2 in matrix_map[(row, c1)]: next_row[c2] += pre_image[c1] pre_image = next_row return sum(pre_image.values()) g = [[True, False, True], [False, True, False], [True, False, True]] assert answer(g) == 4 g = [[True, False, True, False, False, True, True, True], [True, False, True, False, False, False, True, False], [True, True, True, False, False, False, True, False], [True, False, True, False, False, False, True, False], [True, False, True, False, False, True, True, True]] assert answer(g) == 254 g = [[True, True, False, True, False, True, False, True, True, False], [True, True, False, False, False, False, True, True, True, False], [True, True, False, False, False, False, False, False, False, True], [False, True, False, False, False, False, True, True, False, False]] assert answer(g) == 11567
d5d2ac28e6e566984101db96010427dc702f18f5
jmishra01/Google_foobar_Challenge
/3/3_5 Find_the_Access_Codes.py
2,567
3.8125
4
# Find the Access Codes # ===================== # In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured # with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that includes the locks' access codes, but # only she knows how to figure out which of several lists contains the access codes. You need to find a way to determine which list contains the access # codes once you're ready to go in. # Fortunately, now that you're Commander Lambda's personal assistant, she's confided to you that she made all the access codes "lucky triples" in order to # help her better find them in the lists. A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4). With that information, # you can figure out which list contains the number of access codes that matches the number of locks on the door when you're ready to go in (for example, # if there's 5 passcodes, you'd need to find a list with 5 "lucky triple" access codes). # Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet # the requirement i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within # a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0. # For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total. # Languages # ========= # To provide a Python solution, edit solution.py # To provide a Java solution, edit solution.java # Test cases # ========== # Inputs: # (int list) l = [1, 1, 1] # Output: # (int) 1 # Inputs: # (int list) l = [1, 2, 3, 4, 5, 6] # Output: # (int) 3 # Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your # solution passes the test cases, it will be removed from your home folder. def answer(l): res = 0 i = 0 n_l = len(l) - 2 while i < n_l: first = l[i] j = i + 1 while j < n_l + 1: if l[j]%first == 0: res += sum([1 for k in l[j+1:] if k%l[j]==0]) j+=1 i+=1 return res assert answer([1,2,3,4,5,6])==3 assert answer([1,1,1])==1 assert answer([1,2,3,5,7,11])==0
6e59bbbea25aca648e640db7e36bcde89272d4a4
ArielGz08/unaj-2021-s2-unidad3-com16
/reuso_codigo_fuente.py
1,266
3.859375
4
# Vamos a ver como a través del uso de funciones podemos evitar tener código fuente repetido # Código fuente aportado por Walter Grachot (tiene unos 34 sentencias originalmente) def carga_producto_y_calcula_subtotal(): producto= input("Ingrese nombre del producto comprado: ") valor= float(input("Ingrese su valor: ")) cantidad= int(input("Ingrese la cantidad: ")) total= (valor*cantidad) producto = (producto, valor, cantidad) print(total) print() return total, producto def imprimir_subtotales(producto): print("Compró " + str(producto[1][2]) + " " + str(producto[1][0]) + " a un Precio Unitario de $" + str(producto[1][1]) + " por un total de " + str(producto[0])) print("Bienvenido al Supermercado Don Erne") print("-" * 80) dato_producto1 = carga_producto_y_calcula_subtotal() dato_producto2 = carga_producto_y_calcula_subtotal() dato_producto3 = carga_producto_y_calcula_subtotal() dato_producto4 = carga_producto_y_calcula_subtotal() imprimir_subtotales(dato_producto1) imprimir_subtotales(dato_producto2) imprimir_subtotales(dato_producto3) imprimir_subtotales(dato_producto4) total_general = dato_producto1[0] + dato_producto2[0] + dato_producto3[0] +dato_producto4[0] print ("Ha gastado en total " + str(total_general))
6ba4b5dedebb3eeca01e63654515cfbd086881aa
xiaojieluo/yygame
/game/calculator.py
7,110
4.34375
4
#!/usr/bin/env python # coding=utf-8 # copy from http://blog.chriscabin.com/coding-life/python/python-in-real-world/1101.html # Thanks class Stack(object): """ The structure of a Stack. The user don't have to know the definition. """ def __init__(self): self.__container = list() def __is_empty(self): """ Test if the stack is empty or not :return: True or False """ return len(self.__container) == 0 def push(self, element): """ Add a new element to the stack :param element: the element you want to add :return: None """ self.__container.append(element) def top(self): """ Get the top element of the stack :return: top element """ if self.__is_empty(): return None return self.__container[-1] def pop(self): """ Remove the top element of the stack :return: None or the top element of the stack """ return None if self.__is_empty() else self.__container.pop() def clear(self): """ We'll make an empty stack :return: self """ self.__container.clear() return self class Calculator(object): """ A simple calculator, just for fun """ def __init__(self): self.__exp = '' def __validate(self): """ We have to make sure the expression is legal. 1. We only accept the `()` to specify the priority of a sub-expression. Notes: `[ {` and `] }` will be replaced by `(` and `)` respectively. 2. Valid characters should be `+`, `-`, `*`, `/`, `(`, `)` and numbers(int, float) - Invalid expression examples, but we can only handle the 4th case. The implementation will be much more sophisticated if we want to handle all the possible cases.: 1. `a+b-+c` 2. `a+b+-` 3. `a+(b+c` 4. `a+(+b-)` 5. etc :return: True or False """ if not isinstance(self.__exp, str): print('Error: {}: expression should be a string'.format(self.__exp)) return False # Save the non-space expression val_exp = '' s = Stack() for x in self.__exp: # We should ignore the space characters if x == ' ': continue if self.__is_bracket(x) or self.__is_digit(x) or self.__is_operators(x) \ or x == '.': if x == '(': s.push(x) elif x == ')': s.pop() val_exp += x else: print('Error: {}: invalid character: {}'.format(self.__exp, x)) return False if s.top(): print('Error: {}: missing ")", please check your expression'.format(self.__exp)) return False self.__exp = val_exp return True def __convert2postfix_exp(self): """ Convert the infix expression to a postfix expression :return: the converted expression """ # highest priority: () # middle: * / # lowest: + - converted_exp = '' stk = Stack() for x in self.__exp: if self.__is_digit(x) or x == '.': converted_exp += x elif self.__is_operators(x): converted_exp += ' ' tp = stk.top() if tp: if tp == '(': stk.push(x) continue x_pri = self.__get_priority(x) tp_pri = self.__get_priority(tp) if x_pri > tp_pri: stk.push(x) elif x_pri == tp_pri: converted_exp += stk.pop() + ' ' stk.push(x) else: while stk.top(): if self.__get_priority(stk.top()) != x_pri: converted_exp += stk.pop() + ' ' else: break stk.push(x) else: stk.push(x) elif self.__is_bracket(x): converted_exp += ' ' if x == '(': stk.push(x) else: while stk.top() and stk.top() != '(': converted_exp += stk.pop() + ' ' stk.pop() # pop all the operators while stk.top(): converted_exp += ' ' + stk.pop() + ' ' return converted_exp def __get_result(self, operand_2, operand_1, operator): if operator == '+': return operand_1 + operand_2 elif operator == '-': return operand_1 - operand_2 elif operator == '*': return operand_1 * operand_2 elif operator == '/': if operand_2 != 0: return operand_1 / operand_2 else: print('Error: {}: divisor cannot be zero'.format(self.__exp)) return None def __calc_postfix_exp(self, exp): """ Get the result from a converted postfix expression e.g. 6 5 2 3 + 8 * + 3 + * :return: result """ assert isinstance(exp, str) stk = Stack() exp_split = exp.strip().split() for x in exp_split: if self.__is_operators(x): # pop two top numbers in the stack r = self.__get_result(stk.pop(), stk.pop(), x) if r is None: return None else: stk.push(r) else: # push the converted number to the stack stk.push(float(x)) return stk.pop() def __calc(self): """ Try to get the result of the expression :return: None or result """ # Validate if self.__validate(): # Convert, then run the algorithm to get the result return self.__calc_postfix_exp(self.__convert2postfix_exp()) else: return None def get_result(self, expression): """ Get the result of an expression Suppose we have got a valid expression :return: None or result """ self.__exp = expression.strip() return self.__calc() """ Utilities """ @staticmethod def __is_operators(x): return x in ['+', '-', '*', '/'] @staticmethod def __is_bracket(x): return x in ['(', ')'] @staticmethod def __is_digit(x): return x.isdigit() @staticmethod def __get_priority(op): if op in ['+', '-']: return 0 elif op in ['*', '/']: return 1 # usage c = Calculator() print('result: {:f}'.format(c.get_result('8+10/2'))) print(int(c.get_result('8+10'))) # output: result: 0.666000
aee33d9d32071f96b20643094deb1c6fc6158768
EwertonLuan/Curso_em_video
/56_cadastro_de_pessoas.py
881
3.703125
4
ida = 0 # idade dos dois somados h_velho = 0 # idade do homem mais velho h_vn = '' # Nome do homem mais velho m_20 = 0 # mulheres com 20 anos for i in range(1, 5): nome = str(input('Digite o nome {}ª pessoa: '.format(i))) idade = int(input('Dite idade {}ª pessoa: '.format(i))) ida += idade sexo = str(input('Qual o sexo da {}ªpessoa (H/M): '.format(i))).upper().strip() if sexo == 'H' and i == 1: h_velho = idade h_vn = nome elif idade > h_velho: h_velho = idade h_vn = nome if sexo == 'M' and idade < 20: m_20 += 1 media = ida / 4 print('Media de idade entre homens e mulheres é de {}'.format(media)) print('O homem mais velho é o {} com {} anos de idade'.format(h_vn, h_velho)) print('{} mulheres com menos de 20 anos'.format(m_20))
c966acf1bedce7a5d9ff29d21a4e9db069c70141
EwertonLuan/Curso_em_video
/41_categoria_atleta.py
714
3.8125
4
from datetime import date print('\033[1;32m##\033[m' * 20+'\nPrograma para ver a categoria dos atletas\n'+'\033[1;32m##\033[m'*20) ida = date.today().year - int(input('Qual a idade do atleta: ')) if ida <= 9: print('Atleta esta com {} anos, sua categoria é \033[1;33mMIRIM\033[m'.format(ida)) elif ida <= 14: print('Atleta esta com {} anos, sua categoria é \033[1;34mINFANTIL\033[m'.format(ida)) elif ida <= 19: print('Atleta esta com {} anos, sua categoria é \033[1;35mJUNIOR\033[m'.format(ida)) elif ida <= 20: print('Atleta esta com {} anos, sua categoria é \033[1;36mSENIOR\033[m'.format(ida)) else: print('Atleta esta com {} anos, sua categoria é \033[1;31mMASTER\033[m'.format(ida))
0fa3b0ba1cc789068b001406df17eba6a53c8628
changzhai/project_euler
/project_euler/src/pe23.py
1,726
4.0625
4
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. instructions = """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ import utils def is_abundant(n): if sum(utils.factors(n)) - n > n: return True else: return False abundant = [] total = 0 for x in range(1,28123+1): not_abundant = True if is_abundant(x): abundant.append(x) print(str(x) + ' is abundant') for n in [n for n in abundant if x/n>=2]: if (x - n) in abundant: not_abundant = False break if not_abundant: total += x print(str(x) + ', total = ' + str(total)) else: print(str(x) + 'is the sum of abundants') print(total)
a0c074a2bca1cb02d862c7f5ce267ee28785adc4
kbethany/LPTHW
/ex19_drill.py
754
3.53125
4
#create new function, cheese_and_crackers, which has two variables def pets(cat_count, dog_count): #the function has four things inside it contains, 4 print statements print "You have %d cat!" % cat_count print "You have %d dog!" % dog_count print "Man, those are hungry pets!" print "Give them a boost!\n" print "We can just give the function numbers directly:" #prints the functino where 20 and 30 map to first and second variables pets(1, 1) print "OR, we can use variables from our script:" amount_of_cat = 1 amount_of_dog = 5 pets(amount_of_cat, amount_of_dog) print "We can even do math inside, too:" pets(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" pets(amount_of_cat + 100, amount_of_dog + 1000)
feb27cb841884e8a2460cbe7cc645bb2ba7ae2fb
kbethany/LPTHW
/ex15.py
912
3.765625
4
#sys is a package, argv says to import only the vars listed #when you call up the program (ex15.py filename), where argv is any #module i want retrieved from that package. from sys import argv #argv is the arguments vector which contains the arguments passed #to the program. script, filename = argv #opens the filnemae listed above txt = open(filename) #prints the name of the file as defined above print " Here's your file %r:" % filename #prints everything inside the text file print txt.read() #calls a function on txt named 'read' print "Type the filename again:" #prompts the user to input the filename again (see print command above) #and sets what she enters to file_again file_again = raw_input("> ") #function that opens the text of file_again and sets the whole text #as txt_again txt_again = open(file_again) #function that prints everything in txt_again without modification print txt_again.read()
a9d1ca7beb482a72282d801a27858350ff365c7a
migeller/thinkful
/pip_001/fizz_buzz/fizz_buzz.py
642
3.828125
4
#!/usr/bin/env python import sys def modulo(x, y): """ Determines if we can divide x from y evenly. """ return x % y == 0 def stepper(limit = 100): """ Steps through from 1 to limit and prints out a fizzbuzz sequence. """ print "Our Upper Limit is %d! Let's go!" % limit for n in xrange(1, limit + 1): if modulo(n, 3): print "fizz", if modulo(n, 5): print "\b-buzz" else: print "\b" elif modulo(n, 5): print "buzz" else: print n if __name__ == '__main__': try: i = sys.argv[1] except IndexError: stepper() else: try: limit = int(i) except ValueError: stepper() else: stepper(limit)
3b78e75671e8048fe45e4dfa2319d6cbc7d3bfe1
YoZe24/lingi2364-projects
/project1/src/apriori_prefix_vdb.py
3,406
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def apriori(filepath, minFrequency, verbose=True): """Runs the apriori algorithm on the specified file with the given minimum frequency. This version has: - intelligent candidate generation using prefixes (implemented using lists); - frequency computation using union of singleton database projections, with break if minsup cannot be reached; - no additional anti-monotonicity pruning.""" ngen = 0 nsupp = 0 nfreq = 0 # read data; this is heavily inspired from the provided template transactions_set = list() lines = filter(None, open(filepath, "r").read().splitlines()) app = transactions_set.append items = 0 for line in lines: transaction = list(map(int, line.rstrip().split(" "))) items = max(items, transaction[-1]) # transactions are sorted, find number of items app(set(transaction)) trans = len(transactions_set) # number of transactions member = [set() for i in range(items+1)] for t in range(len(transactions_set)): for i in transactions_set[t]: member[i].add(t) # store the transactions t in which item i appears minSupport = trans * minFrequency if not minSupport == int(minSupport): minSupport = int(minSupport) + 1 def frequency(itemset): """Returns the frequency of the given itemset for the current list of transactions""" # compute the intersection of all member[i] where i in itemset # this intersection contains all the transactions covered by itemset s = member[itemset[0]] if len(itemset) > 1: for i in itemset[1:]: s = s & member[i] if len(s) < minSupport: return 0 return len(s)/trans F = [] # frequent sets for i in range(items): nsupp += 1 ngen += 1 freq = frequency([i + 1]) if freq >= minFrequency: F += [[i+1]] if verbose: nfreq += 1 print("%s (%g)" % ([i+1], freq)) # print frequent singleton sets while F != []: # list of subsets of items of size level l = F[:] # deep copy the list F = [] cnt = 1 for l1 in l[:-1]: l11 = l1[:-1] # take prefix for l2 in l[cnt:]: if l11 == l2[:-1]: # if the sets share a common prefix newl = l1 + [l2[-1]] # new candidate based on sets sharing prefixes freq = frequency(newl) nsupp += 1 ngen += 1 if freq >= minFrequency: F += [newl] if verbose: nfreq += 1 print("%s (%g)" % (newl, freq)) # print frequent sets else: # prefix will never be the same again, we can skip break cnt += 1 if verbose: print(ngen) print(nsupp) print(nfreq) if __name__ == "__main__": """ ti = 0 for i in range(10): s = time.perf_counter() apriori("../statement/Datasets/accidents.dat", 0.9, verbose=False) ti += time.perf_counter() - s print(ti/10) """ apriori('../statement/Datasets/chess.dat', 0.99, verbose=True)
a6f2c1f7a0acbdf5f1685ebd3456be49aeb01aed
peter0703257153/School-project
/school_directory.py
3,555
3.78125
4
__author__ = 'pedro' class School_directory(object): def __init__(self): self.schools = [] def add(self, school_name): self.schools.append(school_name) def find(self, name): for school in self.schools: if school.school_name == name: return school def get_school(self): return self.schools class School(object): def __init__(self, school_name): self.streams = [] self.school_name = school_name def add(self, stream): self.streams.append(stream) def find(self, stream_name): for stream in self.streams: if stream.name == stream_name: return stream def __repr__(self): return self.school_name school_directory = School_directory() class Stream(object): def __init__(self, name): self.name = name self.students = [] self.teachers = [] def add_student(self, student): self.students.append(student) def add_teacher(self, teacher): self.teachers.append(teacher) def find_student(self, student_name): for student in self.students: if student.name == student_name: return student.name def find_teacher(self, teacher_name): for teacher in self.teachers: if teacher.name == teacher_name: return teacher.name def get_students(self): return self.students class Student(object): def __init__(self, name, age, parent_name): self.name = name self.age = age self.parent_name = parent_name def __repr__(self): return self.name class Teacher(object): def __init__(self, name): self.name = name def register_student(): stream_name = raw_input("Enter the stream") school = raw_input("Enter name of the school") name = raw_input("Enter student name") age = raw_input("Enter age") parent = raw_input("Enter parent name") school_name = school_directory.find(school) student = Student(name, age, parent) stream = school_name.find(stream_name) stream.add_student(student) school_name = school_directory.find(school) stream = school_name.find(stream_name) print stream.get_students() showmenue() def register_teacher(): name = raw_input("Enter teacher name") teacher = Teacher(name) stream = Stream() stream.add_teacher(teacher) showmenue() def register_stream(): school = raw_input("Enter name of the school") stream_name = raw_input("Enter stream name") stream = Stream(stream_name) school_name = school_directory.find(school) school_name.add(stream) showmenue() def register_school(): school_name = raw_input("Enter school name") school = School(school_name) school_directory.add(school) print school_directory.get_school() showmenue() def showmenue(): print "1 - Enter stream" print "2 - Enter student" print "3 - Enter teacher" print "4 - Enter school name" print "5 - Find school" print "6 - Find teacher" print "7 - Find student" menue = int(raw_input("Choose any number")) if menue == 2: register_student() elif menue == 3: register_teacher() elif menue == 1: register_stream() elif menue == 4: register_school() showmenue()
381d4fa43d359440ffc3198333987812e06308c7
aishwariya-7/apple
/main.py
324
3.703125
4
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' Str ="I LOVE BEEZ LAB"; count =0; for(i in range(0.len(Str))): if(Str[i]!=' '): count=count+1; print(Str(count));
ff73cf14435050af2da53a669de66c9aa5de32aa
bruyneron/python_ds
/algo/bubble_sort.py
625
3.859375
4
# TC - O(n^2) def ascending_sort(a): n = len(a) for i in range(0, n): for j in range(0, n-1-i): # (n-1)-i => n-1 becuase we are doing a[j] & a[j+1]. We don't want to go over the limit of j and get index out of range error. if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] def descending_sort(a): n = len(a) for i in range(0, n): for j in range(0, n-1-i): if a[j] < a[j+1]: a[j], a[j+1] = a[j+1], a[j] if __name__ == '__main__': arr = [23, 43, 541, 12, 1, 12, 323] print(arr) descending_sort(arr) print(arr)
83dfa83903466ca2eca35f96a9351f76d7dc9adb
bruyneron/python_ds
/ds/queue.py
4,221
3.78125
4
''' 1) List enqueue() | q.append() dequeue() | q.pop(0) 1st element is 0 size() | len(q) is_empty() | len(q)==0 2) SLL/DLL (Have to use DLL. Reason: With SLL deletion takes O(n), Queue is supposed to take O(1) for deletion) <--- This is dumb why?? SLL with head and tail. Insertion @ tail (No deletion @ tail) -> O(1) Deletion @ head (No insertion @ head) -> O(1) 1 -> 2 -> 3 -> | | head Tail ------------------------------------------------------------------------------------ FIFO - QUEUE Insertion | O(1) Deletion | O(1) Access/Search | O(n) ''' class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class Queue: def __init__(self): self.head = None self.tail = None def is_empty(self): # if (self.head is self.tail) doesn't work for identifying empty queue # Reason: If queue has only one element, then head and tail pint to the same element return self.head is None and self.tail is None def enqueue(self, data): ''' 2 cases: 1) Empty queue 2) Non empty queue ''' if self.is_empty(): self.head = self.tail = Node(data, None) return self.tail.next = Node(data, None) self.tail = self.tail.next def dequeue(self): ''' 3 cases: 1) Empty queue 2) Non-empty queue with more than 1 elements 3) Non-empty queue with exactly 1 element ''' if self.is_empty(): raise Exception('Queue is empty. Can\'t dequeue') dequeued_element = self.head.data # Don't return node itself. If node is returned returned node can be used to traverse the Queue self.head = self.head.next # In case of a Queue 'q' with one element # 1 --> None # /\ # head tail # # After: q.dequeue() # # 1 --> None # | | # tail head # # Tail would still be pointing to an element. Hence queue won't be empty. So tail should be reset # For queue to be empty condition is: (self.head is None) and (self.tail is None) # if self.head is None: self.tail = None return dequeued_element def size(self): if self.is_empty(): return 0 itr = self.head length = 0 while itr: length += 1 itr = itr.next return length def reverse(self): if self.is_empty(): return # Reverse links (Reversing linked list) prev = None curr = self.head while curr: next = curr.next curr.next = prev prev = curr curr = next # Reverse head and tail markers temp = self.head self.head = self.tail self.tail = temp def print(self): if self.is_empty(): print('Queue is empty') return itr = self.head qstr = '' while itr: qstr += str(itr.data) + '-->' itr = itr.next print(qstr) if __name__ == '__main__': q = Queue() q.print() print(q.head, q.tail) q.enqueue(1) q.print() print(q.head.data, q.tail.data) q.enqueue(2) q.print() print(q.head.data, q.tail.data) q.enqueue(3) q.print() print('Size', q.size()) print(q.head.data, q.tail.data) print(q.dequeue()) q.print() print(q.head.data, q.tail.data) print(q.dequeue()) q.print() print(q.head.data, q.tail.data) print(q.dequeue()) q.print() print(q.head, q.tail) print('Size', q.size()) #q.dequeue() print('For fun\n==========') q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) q.print() print(f'head = {q.head.data}, tail = {q.tail.data}') q.reverse() q.print() print(f'head = {q.head.data}, tail = {q.tail.data}') q.enqueue(0) q.print() q.dequeue() q.print()
751fab2eb3a2da8e335dff8b2ae2da160df1872f
lx881219/webley-puzzle
/webley.py
3,392
3.78125
4
import csv import sys import pathlib class Solution: def __init__(self): self.result = [] self.target_price = None self.menu = [] def handle_file_error(self): print('Please provide a valid csv file in the following format. (python webley.py example.csv)') print(""" Target price, $14.55 mixed fruit,$2.15 french fries,$2.75 side salad,$3.35 hot wings,$3.45 mozzarella sticks,$4.20 sampler plate,$5.80 """) def get_price(self, raw_price): """ convert raw price to float :param raw_price: raw price in string format :return: price in float format """ try: price = float(raw_price.split('$')[-1]) except ValueError: print("Invalid price") sys.exit() return price def parse_csv(self, csv_file): """ parse the csv file :param csv_file: csv file name :return: True when file is successfully parsed """ current_dir = pathlib.Path.cwd() file = pathlib.Path(current_dir, csv_file) if file.exists(): with open(file, mode='r') as f: csv_reader = csv.reader(f) first_row = next(csv_reader, None) if not first_row: self.handle_file_error() return False if 'Target price' in first_row: self.target_price = self.get_price(first_row[1]) for row in csv_reader: if row: menu_item, menu_price = row[0], self.get_price(row[1]) self.menu.append((menu_item, menu_price)) # sort the menu by price for fast lookup self.menu.sort(key=lambda x: x[1]) return True self.handle_file_error() return False def find_combination(self, target, index, current): """ a recursive function to find the right combination :param target: the target price :param index: current index :param current: current combination :return: """ if target == 0.0: # hard copy the current combination self.result = list(current) return True for i in range(index, len(self.menu)): if target < self.menu[i][1]: break current.append(i) found = self.find_combination(target-self.menu[i][1], i, current) if found: return True else: current.pop() def solution(self): args = sys.argv if len(args) < 2: self.handle_file_error() else: parse_result = self.parse_csv(str(args[1])) if parse_result: self.find_combination(self.target_price, 0, []) if self.result: print("We can order the following dishes given the target price $%f:" % self.target_price) for i in self.result: print(self.menu[i][0], ''.join(['$', str(self.menu[i][1])])) else: print("There is no combination of dishes that is equal to the target price") s = Solution() s.solution()
96265a429106573491aed434cec6d734534eea5a
backcover7/Algorithm
/15. 3Sum.py
3,174
3.515625
4
import bisect class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] if len(nums)<3: return res length = len(nums) listsort = sorted(nums) for start in range(length-2): if listsort[start] > 0: break if start > 0 and listsort[start] == listsort[start-1]: continue point = start + 1 end = length - 1 while point<end: total = listsort[start] + listsort[point] + listsort[end] if total < 0: point += 1 elif total > 0: end -= 1 else: res.append([listsort[start], listsort[point], listsort[end]]) while point < end and listsort[point] == listsort[point+1]: point += 1 while point< end and listsort[end] == listsort[end-1]: end -= 1 point += 1 end -= 1 return res def threeSum_180ms(self, nums): ans = [] numcounts = self.count(nums) # get set(nums) and their counts nums = sorted(numcounts) # same as set(nums) for i, num in enumerate(nums): ''' We consider two scenarios: When there are duplicate nums in a solution When all values in a solution are unique at which point, we perform twosum for each negative num ''' if numcounts[num] >= 2: # there are 2 scenarios for 2 duplicate vals if num == 0: # zeros if numcounts[num] >= 3: ans.append([0, 0, 0]) else: # and non-zeros if (-2 * num) in nums: ans.append([num, num, -2 * num]) if num < 0: ans = self.twosum(ans, nums, numcounts, num, i) return ans def twosum(self, ans, nums, numcounts, num, i): """Find two numbers a, b such that a + b + num = 0 (a + b = -num)""" twosum = -num # find 2 nums that sum up to this positive num left = bisect.bisect_left(nums, (twosum - nums[-1]), i + 1) # minval right = bisect.bisect_right(nums, (twosum // 2), left) # maxval for num2 in nums[left:right]: # we do this knowing the list is sorted num3 = twosum - num2 if num3 in numcounts and num3 != num2: ans.append([num, num2, num3]) return ans def count(self, nums): """Organize nums by `{num: occurence_count}`""" count = {} for num in nums: if num in count: count[num] += 1 else: count[num] = 1 return count s = Solution() s.threeSum_180ms([-1, 0, 1, 2, -1, -4]) # Given array nums = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1], # [-1, -1, 2] # ]
d4eec8ca65674a001474dcd2574fcbfea7d9df70
backcover7/Algorithm
/70. Climbing Stairs.py
1,148
3.59375
4
class Solution(object): def climbStairs_recurse(self, n): """ :type n: int :rtype: int """ # recurse but time limit exceeded # Time complexity: O(2^n) if n <= 1: return 1 return self.climbStairs_recurse(n-1) + self.climbStairs_recurse(n-2) # recurse with memory: Top-to-Down, main problem first # def __init__(self): # self.mem = {0:1, 1:1} def climbStairs_recurse_with_memory(self, n): if n not in self.mem: self.mem[n] = self.climbStairs_recurse_with_memory(n - 1) + self.climbStairs_recurse_with_memory(n - 2) return self.mem[n] def climbStairs_dp_with_onearray(self, n): # Down-to-Top, subproblem first # space complexity: O(n) dp = [1] * (n+1) for i in xrange(2, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] def climbStairs(self, n): # one param, space complexity: O(1) dp1, dp2 = 1, 1 for x in xrange(2, n+1): dp2, dp1 = dp1+dp2, dp2 return dp2 S = Solution() print S.climbStairs(36)
65da66866a817543e61627a73d2eed4cc2e6abb2
backcover7/Algorithm
/513. Find Bottom Left Tree Value.py
714
3.9375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ if not root: return max_depth = 0 queue = [(root, 1)] while queue: curr, level = queue.pop(0) if curr: if level > max_depth: max_depth = level ans = curr.val queue.append((curr.left, level+1)) queue.append((curr.right, level+1)) return ans
ac51f8eefc234d49caf3a6a2eaee68f88f018e38
backcover7/Algorithm
/29. Divide Two Integers.py
862
3.640625
4
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ # https://www.youtube.com/watch?v=htX69j1jf5U sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: x = 0 # 2^x # b*2^0; b*2^1; b*2^2 while a >= b << (x + 1): x += 1 res += 1 << x a -= b << x ''' 3*2^0=3, 10>3, x=0 3*2^1=6, 10>6, x=1 3*2^2=12, 10<12, x=2 [NO] res = 1<<x = 2^1 = 2 10-3*2^1=10-6=4 4->res=2+{1}=3 #This is the answer ''' return min(res if sig else -res, 2147483647) a = 10 b = 3 S = Solution() print S.divide(a, b)
1451fa9c04e5ce8636d023001c663fb6a988b0bf
wajishagul/wajiba
/Task4.py
884
4.375
4
print("*****Task 4- Variables and Datatype*****") print("Excercise") print("1. Create three variables (a,b,c) to same value of any integer & do the following") a=b=c=100 print("i.Divide a by 10") print(a,"/",10,"=",a/10) print("ii.Multiply b by 50") print(b,"*",50,"=",b*50) print("iii.Add c by 60") print(c,"+",50,"=",b+50) print("2.Create a String variable of 5 characters and replace the 3rd character with G") str="ABCDE" print("Length of the string is:",len(str)) s1="C" s2="G" print("new string after replacement:",str.replace(s1,s2)) print("3.Create two values (a,b) of int,float data type & convert the vise versa") a,b=200,55.5 print("a=",a,"b=",b) a=float(a) b=int(b) print("value of a and b after type conversion:") print("a=",a,"b=",b) print("data type of a after conversion:",type(a)) print("data type of b after conversion:",type(b)) print("-----Task 4 Completed-----")
ac8beccafc68748818a0de9915cfc0cec1c81cb7
Reynbra/Portfolio
/python/TurtleFrogger/scoreboard.py
1,993
3.921875
4
from turtle import Turtle FONT = ("Courier", 20, "normal") SCORE_COLOR = "white" ROAD_LINE_COLOR = "white" SCORE_ALIGNMENT = "left" LIVES_ALIGNMENT = "right" GAME_OVER_ALIGNMENT = "center" LEVEL_TEXT = "Level" LIVES_TEXT = "Lives" GAME_OVER = "GAME OVER" class Scoreboard(Turtle): def __init__(self): super().__init__() self.penup() self.color(SCORE_COLOR) self.level = 0 self.lives = 3 self.update_level() # self.car_chance = CAR_SPAWN_RATE_CHANCE def draw_road_lines(self): self.hideturtle() self.penup() self.pencolor(ROAD_LINE_COLOR) self.goto(280, -230) self.setheading(180) for _ in range(600): self.pendown() self.forward(20) self.penup() self.forward(20) self.goto(280, 230) self.setheading(180) for _ in range(600): self.pendown() self.forward(20) self.penup() self.forward(20) # TODO Make the goto function iterate by a total of 40 pixels # TODO Make the loop use the new increased value for position # TODO Possibly optimize the drawing function by repeating 10 or so times def update_level(self): self.draw_road_lines() self.goto(-290, 260) self.write(f"{LEVEL_TEXT}: {self.level}", align=SCORE_ALIGNMENT, font=FONT) self.goto(290, 260) self.write(f"{LIVES_TEXT}: {self.lives}", align=LIVES_ALIGNMENT, font=FONT) def increase_level(self): self.level += 1 # self.car_chance -= 1 self.clear() self.update_level() def decrease_lives(self): self.lives -= 1 self.clear() self.update_level() def game_over(self): if self.lives == 0: self.goto(0, 0) self.write(arg=f"GAME OVER", align=GAME_OVER_ALIGNMENT, font=FONT) return False else: return True
fc7353b01d945e9bbbaebd7aa6a6dd8f59ed8d2a
LucindaDavies/codeclan_caraoke
/tests/room_test.py
1,236
3.671875
4
import unittest from classes.room import Room from classes.guest import Guest from classes.song import Song class TestRoom(unittest.TestCase): def setUp(self): self.song1 = Song("Help", "The Beatles") self.song2 = Song("Saturday Night", "Sam Cooke") self.songs = [self.song1, self.song2] self.guest1 = Guest("Hannah") self.guest2 = Guest("Louise") self.guest3 = Guest("Harry") self.guests = [self.guest1, self.guest2, self.guest3] self.room = Room("Motown", 3) def test_room_has_name(self): self.assertEqual("Motown", self.room.get_name()) def test_can_add_song(self): song = self.song2 self.room.add_song_to_room(song) self.assertEqual(1, self.room.number_of_songs()) def test_can_check_in_guest(self): self.room.check_in_guest(self.guest1) self.assertEqual(1, self.room.number_of_guests()) def test_room_has_capacity(self): self.assertEqual(3, self.room.get_capacity()) def test_can_check_guest_out(self): self.room.check_in_guest(self.guest3) self.room.check_out_guest(self.guest3) self.assertEqual(0, self.room.number_of_guests())
302f242cb6fc42a6350e476cc19a5460bd56361f
50Leha/automation_tests
/rospartner/utils.py
390
4.0625
4
""" Module with utility functions """ from random import choice import string def generate_email_name(): """ utility to generate random name and email :return: tuple(email, name) """ name = [choice(string.ascii_letters) for _ in range(5)] email_tail = '@foo.bar' # join to string name = ''.join(name) email = name + email_tail return email, name
c6f8241e148b4e503af3f3709885ee964e931838
x-jeff/Tensorflow_Code_Demo
/Demo3/3.1.MNIST_classification_simple_version.py
1,542
3.53125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 #该语句会自动创建名为MNIST_data的文件夹,并下载MNIST数据集 #如果已存在,则直接读取数据集 mnist=input_data.read_data_sets("MNIST_data",one_hot=True) #mini-batch size batch_size=100 #训练集的数目 #print(mnist.train.num_examples)#55000 #一个epoch内包含的mini-batch个数 n_batch=mnist.train.num_examples // batch_size #定义网络的输入和输出 x=tf.placeholder(tf.float32,[None,784])#28*28*1=784 y=tf.placeholder(tf.float32,[None,10])#0,1,2,3,4,5,6,7,8,9 #创建一个简单的神经网络(无隐藏层) W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) prediction=tf.nn.softmax(tf.matmul(x,W)+b) #均方误差 loss=tf.reduce_mean(tf.square(y-prediction)) #梯度下降法 train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化变量 init=tf.global_variables_initializer() #统计预测结果 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#返回一个布尔型的列表 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("Iter "+str(epoch)+", Testing Accuracy "+str(acc))
340e077ad8099cd7baca8c3b057c004ea81f827e
vspatil/Python3-HandsOn
/Chapter_4_IF_stmts/exercise_5.1.py
863
3.796875
4
car ='golf' car == 'olf' ##print(car) """ car = 'Golf' print("Is car == 'Golf'? , I predict True.") print(car == 'Golf') print("\nIs car == 'Audi'? , I predict False.") print(car == 'Audi') deserts = 'Kheer' print("Is desrt == 'Kheer'? , I predict True.") print(deserts == 'Kheer') print("Is desert == 'Ice Cream'? , I predict False.") print (deserts == 'Ice Cream') name = 'vani' print(name == 'vani') print(name== 'Trisha') print(name == 'Vani') print(name.title()== 'Vani') print(name.upper() == 'vani') print(name.lower() == 'vani') print(name != 'vani') age = 18 print( age > 21) print(age < 21) print( age == 21) print (age > 10 and age < 15 ) print(age > 10 and age < 20 ) print (age> 10 or age <15) print(age != 18) print(age) """ name = ['Santosh','Vani','Trisha','Aditi'] print('Vani' in name) print('Usha' in name) print('Vani' not in name)
209d0d207a72810d04216d15b8bafdbea0c50c36
vspatil/Python3-HandsOn
/Chapter_8_Classes_Methods/Exercise_9.13.py
675
3.890625
4
#9.13 """ from collections import OrderedDict favourite_languages = OrderedDict() favourite_languages['Brad'] = 'SQL' favourite_languages['Adam'] = 'ERP' favourite_languages['Mike'] = 'Python' favourite_languages['Chris'] = 'JAVA' for name , language in favourite_languages.items(): print( name.title() + " 's favourite language is : " + language.title()) """ #9.14 #from random import randint #x = randint(1,6) #print(x) from random import randint class dice(): def __init__(self,sides): self.sides = sides def roll_dice(self): x= randint(1,self.sides) print( "Random number now we got is : " + str(x)) d= dice(20) d.roll_dice()
e4849cacfa472b48f1fdb666339c05655b491ffa
vspatil/Python3-HandsOn
/Chapter_6_UserInputs_whileLoops/Exercise_7.5.py
1,580
4.15625
4
"""prompt = "Enter a series of toppings : " message = "" while message != 'quit': message = input(prompt) if message == 'quit': break else: print("We will add " + message + " to the pizza!")""" """ age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age < 3: print("The ticket is free!") elif age > 3 and age < 12: print("The ticket costs $10!") else: print("The ticket costs $15!") """ #using condition in the while stmt """age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") elif age > 12 : print("The ticket costs $15!")""" #Using active variable to control the loop """active = True while active: age = input("Enter your age : ") if age == 'quit': active = False elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") else: print("The ticket costs $15!")""" #using break stmt to exit the loop """ age='' while age != 'quit': age = input("Enter your age : ") if age == 'quit': break elif age <= 3: print("The ticket is free!") elif age > 3 and age <= 12: print("The ticket costs $10!") else: print("The ticket costs $15!")""" # loop that never ends or infinte loop x = 1 while x <= 5: print(x) # x=x+1
9badd15b93c998b8ae1eae271cbb7062d96aa860
duxinn/data_structures_algorithms
/算法和数据结构的应用/顺序表相关/search.py
1,168
3.953125
4
# 搜索是在一个项目集合中找到一个特定项目的算法过程。搜索通常的答案是真的或假的,因为该项目是否存在。 # 当然可以按照具体需求,返回值可以设为要查找的元素的下标,不存在返回-1 # 搜索的几种常见方法:顺序查找、二分法查找、二叉树查找、哈希查找 # 本文只是基于顺序表实现的查找算法,二叉树,哈希以后在介绍 def find(L, item): '''顺序查找,对排序的顺序表没有要求 最优:O(1) 最差:O(n) ''' for i in L: if i == item: return True return False def binary_search(L, item): '''二分查找,也叫折半查找, 对排序的顺序表要求是:有序列表,不可以是链表(链表不能定位访问) 最优:O(1) 最差:O(logn) ''' n = len(L) if n == 0: return False mid = n // 2 if L[mid] == item: return True elif L[mid] < item: return binary_search(L[mid + 1:], item) else: return binary_search(L[:mid - 1], item) if __name__ == '__main__': l = [x for x in range(10)] print(l) # 顺序查找测试 print(find(l, 88)) # 二分查找测试 print(binary_search(l, 9))
fd54b8243950b9f4fa2a96387dae8962fc2aa9d1
duxinn/data_structures_algorithms
/数据结构/栈和队列/queue.py
597
4
4
class Queue(object): '''队列的实现,通过list存储数据''' def __init__(self): self.__queue = [] def enqueue(self, item): '''入队操作''' self.__queue.append(item) def dequeue(self): '''出队操作''' return self.__queue.pop(0) def is_empty(self): '''判断是否为空''' return not self.__queue def size(self): '''返回队列的长度''' return len(self.__queue) if __name__ == '__main__': queue = Queue() queue.enqueue(5) queue.enqueue(4) queue.enqueue(3) queue.enqueue(2) print(queue.size()) print(queue.is_empty()) print(queue.dequeue())
26248c4900a2793b3fa9d03434f62af8cffacbc9
mihail-serafim/Pytest_Doxygen_Flake8
/src/CircleT.py
1,887
3.65625
4
## @file CircleT.py # @author Mihail Serafimovski # @brief Defines a circle ADT # @date Jan. 10, 2021 from Shape import Shape ## @brief Defines a circle ADT. Assumption: Assume all inputs # provided to methods are of the correct type # @details Extends the Shape interface class CircleT(Shape): ## @brief Constructor for CircleT # @param x A real number which is the x-component of the center of mass # @param y A real number which is the y-component of the center of mass # @param r A real number which is the radius of the circle # @param m A real number which is the mass of the circle # @throws ValueError if the radius or mass are not both greater than zero def __init__(self, x, y, r, m): if not(r > 0 and m > 0): raise ValueError self.x = x self.y = y self.r = r self.m = m ## @brief Getter for x-component of center of mass # @returns A real number which is the x-component # of the circle's center of mass def cm_x(self): return self.x ## @brief Getter for y-component of center of mass # @returns A real number which is the y-component # of the circle's center of mass def cm_y(self): return self.y ## @brief Getter for mass of circle # @returns A real number which is the mass of the circle def mass(self): return self.m ## @brief Getter for moment of inertia of the circle # @returns A real number which is the moment of inertia of the circle def m_inert(self): return self.m * (self.r**2) / 2 ## @brief Method to help with object comparison when testing # @param other Another shape to test for equality # @returns A boolean, true iff both objects have the same state variables def __eq__(self, other): return self.__dict__ == other.__dict__
a3824f6e28c7cc6f87bca06600ee9f162c03f1f7
AliMorty/B.SC.-Project
/Code/Queen.py
3,023
3.703125
4
from random import randint from ProblemFile import ProblemClass gameSize = 8 class QueenProblem(ProblemClass): def get_initial_state(self): arr = [] for i in range( 0 , gameSize): arr.append(i) # for i in range (0 , gameSize): # print(arr[i]) return QueenState(arr) def get_initial_state_random(self): arr = [] for i in range( 0 , gameSize): arr.append(-1) for i in range (0 , gameSize): rand = randint(0,7-i) count=0 for j in range (0, gameSize): if arr[j]==-1: if count == rand: arr[j] = i break if count != rand: count += 1 return QueenState(arr) def get_actions(self, state): # print ("This is a test!") return state.get_actions() def get_result(self, state, action): arr = list(state.arr) i= action.first j= action.second tmp=arr[i] arr[i]=arr[j] arr[j]=tmp return QueenState(arr) def is_goal(self, state): return state.is_goal() def get_score(self, state): return state.get_score() def get_cost(self, state, action): return 1 def is_equal(self, state1, state2): return state1.is_equal(state2) def show_state(self, state): state.show_state() class QueenState(): def __init__(self, initialArr): self.arr = initialArr return def get_actions (self): actions = [] for i in range (0, gameSize): for j in range (i+1, gameSize): actions.append(QueenAction(i, j)) # print("actions", len(actions)) return actions def is_goal(self): for i in range (0 , gameSize): for j in range (i+1, gameSize): if (abs(self.arr[j]-self.arr[i])==j-i): return False return True def get_score(self): score=0 for i in range (0 , gameSize): for j in range (i+1, gameSize): if (abs(self.arr[j]-self.arr[i])==j-i): score+=1 score=-score return score def is_equal (self, s): arr = s.arr for i in range (0 , gameSize): if self.arr[i] !=arr[i]: return False return True def show_state(self): # for i in range (0 , gameSize): # for j in range (0, gameSize): # if (self.arr[i]==j): # print ("#", end='') # else: # print ("-", end='') # print() print("[", end='') for i in range (0, gameSize -1 ): print (self.arr[i], ",", end='') print(self.arr[gameSize-1],"]") class QueenAction(): def __init__(self, first, second): self.first= first self.second=second return
45dfca16469965060a325a60de88582be64df8ce
gousiosg/attic
/coding-puzzles/graph.py
2,340
3.828125
4
#!/usr/bin/env python3 import queue as q from typing import List class Node(): def __init__(self, value): self.visited = False self.neighbours: List[Node] = [] self.value = value def __repr__(self): return str(self.value) class Graph(): def __init__(self, nodes): self.nodes: List[Node] = nodes def reset(self): for n in self.nodes: n.visited = False def bfs(self, n_start: Node) -> List[Node]: result = [] work_queue = q.Queue() work_queue.put(n_start) result.append(n_start) n_start.visited = True while not work_queue.empty(): cur = work_queue.get() for n in cur.neighbours: if not n.visited: work_queue.put(n) n.visited = True result.append(n) return result def dfs(self, n_start: Node) -> List[Node]: result = [] result.append(n_start) n_start.visited = True for n in n_start.neighbours: if not n.visited: for r in self.dfs(n): result.append(r) return result def topo_visit(self, node, stack = [], visited : set = set()) -> List[Node]: if node not in visited: visited.add(node) for neighbour in node.neighbours: self.topo_visit(neighbour, stack, visited) stack.append(node) def topo(self): stack = [] visited = set() for node in self.nodes: self.topo_visit(node, stack, visited) return stack a, b, c, d, e, f = Node("A"), Node("B"), Node("C"), Node("D"), Node("E"), Node("F") h = Node("H") a.neighbours = [b, c, e] b.neighbours = [d, a] c.neighbours = [a, d, h] d.neighbours = [b, c, f] e.neighbours = [a] f.neighbours = [d] h.neighbours = [c, f] #g = Graph([a, b, c, d, e, f, h]) #assert(g.bfs(a) == ['A', 'B', 'C', 'E', 'D', 'H', 'F']) #assert(g.bfs(h) == ['H', 'C', 'F', 'A', 'D', 'B', 'E']) #print(f"BFS from A:{g.bfs(a)}") #print(f"BFS from A:{g.dfs(a)}") a.neighbours = [b, c, e] b.neighbours = [d] c.neighbours = [h, d] d.neighbours = [f] e.neighbours = [] f.neighbours = [] h.neighbours = [f] g = Graph([a, b, c, d, e, f, h]) print(f"Topological sort:{g.topo()}")
e1c3c0e94463b139ac244a685556d19698fd0e5c
grigil/Useless_functions
/sortByHeight/sortByHeight.py
204
3.625
4
def sortByHeight(a): b=0 k=0 while k < len(a): i=0 while i < len(a): if a[i]!=-1: if a[k]!=-1: if a[k]<a[i]: b=a[i] a[i]=a[k] a[k]=b i=i+1 k=k+1 return a a
8386925eadcb21fba3a504222cac6fadbc610e37
ashwani-rathee/DIC_AI_PROGRAM
/8-andgate.py
3,269
3.5
4
# create a proper neural network to classify 00,01,10,11 # importing numpy library import numpy as np from numpy import linspace import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d from scipy import signal # sigmoid function def sigmoid(x): return 1/(1+np.exp(-x)) x1 = 0 x2 = 1 w1 = np.random.random() w2 = np.random.random() w3 = np.random.random() w4 = np.random.random() w5 = np.random.random() w6 = np.random.random() w7 = np.random.random() w8 = np.random.random() w9 = np.random.random() b1 = np.random.random() b2 = np.random.random() b3 = np.random.random() b4 = np.random.random() z1 = 0 z2 = 0 z3 = 0 a1 = 0 a2 = 0 a3 = 0 z4 = 0 a4 = 0 losses = [] def plotgraph(name ,x = range(1,10000), y = losses): # Data for plotting fig, ax = plt.subplots() ax.plot(x, y) ax.set(xlabel='Steps(i)', ylabel='Loss(loss)', title='Loss Vs Steps') ax.grid() fig.savefig("{}.png".format(name)) plt.show() return def forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4): global z1, z2, z3, z4, a1, a2, a3, a4 z1 = w1*x1 + w4*x2 + b1 z2 = w2*x1 + w5*x2 + b2 z3 = w3*x1 + w6*x2 + b3 a1 = sigmoid(z1) a2 = sigmoid(z2) a3 = sigmoid(z3) z4 = w7*a1 + w8*a2 + w9*a3 + b4 a4 = sigmoid(z4) def backwardpropagation(expected_output): global w1, w2, w3, w4, w5, w6, w7, w8, w9, b1, b2, b3, b4 global z1, z2, z3, z4, a1, a2, a3, a4 # calculating derivative of loss function dl_da4 = -(expected_output - a4) # calculating derivative of sigmoid function dl_dz4 = dl_da4 * a4 * (1-a4) dl_db4 = dl_dz4 dl_dw7 = dl_dz4 * a1 dl_dw8 = dl_dz4 * a2 dl_dw9 = dl_dz4 * a3 dl_da1 = dl_dz4*w7 dl_da2 = dl_dz4*w8 dl_da3 = dl_dz4*w9 dl_dz1 = dl_da1*a1*(1-a1) dl_dz2 = dl_da2*a2*(1-a2) dl_dz3 = dl_da3*a3*(1-a3) dl_db1 = dl_dz1 dl_db2 = dl_dz2 dl_db3 = dl_dz3 dl_dw1 = dl_dz1*x1 dl_dw2 = dl_dz2*x1 dl_dw3 = dl_dz3*x1 dl_dw4 = dl_dz1*x2 dl_dw5 = dl_dz2*x2 dl_dw6 = dl_dz3*x2 lr = 1 w1 = w1 - lr*dl_dw1 w2 = w2 - lr*dl_dw2 w3 = w3 - lr*dl_dw3 w4 = w4 - lr*dl_dw4 w5 = w5 - lr*dl_dw5 w6 = w6 - lr*dl_dw6 w7 = w7 - lr*dl_dw7 w8 = w8 - lr*dl_dw8 w9 = w9 - lr*dl_dw9 b1 = b1 - lr*dl_db1 b2 = b2 - lr*dl_db2 b3 = b3 - lr*dl_db3 b4 = b4 - lr*dl_db4 loss = 0.5*(expected_output - a4)**2 return loss for i in range(1,10000): dataset = [[0,0,0],[0,1,0],[1,0,0],[1,1,1]] print("Step:",i) i = np.random.randint(0,4) x1 = dataset[i][0] x2 = dataset[i][1] expected_output = dataset[i][2] # print("x1: ",x1,"x2: ",x2,", expected_output: ",expected_output) forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) loss = backwardpropagation(expected_output) losses.append(loss) print("Loss :{0:.3f}".format(loss)) if loss == 0: break # plotgraph("And") # graph of loss versus steps while(True): x1 = int(input("Enter x1 : ")) x2 = int(input("Enter x2 : ")) forwardpropagation(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) print(x1,x2,w1,w2,w3,w4,w5,w6,w7,w8,w9,b1,b2,b3,b4) print("Output : {0:.3f}".format(a4))
04859558d6e5f72cfb55f04050eb86543567c754
JonathanGrimmSD/projecteuler
/031-040.py
8,156
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division __author__ = "Jonathan Grimm" __date__ = "07.02.18" import math # 031: Coin sums: def count(S, m, n): if n == 0: return 1 if n < 0: return 0 if m <= 0 and n >= 1: return 0 return count(S, m - 1, n) + count(S, m, n - S[m - 1]) def project031(): d = [200, 100, 50, 20, 10, 5, 2, 1] m = len(d) return count(d, m, 200) # 032: Pandigital products: def project032(): erg=[] for i in range(1,100): for j in range(100,10000): temp=str(i)+str(j)+str(i*j) if "0" not in temp: if len(temp)==9 and len(set(temp))==9: if i*j not in erg: erg.append(i*j) return sum(erg) # 033: Digit cancelling fractions: def project033(): frac=[1,1] for numerator in range(10,100): for denominator in range(numerator+1,100): if numerator%10!=0 or denominator%10!=0: dupes=getduplicates(numerator,denominator) if dupes is not None: num=str(numerator).replace(dupes,"") den=str(denominator).replace(dupes,"") if numerator/denominator==int(num)/int(den): frac=[frac[0]*numerator,frac[1]*denominator] return frac[1]//ggt(frac[0],frac[1]) def ggt(x,y): if y>x: temp=x x=y y=temp while True: if x%y==0: return y else: rest=x%y x=y y=rest def getduplicates(x,y): xy=str(x)+str(y) myset=set(xy) duplicates=[] for each in myset: count = xy.count(each) if count==2: duplicates.append(each) if len(duplicates)==1 and xy.count("0")==0 and str(x).count(duplicates[0])==1: return duplicates[0] else: return # 034: Digit factorials def nfak(n): fak = 1 i = 1 while i < n + 1: fak *= i i += 1 return fak def check034(x): res = 0 for i in xrange(len(str(x))): res += nfak(int(str(x)[i])) return res == x def project034(): n = 1 while n * nfak(9) > 10 ** n: n += 1 res = 0 for i in xrange(3, 10 ** n): if check034(i): res += i return res # 035: Circular primes: class project035: def __init__(self): self.digits = "024568" # if one of these is last digit it cant be a prime number self.primes = [] for i in xrange(1000000): if self.is_prime(i) and self.intersect(i): self.primes.append(i) def intersect(self, x): if len(str(x)) == 1: return True else: return not (len(set(str(x)).intersection(set(self.digits))) > 0) def is_prime(self, n): if n == 2: return True if n % 2 == 0 or n <= 1: return False sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: return False return True def rotation(self, n): n = str(n) r = [int(n)] for i in range(len(n) - 1): n = n[1:] + n[0] r.append(int(n)) return list(set(r)) def calc(self): res = 0 n = 0 while True: if n + 1 >= len(self.primes): break prm = self.rotation(self.primes[n]) if set(prm).issubset(self.primes): res += len(prm) self.primes = [x for x in self.primes if x not in prm] else: n += 1 return res # 036: Double-base palindromes def check_palindrome(x): if len(str(x)) == 1: return True for i in range(len(str(x)) / 2): if str(x)[i] != str(x)[-1 * (i + 1)]: return False return True def project036(): res = 0 for i in range(0, 1000000): if check_palindrome(i): if check_palindrome(int("{0:b}".format(i))): print i, " --- ", int("{0:b}".format(i)) res += i return res # 037: Truncatable primes: from math import sqrt; from itertools import count, islice def isPrime(n): return not (n > 1 and all(n % i for i in islice(count(2), int(sqrt(n) - 1)))) def primes2(n): #credit to 'Robert William Hanks' https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n - n % 6 + 6, 2 - (n % 6 > 1) sieve = [True] * (n / 3) for i in xrange(1, int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[k * k / 3::2 * k] = [False] * ((n / 6 - k * k / 6 - 1) / k + 1) sieve[k * (k - 2 * (i & 1) + 4) / 3::2 * k] = [False] * ( (n / 6 - k * (k - 2 * (i & 1) + 4) / 6 - 1) / k + 1) return [2, 3] + [3 * i + 1 | 1 for i in xrange(1, n / 3 - correction) if sieve[i]] def project037(p=100): while True: primes = primes2(p) x = primes x = x[4:] for n in range(len(x) - 1, -1, -1): a = [(x[n] // (10 ** i)) % 10 for i in range(int(math.ceil(math.log(x[n], 10))) - 1, -1, -1)] b = set([0, 4, 6, 8]) if len(set(a).intersection(b)) > 0: del x[n] elif a[0] == 1 or a[-1] == 1: del x[n] trunc = [] for i in x: n = i cond = True for j in xrange(len(str(n)) - 1): if isPrime(int(str(n)[:j + 1])): cond = False break if isPrime(int(str(n)[j + 1:])): cond = False break if cond: trunc.append(i) if len(trunc) >= 11: break else: p *= 10 return sum(trunc) # 038: Pandigital multiples: def project038(): erg=[None,None,0] i=0 cond=True while cond: i+=1 n=1 prod="" while True: prod+=str(i*n) if n==1 and len(prod)>5: cond=False break if prod.count("0")>0: break if len(prod)!=len(set(prod)): break if len(prod)>9: break if len(prod)==9: if int(prod)>int(erg[2]): erg=[i,range(1,n+1),prod] break #print i,range(1,n+1),prod n+=1 return erg[2] # 039: Integer right triangles: def project039_old(): maxlen=[0,None] for p in xrange(2,1000,2): tris=len(getTriangles(p)) if tris>maxlen[0]: maxlen=[tris,p] return maxlen[1] def getTriangles(p): erg=[] for a in xrange(1,p): b=a if p<math.sqrt(a**2+b**2)+a+b: break for b in xrange(a,p): if p>a+b>p-(a+b): if p==math.sqrt(a**2+b**2)+a+b: erg.append([a,b,p-(a+b)]) if p<math.sqrt(a**2+b**2)+a+b: break return erg def project039(): C={} for a in range(1,500): for b in range(a,500): c=int(math.sqrt(a*a+b*b)) if a*a+b*b==c*c: try: C[a+b+c]+=1 except KeyError: C[a+b+c]=1 p=-1 maxvar=-1 for i,j in C.iteritems(): if j>maxvar: p=i maxvar=j return p # 040: Champernowne's constant def project040(): irr = "" i = 1 while len(irr) < 1000000: irr += str(i) i += 1 fac = 1 for i in range(0, 7): fac *= int(irr[(10 ** i) - 1]) return fac import time t = time.time() # print project031() # print project032() # print project033() # print project034() # print project035().calc() # print project036() # print project037() # print project038() # print project039() # print project040() print time.time()-t
4291e627f6dee78285a3d018a8ea6c9fc7a8ffd9
Jackroll/aprendendopython
/exercicios_udemy/Programacao_Procedural/perguntas_respostas_57.py
1,548
3.765625
4
#sistema de perguntas e respostas usando dicionário #criado dicionário Perguntas que contem chave pergunta, e o valor da che é outro dicionário #com perguntas e respostas perguntas = { #{pk} : {pv} 'pergunta 1' : { #{pv[pergunta]} 'pergunta': 'Quanto é 2 + 2 ?', #{rk} : {rv} 'respostas' : {'a': 1, 'b' : 4, 'c': 55}, #{pv[resposta_certa]} 'resposta_certa' : 'b' }, 'pergunta 2' : { 'pergunta': 'Quanto é 2 * 10 ?', 'respostas' : {'a': 20, 'b' : 350, 'c': 55}, 'resposta_certa' : 'a' }, 'pergunta 3' : { 'pergunta': 'Quanto é 15 / 3 ?', 'respostas' : {'a': 230, 'b' : 3, 'c': 5}, 'resposta_certa' : 'c' }, } resposta_certa = 0 #variável para armazenar as respostas certas for pk, pv in perguntas.items(): #iteração para percorrer o dicionário pai print(f'{pk} : {pv["pergunta"]}') print('Respostas :') for rk, rv in pv['respostas'].items(): #iteraão para percorrer o dicionário filho print(f'[{rk}] : {rv}') resposta_usuario = input('Sua resposta : ') if resposta_usuario == pv['resposta_certa']: print('Acertou !! \n') resposta_certa += 1 else: print('Errou !! \n') qtd_perguntas = len(perguntas) erros = qtd_perguntas - resposta_certa percentual = int(resposta_certa / qtd_perguntas * 100) print(f'Acertos: {resposta_certa}\nErros: {erros}\n{percentual} % de acerto')
fc70c57920b9e56aae696754aa6ff347e7971aba
Jackroll/aprendendopython
/exercicios_udemy/desafio_contadores_41.py
375
4.3125
4
"""fazer uma iteração para gerar a seguinte saída: 0 10 1 9 2 8 3 7 4 6 5 5 6 4 7 3 8 2 """ # método 01 - usando while i = 0 j = 10 while i <= 8: print(i, j) i = i+1 j = j-1 print('------------------') # método 02 - usando for com enumerate e range for r, i in enumerate(range(10,1, -1)): #enumerate conta quantas vezes houve a iteração print(r, i)
88cce404c8ad3f07c9e4f09b09d80a8ffc660acb
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/desafio_poo/banco.py
879
3.921875
4
# Classe Banco, possui cadastro com agencias, clientes e contas class Banco: def __init__(self): self.agencia = [111, 222, 333] self.clientes = [] self.contas = [] #método para cadastrar clientes no banco def cadastrar_cliente(self, cliente): self.clientes.append(cliente) #método para cadastrar conta no banco def cadastrar_conta(self, conta): self.contas.append(conta) #método para autenticação, somente será possível fazer transações se o cliente, a cota e a agencia existirem no banco #ou seja se já tiverem sido cadastrados def validacao(self, cliente): if cliente not in self.clientes: return False if cliente.conta not in self.contas: return False if cliente.conta.agencia not in self.agencia: return False return True
972a883e10eda7523b400da701755868927938e8
Jackroll/aprendendopython
/agregacao/classes.py
982
4.3125
4
""" Agregação é quando uma classe pode existir sozinha, no entanto ela depende de outra classe para funcionar corretamente por exemplo: A Classe 'Carrinho de compras' pode existir sózinha, mas depende da classe 'Produtos' para pode funcionar corretamente pois seus métodos dependem da classe produto. E classe Produtos por sua vez existe sozinha e não depende em nada da classe Carrinho de compras """ class CarrinhoDeCompras: def __init__(self): self.produtos = [] def inserir_produto(self, produto): self.produtos.append(produto) def lista_produtos(self): i = 0 for produto in self.produtos: i = i+1 print(f'Item : {i} - {produto.nome} R$ {produto.valor}') def soma_total(self): total = 0 for produto in self.produtos: total += produto.valor return total class Produto: def __init__(self, nome, valor): self.nome = nome self.valor = valor
0c1622a3e7497ab2ef4a8274bf3cae27492824df
Jackroll/aprendendopython
/exercicios/PythonBrasilWiki/exe003_decisao.py
490
4.1875
4
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. letra = str(input('Digite F ou M :')) letra_upper = letra.upper() #transforma a string para Uppercase para não haver erro em caso de digitação da letra em minusculo if letra_upper == 'F': print(f'{letra_upper} - é feminino') elif letra_upper == 'M' : print(f'{letra_upper} - é masculino') else : print ('Sexo invalido')
55dace0617bee83c0abef6e191326eb87f464c6a
Jackroll/aprendendopython
/exercicios_udemy/Programacao_Procedural/arquivos/arquivo_aula_83.py
1,867
4.125
4
file = open('abc.txt', 'w+') #cria o arquivo 'abc.txt' em modo de escrita w+ apaga tudo que ta no arquivo antes de iniciar a escrita file.write('linha 1\n') #escreve varias linhas no arquivo file.write('linha 2\n') file.write('linha 3\n') file.write('linha 4\n') print('-=' * 50) file.seek(0,0) #coloca o cursor no inicio do arquivo para fazer a leitura print('Lendo o arquivo :') print(file.read()) #faz a leitura do arquivo print('-=' * 50) file.seek(0, 0) #coloca o cursor no inicio do arquivo para fazer a leitura print(file.readlines()) #gera uma lista com as linhas do arquivo print('-=' * 50) file.seek(0, 0) for linha in file.readlines(): #lendo atraves de um for print(linha, end='') #end = '' retira a quebra de linha file.close() #fecha o arquivo print('-=' * 50) with open ('abc2.txt', 'w+') as file: #utilizando o with não precisar mandar fechar o arquivo com file.close() file.write('Arquivo 2 - linha 1\n') #escreve varias linhas no arquivo file.write('Arquivo 2 - linha 2\n') file.write('Arquivo 2 - linha 3\n') file.write('Arquivo 2 - linha 4\n') file.seek(0) print(file.read()) print('-=' * 50) with open ('abc3.txt', 'a+') as file: #Adicionando linhas ao arquivo, o a+ manda o cursor para o final do arquivo file.write('Adcicionando linhas 1\n') file.write('Adcicionando linhas 2\n') file.write('Adcicionando linhas 3\n') file.write('Adcicionando linhas 4\n') file.write('Adcicionando linhas 5\n') file.seek(0) print(file.read()) print('-=' * 50) with open ('abc3.txt', 'r+') as file: #lendo oque esta dentro do arquivo e mostrando na tela atraves do r+ print(file.read())
5a335fbe510d1f1f212e5f14d7658c5419433237
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/composicao/main.py
681
3.90625
4
"""Composição: Uma classe é dona de objetos de outra classe Se a classe principal for apagada todas as classes que foram usadas pela classe principal serão apgadas com ela """ #Por conta da composição, não houve a necessidad de importação da classe endereço, já que ela compoe a classe Cliente from classes import Cliente print('-='*15) c1 = Cliente('Jacson', 33) c1.insere_endereco('Imarui', 'SC') c1.lista_enderecos() print('-='*15) c2 = Cliente('Pedro', 12) c2.insere_endereco('Londrina', 'PR') c2.lista_enderecos() print('-='*15) c3 = Cliente('Bia', 43) c3.insere_endereco('Salvador', 'BA') c3.insere_endereco('Belem', 'PA') c3.lista_enderecos() print('-='*15)
d5e351dc79c6ce6ef0e4eff3683a8640af0adfdf
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/composicao/classes.py
931
3.765625
4
#classe cliente que recebe uma instancia da classe endereço para atualizar sua lista de endereços class Cliente: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.enderecos = [] def insere_endereco(self, cidade, estado): self.enderecos.append(Endereco(cidade, estado)) #neste ponto é feita a composição, quando uma instancia da classe Endereço é chamada def lista_enderecos(self): for endereco in self.enderecos: print(endereco.cidade, endereco.estado) #neste ponto tambem é feita a composição através do acesso aos atributos padrão #atraves do instaciamento da classe Endereco() #classe endereço,recebe dois atributos padrão class Endereco: def __init__(self, cidade, estado): self.cidade = cidade self.estado = estado
14aaf8a634e733d0cc8b08e69615b924fc9274ef
Jackroll/aprendendopython
/exercicios_udemy/poo/aula90_classes/pessoas.py
1,555
4.03125
4
from datetime import datetime class Pessoa: ano_atual = int(datetime.strftime(datetime.now(), '%Y')) #atributo de classe def __init__(self, nome, idade, comendo = False, falando=False): #atributo do objeto, o de método self.nome = nome self.idade = idade self.comendo = comendo self.falando = falando def falar(self, assunto): if self.comendo: print(f'{self.nome} esta comendo não pode falar') return if self.falando: print(f'{self.nome} já esta falando') return print(f'{self.nome} esta falando sobre {assunto}') self.falando = True def comer(self, alimento): if self.falando: print(f'{self.nome} esta falando não pode comer') return if self.comendo: print(f'{self.nome} já esta comendo') return print(f'{self.nome} esta comendo {alimento}') self.comendo = True def parar_falar(self): if not self.falando: print(f'{self.nome} já não esta falando') return print(f'{self.nome} parou de falar') self.falando = False def parar_comer(self): if not self.comendo: print(f'{self.nome} já não esta comendo') return print(f'{self.nome} parou de comer') self.comendo = False def ano_nascimento(self): ano = self.ano_atual - self.idade print(f'{self.nome} nasceu em {ano}')
e76d821bf83cad07252a52fd9184058abff76da9
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/context_manager/context_manager_lib.py
839
3.890625
4
#método 02 de criar gerenciador de contexto - usando contextmanager, atraves da criação de uma função. from contextlib import contextmanager # é criado uma função normal, só que decorada com @contextmanager para virar gerenciador de contexto @contextmanager def abrir(arquivo, modo): try: print('Abrindo o arquivo') arquivo = open(arquivo, modo) #abre o arquivo yield arquivo # é igual o return, só que ao contrário do return, executa o código seguinte finally: arquivo.close() #fecha o arquivo with abrir('teste_02.txt', 'w') as arquivo: #para funcionar deve sempre ser usado com o with arquivo.write('linha 01 \n') arquivo.write('linha 02 \n') arquivo.write('linha 03 \n') arquivo.write('linha 04 \n')
2f18dce6db44f8cbde41683bccd3f16611aace20
Jackroll/aprendendopython
/exercicios_udemy/Modulos_uteis/Json/json_main.py
978
4.34375
4
""" trabalhando com json Documentação : https://docs.python.org/3/library/json.html json -> python = loads / load python -> json = dumps / dump """ from aprendendopython.exercicios_udemy.Modulos_uteis.Json.dados import * import json # convertendo dicionário para json dados_json = json.dumps(clientes_dicionario, indent =4) #usado ident=4 para dar a correta identação print(dados_json) #convertendo de json para pyhton (dicionário) print('xx'*50) dicionario_json = json.loads(clientes_json) for v,j in dicionario_json.items(): print(v) print(j) print('xx'*50) #convertendo, criando e gravando um dicionário em json with open('clientes.json', 'w') as arquivo: json.dump(clientes_dicionario, arquivo, indent=4) print('Conversão efetuada !') print('xx'*50) #convertendo e lendo um json em dicionário with open('clientes.json', 'r') as arquivo: dados = json.load(arquivo) for chave, valor in dados.items(): print(chave) print(valor)
1b139816100f6157c1492c44eb552c096fb8b32f
verma-rahul/CodingPractice
/Medium/InOrderTraversalWithoutRecursion.py
2,064
4.25
4
# Q : Given a Tree, print it in order without Traversal # Example: 1 # / \ # 2 3 => 4 2 5 1 3 # / \ # 4 5 import sys import random # To set static Seed random.seed(1) class Node(): """ Node Struct """ def __init__(self,val=None): self.val=val self.right=None self.left=None class BinaryTree(): def __init__(self,root=None): self.root=root def make_random_balnaced_tree(self,size): """ Constructs a random Balanced Tree & prints as an Array Ex: [1,2,3,4,5] => 1 / \ 2 3 / \ 4 5 """ val=random.randint(0, 100) self.root=Node(val) stack=[self.root];size=size-1;arr_tree=[val] while size>0: node=stack.pop(0) val=random.randint(0,100) left=Node(val) arr_tree.append(val) node.left=left stack.append(left) size=size-1 if size>0: val=random.randint(0,100) right=Node(val) node.right=right arr_tree.append(val) stack.append(right) size=size-1 print("Balanced Tree as Array: ", arr_tree) def print_inorder(self): """ Prints the Tree Inorder """ stack=[self.root] node=self.root print("Inorder Traversal of Tree: ") while len(stack)>0: if node!=None and node.left!=None: stack.append(node.left) node=node.left else: poped=stack.pop() print(poped.val) node=poped.right if node!=None: stack.append(node) def main(args): tree=BinaryTree() tree.make_random_balnaced_tree(10) tree.print_inorder() if __name__=='__main__': main(sys.argv[1:])
ffb8dd75a8a0fc099a0bdcdebf42df80831ef9ff
tistaharahap/woods.py
/woods.py
11,344
3.515625
4
import sys class OutOfTheWoods(object): def __init__(self): print chr(27) + "[2J" self.name = "John Doe" self.fragileObjectInFrontOfTree = "" self.fragileObjectCondition = "" self.wildAnimalSeen = "" self.takeTheWildAnimalWithMe = False self.stayWithGranny = False self.torchCarried = 0 self.jumpToPond = False self.askTheEntity = False self.fightBack = True self.beginStory() def beginStory(self): sys.stderr.write("\x1b[2J\x1b[H") print "Before we start, what is your name?", self.name = raw_input() print "\nOk", self.name, "let's start.." print "\n\n>> It is a sun shining brightly day and you are on your way climbing a mountain with your friends." print ">> As you are enjoying the views surrounding you, somehow you were separated from your friends." print ">> You find yourself now all alone where woods and forest is all around you." self.pressAnyKey() self.theFragilityOfYourHeart() def theFragilityOfYourHeart(self): self.clearScreen() print ">> Just when you thought things couldn't be any worse than this, you are shocked to see there's this fragile object in front of a big tree." self.thisIsYourHeart() self.yourHeartNow() print "\n>> You just stood there but it didn't take long to continue your way around the forest." self.pressAnyKey() self.whoAreYou() def yourHeartNow(self): print "\nHow is the condition of the %s? Is it broken, cracked or still whole?" % (self.fragileObjectInFrontOfTree), self.fragileObjectCondition = raw_input() if not (self.fragileObjectCondition == "broken" or self.fragileObjectCondition == "cracked" or self.fragileObjectCondition == "whole"): self.yourHeartNow() def thisIsYourHeart(self): print "\nWhat fragile object do you see in front of that big tree?", self.fragileObjectInFrontOfTree = raw_input() if self.fragileObjectInFrontOfTree == "": self.thisIsYourHeart() def whoAreYou(self): self.clearScreen() print ">> As you are walking, you are put into a narrow path." print ">> Out of nowhere, you see a wild animal right in front of you." self.thisIsYou() self.naturalBornLeader() self.pressAnyKey() self.areYouCautious() def areYouCautious(self): self.clearScreen() print ">> The sun is setting and darkness will follow, soon." print ">> You see some light not far from where you are, you follow the light." print ">> When you get there, you see a hut with an old fashioned water well just in front of it." print ">> In its frontyard, there's an old lady brooming the leaves away from her frontyard." print "\n>> You have 2 options: ask for directions or stay the night, it's dark." self.soAreYouCautious() self.pressAnyKey() self.theFidelity() def theFidelity(self): self.clearScreen() print ">> You are continuing your journey, no matter you asked or stayed, it's getting dark, again." print ">> Just in front of you, there's an abandoned cave with lots of torches lying around." print ">> Let's just say you have a lighter and you can light the torches." print "\nHow many torches are you taking with you?", self.torchCarried == raw_input() self.pressAnyKey() self.marvinStyle() def marvinStyle(self): self.clearScreen() print ">> With your torch lighted, you come across a river stream just ahead." print ">> The tide is gentle and you can see it's deep enough to get soakingly fresh." print "\n>> You have 2 options: you freshen things up a little or you get wet all in." self.barryIsThePapa() self.pressAnyKey() self.theEntity() def theEntity(self): self.clearScreen() print ">> You are refreshed and on your way through the woods." print ">> In a blink of an eye, there's an unknown entity in front of you, hovering from the ground!" print ">> You're really frustrated at this point." print "\n>> You have 2 options: run for your life or ask for directions" self.higherBeing() self.pressAnyKey() self.fightOrSurrender() def fightOrSurrender(self): self.clearScreen() print ">> The skies are getting its daily dose of light from the sun." print ">> It's early morning and you can see a way out from the woods." print ">> You reacted and started to walk faster towards the exit." print ">> When you got out, a war in the middle of nowhere has just started." print ">> One of the soldiers is pointing a gun on your forehead." print "\n>> You have 2 options: fight for your life or just surrender?" self.fight() self.pressAnyKey() self.concludeNow() def concludeNow(self): self.clearScreen() print ">> Thank you %s for answering all of the questions." % self.name print ">> Now is the time to know more about yourself." print "\n>> For every answer, the questions represent a part of your identity and of course your personality." print ">> Any conclusions you are about to read can change in the future depending on yourself." print ">> Some people struggle to change, some just change. It's your call." self.pressAnyKey() self.clearScreen() print ">> You saw a %s in front of a big tree" % self.fragileObjectInFrontOfTree print "\n>> That fragile object is your heart at the moment. The bigger the object, the bigger your heart is." print ">> Big or Small does not pertain to quality, this is your capacity at the moment." self.pressAnyKey() self.clearScreen() print ">> The fragile object is %s." % self.fragileObjectCondition print "\n>> A whole heart is a healthy heart, all the vitamins and nutrition to keep it whole are fed perfectly." print ">> If it's cracked or broken, you must find some way to heal or at least get some closure." print ">> Don't bleed your heart, no one deserves a bleeding heart." self.pressAnyKey() self.clearScreen() print ">> The wild animal you see is a %s." % self.wildAnimalSeen print "\n>> This wild animal is actually how you see yourself as in your character." print ">> You have your own subjectivity towards this animal and that's all right." print ">> The thing is, this animal is still wild. Your next answer is a defining one." if self.takeTheWildAnimalWithMe == True: print "\n>> You choose to tame and take the %s with you." % self.wildAnimalSeen print "\n>> Your answer shows that you are a Natural Born Leader." print ">> While people struggle to be leaders, you don't." print ">> The more the people around you struggle, the more obvious you are as a leader." print ">> Just to remember to have fun once in a while." else: print "\n>> You choose to run from the %s." % self.wildAnimalSeen print "\n>> You are best to function collectively." print ">> Your job is your job, that's just it, it's a job." print ">> A career is made of horizontal decisions." print ">> Try looking what's up there at the top, inspire yourself." self.pressAnyKey() self.clearScreen() print ">> You brought %d torch(es) with you." % self.torchCarried print "\n>> The more torch you carry, the more infidel you are with your love life." print ">> Be careful not to spread yourself too thin." print ">> Fidelity is like chivalry these days, rare and ideal." print ">> No matter how many torches, focus on 1, you can't light them all up anyways." self.pressAnyKey() self.clearScreen() action = "" if self.jumpToPond: action = "get wet" else: action = "freshen" print ">> You found a river stream and you choose to %s" % action print "\n>> If you choose to freshen, you are picky when it comes to bedding your sexual counterpart." print ">> On the contrary, if you choose to get wet, you're less picky, even not picky at all." print ">> No matter what you choose, play safe :)" self.pressAnyKey() self.clearScreen() if self.askTheEntity: action = "ask" else: action = "run" print ">> So there's this entity hovering in front of you. You choose to %s." % action print "\n>> If you choose to ask, you have a tendency of asking the Guy above first for His guidances when you run into problems." print ">> The other way around, if you choose to run, you tend to try the problem at hand first and ask for His guidances later." print ">> There is no wrong or right, it's just your own belief." self.pressAnyKey() self.clearScreen() if self.fightBack: action = "fight" else: action = "surrender" print ">> You found a way out of the woods only to find you have a gun pointing at you on your forehead. You %s." % action print "\n>> When you choose to fight, it's obvious that you don't go down easily. You are persistent and you will persevere what's needed to achieve your goals." print ">> If you surrender, you are more likely to accept logical reasonings beyond anything. Everything is in grey and there is no right or wrong, just logical or not logical." print ">> A combination of both is healthy, be open." self.pressAnyKey() self.clearScreen() def fight(self): print "\nFight or Surrender?", self.fightBack = raw_input() if self.fightBack == "fight" or self.fightBack == "surrender": if self.fightBack == "fight": self.fightBack = True elif self.fightBack == "surrender": self.fightBack = False else: self.fight() else: self.fight() def higherBeing(self): print "\nRun or Ask?", self.askTheEntity = raw_input() if self.askTheEntity == "run" or self.askTheEntity == "ask": if self.askTheEntity == "run": self.askTheEntity = False elif self.askTheEntity == "ask": self.askTheEntity = True else: self.higherBeing() else: self.higherBeing() def barryIsThePapa(self): print "\nFreshen or Wet?", self.jumpToPond = raw_input() if self.jumpToPond == "freshen" or self.jumpToPond == "wet": if self.jumpToPond == "freshen": self.jumpToPond = False elif self.jumpToPond == "wet": self.jumpToPond = True else: self.barryIsThePapa() else: self.barryIsThePapa() def soAreYouCautious(self): print "\nAsk or Stay?", self.stayWithGranny = raw_input() if self.stayWithGranny == "ask" or self.stayWithGranny == "stay": if self.stayWithGranny == "ask": self.stayWithGranny == False elif self.stayWithGranny == "stay": self.stayWithGranny == True else: self.soAreYouCautious() else: self.soAreYouCautious() def thisIsYou(self): print "\nWhat animal do you see?", self.wildAnimalSeen = raw_input() if self.wildAnimalSeen == "": self.thisIsYou() def naturalBornLeader(self): print "\n>> You are thinking of 2 things, either run away from it or instead you cautiously try to tame it and take it with you.", print "\n\nDo you run or tame?", self.takeTheWildAnimalWithMe = raw_input() if self.takeTheWildAnimalWithMe == "run" or self.takeTheWildAnimalWithMe == "tame": if self.takeTheWildAnimalWithMe == "tame": self.takeTheWildAnimalWithMe = True else: self.takeTheWildAnimalWithMe = False else: self.naturalBornLeader() def clearScreen(none): sys.stderr.write("\x1b[2J\x1b[H") def pressAnyKey(none): print "\nPress any key to continue >>", dummy = raw_input() me = OutOfTheWoods()
72e74e7dfbb1bc401f524e41e649fd8fc74da6dd
search-94/Genetic_algorithm
/inventario de carne.py
9,057
3.625
4
#ALGORITMO GENETICO INVENTARIO OPTIMO DE ALMACEN DE CARNE import random class algoritmoGenetico: def __init__(self): #creacion de variables self.poblacion = [] self.genotipo = [] self.bondad = [] self.cc = [] self.fprobabilidad = [] self.eliteq = [] self.elitecosto = [] self.npoblacion = 50 self.mayor = 0 print ("Cálculo de cantidad óptima de pedido 'Q*' para el manejo de inventario de productos cárnicos\n") self.d = int(input("Introduzca la demanda constante\n")) self.tiempo = int(input("Introduzca la cantidad de tiempo en dias requerida para satisfacer la demanda\n")) self.almacen = int(input("Introduzca la capacidad de las neveras \n")) self.c0 = int(input("Introduzca el costo de cada pedido Co \n")) self.mantenimiento = int(input("Introduzca el costo de mantenimiento por kilo\n")) self.depreciacion = int(input("Introduzca el costo de depreciación de un kilo por día\n")) self.ntramos = int(input("Introduzca la cantidad de tramos\n")) self.tramoinferior = [] self.tramosuperior = [] self.tramopreciocompra = [] print ("Introduzca el límite inferior del tramo 1") n = int(input()) self.tramoinferior.append(n) print ("Introduzca el límite superior del tramo 1") n = int(input()) self.tramosuperior.append(n) print ("Introduzca el costo de compra asociado al tramo 1") n = int(input()) self.tramopreciocompra.append(n) for i in range(1,self.ntramos): n = self.tramosuperior[i-1] + 1 self.tramoinferior.append(n) print ("Introduzca el límite superior del tramo ",i+1) n = int(input()) self.tramosuperior.append(n) print ("Introduzca el costo de compra asociado al tramo ",i+1) n = int(input()) self.tramopreciocompra.append(n) #Generación de población inicial if (self.almacen > self.tramosuperior[self.ntramos-1]): self.limitesuperior = self.tramosuperior[self.ntramos-1] else: self.limitesuperior = self.almacen self.limiteinferior = self.tramoinferior[0] a = bin(self.limitesuperior) self.posiciones = len(a)-2 secuencia = [] for i in range(self.limiteinferior, self.limitesuperior+1): secuencia.append(i) for i in range(self.npoblacion): a = random.choice(secuencia) self.poblacion.append(a) secuencia.remove(a) for i in range(self.npoblacion): a = bin(self.poblacion[i]) a = a.lstrip("0b") self.genotipo.append(a) while len(self.genotipo[i]) < self.posiciones: self.genotipo[i] = "0"+self.genotipo[i] for i in range (self.npoblacion): for j in range (self.ntramos): if self.poblacion[i] >= self.tramoinferior[j] and self.poblacion[i] <= self.tramosuperior[j]: self.cc.append(self.tramopreciocompra[j]) print ("Conjunto de Q* iniciales") print (self.poblacion,"\n") print ("Genotipo de la poblacion inicial") print (self.genotipo, "\n") print ("Costo de compra en kilos de cada pedido") print (self.cc,"\n") def evaluar(self): self.bondad = [] for i in range(self.npoblacion): #evaluar costo total de inventario cp = self.d/self.poblacion[i] p = self.tiempo/cp cua = self.mantenimiento + (self.depreciacion*p) ct = (self.c0 * self.d/self.poblacion[i]) + (cua * self.poblacion[i]/2) + self.cc[i]*self.d ct = round(ct,2) if ct > self.mayor: self.mayor = ct self.bondad.append(ct) def ruleta(self): totalbondad = 0 funcion = [] suma = 0 self.fprobabilidad = [] posicionmejor = 0 mejor = self.bondad[0] print ("Costo total para cada Q (bondad)") print (self.bondad,"\n") #sacar complemento self.mayor = self.mayor * 1.1 for i in range(self.npoblacion): n = self.mayor - self.bondad[i] totalbondad = totalbondad + n funcion.append(n) for i in range (self.npoblacion): #crear funcion de probabilidad con complemento suma = suma + funcion[i] n = (suma / totalbondad) * 100 n = round(n,2) self.fprobabilidad.append(n) print ("Función de probabilidad generada a partir de probabilidad de selección de cada Q") print (self.fprobabilidad) for i in range (self.npoblacion): if self.bondad[i] <= mejor: mejor = self.bondad[i] posicionmejor = i self.eliteq.append(self.poblacion[posicionmejor]) self.elitecosto.append(self.bondad[posicionmejor]) print("Q optimo de la generacion") print (self.eliteq) print ("Costo optimo de la generacion") print (self.elitecosto) aleatorio = [] for i in range (10000): #seleccion por ruleta aleatorio.append(i) nuevageneracion= [] s = "" while len(nuevageneracion) < self.npoblacion: esigual = True while esigual == True: a = random.choice(aleatorio) b = random.choice(aleatorio) if a!=b: esigual = False a = a/100 b = b/100 posiciona = 0 posicionb = 0 for j in range(self.npoblacion): #obtengo individuos a cruzar if j==0: if a <= self.fprobabilidad[j]: posiciona = j if b <= self.fprobabilidad[j]: posicionb = j else: if a <= self.fprobabilidad[j] and a > self.fprobabilidad[j-1]: posiciona = j if b <= self.fprobabilidad[j] and b > self.fprobabilidad[j-1]: posicionb = j #cruzar descendencia = [] padrea = self.genotipo[posiciona] padreb = self.genotipo[posicionb] for i in range(self.posiciones): descendencia.append(i) padrea = list(padrea) padreb = list(padreb) corte = random.randrange(self.posiciones) descendencia[:corte] = padrea[:corte] descendencia [corte:] = padreb[corte:] descendencia = s.join(descendencia) prueba = int(descendencia,2) if prueba <= self.limitesuperior and prueba >= self.limiteinferior: nuevageneracion.append(descendencia) self.genotipo = [] self.genotipo = nuevageneracion self.poblacion = [] for i in range (self.npoblacion): n = self.genotipo[i] n = int(n,2) self.poblacion.append(n) self.cc = [] for i in range (self.npoblacion): for j in range (self.ntramos): if self.poblacion[i] >= self.tramoinferior[j] and self.poblacion[i] <= self.tramosuperior[j]: self.cc.append(self.tramopreciocompra[j]) print ("poblacion nueva") print (self.poblacion) print ("Genotipo") print (self.genotipo) print ("Costo de compra") print (self.cc) def mutacion(self): for i in range(self.npoblacion): for j in range(self.posiciones): n = random.randint(0,99) if n == 0: aux = self.genotipo[i] aux = list(aux) if aux[j] == "0": aux[j] = "1" else: aux[j] = "0" s="" aux = s.join(aux) a = int(aux,2) if a>=self.tramoinferior[0] and a<= self.tramosuperior[self.ntramos-1]: print ("antes de mutacio ",self.genotipo[i]) self.genotipo[i] = aux print ("mutacion exitosa ",self.genotipo[i]) else: print("mutacion fallida") uno = algoritmoGenetico() uno.evaluar() for i in range (100): uno.ruleta() uno.mutacion() uno.evaluar() mejorq = uno.eliteq[0] mejorcosto = uno.elitecosto[0] for i in range(len(uno.eliteq)): if uno.elitecosto[i] < mejorcosto: mejorcosto = uno.elitecosto[i] mejorq = uno.eliteq[i] print ("El menor costo de inventario es ",mejorcosto," con una Q de ",mejorq)
14dc9c14dabdbc50f0924f6695e343c5832b4a4c
brunoatos/Aprendendo-programar-Python
/exercicio 16 com função del student pen test.py
368
3.9375
4
lista=['virus','notebook','desktop','S.O','Memoria'] print (lista) remover_lista=lista.pop() print (lista) print (remover_lista) #é simples, criei uma nova variavel e adicionei uma função pop() nela. depois printei a variavel lista depois de usar a função pop() e por ultimo printei a variavel que removi da lista.a função pop() remove o ultimo valor da lista.
2d3c4ff762249c691d6f3d6ac5831727a8b10856
brunoatos/Aprendendo-programar-Python
/exercicio 8 student pen test.py
248
4.03125
4
list=['maça','banana','pêra'] print (list[0]) '''nesse caso para imprimir uma lista de string , ela começa da esquerda para a direita com primeiro ordem 0 , tudo que está entre conchetes chama-se lista e cada string ou seja nomes com aspas .'''
9796ce266ad609f77291d57651f921f20800e65d
beenlyons/Ex_python
/Ex_collections/order_dict_test.py
264
3.515625
4
from collections import OrderedDict user_dict = OrderedDict() user_dict["asd"] = 0 user_dict["b"] = "2" user_dict["c"] = "3" user_dict["a"] = "1" # 删除第一个 print(user_dict.popitem(last=False)) # 移动到最后 user_dict.move_to_end("b") print(user_dict)
3ea969feb1deb687f7dd9e573bdb0c18d4a6bef1
maweefeng/baidubaikespider
/test/html_parse.py
1,309
3.609375
4
from bs4 import BeautifulSoup import re html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc,'html.parser',from_encoding='utf8') # 查找所有标签为a的节点 links = soup.find_all('a') for link in links: print(link.name,link['href'],link.get_text()) # 查找所有标签为a 链接符合http://example.com/lacie形式的节点 link_node = soup.find('a',href='http://example.com/lacie') print(link_node.name,link_node['href'],link_node.get_text()) # 正则表达式匹配 link_nodes = soup.find_all('a',href=re.compile(r'ill')) for link in link_nodes: print(link.name,link['href'],link.get_text()) #查找所有标签为div class 为abc 文字为python的节点 link_classnodes = soup.find_all('p',class_='story',text='...') for link in link_classnodes: print(link.name,link.get_text())
f6011e9bc0bbb8a46e698b872d66dce993462449
JarredAllen/EncryptionCracker---APCSP-Create-Task
/encryptions/dictionary.py
4,396
4.1875
4
''' The dictionary class, which handles verifying if something is a word, as well as how common the word is @author: Jarred ''' #from encryptions.base_class import base_class supported_languages=['english', 'french'] list_of_english_words=[] def build_list_of_english_words(): if list_of_english_words: return list_of_english_words #note: this file just contains a list of all English words with open('words.txt') as f: for line in f: list_of_english_words.append(line.strip()) return list_of_english_words list_of_common_english_words=[] def build_list_of_common_english_words(): if list_of_common_english_words: return list_of_common_english_words #note: This file contains a list of common English words (top 10K-ish) with open('common_words.txt') as f: for line in f: list_of_common_english_words.append(line.strip()) return list_of_common_english_words list_of_french_words=[] def build_list_of_french_words(): if list_of_french_words: return list_of_french_words #note: this file just contains a list of all French words with open('french_words.txt') as f: for line in f: list_of_french_words.append(line.strip()) return list_of_french_words list_of_common_french_words=[] def build_list_of_common_french_words(): if list_of_common_french_words: return list_of_common_french_words #note: This file contains a list of common French words (top 600-ish) with open('common_french_words.txt') as f: for line in f: list_of_common_french_words.append(line.strip()) return list_of_common_french_words class dictionary: def __init__(self, language='english'): """ Constructor for dictionary objects. Has one optional argument for the language that it is to decrypt in. If unspecified or left as None, it defaults to English. """ language=language.lower() if language==None or language=='english': self.words=build_list_of_english_words() self.common_words=build_list_of_common_english_words() elif language=='french': self.words=build_list_of_french_words() self.common_words=build_list_of_common_french_words() else: raise ValueError('Unrecognized or unsupported language') def get_words(self, reverse=False): if reverse: return self.reverse_words return self.words def get_common_words(self, reverse=False): if reverse: return self.reverse_common_words return self.common_words def is_word(self, word): return binary_search(word, self.words) def is_common_word(self, word): return binary_search(word, self.common_words) def get_score(self, word): word=word.strip() if self.is_common_word(word): return 2. if self.is_word(word): return 1. return -2 def binary_search(term, sequence): left=0 right=len(sequence) index=(left+right)//2 while left<right-1: if term==sequence[index]: return True elif term<sequence[index]: right=index else: left=index #print(sequence[index], left, right) index=(left+right)//2 return term==sequence[left] if __name__=='__main__': english=dictionary() french=dictionary('french') """ t=['a', 'b', 'c', 'd', 'f'] print(binary_search('a', t)) print(binary_search('b', t)) print(binary_search('c', t)) print(binary_search('d', t)) print(binary_search('e', t)) print(binary_search('f', t)) print(binary_search('ba', t)) """ """ def clear_dictionary_of_words_with_nonalphanumeric_characters(): words=[] with open('common_words.txt') as f: for line in f: line=line.strip() if not contains_nonalpha(line) and len(line)>0: words.append(line) words.sort() content='' for word in words: content+=word+'\n' #print(words) #print(content) with open('common_words.txt', 'w') as f: f.write(content) def contains_nonalpha(word): for i in word: if not i.isalpha(): return True return False clear_dictionary_of_words_with_nonalphanumeric_characters()"""
b9b33ab2d004d734e4c27fa5c53e2233dceb0589
agaevusal/base-of-python
/MyIterator.py
589
3.6875
4
class MyIterator: def __init__(self, lst): self.lst = lst self.i = 0 self.k = len(self.lst) - 1 def __next__(self): while True: if self.i <= self.k: if self.lst[self.i] % 2 != 0: self.i += 1 return self.lst[self.i - 1] else: self.i += 1 return 'not even' else: return 'the end!' def __iter__(self): return self x = MyIterator([1,2,3,4,5]) for i in x: print(i)
78d23605c09e0aff64a21f8fb8b8adc26ccd48ec
Fedor-Pomidor/primeri
/primer3.py
437
3.9375
4
import math x = float(input("Введите значение 'x'")) y = float(input("Введите значение 'y'")) z = float(input("Введите значение 'z'")) #вводите не меньше 4.4 if z >= 4.4: def primer1 (x, y, z): chislitel = math.sqrt(25 * ((x * y * math.sqrt(z - 4.4)) ** 2 + 5)) znamenatel = 8 + y return chislitel / znamenatel print(primer1(x, y, z))
b036a5e8f32b0b4921be8bd523a5ab5be07ed0f4
RyanTucker1/Tkinter
/playground.py
464
4.0625
4
from Tkinter import * #gives us access to everything in the Tkinter class root = Tk() #gives us a blank canvas object to work with root.title("Here Comes the Dong") button1 = Button(root, text="Button 1") button1.grid(row=1, column=1) entry1 = Entry(root) entry1.grid(row=1, column=0) label1 = Label(root, text="Owen Wilson", bg="pink",anchor=E) label1.grid(row=0, column=0, sticky=EW) mainloop() #causes the windows to display on the screen until program closes
da2230aea01a610ec306f52b65855d0fcc48d558
BenjaminSchubert/SysAdmin-scripts-for-linux
/pyDuplicate/filehandler.py
2,155
3.859375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This file contains functions to handle files, list, order, and removing some """ from os import walk from os.path import join, isfile, getsize, isdir import logger import const def tree_walk_with_size(_dir): """ Takes a directory and returns a list of file with their weight :param _dir: the root directory where to list all files contained in it :return: list of tuple containing (file, file's size) """ files = [] for (dir_name, sub_dirs, file_names) in walk(_dir): sub_dirs[:] = [x for x in sub_dirs if x not in const.FOLDERS_NOT_TO_CHECK] for name in file_names: file_path = join(dir_name, name) if isfile(file_path) and not file_path.endswith(const.EXTENSIONS_NOT_TO_CHECK): files.append((file_path, getsize(file_path))) return files def order_files_by_size(weighted_files): """ Orders a list of files by their weight :param weighted_files: a list of tuples (file, file's size) :return: a dict with keys being file's size and values the file with that size """ dict_files = {} for file in weighted_files: if file[1] == 0: continue # we don't care about files of size 0 indices = file[1] if not indices in dict_files: dict_files[indices] = [file[0]] else: dict_files[indices].append(file[0]) return dict_files def handle_bad_folders(folders, force=False): """ Checks if every folder in the list given exists. If not : exits if force is false, else it is removed from the list :param folders: folders list to check :param force: boolean (default : False) :return: list of correct folders """ bad_folders = [str(x) for x in folders if not isdir(x)] if bad_folders and not force: logger().get_logger().error( "Some of the directories you gave are wrong, please check :\n {0}".format( '\n '.join(bad_folders))) exit(1) elif bad_folders and force: folders = [x for x in folders if x not in bad_folders] return folders
110e743b74b52c326956398c48bdcc4d5ef10902
kotsky/py-libs
/algorithms/merge/array_merge_algorithms.py
3,960
3.96875
4
"""Array Merge functions - merge_sorted_arrays(arrays) - to merge sorted arrays into one sorted """ # O(N*log(K) + K) Time / O(N + K) S # where N - total number of elements # K - number of subarrays def merge_sorted_arrays(arrays): if not len(arrays): return arrays # O(K) Time & Space def create_min_heap_from_first_element(arrays): min_heap = ModifiedMinHeap() for i in range(len(arrays)): # node_config = [initial_element, sub_array_idx, # initial_idx, sub_array_length] node_config = [arrays[i][0], i, 0, len(arrays[i])] min_heap.add_node(node_config) min_heap.head = min_heap.heap[0] return min_heap def merge_and_sort(arrays, min_heap): merged_array = [] while min_heap.head is not None: head = min_heap.head merged_array.append(head.value) head.idx += 1 if head.idx < head.limit: head.value = arrays[head.sub_array_idx][head.idx] min_heap.siftDown(0) min_heap.head = min_heap.heap[0] else: min_heap.removeHead() return merged_array class ModifiedMinHeap: class MinHeapNode: def __init__(self, config): value, sub_array_idx, idx, limit = config self.value = value self.sub_array_idx = sub_array_idx self.idx = idx self.limit = limit def __init__(self): self.heap = [] self.head = None def add_node(self, node_config): node = self.MinHeapNode(node_config) self.heap.append(node) self.sift_up(-1) def sift_down(self, start_index): heap = self.heap child_one_index = 2 * start_index + 1 child_two_index = 2 * start_index + 2 while child_one_index < len(heap): if child_two_index < len(heap): if heap[child_one_index].value <= heap[child_two_index].value and \ heap[start_index].value > heap[child_one_index].value: new_index = child_one_index elif heap[child_one_index].value > heap[child_two_index].value and \ heap[start_index].value > heap[child_two_index].value: new_index = child_two_index else: break else: if heap[start_index].value > heap[child_one_index].value: new_index = child_one_index else: break self.swap(start_index, new_index, heap) start_index = new_index child_one_index = 2 * start_index + 1 child_two_index = 2 * start_index + 2 def remove_head(self): if self.head is not None: if len(self.heap) > 1: self.swap(0, len(self.heap) - 1, self.heap) self.heap.pop() self.sift_down(0) self.head = self.heap[0] else: self.head = None self.heap.pop() def sift_up(self, idx): if idx < 0: idx = len(self.heap) + idx while idx > 0: parent_idx = (idx - 1) // 2 if self.heap[idx].value < self.heap[parent_idx].value: self.swap(idx, parent_idx, self.heap) idx = parent_idx else: break def swap(self, i, j, array): array[i], array[j] = array[j], array[i] search_heap = create_min_heap_from_first_element(arrays) merged_sorted_array = merge_and_sort(arrays, search_heap) return merged_sorted_array
c806d61916dedef457259a49a3a71b8a3d88479a
kotsky/py-libs
/data_structures/heaps/heaps_tree_implementation.py
4,503
4.0625
4
"""Min-Heap tree structure Thin Min-Heap implementation is based on pure binary tree structure with certain balancing optimisation by using additional attribute direction. Min-Heap methods: - class MinHeap() - Build Min-Heap from an any array with integers with a complexity O(N) Time / O(N) Space - peek() - check root of that heap - insert() - insert value - pop() - return and delete min head - is_empty() - check if heap is empty Example: INSERT = "insert" REMOVE = "remove" PEEK = "peek" BUILD = "build" def main(): min_heap = MinHeap() while 1: user_input = input() user_commands = user_input.split(" ") command = user_commands[0] try: value = int(user_commands[1]) except: value = None if command == INSERT: min_heap.insert(value) print("Added ", value) elif command == PEEK: print("Peek is ", min_heap.peek()) elif command == REMOVE: min_heap.pop() print("Removed. New peek is ", min_heap.peek()) elif command == BUILD: array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41] min_heap.build(array) min_heap.insert(9) min_heap.insert(-200) print(len(min_heap)) while not min_heap.is_empty(): output = min_heap.pop() print("Removed ", output) if __name__ == '__main__': # app.run(main) main() """ LEFT = 0 RIGHT = 1 class MinHeapNode: def __init__(self, value): self.value = value self.left = None self.right = None self.direction = LEFT def __str__(self): return repr(self.value) def flip_direction(self): self.direction = ~self.direction class MinHeap: def __init__(self, array=None): self.root = None self.count = 0 if array is not None: self.build(array) def build(self, array): for value in array: self.insert(value) def __len__(self): return self.count def __del__(self): pass def insert(self, value): def swap_values(node1, node2): node1.value, node2.value = node2.value, node1.value new_node = MinHeapNode(value) self.count += 1 if self.root is None: self.root = new_node return current_node = self.root is_completed = False while not is_completed: current_node.flip_direction() if current_node.value > new_node.value: swap_values(current_node, new_node) if current_node.direction == LEFT: if current_node.left is None: current_node.left = new_node is_completed = True else: current_node = current_node.left else: if current_node.right is None: current_node.right = new_node is_completed = True else: current_node = current_node.right def peek(self): return self.root def is_empty(self): return self.count == 0 def pop(self): if self.count == 0: return None self.count -= 1 value = self.root.value self.fix_tree() return value def fix_tree(self): def swap_values(node1, node2): node1.value, node2.value = node2.value, node1.value current_node = self.root parent_node = None current_node.value = None while current_node.left is not None or current_node.right is not None: if current_node.left is not None and current_node.right is not None: if current_node.left.value <= current_node.right.value: parent_node = current_node current_node = current_node.left else: parent_node = current_node current_node = current_node.right elif current_node.left is not None: parent_node = current_node current_node = current_node.left else: parent_node = current_node current_node = current_node.right swap_values(parent_node, current_node) if parent_node is None: self.root = None else: if parent_node.left == current_node: parent_node.left = None else: parent_node.right = None
a9aac54689126f3e08fe3fe9c1c751934a2704c5
kotsky/py-libs
/algorithms/sort/array_sort_algorithms.py
6,548
4.03125
4
""" In this sheet, sorted algorithms are implemented in the most optimal way. The following list: Merge Sort Heap Sort Quick Sort Selection Sort Insertion Sort Bubble Sort """ # Avg: Time O(N*log(N)) / Space O(N) # Worst: Time O(N*log(N)) / Space O(N) # Idea: # Create auxiliary array, where you can # store intermediate elements. # Recursively, divide array/subarrays until # you have only 1-2 elements, and then do # their swapping, and then merge (doMerge) # these subarrays on each recursive level. def mergeSort(array): def mergeSubarrays(merge_array, additional_array, start_idx, end_idx): if end_idx - start_idx < 1: return middle_idx = (end_idx + start_idx) // 2 mergeSubarrays(additional_array, merge_array, start_idx, middle_idx) mergeSubarrays(additional_array, merge_array, middle_idx + 1, end_idx) doMerge(merge_array, additional_array, start_idx, middle_idx + 1, end_idx) def doMerge(merge_array, additional_array, start_one, start_two, end_idx): p1 = start_one p2 = start_two p0 = p1 while p1 < start_two and p2 <= end_idx: if additional_array[p1] > additional_array[p2]: merge_array[p0] = additional_array[p2] p2 += 1 else: merge_array[p0] = additional_array[p1] p1 += 1 p0 += 1 while p1 < start_two: merge_array[p0] = additional_array[p1] p1 += 1 p0 += 1 while p2 <= end_idx: merge_array[p0] = additional_array[p2] p2 += 1 p0 += 1 if not len(array) or len(array) <= 1: return array else: merge_array = array additional_array = array.copy() mergeSubarrays(merge_array, additional_array, 0, len(array) - 1) return merge_array # Avg: Time O(N*log(N)) / Space O(1) # Worst: Time O(N*log(N)) / Space O(1) # Idea: # Convert array to min heap and use log(N) heap # property to find min N times of subarray N def heapSort(array): def buildHeap(array): for i in range(len(array) - 1, 0, -2): parent_idx = (i - 1) // 2 siftDown(array, parent_idx, len(array) - 1) return array def siftDown(array, parent_idx, end_idx): while parent_idx >= 0: child_one = 2 * parent_idx + 1 child_two = 2 * parent_idx + 2 if child_one > end_idx: break if child_two > end_idx: if array[parent_idx] < array[child_one]: swap(array, parent_idx, child_one) break if array[parent_idx] < max(array[child_one], array[child_two]): if array[child_one] >= array[child_two]: swap(array, parent_idx, child_one) parent_idx = child_one else: swap(array, parent_idx, child_two) parent_idx = child_two else: break if len(array) < 2: return array array = buildHeap(array) start_idx = 0 end_idx = len(array)-1 while (end_idx - start_idx) > 0: siftDown(array, start_idx, end_idx) swap(array, start_idx, end_idx) end_idx -= 1 return array # Avg: Time O(N*log(N)) / Space O(log(N)) # Worst: Time O(N^2) / Space O(log(N)) # Idea: # You have 3 pointers: pivot, left and right. # You compare left and right with pivot # and then swap left or right vs pivot accordingly, # depends on certain condition. Once you swapped, # you have subarrays from the left and from the # right respect to the pivot. Pivot element is in # a write order. Now, do quickSort for these # 2 subarrays. def quickSort(array): def sortHelper(array, start_idx, end_idx): if end_idx <= start_idx: return pivot = start_idx start_idx += 1 list_range = [pivot, end_idx] while end_idx >= start_idx: if array[start_idx] > array[pivot] > array[end_idx]: swap(array, start_idx, end_idx) if array[start_idx] <= array[pivot]: start_idx += 1 if array[end_idx] >= array[pivot]: end_idx -= 1 swap(array, pivot, end_idx) left_sub_isSmaller = list_range[0] - end_idx < end_idx+1, list_range[1] if left_sub_isSmaller: sortHelper(array, list_range[0], end_idx) sortHelper(array, end_idx+1, list_range[1]) else: sortHelper(array, end_idx+1, list_range[1]) sortHelper(array, list_range[0], end_idx) sortHelper(array, 0, len(array)-1) return array # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # By traversing, we go through elements and do # swapping if the element before if greater than # the element after. If we do at least one swap, # then we do new traversing until there won't be # swaps. def bubbleSort(array): if not array: return None len_array = len(array) while True: was_swap = False index = 0 while index < (len_array - 1): if array[index] > array[index + 1]: swap(array, index, index + 1) was_swap = True index += 1 if was_swap is False: return array len_array -= 1 # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # We try to insert elements before others, if they # are smaller. def insertionSort(array): for i in range(1, len(array)): second = i while second != 0: if array[second] < array[second - 1]: swap(array, second, second-1) second -= 1 else: break return array # Avg: Time O(N^2) / Space O(1) # Worst: Time O(N^2) / Space O(1) # Idea: # Every iteration we search for the smallest number # in remaining subarray, and then do swap with # respective place in the array. def selectionSort(array): for j in range(len(array) - 1): upper_pointer = j lower_pointer = j for i in range(lower_pointer, len(array)): if array[upper_pointer] > array[i]: upper_pointer = i swap(array, lower_pointer, upper_pointer) return array # Simple swap of elements inside of array def swap(array, idx_one, idx_two): array[idx_one], array[idx_two] = array[idx_two], array[idx_one]
6c9fc9c03b1d6ab243793f33bc481c57fae9b639
cardboardcode/pycrypt
/src/parserlib.py
4,209
3.9375
4
import sys import os def encryptFile(st, text): for letter in text: if (letter == 'a'): st+=str('1') if (letter == 'b'): st+=str('2') if (letter == 'c'): st+=str('3') if (letter == 'd'): st+=str('4') if (letter == 'e'): st+=str('5') if (letter == 'f'): st+=str('6') if (letter == 'g'): st+=str('7') if (letter == 'h'): st+=str('8') if (letter == 'i'): st+=str('9') if (letter == 'j'): st+=str('a') if (letter == 'k'): st+=str('b') if (letter == 'l'): st+=str('c') if (letter == 'm'): st+=str('d') if (letter == 'n'): st+=str('e') if (letter == 'o'): st+=str('f') if (letter == 'p'): st+=str('g') if (letter == 'q'): st+=str('h') if (letter == 'r'): st+=str('i') if (letter == 's'): st+=str('j') if (letter == 't'): st+=str('k') if (letter == 'u'): st+=str('l') if (letter == 'v'): st+=str('m') if (letter == 'w'): st+=str('n') if (letter == 'x'): st+=str('o') if (letter == 'y'): st+=str('p') if (letter == 'z'): st+=str('q') if (letter == ' '): st+=str(' ') #Capital Letters Lexicon start if (letter == 'A'): st+=str('Z') if (letter == 'B'): st+=str('Y') if (letter == 'C'): st+=str('X') if (letter == 'D'): st+=str('W') if (letter == 'E'): st+=str('V') if (letter == 'F'): st+=str('U') if (letter == 'G'): st+=str('T') if (letter == 'H'): st+=str('S') if (letter == 'I'): st+=str('R') if (letter == 'J'): st+=str('Q') if (letter == 'K'): st+=str('P') if (letter == 'L'): st+=str('O') if (letter == 'M'): st+=str('N') if (letter == 'N'): st+=str('M') if (letter == 'O'): st+=str('L') if (letter == 'P'): st+=str('K') if (letter == 'Q'): st+=str('J') if (letter == 'R'): st+=str('I') if (letter == 'S'): st+=str('H') if (letter == 'T'): st+=str('G') if (letter == 'U'): st+=str('F') if (letter == 'V'): st+=str('E') if (letter == 'W'): st+=str('D') if (letter == 'X'): st+=str('C') if (letter == 'Y'): st+=str('B') if (letter == 'Z'): st+=str('A') return st def decryptFile(st, text): for letter in text: if (letter == '1'): st+=str('a') if (letter == '2'): st+=str('b') if (letter == '3'): st+=str('c') if (letter == '4'): st+=str('d') if (letter == '5'): st+=str('e') if (letter == '6'): st+=str('f') if (letter == '7'): st+=str('g') if (letter == '8'): st+=str('h') if (letter == '9'): st+=str('i') if (letter == 'a'): st+=str('j') if (letter == 'b'): st+=str('k') if (letter == 'c'): st+=str('l') if (letter == 'd'): st+=str('m') if (letter == 'e'): st+=str('n') if (letter == 'f'): st+=str('o') if (letter == 'g'): st+=str('p') if (letter == 'h'): st+=str('q') if (letter == 'i'): st+=str('r') if (letter == 'j'): st+=str('s') if (letter == 'k'): st+=str('t') if (letter == 'l'): st+=str('u') if (letter == 'm'): st+=str('v') if (letter == 'n'): st+=str('w') if (letter == 'o'): st+=str('y') if (letter == 'p'): st+=str('z') if (letter == ' '): st+=str(' ') #Capital Letters Lexicon start if (letter == 'A'): st+=str('Z') if (letter == 'B'): st+=str('Y') if (letter == 'C'): st+=str('X') if (letter == 'D'): st+=str('W') if (letter == 'E'): st+=str('V') if (letter == 'F'): st+=str('U') if (letter == 'G'): st+=str('T') if (letter == 'H'): st+=str('S') if (letter == 'I'): st+=str('R') if (letter == 'J'): st+=str('Q') if (letter == 'K'): st+=str('P') if (letter == 'L'): st+=str('O') if (letter == 'M'): st+=str('N') if (letter == 'N'): st+=str('M') if (letter == 'O'): st+=str('L') if (letter == 'P'): st+=str('K') if (letter == 'Q'): st+=str('J') if (letter == 'R'): st+=str('I') if (letter == 'S'): st+=str('H') if (letter == 'T'): st+=str('G') if (letter == 'U'): st+=str('F') if (letter == 'V'): st+=str('E') if (letter == 'W'): st+=str('D') if (letter == 'X'): st+=str('C') if (letter == 'Y'): st+=str('B') if (letter == 'Z'): st+=str('A') return st
745d6348846a729ba22f518714f39d8f0deb861d
Vrndavana/Sprint-Challenge--Intro-Python
/src/cityreader/cityreader.py
872
3.859375
4
import csv cities = [] class City: def __init__(self, name,lat,lon): self.name = name self.lat = lat self.lon = lon def cityreader(cities=[]): with open("cities.csv") as p: city_parser = csv.DictReader(p, delimiter= ",", quotechar = "|") for row in city_parser: city = City(row["city"], float(row["lat"]), float(row["lng"])) cities.append(city) # TODO Implement the functionality to read from the 'cities.csv' file # For each city record, create a new City instance and add it to the # `cities` list # so call the csv function then pass dth a tex tfile i want to iterate teham ti aute #iterate the fucntion putting the for loop insife of the cities list. return cities cityreader(cities) # Print the list of cities (name, lat, lon), 1 record per line. for c in cities: print(c) print(c.name, c.lat, c.lon)
be5a272602da6854598512c0b5a9b34d80c39a7c
nicovandenhooff/project-euler
/solutions/p22.py
3,229
3.59375
4
# Project Euler: Problem 22 # Names scores # Author: Nico Van den Hooff # Github: https://github.com/nicovandenhooff/project-euler # Problem: https://projecteuler.net/problem=22 # Note: I implement a vectorized implementation with NumPy for this problem. # Specifically, I first create a vector for each name, where the vectors # shape is (26, 1). Each position in the vector is then filled with the # number of times a letter shows up in a given name. I then combine all # of the vectors into a names matrix, which is of shape (5163, 26). Next, # I simply multiply the matrix by a points vector of shape (26, 1), which # gives us a vector of shape (5163, 1) that represents the points value # for each persons name. Finally, I multiply the points value vector by # a "position" vector of shape (5163, 1) that represents each position a # name has in the list (element-wise multiplication here). To get the # answer, the sum is taken over the final vector. import string import numpy as np import csv # path to the names text file PATH = "./project-euler/data/p022_names.txt" def get_names_list(path): """Creates a sorted list of names and a "positions" vector. Parameters ---------- path : str The path of the names .txt file. Returns ------- names, positions : list of str, numpy array The names list and positions vector. The positions vector has shape (1, number of names). """ # the names list names = [] # read in names with open(path) as f: for row in csv.reader(f): names.extend(row) # sort names names.sort() # create positions vector positions = np.arange(1, len(names) + 1) return names, positions def create_names_matrix(names, vector_shape=(26,), start=1, stop=27): """Creates a names matrix and points vector. Parameters ---------- names : list of str The list of names. vector_shape : int, optional The shape of each name vector, by default (26,). start : int, optional Starting points value (inclusive), by default 1. stop : int, optional Ending points value (exclusive), by default 27. Returns ------- names_matrix, points : 2D numpy array, 1D numpy array The names matrix and points vector. """ # to store the vectorized names vectorized_names = [] # the points vector points = np.arange(start, stop) # dictionary mapping letters to points char_to_points = dict(zip(string.ascii_uppercase, range(start, stop))) # vectorize each name for name in names: vector = np.zeros(vector_shape) for char in name: # have to be careful with indexing here index = char_to_points[char] vector[index - 1] += 1 # append each name to vectorized names list vectorized_names.append(vector) # create names matrix from vectors names_matrix = np.array(vectorized_names) return names_matrix, points names, positions = get_names_list(PATH) names_matrix, points = create_names_matrix(names) print(np.sum(np.matmul(names_matrix, points) * positions))
f9fa0a430f651302cd9cce0092eaa8fadb18930e
nicovandenhooff/project-euler
/solutions/p48.py
1,016
3.703125
4
# Project Euler: Problem 48 # Self powers # Author: Nico Van den Hooff # Github: https://github.com/nicovandenhooff/project-euler # Problem: https://projecteuler.net/problem=48 DIGITS = 10 def self_powers_sum(start, stop): """Calculates the sum of a series of self powers. Parameters ---------- start : int The first number in the series. stop : int The last number in the series. Returns ------- total : int The sum of the series of self powers. """ total = 0 # calculate total for i in range(start, stop): total += i ** i return total def last_digits(n, length): """Returns the last k digits of a number. Parameters ---------- n : int The number. length : int The last k number of digits. Must be <= n Returns ------- [description] """ digits = str(total)[-length:] return digits total = self_powers_sum(1, 1001) digits = last_digits(total, DIGITS) print(digits)
0a5c041eb9e714cdda7ffc9df287233452add307
caiorss/OSlash
/oslash/applicative.py
1,383
3.96875
4
from abc import ABCMeta, abstractmethod class Applicative(metaclass=ABCMeta): """Applicative functors are functors with some extra properties. Most importantly, they allow you to apply functions inside the functor (hence the name). """ @abstractmethod def apply(self, something: "Applicative") -> "Applicative": """(<*>) :: f (a -> b) -> f a -> f b. Apply (<*>) is a beefed up fmap. It takes a functor value that has a function in it and another functor, and extracts that function from the first functor and then maps it over the second one. """ return NotImplemented def __mul__(self, something: "Applicative"): """(<*>) :: f (a -> b) -> f a -> f b. Provide the * as an infix version of apply() since we cannot represent the Haskell's <*> operator in Python. """ return self.apply(something) def lift_a2(self, func, b): """liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c.""" return func % self * b @classmethod def pure(cls, x: "Callable") -> "Applicative": """The Applicative functor constructor. Use pure if you're dealing with values in an applicative context (using them with <*>); otherwise, stick to the default class constructor. """ return cls(x)
3169664c0f8cd32d7389d4dbb2a907fb916be13e
bogdanf555/randomNumberGuessingGame
/bin/functionalities.py
8,134
3.875
4
import ast # difficulty levels for the game difficultyPool = ("easy", "normal", "hard", "impossible") # dictionary that associates a level of difficulty to # the proper range of guess, the number of attempts and # the maximum value that a secret number can get # format of dictionary : difficulty - range, attempts, maximum number mode = { "easy" : (20, 4, 99), "normal" : (100, 6, 999), "hard" : (500, 8, 999), "impossible" : (1000, 9, 9999) } #displaying the default welcoming message def welcomingMessage(): try: welcomeFile = open("..\\data\\welcomingMessage.txt", "r") except: welcomeFile = open("data\\welcomingMessage.txt", "r") welcomeMessage = welcomeFile.read() welcomeFile.close() print(welcomeMessage) # record the play again decision def waitOnReplay(): retry = None while True: retry = input("Would you like to play again? (yes/no)\n") if retry == "yes": print("Great!") break elif retry == "no": print("Well, see ya then!") break else: print("I'm afraid I can't understand you, please tell me yes or no.") return retry # present the set of rules to the player def displayRules(): try: rulesFile = open("..\\data\\rules.txt", "r") except: rulesFile = open("data\\rules.txt", "r") rulesMessage = rulesFile.read() rulesFile.close() print(rulesMessage) #displayes the help guide of the the game def displayHelp(): try: helpFile = open("..\\help.txt", "r") except: helpFile = open("help.txt", "r") helpMessage = helpFile.read() print(helpMessage) helpFile.close() # displayes the Highscore table to the user def displayHighscoreBoard(): highscoreDict = readHighscoreFile() board = None while True: print("What leaderboard are you interested in?") difficultyRequested = input("(easy, normal, hard, impossible)\n") if difficultyRequested in ("easy", "normal", "hard", "impossible"): board = highscoreDict[difficultyRequested] break else: print("I'm afraid I did not get that.") if board[1][0] == '-': print("Nobody registered their highscore yet for this difficulty.") else: print("Place | Name | Attempts") for index in board: if board[index][0] == '-': break #print(str(index) + ".", board[index][0], str(board[index][1])) print("{:5.5} | {:16.16} | {}".format(str(index) + ".", board[index][0], str(board[index][1]))) # hints to display for the player # start and end represent the interval in which the number was choosen # attempts represents the number of trie to give to the player def generatedInformation(start, end, attempts): print("The number has been choosen. It is a natural number between {} and {}.".format(start, end)) print("You have {} attempts to guess the number.".format(attempts)) print("Now let's see if you can guess it.") # message to display when losing the game # number reveals the secret random number to the player def failureMessage(number): print("I'm sorry, maybe you need more training or luck.") print("The number to be guessed was {}.".format(number)) # sets the difficuly of the game based on player input def setDifficulty(): while True: print("Choose the desired difficulty to play:") difficulty = input("(easy, normal, hard, impossible)\n") if difficulty not in difficultyPool: print("Please try again, you misspelled the difficulty.") else: try: difficultyFile = open("..\\data\\difficulty.txt", "w") except: difficultyFile = open("data\\difficulty.txt", "w") difficultyFile.write(difficulty) difficultyFile.close() print("Difficulty successfully changed to {}.".format(difficulty)) break # gets the default difficulty from the difficulty.txt file def getDifficulty(): try: difficultyFile = open("..\\data\\difficulty.txt", "r") except: difficultyFile = open("data\\difficulty.txt", "r") difficulty = difficultyFile.read() difficultyFile.close() return difficulty # reads the highscore file and returns a dictionary containing # highscore information def readHighscoreFile(): try: highscoreFile = open("..\\data\\highscore.txt", "r") except: highscoreFile = open("data\\highscore.txt", "r") highscoreString = highscoreFile.read() highscoreFile.close() highscoreDict = ast.literal_eval(highscoreString) return highscoreDict # receives as input a dicitionary containing the highscore board # writes the new highscore board to the file def writeHighscoreFile(highscore): while True: try: highscoreFile = open("..\\data\\highscore.txt", "w") except: highscoreFile = open("data\\highscore.txt", "w") break if highscoreFile == None: print("Error : Please close the highscore.txt file on your computer.") print("Then retry to register your highscore.") while True: response = input("Ready? (yes, when you successfully closed the file)\n") if response == "yes": break highscoreFile.write(str(highscore)) highscoreFile.close() print("Congratulations, you're on the leaderboards!") # returns true if the comparison of the highscore file # and the template highscore file has as result an equality # false otherwise def isHighscoreFileEmpty(): try: highscoreFile = open("..\\data\\highscore.txt", "r") except: highscoreFile = open("data\\highscore.txt", "r") highscoreString = highscoreFile.read() highscoreFile.close() return len(highscoreString) == 0 # deletes all the highscores recorded in the highscore.txt # file by replacing its content with the template located # in the highscoreTemplate.txt def eraseHighscoreFile(display): try: try: template = open("..\\data\\highscoreTemplate.txt", "r") highscoreFile = open("..\\data\\highscore.txt", "w") except: template = open("data\\highscoreTemplate.txt", "r") highscoreFile = open("data\\highscore.txt", "w") templateString = template.read() highscoreFile.write(templateString) template.close() highscoreFile.close() if display: print("All recorded highscores have been removed successfully.") except: print("An error occured, please restart the game.") # the process in which the player tries to guess the secret number # returns a boolean that is used to check if the number was guessed # and a number which represents the score (number of attemps at guessing # used by the player) def guessingProcess(attempts, secretNumber): guessed = False tries = attempts for guess in range(1, attempts + 1): while True: try: numberGiven = int(input("Make your choice: ({} more attempts)\n".format(attempts + 1 - guess))) break except ValueError: print("Non numbers values are not accepted, please retry.") if numberGiven == secretNumber: print("Congratulations, you guessed it in {} attempts.".format(guess)) guessed = True tries = guess break elif guess < attempts: if numberGiven < secretNumber: print("The secret number is greater.") else: print("The secret number is lower.") return guessed, tries # this function copies the highscore file content into a dictionary # then modifies it in order to include the new record inside it # as parameters : difficulty will select which leaderboard needs to be modified # and attempts will be the new record established by the player # returns the hole new dictionary of highscores def recordHighscore(difficulty, attempts): highscoreBoards = readHighscoreFile() highscoreDict = highscoreBoards[difficulty] stack = [] key = 5 while key > 0 and attempts < highscoreDict[key][1]: if highscoreDict[key][0] != '-': stack.append(highscoreDict[key]) key -= 1 if key < 5: print("Your score is eligible for leaderboards recording.") while True: name = input("Please give me your name to put it in the hall of fame:\n(max 16 characters)\n") if name == "-" or len(name) > 16: print('The provided name is no a legal one, please input another.') else: break highscoreDict[key + 1] = (name, attempts) key += 2 while stack and key < 6: highscoreDict[key] = stack.pop(-1) key += 1 highscoreBoards[difficulty] = highscoreDict else: highscoreBoards = None del stack return highscoreBoards
237e8e64ed9f6967042daee49a8b0f72c64e63a0
moses4real/python
/Conditionals/For Loop.py
109
3.515625
4
Emails = ['Adewarasalavtion56@gmail.com','Oluwadamilare.m@yhaoo.com','Oluwadamilaremoses56@gmail.com'] for item in Emails: if 'gmail' in item: print(item)
3c1956e8a1f44ea31ff37e0a78e965bd4ae05b28
Menelaos92/Library-Management-System
/frontend.py
6,418
3.921875
4
from tkinter import * import backend def view_command(): list1.delete(0,END) # Deleting everything from start to end. for count, row in enumerate(backend.view_all()): list1.insert(END,(count+1,row)) # The first argument sets the position where its going to get settled the incoming string inside the view box, e.g. 0,1,2... END. # print(count+1) def search_command(): list1.delete(0,END) for row in backend.search(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()): # Below, the arguments used in entries are defined as string objects using the method StringVar() and not as simple strings. So to get a simple string and use it in the backend.search() function as needed, there must be appended in the arguments the get() method which produces a simple string. list1.insert(END,row) def add_command(): backend.insert(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()) # This inserts the inputed arguments inside the database table list1.delete(0,END) list1.insert(END,(title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get())) # while this inserts them in to the view box of the app. # Also note that the arguments are inputed inside brackets as a single value, as a result in the output list we take one line of string and not many as the number of the imported arguments. def delete_command(): index_of_listbox=list1.curselection()[0] # Using this to get the number of the selected line of the listbox. index_of_database=list1.get(index_of_listbox)[1][0] # Using this to get the the number of line which is registered in the database. (content enumeration: database table different from listbox) backend.delete(index_of_database) list1.delete(0,END) for count, row in enumerate(backend.view_all()): # Updating the listbox after deleting list1.insert(END,(count+1,row)) # print(index_of_database) def update_command(): # list1.delete(0,END) index_of_listbox=list1.curselection()[0] # Using this to get the number of the selected line of the listbox. index_of_database=list1.get(index_of_listbox)[1][0] # Using this to get the the number of line which is registered in the database. (for content enumeration: database table different from listbox) backend.update(index_of_database,title_text_input.get(),author_text_input.get(),year_text_input.get(),isbn_text_input.get()) list1.delete(0,END) for count, row in enumerate(backend.view_all()): # Updating the listbox after updating the database. list1.insert(END,(count+1,row)) # print(index_of_database) def fill_entries(evt): # Fill entries with info form the selected row. Connected with list1.bind() method in Listbox sector below. # Note here that Tkinter passes an event object to fill_entries(). In this exapmle the event is the selection of a row in the listbox. try: index_of_listbox=list1.curselection()[0] index_of_database=list1.get(index_of_listbox) e1.delete(0,END) e1.insert(END, index_of_database[1][1]) # Here the use of try and except block, excepts the error produced when clicking inside an empty listbox. e2.delete(0,END) # The <<index_of_listbox=list1.curselection()[0]>> gives a list from which we took the first object. So when the listbox is empty we will take an empty list with no objects which produces an error. e2.insert(END, index_of_database[1][2]) e3.delete(0,END) e3.insert(END, index_of_database[1][3]) e4.delete(0,END) e4.insert(END, index_of_database[1][4]) # print(index_of_database[1][2]) except IndexError: pass def clean_entries_command(): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) e4.delete(0,END) ########################################### # Creation of GUI and its elements elements ########################################### # All the element alligning happens inside a grid. # Each element declares its own position inside the grid. # Creating a window object window=Tk() # window.create_window(height=100, width=100) # Window title window.wm_title('Book Library') # Labels l1=Label(window,text="Title") l1.grid(row=1,column=0) l2=Label(window,text="Author") l2.grid(row=2,column=0) l3=Label(window,text="Year") l3.grid(row=3,column=0) l4=Label(window,text="ISBN") l4.grid(row=4,column=0) #Entries title_text_input=StringVar() e1=Entry(window,textvariable=title_text_input) e1.grid(row=1,column=1) author_text_input=StringVar() e2=Entry(window,textvariable=author_text_input) e2.grid(row=2,column=1) year_text_input=StringVar() e3=Entry(window,textvariable=year_text_input) e3.grid(row=3,column=1) isbn_text_input=StringVar() e4=Entry(window,textvariable=isbn_text_input) e4.grid(row=4,column=1) #ListBox list1=Listbox(window,height=10,width=90,highlightcolor='green',selectbackground='green') list1.grid(row=1,column=2,rowspan=4,columnspan=6) list1.bind('<<ListboxSelect>>', fill_entries) # The fill_entries function is going to be executed when a row of the listbox is selected. Check for more http://www.tcl.tk/man/tcl8.5/TkCmd/event.htm#M41] #Scrollbars # sb1=Scrollbar(window) # sb1.grid(row=2,column=2,rowspan=6) # # list1.configure(yscrollcommand=sb1.set) # sb1.configure(command=list1.yview) #Buttons b1=Button(window,text="View All", width=14, command=view_command) # Using the function without brackets to execute it when the button is pushed without waiting this line of the script gets read. b1.grid(row=0,column=2) b2=Button(window,text="Search Entry", width=14, command=search_command) b2.grid(row=0,column=3) b3=Button(window,text="Add Entry", width=14, command=add_command) b3.grid(row=0,column=4) b4=Button(window,text="Update", width=14, command=update_command) b4.grid(row=0,column=5) b5=Button(window,text="Delete", width=14, command=delete_command) b5.grid(row=0,column=6) b6=Button(window,text="Close", width=4, command=window.destroy) b6.grid(row=0,column=0) b7=Button(window,text="Clean", width=15, command=clean_entries_command) b7.grid(row=0,column=1) # Show created window with its contained elements window.mainloop()
7c5abeb358b5790cff1bdfbf801c5093fa286443
SavinKumar/Python_lib
/Original files/Library.py
34,819
3.734375
4
from tkinter import * import sqlite3 import getpass from functools import partial from datetime import date conn = sqlite3.connect('orgdb.sqlite') cur = conn.cursor() def passw(): pa=getpass.getpass() passwo='seKde7sSG' print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() while s: print('Enter the correct password again: ') pa=getpass.getpass() print('Entered password is of ',len(pa),' characters, To continue press Enter otherwise Enter the passwords again') s=input() if pa==passwo: return 1; else: return 0; def p_exit(): exit() def p_add1(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Added") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to add: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_addrng(): add1=Tk() add1.title("Add records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''INSERT OR IGNORE INTO Records('Roll_no') VALUES (?)''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Added") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Add",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_del1(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) cur.execute('''DELETE FROM Records where Roll_no = ?''',(i,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = E_2.get()+" Deleted") L_.place(x=10,y=150) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number to delete: ") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=100) add1.mainloop() def p_delrng(): add1=Tk() add1.title("Delete records") add1.geometry("900x300") def p_ad(): i=int(E_2.get()) j=int(E_3.get()) for k in range(i,j+1): cur.execute('''DELETE FROM Records where Roll_no = ?''',(k,)) conn.commit() L_ = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = str(j-i+1)+" Recods Deleted") L_.place(x=10,y=250) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Initial Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Final Roll number") L2.place(x=50,y=100) E_3 = Entry(add1,font=16,textvariable = c) E_3.place(x=410,y=100) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Delete",command = p_ad) B_1.place(x=350,y=190) add1.mainloop() def p_issue(): add1=Tk() add1.title("Issue Books") add1.geometry("900x900") def p_book(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break mpty=0 if book1==0: mpty+=1 if book2==0: mpty+=1 if book3==0: mpty+=1 if book4==0: mpty+=1 if book5==0: mpty+=1 tt='You can issue '+str(mpty)+' number of books only as per the rule.' def p_lock(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books for issue= "+str(5-aaa)) L8.place(x=50,y=510) aaa=5-aaa lst=[] if aaa==5: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) lst.append(b5) elif aaa==4: lst.append(b1) lst.append(b2) lst.append(b3) lst.append(b4) elif aaa==3: lst.append(b1) lst.append(b2) lst.append(b3) elif aaa==2: lst.append(b1) lst.append(b2) elif aaa==1: lst.append(b1) for j in range(len(lst)): aaa-=1 if book1==0: book1=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book1=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI1=? where Roll_no=?''',(di,i)) conn.commit() elif book2==0: book2=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book2=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI2=? where Roll_no=?''',(di,i)) conn.commit() elif book3==0: book3=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book3=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI3=? where Roll_no=?''',(di,i)) conn.commit() elif book4==0: book4=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book4=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI4=? where Roll_no=?''',(di,i)) conn.commit() elif book5==0: book5=lst[j] di=date.today().strftime("%d-%m-%Y") conn.execute('''UPDATE Records set book5=? where Roll_no=?''',(lst[j],i,)) conn.execute('''UPDATE Records set DdI5=? where Roll_no=?''',(di,i)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Books issued= "+str(len(lst))) L9.place(x=50,y=570) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = tt) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Book",command = p_lock) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_book) B_1.place(x=350,y=100) def p_delete(): add1=Tk() add1.title("Return book") add1.geometry("900x900") def p_del(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] break strr="" if book1!=0: strr=strr+str(book1)+',' if book2!=0: strr=strr+str(book2)+',' if book3!=0: strr=strr+str(book3)+',' if book4!=0: strr=strr+str(book4)+',' if book5!=0: strr=strr+str(book5) strr='You have these books issued '+strr def p_cal(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) dys_free=0 total=0 for j in range(len(lst)): if book1==lst[j]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book2==lst[j]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book3==lst[j]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book4==lst[j]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys elif book5==lst[j]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>dys_free: dys=dys-dys_free else: dys=0 total+=0.50*dys def p_conf(): i=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(i,)) book1 = 0 book2 = 0 book3 = 0 book4 = 0 book5 = 0 for rec in row: book1=rec[1] book2=rec[2] book3=rec[3] book4=rec[4] book5=rec[5] d1=rec[6] d2=rec[7] d3=rec[8] d4=rec[9] d5=rec[10] break b1=E_3.get() b2=E_4.get() b3=E_5.get() b4=E_6.get() b5=E_7.get() aaa=0 if b1=="": aaa+=1 if b2=="": aaa+=1 if b3=="": aaa+=1 if b4=="": aaa+=1 if b5=="": aaa+=1 aaa=5-aaa lst=[] if aaa==5: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) lst.append(int(b5)) elif aaa==4: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) lst.append(int(b4)) elif aaa==3: lst.append(int(b1)) lst.append(int(b2)) lst.append(int(b3)) elif aaa==2: lst.append(int(b1)) lst.append(int(b2)) elif aaa==1: lst.append(int(b1)) for j in range(len(lst)): if book1==lst[j]: conn.execute('''UPDATE Records set 'book1'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI1'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book2==lst[j]: conn.execute('''UPDATE Records set 'book2'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI2'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book3==lst[j]: conn.execute('''UPDATE Records set 'book3'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI3'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book4==lst[j]: conn.execute('''UPDATE Records set 'book4'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI4'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() elif book5==lst[j]: conn.execute('''UPDATE Records set 'book5'=? where Roll_no=?''',(0,i,)) conn.execute('''UPDATE Records set 'DdI5'=? where Roll_no=?''',('00-00-0000',i,)) conn.commit() L9 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "done") L9.place(x=350,y=720) L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine: "+str(total)) L8.place(x=50,y=580) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=7,bd=5,bg='Yellow',font=16, text = "Confirm",command = p_conf) B_2.place(x=350,y=650) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = strr) L2.place(x=50,y=180) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book1") L3.place(x=50,y=260) E_3 = Entry(add1,font=16) E_3.place(x=410,y=260) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book2") L4.place(x=50,y=310) E_4 = Entry(add1,font=16) E_4.place(x=410,y=310) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book3") L5.place(x=50,y=360) E_5 = Entry(add1,font=16) E_5.place(x=410,y=360) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book4") L6.place(x=50,y=410) E_6 = Entry(add1,font=16) E_6.place(x=410,y=410) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book5") L7.place(x=50,y=460) E_7 = Entry(add1,font=16) E_7.place(x=410,y=460) B_2 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=7,bg='Yellow',font=16, text = "Return",command = p_cal) B_2.place(x=350,y=510) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text = "Continue",command = p_del) B_1.place(x=350,y=100) def p_mail(): add1=Tk() add1.title("Mail to students") add1.geometry("700x300") import smtplib row =conn.execute('''select * from Records''') lst1=[] for rec in row: mpty=0 book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] if book1!=0: mpty+=1 if book2!=0: mpty+=1 if book3!=0: mpty+=1 if book4!=0: mpty+=1 if book5!=0: mpty+=1 total=0 free_days=0 for i in range(mpty): if book1 !=0: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book2 !=0: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book3 !=0: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book4 !=0: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>free_days: dys=dys-free_days else: dys=0 total+=0.50*dys if total!=0: lst1.append(rec[0]) lst2=[] for rrol in lst1: row =conn.execute('''select * from RecordsEmail where Roll_no=?''',(rrol,)) for rec in row: eme=rec[1] lst2.append(eme) lstt=lst2 L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =str(len(lstt))+" are number of students whose fine started.") L1.place(x=10,y=10) sender = "systemlibrary567@gmail.com" recipient = lstt password = getpass.getpass() # Your SMTP password for Gmail subject = "UIET KUK LIBRARY" text = ''' Dear student, This is gentle remainder from uiet kuk library that we have started fine. This is automatic mailing so don't reply. This is only for uiet kuk student. If you are not student so please ignore it. ''' smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465) smtp_server.login(sender, password) message = "Subject: {}\n\n{}".format(subject, text) if len(lstt)>0: smtp_server.sendmail(sender, recipient, message) smtp_server.close() L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Done mailed.") L2.place(x=10,y=110) def p_details(): def p_show(): rol=int(E_2.get()) row =conn.execute('''select * from Records where Roll_no = ?''',(rol,)) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(rol,)) for rec in row1: L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Email of student: "+rec[1]) L2.place(x=50,y=160) break lst1=[] total=0 mpty=0 for rec in row: book1=rec[1] d1=rec[6] book2=rec[2] d2=rec[7] book3=rec[3] d3=rec[8] book4=rec[4] d4=rec[9] book5=rec[5] d5=rec[10] break if book1!=0: mpty+=1 lst1.append(book1) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book1)+" Issue Date: "+ d1) L3.place(x=50,y=220) if book2!=0: mpty+=1 lst1.append(book2) L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+ str(book2)+" Issue Date: "+ d2) L4.place(x=50,y=280) if book3!=0: mpty+=1 lst1.append(book3) L5 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book3)+" Issue Date: "+ d3) L5.place(x=50,y=340) if book4!=0: mpty+=1 lst1.append(book4) L6 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Book Number= "+str(book4)+" Issue Date: "+ d4) L6.place(x=50,y=400) if book5!=0: mpty+=1 lst1.append(book5) L7 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text ="Book Number= "+ str(book5)+" Issue Date: "+ d5) L7.place(x=50,y=460) days_free=0 for i in range(len(lst1)): if book1 == lst1[i]: r_dat=date.today() a=int(d1[6:]) b=int(d1[3:5]) c=int(d1[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book2 == lst1[i]: r_dat=date.today() a=int(d2[6:]) b=int(d2[3:5]) c=int(d2[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book3 == lst1[i]: r_dat=date.today() a=int(d3[6:]) b=int(d3[3:5]) c=int(d3[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book4 == lst1[i]: r_dat=date.today() a=int(d4[6:]) b=int(d4[3:5]) c=int(d4[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys elif book5 == lst1[i]: r_dat=date.today() a=int(d5[6:]) b=int(d5[3:5]) c=int(d5[:2]) i_dat=date(a,b,c) delta=r_dat-i_dat dys=delta.days if dys>days_free: dys=dys-days_free else: dys=0 total+=0.50*dys L8 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Total fine= "+str(total)) L8.place(x=50,y=520) add1=Tk() add1.title("Show Details") add1.geometry("900x900") L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Show",command = p_show) B_1.place(x=350,y=100) add1.mainloop() def p_mail_change(): add1=Tk() add1.title("Edit Details") add1.geometry("900x900") def p_changeg(): i=int(E_2.get()) row1=conn.execute('''select * from RecordsEmail where Roll_no = ?''',(i,)) ssa='' for rec in row1: ssa='Email for rollno '+str(i)+' is '+rec[1] def p_change_conf(): rol=int(E_2.get()) newEmail=E_3.get() conn.execute('''UPDATE RecordsEmail set 'Email'=? where Roll_no=?''',(newEmail,rol,)) conn.commit() L4 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'Done') L4.place(x=150,y=360) L2 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = ssa) L2.place(x=50,y=160) L3 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = 'New Email: ') L3.place(x=50,y=220) E_3 = Entry(add1,font=16) E_3.place(x=410,y=220) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=8,bd=5,bg='Yellow',font=16, text = "Change",command = p_change_conf) B_1.place(x=350,y=300) L1 = Label(add1,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text = "Roll Number") L1.place(x=50,y=10) E_2 = Entry(add1,font=16,textvariable = b) E_2.place(x=410,y=10) B_1 = Button(add1,activebackground='Green',activeforeground='Red',width=5,bd=5,bg='Yellow',font=16, text = "Edit",command = p_changeg) B_1.place(x=350,y=100) add1.mainloop() if not(passw()): exit() root = Tk() root.title("Library_Management") root.geometry("900x900") a='''UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY KURUKSHETRA UNIVERSITY KURUKSHETRA''' c= StringVar() b = StringVar() rol = StringVar() L = Label(root,activebackground='Green',activeforeground='Red',bg="light green",bd=5,font=16, text =a) L.place(x=150,y=10) b1="Enroll 1 or more student(s) having different roll numbers" B_1 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b1,command = p_add1) B_1.place(x=150,y=100) b2="Enroll students in a range" B_2 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b2, command=p_addrng) B_2.place(x=150,y=160) b3 = "Delete 1 or more students(s) having different roll numbers" B_3 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b3,command = p_del1) B_3.place(x=150,y=220) b4="Delete students in a range" B_4 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b4, command=p_delrng) B_4.place(x=150,y=280) b5="Issue book(s) for a roll number" B_5 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b5, command=p_issue) B_5.place(x=150,y=340) b6="Return book(s) by any student using roll number" B_6 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b6, command=p_delete) B_6.place(x=150,y=400) b7="To get mail those students whose fine already started" B_7 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b7, command= p_mail) B_7.place(x=150,y=460) b8="To get all details related to any student" B_8 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b8,command= p_details) B_8.place(x=150,y=520) b9="Edit the details i.e. change Email of any student" B_9 = Button(root,activebackground='Green',activeforeground='Red',width=53,bd=5,bg='Yellow',font=16, text =b9, command=p_mail_change) B_9.place(x=150,y=580) B_10 = Button(root,activebackground='Green',activeforeground='Red',width=10,bd=5,bg='Yellow',font=16, text ="Exit",command = p_exit) B_10.place(x=400,y=640) root.mainloop()
b0670e3cdb4f9647102f477224de46ad97ff78d3
nsc1114/comp110-21f-workspace
/exercises/ex02/repeat_beat.py
378
3.96875
4
"""Repeating a beat in a loop.""" __author__ = "730394272" beat: str = input("What beat do you want to repeat?") num: str = input("How many times do you want to repeat it?") total: str = beat if int(num) <= 0: print("No beat...") else: runtime: int = int(num) while runtime > 1: total = total + " " + beat runtime = runtime - 1 print(total)
8b859bf457f2da415c393ea7f56d62495e778835
MarynaNogtieva/mipt
/practice1/spider.py
280
3.609375
4
import turtle import math t = turtle.Turtle() t.shape('turtle') legs_angle = 360 / 12 for i in range(12): t.forward(100) t.stamp() t.left(180) # turn to face center on the way back t.forward(100) t.right(180) # turn to face border on the way forward t.right(legs_angle)
d9d7f6302c0c7c3721bd63c6b2866c6f111ee243
MarynaNogtieva/mipt
/practice1/10_indended_sqares.py
373
4.09375
4
import turtle import math t = turtle.Turtle() t.shape('turtle') side_size = 50 def draw_square(t, side_size): for i in range(4): t.forward(side_size) t.left(90) for i in range(10): draw_square(t,side_size) # t.forward(side_size) side_size += 20 t.penup() # lift turtle # move turtle outside t.backward(10) t.right(90) t.forward(10) t.left(90) t.pendown()
81eba7d41e0f8962458519751b02c21dc52c88a5
Sreenidhi220/IOT_Class
/CE8OOPndPOP.py
1,466
4.46875
4
#Aum Amriteshwaryai Namah #Class Exercise no. 8: OOP and POP illustration # Suppose we want to model a bank account with support for 'deposit' and 'withdraw' operations. # One way to do that is by Procedural Programming # balance = 0 # def deposit(amount): # global balance # balance += amount # return balance # def withdraw(amount): # global balance # balance -= amount # return balance #The above example is good enough only if we want to have just a single account. #Things start getting complicated if we want to model multiple accounts. # Have multiple accounts as list or dictionary or separate variables? def deposit(name, amount): Accounts[name] += amount return Accounts[name] def withdraw(name, amount): Accounts[name] -= amount return balance Accounts = {} Accounts["Arya"] = 2000 Accounts["Swathi"] = 2000 Accounts["Urmila"] = 2000 print("Arya's balance is %d" % deposit("Arya", 200)) class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance Arya = BankAccount() Swathi = BankAccount() Urmila = BankAccount() Swathi.deposit(400) Urmila.deposit(700) print(Urmila.balance) #Referece :https://anandology.com/python-practice-book/object_oriented_programming.html
85b42725e82771c0e8e6e04f84e2c5e1fbec0606
sisinflab/Perceptual-Rec-Mutation-of-Adv-VRs
/src/utils/__init__.py
904
3.515625
4
import sys import os import socket def cpu_count(): """ Returns the number of CPUs in the system """ if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def get_server_name(): return socket.gethostname()
cd6b3802242956ea0c86e3ca72e844c80484ccc6
arcann/mstr_python_api
/microstrategy_api/task_proc/bit_set.py
262
3.515625
4
from enum import Enum class BitSet(set): def combine(self): result = 0 for entry in self: if isinstance(entry, Enum): result |= entry.value else: result |= entry return result
c79f3df4eb01631e73363cd6e5e6546e15380b30
edran/ProjectsForTeaching
/Classic Algorithms/sorting.py
2,073
4.28125
4
""" Implement two types of sorting algorithms: Merge sort and bubble sort. """ def mergeMS(left, right): """ Merge two sorted lists in a sorted list """ llen = len(left) rlen = len(right) sumlist = [] while left != [] and right != []: lstack = left[0] while right != []: rstack = right[0] if lstack < rstack: sumlist.append(lstack) left.pop(0) break else: sumlist.append(rstack) right.pop(0) if left == []: sumlist += right else: sumlist += left return sumlist def mergeSort(l): """ Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list. """ # I actually implemented without reading any of the formal algorithms, # so I'm not entirely sure I did a good job. I have to read up and compare # my solution with a standard one. if len(l) == 1: return l split = len(l) / 2 a = mergeMS(mergeSort(l[:split]), mergeSort(l[split:])) return a def bubbleSort(l): """ simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order """ n = list(l) swapped = True k = len(n) - 1 while swapped: swapped = False i = k while i > 0: u = n[i] d = n[i - 1] if u < d: n[i] = d n[i -1] = u swapped = True i -= 1 return n def main(): t = raw_input("List of numbers> ") t = eval("[" + t + "]") r = mergeSort(t) b = bubbleSort(t) print "MergeSort: ", r print "BubbleSort: ", b if __name__ == "__main__": main()
4b41489f518c4cbca1923440c3416cdfef345f88
edran/ProjectsForTeaching
/Numbers/factprime.py
657
4.28125
4
""" Have the user enter a number and find all Prime Factors (if there are any) and display them. """ import math import sys def isPrime(n): for i in range(2,int(math.sqrt(n)) + 1): # premature optimization? AH! if n % i == 0: return False return True def primeFacts(n): l = [] for i in range(1,int(math.ceil(n/2))+1): if n % i == 0 and isPrime(i): l.append(i) if n not in l and isPrime(n): l.append(n) # for prime numbers return l def main(): i = int(raw_input("Factors of which number? ")) print primeFacts(i) if __name__ == "__main__": while 1: main()
05acb3ccc06473b83b430816bd688b410a97871f
edran/ProjectsForTeaching
/Numbers/alarm.py
2,457
3.671875
4
""" A simple clock where it plays a sound after X number of minutes/seconds or at a particular time. """ import time import pyglet def passedTime(t, typetime): """ Returns time passed since t (seconds) typetime can be <m> or <s> to specify the returning type (minutes or seconds) """ try: passed = time.time() - t except TypeError: "Argument is not a time" if typetime == "m": # minutes return passed / 60.0 elif typetime == "s": # seconds return passed else: print "Type not valid" mario = pyglet.media.load("oneup.wav", streaming=False) def playSound(): mario.play() def cronometer(t, typetime): start = time.time() flag = True # for counter while 1: p = passedTime(start, typetime) if flag: # get first p r = p flag = False if int(r) != int(p): print "Remaining " + str(int(t) - int(p)) + typetime r = p if t < p: print "END of cronometer!" break playSound() time.sleep(1) def alarm(hours, minutes): h = int(hours) m = int(minutes) if not (h in range(24) and m in range(60)): print "Wrong time values" return flag = True while 1: t = time.localtime() # gmtime is UTC if t.tm_hour == int(h) and t.tm_min == int(m): break if flag: # get first p past_hr = t.tm_hour past_min = t.tm_min flag = False if past_hr != t.tm_hour or past_min != t.tm_min: remaining = ((h - t.tm_hour) * 60) + (m - t.tm_min) # mmm print "Remamining minutes: " + str(remaining) past_hr = t.tm_hour past_min = t.tm_min playSound() time.sleep(1) def main(): inp = raw_input("Cronometer or Alarm? [c/a] ") if inp == "C" or inp == "c": typetime = raw_input("Minutes or seconds? [s/m] ") t = float(raw_input("How many minutes/seconds? ")) cronometer(t, typetime) elif inp == "A" or inp == "a": print "When would you like the alarm to go off?" hours = raw_input("Hours[0-23]> ") minutes = raw_input("Minutes[0-59]> ") alarm(hours, minutes) if __name__ == "__main__": main()
9f7f047dbb43adc3798df7b33e7de4554a64c0ac
DanielWillim/AoC2019
/day1.py
354
3.609375
4
def fuel_cost(mass): mass_fuel = (mass // 3) - 2 if mass_fuel <= 0: return 0 return mass_fuel + fuel_cost(mass_fuel) inp = open('inp_day1', "r") lines = inp.readlines() total_cost = 0 print(fuel_cost(14)) print(fuel_cost(100756)) for line in lines: total_cost += fuel_cost(int(line)) print(total_cost) inp.close()
bafd57196a0350f468390680e923c9fe9541e77a
keyman9848/bncgit
/xmjc_analysis/dataDeal/dataCollection/txtCollection.py
609
3.515625
4
import pymysql # 打开数据库连接 db = pymysql.connect(host='172.16.143.66',port = 3306,user='kjt', passwd='kjt$',db ='kjt',charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "SELECT VERSION()" sql1= "select * from users" cursor.execute(sql1) # 获取所有记录列表 results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印结果 print (fname, lname, age, sex, income) # 关闭数据库连接 db.close()
d0659e52a363d340934df53c5ae71b1e9fd16209
ClayMav/BPlus-Tree
/bplustree/bplustree.py
8,164
3.890625
4
""" This is a group project, to be worked on and completed in collaboration with the group to which you were assigned in class. One final report is due per group. A number of groups, selected randomly, will be asked to demonstrate the correctness of your program for any input data. Your task is to develop and test a program that generates a B+ tree of order 4 for a sequence of unique index values. In addition, it must support insert and delete operations. 1) Input is: a. a sequence of numeric key values (three digits at most) for initial generation of B+ tree, and b. a sequence of insert and delete commands. 2) For initial sequence of key values, your program should generate and print out the generated index tree. In addition, for each insert and delete command it should also generate and print out the resulting index tree. 3) Test data will be made available on April 5. Your report should show that your program operates correctly for this test data. 4) Your final technical report should include: a. a description of your overall approach and the logic of your program, b. pseudo code for your program, c. output as explained in (2), and d. a hard copy of your program. 5) Please note that the deadline is firm and will not change under any circumstances. """ import math from graphviz import Digraph, nohtml from node.node import Node class BPlusTree(object): DEFAULT_ORDER = 3 def __init__(self, order=DEFAULT_ORDER): self.order = order self.root = Node(order=order) @property def order(self): """An integer denoting the order of the tree""" return self._order @order.setter def order(self, value): """Set the order of the tree""" self._order = value @property def root(self): """The root node of the tree""" return self._root @root.setter def root(self, value): """Set the root node of the tree""" self._root = value def _insert(self, value, root=None): root = self.root if root is None else root if not root.is_leaf_node: split = self._insert(value, root.find_child(value)) if split is not None: new_node, split_value = split if not root.is_split_imminent: root.insert(split_value) root.add_child(new_node) else: second_new_node, second_split_value = root.insert(split_value) if root.find_child(new_node.max) is None: root.add_child(new_node) else: second_new_node.add_child(new_node) parent_node = root.parent if parent_node is None: parent_node = Node(values=[second_split_value], order=self.order, is_internal=True) parent_node.add_child(root) parent_node.add_child(second_new_node) self.root = parent_node else: return second_new_node, second_split_value else: if not root.is_split_imminent: root.insert(value) else: new_node, split_value = root.insert(value) parent_node = root.parent if parent_node is None: parent_node = Node(values=[split_value], order=self.order, is_internal=True) parent_node.add_child(root) parent_node.add_child(new_node) self.root = parent_node else: return new_node, split_value def _connect_leaves(self): queue = [self.root] leaves = [] while queue: root = queue.pop(0) if root.is_leaf_node: leaves.append(root) if len(leaves) > 1: leaves[-2].next = leaves[-1] leaves[-1].prev = leaves[-2] for i, child in enumerate(root.children): if child is not None: queue.append(child) def insert(self, value): self._insert(value) self._connect_leaves() def _render_node_str(self, node): values = [' ']*(self.order-1) f_idx = 0 buffer = [] for i, value in enumerate(node.values): values[i] = str(value) for i, value in enumerate(values): buffer.append('<f%d> |<f%d> %s|' % (f_idx, f_idx+1, value)) f_idx += 2 buffer.append('<f%d>' % (f_idx,)) return ''.join(buffer) def _render_graph(self, g): queue = [self.root] while queue: root = queue.pop(0) g.node('%s' % (id(root),), nohtml(self._render_node_str(root))) if root.next is not None: g.edge('%s' % (id(root),), '%s' % (id(root.next),), constraint='false') for i, child in enumerate(root.children): if child is not None: queue.append(child) g.edge('%s:f%d' % (id(root), i*2), '%s:f%d' % (id(child), self.order)) def render(self, filename='btree.gv'): g = Digraph('g', filename=filename, node_attr={'shape': 'record', 'height': '.1'}) self._render_graph(g) g.view() def _delete(self, val, root=None): """Deletes specified value""" root = self.root if root is None else root if not root.is_leaf_node: merged = self._delete(val, root.find_child(val)) if merged: if len(root.values) != root.num_children-1: if root.parent: return root.merge(val) else: if root.num_children == 1: root = self.root self.root = root.children[0] root.remove_child(self.root) else: root.values.pop(-1) else: if val in root.values: success = root.remove(val) if not success: if not root.redistribute(val): return root.merge(val) def delete(self, val, root=None): self._delete(val, root) def find(self, val, root=None): """Determines if value exists in tree""" # Technically this function works, but it doesn't take advantage of the # Optimizations of the B+ Tree. Will fix later. # TODO FIX root = self.root if root is None else root # Stopping Conditions if val in root.values: # If val is in this node return True if root.num_children == 0: # If val is not in node, and there are no children return False # Recursion if val <= root.values[0]: # If val smaller or equal to first value in the root # Go to first child print("LESS THAN OR EQUAL TO FIRST", val, root.values[0]) return self.find(val, root.children[0]) if val > root.values[-1]: # If val greater than the last value in the root # Go to last child print("GREATER THAN LAST", val, root.values[-1]) return self.find(val, root.children[len(root.values)]) for index, value in enumerate(root.values): if not index == len(root.values) - 1 and val > value and \ val <= root.values[index + 1]: # If in between two values in the root, go to child in between # Go to child at root.children[index + 1] print("BETWEEN", value, "<", val, "<=", root.values[index + 1]) return self.find(val, root.children[index + 1]) def __str__(self): return "order={}, root={}".format(self.order, self.root)
2b7c6bb7e8405efe52a594d97bc7c7ac1584417c
kujaku11/mt_metadata
/mt_metadata/utils/list_dict.py
7,082
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 16 11:08:25 2022 @author: jpeacock """ # ============================================================================= # Imports # ============================================================================= from collections import OrderedDict # ============================================================================= class ListDict: """ Hack together an object that acts like a dictionary and list such that a user can get an item by index or key. This is the first attempt, seems to work, might think about inheriting an OrderedDict and overloading. """ def __init__(self, values={}): self._home = OrderedDict(values) def __str__(self): lines = ["Contents:", "-" * 12] for k, v in self._home.items(): lines.append(f"\t{k} = {v}") return "\n".join(lines) def __repr__(self): return self._home.__repr__() def __eq__(self, other): return self._home.__eq__(other._home) def __len__(self): return self._home.__len__() def _get_key_from_index(self, index): try: return next(key for ii, key in enumerate(self._home) if ii == index) except StopIteration: raise KeyError(f"Could not find {index}") def _get_index_from_key(self, key): try: return next(index for index, k in enumerate(self._home) if k == key) except StopIteration: raise KeyError(f"Could not find {key}") def _get_key_from_object(self, obj): """ Get the key from the metadata object :param obj: DESCRIPTION :type obj: TYPE :return: DESCRIPTION :rtype: TYPE """ if hasattr(obj, "id"): return obj.id elif hasattr(obj, "component"): return obj.component else: raise TypeError("could not identify an appropriate key from object") def __deepcopy__(self, memodict={}): """ Need to skip copying the logger need to copy properties as well. :return: DESCRIPTION :rtype: TYPE """ copied = type(self)() for key, value in self.items(): if hasattr(value, "copy"): value = value.copy() copied[key] = value return copied def copy(self): """ Copy object """ return self.__deepcopy__() def _get_index_slice_from_slice(self, items, key_slice): """ Get the slice index values from either an integer or key value :param items: DESCRIPTION :type items: TYPE :param key_slice: DESCRIPTION :type key_slice: TYPE :raises TypeError: DESCRIPTION :return: DESCRIPTION :rtype: TYPE """ if key_slice.start is None or isinstance(key_slice.start, int): start = key_slice.start elif isinstance(key_slice.start, str): start = self._get_index_from_key(key_slice.start) else: raise TypeError("Slice start must be type int or str") if key_slice.stop is None or isinstance(key_slice.stop, int): stop = key_slice.stop elif isinstance(key_slice.stop, str): stop = self._get_index_from_key(key_slice.stop) else: raise TypeError("Slice stop must be type int or str") return slice(start, stop, key_slice.step) def __getitem__(self, value): if isinstance(value, str): try: return self._home[value] except KeyError: raise KeyError(f"Could not find {value}") elif isinstance(value, int): key = self._get_key_from_index(value) return self._home[key] elif isinstance(value, slice): return ListDict( list(self.items())[ self._get_index_slice_from_slice(self.items(), value) ] ) else: raise TypeError("Index must be a string or integer value.") def __setitem__(self, index, value): if isinstance(index, str): self._home[index] = value elif isinstance(index, int): try: key = self._get_key_from_index(index) except KeyError: try: key = self._get_key_from_object(value) except TypeError: key = str(index) self._home[key] = value elif isinstance(index, slice): raise NotImplementedError( "Setting values from slice is not implemented yet" ) def __iter__(self): return iter(self.values()) def keys(self): return list(self._home.keys()) def values(self): return list(self._home.values()) def items(self): return self._home.items() def append(self, obj): """ Append an object :param obj: DESCRIPTION :type obj: TYPE :return: DESCRIPTION :rtype: TYPE """ try: key = self._get_key_from_object(obj) except TypeError: key = str(len(self.keys())) self._home[key] = obj def remove(self, key): """ remove an item based on key or index :param key: DESCRIPTION :type key: TYPE :return: DESCRIPTION :rtype: TYPE """ if isinstance(key, str): self._home.__delitem__(key) elif isinstance(key, int): key = self._get_key_from_index(key) self._home.__delitem__(key) else: raise TypeError("could not identify an appropriate key from object") def extend(self, other, skip_keys=[]): """ extend the dictionary from another ListDict object :param other: DESCRIPTION :type other: TYPE :return: DESCRIPTION :rtype: TYPE """ if isinstance(skip_keys, str): skip_keys = [skip_keys] if isinstance(other, (ListDict, dict, OrderedDict)): for key, value in other.items(): if key in skip_keys: continue self._home[key] = value else: raise TypeError(f"Cannot extend from {type(other)}") def sort(self, inplace=True): """ sort the dictionary keys into alphabetical order """ od = OrderedDict() for key in sorted(self._home.keys()): od[key] = self._home[key] if inplace: self._home = od else: return od def update(self, other): """ Update from another ListDict """ if not isinstance(other, (ListDict, dict, OrderedDict)): raise TypeError( f"Cannot update from {type(other)}, must be a " "ListDict, dict, OrderedDict" ) self._home.update(other)
dc4e1a66e05f8db95dda9efbdc9c4dfc3748b791
IDSF21/assignment-2-samarthgowda
/main.py
4,335
3.5625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import streamlit as st @st.cache def load_songs(): df = pd.read_csv("./data.csv") df = df.drop_duplicates(["id", "name"], keep="last") df = df.dropna(how="any") df["year"] = df["year"].astype(int) return df songs = load_songs() @st.cache def get_years(songs): return list(np.sort(songs["year"].unique())) years = get_years(songs) @st.cache def calculate_songs_agg(songs): songs_agg = songs.groupby("year").agg( { "acousticness": np.mean, "danceability": np.mean, "duration_ms": np.mean, "energy": np.mean, "instrumentalness": np.mean, "liveness": np.mean, "loudness": np.mean, "popularity": np.mean, "speechiness": np.mean, "tempo": np.mean, "valence": np.mean } ) songs_agg.index = pd.to_datetime(songs_agg.index, format="%Y") return songs_agg songs_agg = calculate_songs_agg(songs) with st.container(): """ # 🎶 How Music has Changed from 1921-2020 Information about these songs are from Spotify Web API. Dataset provided from [Kaggle](https://www.kaggle.com/ektanegi/spotifydata-19212020). """ if st.checkbox("Show raw dataframe of Spotify 1921-2020 Songs Dataset"): songs if st.checkbox("Show dataframe of average values for different columns in Spotify Songs grouped by Year"): songs_agg with st.container(): """ ### 📅 Understanding how different aspects of songs have changed over time Overtime, song attributes have changed a lot. Take a look at how certain attributes are very similar overtime from 1921 to 2020 and how other attributes change drastically over the last century. """ overall_variable_select = st.selectbox( "Select the variable that you would like to explore.", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="overall_variable", ) songs_agg_data = songs_agg[[overall_variable_select]] songs_agg_data["year"] = songs_agg_data.index fig, ax = plt.subplots() ax.plot("year", overall_variable_select, data=songs_agg_data) ax.set_xlabel("Release Year") ax.set_ylabel(overall_variable_select) ax.set_title(f"{overall_variable_select} vs Release Year for Spotify Song Data 1921-2021") st.pyplot(fig) with st.container(): """ ### 🔊 Understanding the distribution of aspects of songs for a given release year range Select a start year, end year, and a song attribute and observe the distribution of the song attribute's distribution over the date range. There are interesting differences between certain attributes as you change the start and end years. """ col1, col2 = st.columns(2) with col1: start_year, end_year = st.select_slider("Select a range of years to explore", options=years, value=[years[0], years[-1]]) with col2: year_variable_select = st.selectbox( "Select the variable that you would like to explore", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="year_variable", ) with st.container(): after_start = songs["year"] >= start_year before_end = songs["year"] <= end_year between_years = after_start & before_end songs_data = songs.loc[between_years] songs_data = songs_data[["year", year_variable_select]] fig, ax = plt.subplots() ax.hist(songs_data[year_variable_select]) ax.set_ylabel(f"Frequency") ax.set_xlabel(year_variable_select) ax.set_title(f"Frequency of {year_variable_select} for Spotify Song Data {start_year} to {end_year}") st.pyplot(fig)
1ab87bc5c2863c90dea96185241b0869f2259f30
sonusbeat/intro_algorithms
/Recursion/group_exercise2.py
489
4.375
4
""" Group Exercise Triple steps """ def triple_steps(n): """ A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Count how many possible ways the child can run up the stairs. :param n: the number of stairs :return: The number of possible ways the child can run up the stairs. """ if n <= 2: return n return triple_steps(n-1) + triple_steps(n-2) + triple_steps(n-3) print(triple_steps(3))
916e2aa4bc23a717c6ba3d196b26cb44a02e6c78
sonusbeat/intro_algorithms
/7.Loops/01.exercise.py
469
4.21875
4
# Exercises # 1. Write a loop to print all even numbers from 0 to 100 # for num in range(101): # if num % 2 == 0: # print(num) # list comprehension # [print(i) for i in range(101) if i % 2 == 0] # 2. Write a loop to print all even numbers from 0 to 100 # for i in range(0, 101): # if i % 2 == 1: # print(i, end=" ") # print() # print("*" * 40) # for ch in "hello": # print(ch) # for ch in ["hello", "Hola", "Konichiwa"]: # print(ch)
ec45e6109ddd2f2f3b9984404f015b828f0ca4f1
sonusbeat/intro_algorithms
/SearchingAlgorithms/2.binary_search.py
1,037
4.28125
4
""" Binary Search - how you look up a word in a dictionary or a contact in phone book. * Items have to be sorted! """ alist = [ "Australia", "Brazil", "Canada", "Denmark", "Ecuador", "France", "Germany", "Honduras", "Iran", "Japan", "Korea", "Latvia", "Mexico", "Netherlands", "Oman", "Philippines", "Qatar", "Russia", "Spain", "Turkey", "Uruguay", "Vietnam", "Wales", "Xochimilco", "Yemen", "Zambia" ] def binary_search(collection, target): start = 0 end = len(collection) - 1 steps = 0 while start <= end: mid = (start + end) // 2 steps += 1 if collection[mid] == target: steps_message = "s" if steps > 1 else "" return F"\"{collection[mid]}\" is at position {str(mid)} and it took {str(steps)} step{steps_message}" elif collection[mid] < target: start = mid + 1 else: end = mid - 1 return F"Your country \"{target}\" is not on the list!" print(binary_search(alist, input("What's your country? ")))
07f7fc0b352b9919350390eab9eba036b89fba66
sonusbeat/intro_algorithms
/Labs/Lab0.py
492
3.84375
4
import turtle screen = turtle.Screen() screen.bgcolor("#90ee90") t = turtle.Turtle() t.pensize(5) t.shape('turtle') t.color("blue") t.stamp() for _ in range(12): t.penup() t.forward(100) t.pendown() t.forward(10) t.penup() t.forward(20) t.pendown() t.stamp() t.penup() t.backward(130) t.left(30) screen.exitonclick() # the pensize (thickness) = 5 # from center to the tick = 100 # the length of the tick = 10 # from the tick to turtle = 10
d7d7dddc18064c4b24885e0caa07872f3fcde5d3
CavHack/Manhattanite-
/EM-GMM/k_clustering.py
2,969
3.9375
4
############################################################################################################## # Author: Karl Whitford # # Manhattanite- Multi-disciplinary Machine Learning/A.I Toolkit with Python # # Extracted from project description: # WHAT YOUR PROGRAM OUTPUTS # # You should write your K-means and EM-GMM codes to learn 5 clusters. Run both algorithms for 10 iterations. # You can initialize your algorithms arbitrarily. We recommend that you initialize the K-means centroids by # randomly selecting 5 data points. For the EM-GMM, we also recommend you initialize the mean vectors in the # same way, and initialize pi to be the uniform distribution and each Sigma_k to be the identity matrix. ############################################################################################################## import sys import numpy as np def load_data(input_file): """ Load the dataset. Assumes a *.csv is fed without header, and the output variable in the last column """ data = np.genfromtxt(input_file, delimiter=',', skip_header=0, names=None) return data def KMeans(X, K=5, maxit=10, saveLog=true): """ Apply KMeans for clustering a dataset given as input, and the number of clusters (K). Input: x1, ..., xn where x in R^d, and K Output: Vector c of cluster assignments, and K mean vectors mu """ #Sample size N = X.shape[0] #Initialize output variable c = np.zeros(N) mu = X[np.random.choice(N, K, replace=False), :] for i in xrange(N): kmin = 1 minDist = float('Inf') for k in xrange(K): dist = np.linalg.norm(X[i, :] - mu[k, :]) if dist < minDist: minDist = dist kmin = k c[i] = kmin + 1 cNew = np.zeros(N) it = 1 while it <= maxit and not all (c==cNew): #write the output file if required if saveLog: with open('centroids-'+ str(it) + '.csv', 'w') as f: for mu_i in mu: for j in xrange(len(mu_i)-1): f.write(str(mu_i[j]) + ',') f.write(str(mu_i[len(mu_i) -1 ]) + '\n') c = np.copy(cNew) for i in xrange(N): kmin = 1 minDist = float('Inf') for k in xrange(K): dist = np.linalg.norm(X[i, :]-mu[k, :]) if dist < minDist: minDist = dist kmin = k cNew[i] = kmin + 1 for k in xrange(1, K+1): Xk = X[cNew ==k, :] mu[k - 1] = np.sum(Xk, axis=0) / Xk.shape[0] it += 1 return (c, mu, it) def gauss(mu, cov, x): """ Computes gaussian parametrized by mu and cov, given x. Make sure x dimensions are of correct size """ d = len(x) den = np.sqrt(np.linalg.det(cov))*(2*np.pi)**(0.5*d) num = np.exp(-0.5 * np.dot(x-mu, np.linalg.solve(cov, np.transpose(x-mu)))) return num/den
42a61c3c43eaa30894aeb3bd7980dfc679b34475
the-economancer/Project-Euler
/Problem003.py
789
4
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 16 15:53:11 2016 Functions to compute largest prime factor of a given number @author: michael """ import math import time def isPrime(x): for y in range(2,int(math.sqrt(x))+1): if x % y == 0: return False return True def factors(x): factors = [] for y in range (2,int(math.sqrt(x))+1): if y in factors: return factors if x % y == 0: factors.append(y) return factors def primefactors(x): facts = factors(x) pfact = [] for fact in facts: if isPrime(fact): pfact.append(fact) return pfact def maxprime(x): a = time.time() maxprim = max(primefactors(x)) print(time.time() - a) return maxprim
e4c980515428ad2e3bb23d9cf104d9ebf30a2780
molweave532/IntroToProg-Python-Mod07
/HW07-Error-Handling/Assignment07-error-handling-MW.py
1,010
4.03125
4
# ------------------------------------------------- # # Title: HW07 - error handling # Description: A brief description of error handling # ChangeLog: (Who, When, What) # Molly Weaver, 02/27/21, Created Script # ------------------------------------------------- # try: # write a test case here intOne = int(input("Please enter an integer from 1 to 10: ")) except ValueError: # then tell the user there was an error print("That's not what I'm looking for! I need an integer.") except Exception as error: print("That was unexpected!") print(error) else: try: # look to see if the integer is outside the expected range if intOne < 1 or intOne > 10: raise Exception except Exception: # tell the user there was an error (print("That is outside the expected range!")) else: # no errors encountered! print("You entered: ", intOne) finally: # do this every time print("Goodbye!")
8738e0b40f3dd5bd03454d4190fd660bbab6bd43
jameskowalski97/plotting-library
/assignment_4.py
1,273
3.609375
4
#!/bin/python # Import the libraries we are using. It is good practice to import all necessary # libraries in the first lines of a file. import numpy as np import matplotlib.pyplot as plt import pandas as pd #test comment # Create an array (a multi-dimensional table) out of our data file, full of text all_data = np.genfromtxt("data/1302_susc_data.csv", delimiter=',',skip_header=3) #print(all_data) #to divide the data sets in output print("~~~~~~~~~~~~~~~~~~~~~") # Select the data range we are interested in, convert it into a new array, full of numbers susc_data = np.array(all_data[:,:], dtype=float) #print(susc_data) #Create a figure of the processed data susc_figure = plt.figure() susc_plot = plt.scatter (susc_data[:,0],susc_data[:,1]) plt.title ("IODP Expedition 303, Site U1302-03") plt.xlabel ("Meters Composite Depth") plt.ylabel ("Magnetic Susceptibility") plt.show(block=True) susc_figure.savefig('results/susceptibility-with-depth.png') #let script write pandas dataset into .json file all_data = pd.read_csv("data/1302_susc_data.csv", header=2) all_data.info() all_data.to_json("results/data_output.json") print(all_data.loc['0.3':'1',:]) json_data = pd.read_json("results/data_output.json") json_data.info() print(json_data.loc['0.3':'1',:])
795353bbba095affade0e5933b63a0e3fbec7a6e
low101043/final-year-13-project
/final_Game_File.py
3,848
3.703125
4
# Main Game from tkinter import * #This means I can use tkinter #import gamePrototype4 ###################################################################################################################################################################################################################################### def instructions(): """Made By Nathaniel Lowis. 1st Edit: 17/10/18. Latest Edit: 17/10/18 Inputs - None Outputs - None Displays the instructions for how to play the game""" instructionScreen = Tk() #Makes a window instructionScreen.title("Bullet Game") #Name of the window instructionScreen.geometry("500x500") #Size of the window #menu.wm_iconbitmap("favicon.ico") instructionScreen.configure(background = ("navy")) #Background of the window instructionsToDo= Label(instructionScreen, text = "To play the game click on the screen. Controls (Do not have caps lock on) \n q: Fires a horizontal Bullet. Powerful however the enemy will shoot \n w: Fires a Parabolic Bullet. Not so powerful \n Aim: Get to the red block as fast as you can using the least amount of bullets possible and having the most health at the end. \nCyan Block - Enemy\nDark Blue Block - You", bg = "grey", fg = "black") #This will output all the instructions onto the window so the user can see how to play the game instructionsToDo.pack() #Sends the label to the screen ###################################################################################################################################################################################################################################### def play_Game(): """Made By Nathaniel Lowis 1st Edit: 17/10/18 Latest Edit: 17/10/18 Inputs - None Outputs - None Plays the game""" import main_Game #Goes to file named gamePrototype4 and runs it. This will run the game #exec(open("gamePrototype4.py").read()) #Testing ###################################################################################################################################################################################################################################### def database_To_Display(): """Made By Nathaniel Lowis 1st Edit: 18/10/18 Latest Edit: 18/10/18 Inputs - None Outputs - None Will go to the file which ouputs the leaderboard""" import displaying_Database #Goes to file called displaying_Database and runs the code ###################################################################################################################################################################################################################################### #main window = Tk() #Makes a window for the GUI window.title("Bullet Game") #Names the window window.geometry("500x500") #The size of the window #window.wm_iconbitmap("favicon.ico") window.configure(background = ("navy")) #Sets the background colour labelWelcome =Label(window, text = "Bullet Shot", bg = "green", fg = "white") #This is the welcome label saying the name of the game (Bullet Shot) labelWelcome.pack() #Sends it to the main screen buttonInstructions = Button(window, text = "Instructions", bg = "green", fg = "white", command = instructions ) #This is the button to Go to the instructions buttonInstructions.pack() #Sends button to window buttonGame = Button(window, text = "Game", bg = "green", fg = "white", command = play_Game) #This is the button to play the game buttonGame.pack() #Sends button to the screen buttonLeaderboard = Button(window, text = "Leaderboard", bg = "green", fg = "white", command = database_To_Display) #This is the button to go to the leaderboard buttonLeaderboard.pack() #Sends button to the screen window.mainloop() #Infinte loop.
80582061e8c52501b90a818218215639ef8cbdcb
Lackman-coder/collection
/argsandkwargs.py
661
3.5625
4
# *args methods: def name(*args): name(a) print("denser","anitha","lackman","drikas","rakshana" "\n") def animal(*bets): animal(b) print("cat","dog","parrot","fish" "\n") def item(*home): for items in home: print(items) item("tv","fridge","ac","electronics" "\n") #if u not using *args then u cannot give moore arguments on function call example below: ''' def frd(a,b,c): print(a,b,c) frd("frd1","frd2","frd3","frd4")''' #uncmd above code and check error. # **kwargs method: def data(**kwargs): for key , value in kwargs.items(): print("{} is {}".format (key,value)) data(name = "lackman", age=28, gender = "male", occupation = "seaman")
5c70c82b051ae0d488a4562748e5fd235202534c
corinnelhh/data-structures
/Graph/graph_directional.py
3,337
3.75
4
class Node(object): def __init__(self, data): self._data = data self._visited = False class Graph(object): def __init__(self, *data): self._edges = {} self._nodes = [] for node in data: self._nodes.append(Node(node)) def add_node(self, data): a = Node(data) self._nodes.append(a) return a def has_edge(self, n1, n2): return (n1, n2) in self._edges def add_edge(self, n1, n2, w1=None): if not self.has_edge(n1, n2): if n1 not in self._nodes: self._nodes.append(n1) if n2 not in self._nodes: self._nodes.append(n2) self._edges[(n1, n2)] = w1 def delete_edge(self, n1, n2): try: self._edges.pop((n1, n2)) except(KeyError): raise KeyError def delete_node(self, n): if n not in self._nodes: raise IndexError for i in self._nodes: if self.has_edge(n, i): self.delete_edge(n, i) elif self.has_edge(i, n): self.delete_edge(i, n) self._nodes.remove(n) def has_node(self, n): return n in self._nodes def has_neighbors(self, n): neighbors = [] if n not in self._nodes: raise IndexError for i in self._nodes: if self.has_edge(n, i): neighbors.append(i) return neighbors def adjacent(self, n1, n2): if not self.has_node(n1) or not self.has_node(n2): raise IndexError return self.has_edge(n1, n2) def df_traversal(self, n, df): if not self.has_node(n): raise IndexError if not n._visited: n._visited = True df.append(n) neighbors = self.has_neighbors(n) for i in neighbors: self.df_traversal(i, df) def bf_traversal(self, n): if not self.has_node(n): raise IndexError bf = [n] n._visited = True for i in bf: for child in self.has_neighbors(i): if not child._visited: bf.append(child) child._visited = True return bf # def find_shortest_path(self, n1, n2): # if (not self.has_node(n1)) or (not self.has_node(n2)): # raise IndexError # pass def visit_reset(self): for i in self._nodes: i._visited = False if __name__ == '__main__': import random g = Graph() for i in range(10): a = random.randint(10,99) g.add_node(a) for i in range(40): a = random.randint(0,9) b = random.randint(0,9) g.add_edge(g._nodes[a], g._nodes[b]) for i in g._nodes: result = "Node "+str(i._data)+": | " for x in g.has_neighbors(i): result += str(x._data)+" | " print result df = [] g.df_traversal(g._nodes[0] ,df) result = "\nDepth First Search: \n\t" for i in df: result += str(i._data) +" | " g.visit_reset() print result + "\n" bf = g.bf_traversal(g._nodes[0]) result = "\nBreadth First Search: \n\t" for i in bf: result += str(i._data) +" | " print result + "\n" g.visit_reset()
1cc74b32a7fc70815377e099434dc908ee962da7
corinnelhh/data-structures
/Queue/queue.py
935
4
4
class Node(object): def __init__(self, data, next_node=None): self.data = data self.next = next_node self.last = None class Queue(object): def __init__(self, data=None): self.head = None self.tail = None self.size = 0 if data: for val in data: self.enqueue(val) def enqueue(self, data): self.last_node = self.head self.head = Node(data, self.head) if self.last_node: self.last_node.last = self.head if self.tail is None: self.tail = self.head self.size += 1 def dequeue(self): if self.tail is None: print "Sorry, the queue is empty!" raise IndexError our_returned_value = self.tail.data self.tail = self.tail.last self.size -= 1 return our_returned_value def size_me(self): return self.size
0ea7ceffc8365b8d61d10608a240a6c59a05247e
corinnelhh/data-structures
/Heap/binary_heap.py
1,959
3.859375
4
#!/usr/bin/env python #import math, random class BinaryHeap(object): def __init__(self, max_heap="max", *data): self._list = [] self._size = 0 self.max_heap = True if max_heap == "min": self.max_heap = False elif max_heap != "max" and max_heap is not None: self.push(max_heap) if data: for i in data: self.push(i) def push(self, value): self._list.append(value) child = parent = self._size self._size += 1 while parent > 0: parent = (child - 1) // 2 if self.compare(child, parent): break self.swap(child, parent) child = parent def pop(self): if not self._size: print "Yo, this is an empty heap." raise IndexError val = self._list[0] self._list[0] = self._list[-1] self._list.pop() self._size -= 1 parent, left, right = 0, 1, 2 while right < self._size: if (self.compare(left, parent) and self.compare(right, parent)): break if self.compare(right, left): self.swap(parent, left) parent = left else: self.swap(parent, right) parent = right left = parent * 2 + 1 right = left + 1 if left < self._size: if self.compare(parent, left): self.swap(parent, left) return val def swap(self, x, y): self._list[x], self._list[y] = self._list[y], self._list[x] def compare(self, x, y): if self.max_heap: return self._list[x] < self._list[y] else: return self._list[x] > self._list[y] """ #DEBUGGING for x in range(10): a = BinaryHeap(1,*[random.randint(0,100) for i in range(11)]) print str(a._list) """
6954f9970b9f32aa4de9e42e0964ca73a1b1cf88
corinnelhh/data-structures
/Stack/stack.py
542
3.71875
4
class Node(object): def __init__(self, data, next_node=None): self.data = data self.next = next_node class Stack(object): def __init__(self, data=None): self.head = None if data: for val in data: self.push(val) def push(self, data): self.head = Node(data, self.head) def pop(self): if self.head is None: raise IndexError our_returned_value = self.head.data self.head = self.head.next return our_returned_value
2d5ff47ae292ccb66d00aeea9471839310bae822
vamsikrishna6668/python
/class8.py
827
3.859375
4
class Employee: emp_desgination=input("Enter a Employee Desgination:") emp_work_loaction=input("Enter a Employee Work Location:") def fun1(self): print("Iam a function1") def assign(self,idno,name,sal): print("The idno of the Employee:",idno) print("The Name of the Employee:",name) print("The Salary of the Employee:",sal) def show(self,emp_add,emp_wiki): self.emp_add=emp_add self.emp_wiki=emp_wiki print(self.emp_wiki) print(self.emp_add) def display(self,age,cno): self.age=age self.cno=cno print("Iam a Display") #call e1=Employee() e1.fun1() e1.assign(101,"Ismail",96000000) a=input("Enter a Employee address:") b=input("Enter a Employee Wiki:") e1.show(a,b) e1.display(25,8500580594)