blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3b53955c4ca6c92ce453da0839ba9d8661eb0e0f
ISPritchin/Olympiad
/900/Оформлено/Ромадзи.py
306
4.03125
4
word = input() if word[-1] not in "euioa" and word[-1] != "n": print("NO") else: for i in range(1, len(word)): if word[i-1] == "n": continue if word[i-1] not in "euioa" and word[i] not in "euioa": print("NO") break else: print("YES")
80fd536bff788b4c48a07cf007029c1f173f03ea
ansonmau/projects
/SV_Projects/Blackjack.py
2,893
3.90625
4
import random from time import sleep def hit(): cards = [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', ] draw = random.choice(cards) return draw def GetTotal(hand): total = 0 card_values = { 'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, } for card in hand: total += card_values[card] return total def DrawHand(hand): string = '' numCards = len(hand) for i in range(numCards): string += ('+-----+ ') string += '\n' for i in range(numCards): string += ('| | ') string += '\n' for card in hand: string += ('|{:^5}| '.format(card)) string += ' Value: {}\n'.format(GetTotal(hand)) for i in range(numCards): string += ('| | ') string += '\n' for card in hand: string += ('+-----+ ') return string def main(): PLAY = True while PLAY: bot_hand = random.randint(15, 23) plr_hand = [hit(), hit()] print("Your starting hand:\n{}".format( DrawHand(plr_hand), GetTotal(plr_hand))) # assume they did not hit. Need this var because the if statement after the following loop uses will_hit, # and if we start off with >17, it won't know what will_hit is. will_hit = 'n' while GetTotal(plr_hand) <= 17: will_hit = input("hit? (Y/N): ") if will_hit == "Y" or will_hit == "y": plr_hand.append(hit()) print("\nYou drew: {}".format(plr_hand[-1])) sleep(1) print("Your new hand:\n{}".format( DrawHand(plr_hand))) else: break if will_hit == "Y" or will_hit == "y": print("You can no longer hit.") if GetTotal(plr_hand) <= 21: print("\n{:>10}: {}".format("Your total", GetTotal(plr_hand))) print("{:>10}: {}".format("Bot total", bot_hand)) print() if bot_hand <= 21: if GetTotal(plr_hand) > bot_hand: print("You win!") elif GetTotal(plr_hand) < bot_hand: print("You lose :(") else: print("It's a tie!") else: print("The bot went over 21! You win!") else: print("\nYou went over 21 :( You lose!") play_again = input("\nPlay again? (Y/N): ") if play_again != "Y" and play_again != "y": PLAY = False else: print("\n") return if __name__ == "__main__": main()
14f842f01ac576fc754f6e92fb4576b00feda04c
guillermosantiago/intermediate-python-course
/dice_roller.py
269
3.65625
4
import random def main(): num_dices = 2 sum_dices = 0 for i in range(0,num_dices): roll = random.randint(1,6) sum_dices += roll print(f'You rolled a {roll}') pass print(f'So the sum is {sum_dices}') if __name__== "__main__": main()
f766dcc505ffa4fc583151509181637d5e5c31b6
luiz22/code_school
/Examplesfolder/default_Argument_functions.py
1,101
4.1875
4
#default arguments in function #function is defined here # def print_Info(name,age= 20): # print "Name: ", name # this prints a passed info into the function # print "Age", age # return; # #Now call the function # print_Info(age=10, name="fabio") # print_Info(name="fabio") #function definition # def Add(arg1,arg2): # #add both parameters and return them. # total = arg1+arg2 # print "Inside the function: ", total # return # #Call function # total =Add(10,10); #print "Outside function: ", total #functions and variables Global and local #variables defind inside a function body have a local scope #variables defined outside have a global scope #this means local variables can be accessed only inside a function in which they declared #global variables can be accessed throught out the program #example total = 0; #this a global variable #define function def sum(arg1,arg2): #add both parameters and retutn them total = arg1+arg2 # total is a global variable print "inside the fucntion locall total: ", total return total sum(2,2); print "outside the function total :", total
fb072da6a9d65717a9e38d26159e9c57f1e9160f
santhosh2sai/python4me
/shortestword.py
248
4.09375
4
def find_short(s): words = s.split() word = list() for i in words: x = len(i) word.append(x) return min(word) # l: shortest word length print(find_short("bitcoin take over the world maybe who knows perhaps"))
5041e6bfac2601dbe9b3a8446a6eabcf1ed3f568
BabyCakes13/SMS
/tests/test_util/test_strings.py
1,460
3.671875
4
"""Module which contains the class to test methods from the strings.py module.""" import unittest from unittest import mock from util import strings class TestStrings(unittest.TestCase): """Class which tests methods from the strings.py module.""" def setUp(self): """Sets up a new mock object for each test.""" self.mock = mock.Mock() def test_get_config_metrics(self): """Tests if the values from the get_config_metrics method are the correct ones.""" expected = {'disk_usage': 'YES', 'cpu_percent': 'YES', 'memory_info': 'YES', 'cpu_stats': 'YES'} actual = strings.get_config_metrics() self.assertEqual(expected, actual) def test_get_config_db(self): """Tests if the values from the get_config_db method are the correct ones.""" expected = {'db_name': 'database_name', 'db_url': 'database_url'} actual = strings.get_config_db() self.assertEqual(expected, actual) def test_get_config_connection(self): """Tests if the values from the get_config_db method are the correct ones.""" expected = {'send_time': '5', 'address': 'localhost', 'port': '5672', 'flask_port': '500'} actual = strings.get_config_connection() self.assertEqual(expected, actual)
d41899b404504d97df7d9357c899410f0bb5c57b
jamesbond007dj/pythonism
/pythonism.py
1,024
3.921875
4
from functools import wraps class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.current = None def __str__(self): return str(list(iter(self))) def __len__(self): return len(list(iter(self))) def __iter__(self): def generator(): current = self.head while current: yield current.value current = current.next return generator() def append(self, value): node = Node(value) if not self.head: self.head = node return current = self.head while current.next: current = current.next current.next = node def append(func): @wraps(func) def wrapper(*args, **kwargs): value = func(*args, **kwargs) + 1 return value return wrapper @append def multiply_by_two(value): return value + value
691a3961cde038837930c46e907cc495da00e710
YeltsinZ/Python
/array_operations.py
362
4.0625
4
from array import * arr = array('i',[]) n = int(input("Enter the length of the array")) for i in range(n): x = int(input("Enter the value")) arr.append(x) print (arr) value = int(input("Enter the value to search")) for i in arr: if i==value: print("Element found",+value) break print("Element not found")
1cc0a1932056b7826970859d359fbb66f67576c1
hayk0088/Hayeren-Xndragirq
/homework2.py
8,239
3.640625
4
№34 a=int(input()) b=int(input()) c=int(input()) d=int(input()) if a + b == c + d or a + c == b + d or a + d == c + b: print("True") else: print("False") № 36 a=int(input()) b=int(input()) c=int(input()) d=int(input()) if (a % 2 != 0 and b % 2 != 0) or (a % 2 != 0 and c % 2 != 0) or (a % 2 != 0 and d % 2 != 0) or (b % 2 != 0 and c % 2 != 0) or (b % 2 != 0 and d % 2 != 0) or (c % 2 != 0 and d % 2 != 0): print ("True") else: print("False") № 51 c=int(input("Eranish Tiv nermuci ara - ")) if c % 10 == c // 10 % 10 + c // 100: t=True print(t) № 52 c=int(input("Eranish Tiv nermuci ara - ")) if c % 10 == c // 10 % 10 or c % 10 == c // 100 or c // 10 % 10 == c // 100: t=True print(t) else: t=False print(t) № 53 k=((c % 10) + (c // 10 % 10) + (c // 100)) if c > k: print(c / k) else: print(c) / k) № 54 c=int(input("Eranish Tiv nermuci ara - ")) a = c % 10 b = c // 10 % 10 d = c // 100 if a > b: print ((a + b + d) / c) else: print(c) № 62 a = int(input()) if a < 5000: z = a % 10 c = a // 100 % 10 print( a / (z + c)) else: x = a // 10 % 10 v = a // 1000 print ( a / (x + v)) № 63 a = int(input()) count = 0 while a != 0: c = a % 10 a //= 10 if c == 1: print("1") break print("0") № 66 a = int (input()) while a != 0: z = a % 10 c = a // 1000 if z == 4 and c == 4: print ("Yes") else: print("No") № 67 a = int(input()) x = a count = 0 z = 0 while a != 0: z = a % 10 a //= 10 count += z if x == count ** 2: print("Yes") else: print("No") № 70 a = int(input()) x = 1 while a != 0: c = a % 10 a //= 10 x *= c if x > 200: y=0 print (y) else: y=1 print(y) № 151 n = int(input()) sum = 0 for i in range(1,n+1,1): if n % i == 0: sum += i print(sum) № 155 sum=0 for i in range(10,100): if i % 3 ==0: sum+=i print (sum) № 157 sum = 1 for i in range(100,1000): if i % 5 != 0: sum *= i print(sum) №159 sum = 1 for i in range(1,10): if i % 3 == 1 and i % 4 ==2: sum *= i print(sum) № 160 import math tmp = 0 for i in range(100,1000,1): tmp = int(math.sqrt(i * 16)) if tmp ** 2 == i * 16: print(i) break № 161 import math tmp = 0 for i in range (1000,10000,1): tmp = int(math.sqrt(i * 26)) if tmp ** 2 == i * 26: print(i) break № 162 import math tmp = 0 for i in range (10000,1000,-2): tmp = int(math.sqrt(i * 26)) if tmp ** 2 == i * 14: print(i) break № 165 n = int(input()) z = n // 4 while n != 1 : if x // 3 % 2 != 0: print("True") else: print ("False") № 167 x = int (input()) for i in range(1,30,1): if x ** i < 0: print("True") exit (0) print("False") № 168 n = int(input()) flag = 1 min_simple = 2 s = 0 while min_simple <= n/2 and flag == 1: if n % min_simple == 0: flag = 0 else: min_simple += 1 if flag: print("Parz") else: print("Che") № 171 def fact(n): a = 1 for i in range(2,n + 1): a *= i return a n = int(input()) print (fact(n)) № 181 n= int(input()) count = 0 while n > 1: n=n/2 count += 1 print(count) № 182 №1 n = int(input()) max = 0 for i in range (1, n // 2 ): if i ** 2 < n: max = i print (max) №2 def square(n): for i in range(1,n//2): if i ** 2 > n: return i - 1 n = int(input()) print(square(n)) № 183 n = int(input()) half = n // 2 + 1 while n > 1: for k in range (1,half): if 3 ** k > n: print(k) exit(0) № 185 a = int(input("Mutqagreq 1-25 voreve tiv: ")) def avand(a): count = 0 n = 1 gumar = 30000 while 1 < a < 25: gumar = gumar * ((100 + a) / 100) n += 1 count += gumar if gumar > 100000: return n, count print (avand(a)) № 186 p = int(input("Nermuceq 1-50 voreve tiv: ")) def vazq(p): or_1 = 20 or_ = 1 count = 20 while p > 0: or_1 = or_1 * (100 + p) / 100 count += or_1 or_ += 1 if or_1 > 80: return or_ , int(count) print(vazq(p)) № 187 n = int(input("Input your favourite number: ")) def is_prime(n): for i in range(2,n//2): if n % i == 0: return "Num is not prime:" return "Num is prime:" print (is_prime(n)) № 201 n = int(input("Write a number: ")) def number(n): a = 0 while n > 0: if n % 10 != 0: a += 1 n = n // 10 return a print(str(number(n)) + (" nish uni ") + str(n) + (" tivy:")) № 206 n = int(input("Input your favourite number: ")) def new_num(n): num = 0 while n > 0: a = n % 10 num = num * 10 + a n //= 10 return num print("New number is: " + str(new_num(n))) № 209 n = int(input("Input your number: ")) def num(n): while n > 0: if n % 2 != 0: return True n //= 10 return False print(num(n)) № 210 n = int(input("Input your favourite number Areg: ")) def gumar(n): a = b = 0 count_1 = count_2 = 0 n = abs(n) while n > 0: a = n % 10 b = n // 10 % 10 count_1 += a count_2 += b n //= 100 if count_1 == count_2: return True else: return False print(gumar(n)) № 211 def creating_massiv(len): numbers = [] for i in range(0,len): n = int(input("Write your number: ")) numbers.append(n) return numbers def michin_tiv(numbers): count = 0 for i in numbers: if i > 0: count += i return count / len len = int(input("Write the len of numbers: ")) print(michin_tiv(creating_massiv(len))) № 214 def creating_massiv(len): numbers = [] for i in range(0,len): n = int(input("Write your number: ")) numbers.append(n) return numbers def michin_tiv(numbers): count = 0 sum = 0 for i in numbers: if i < 0: sum += i count += 1 return sum / count len = int(input("Write the len of numbers: ")) print(michin_tiv(creating_massiv(len))) № 215 def creating_massiv(len): numbers = [] for i in range(0,len): n = int(input("Write your number: ")) numbers.append(n) return numbers def sum(numbers): count = 0 for i in range(0,len,2): count += numbers[i] return count len = int(input("Write the len of numbers: ")) print(sum(creating_massiv(len))) № 251 def creating_massiv(len): numbers = [] for i in range(0,len): n = int(input("Write your number: ")) numbers.append(n) return numbers def max_num(numbers): max = 0 for x in numbers: if x > max: max = x return max len = int(input("Write your favourite number: ")) print(max_num(creating_massiv(len)))
a468482bce4b527f3bd1f8bafd39d52278b78acc
skandamohan/Euler-Problems
/problem8.py
1,127
3.984375
4
'''https://projecteuler.net/problem=6''' '''Please see the README document for details''' import math import operator def run(big_number, number_of_digits): big_array = put_digits_of_number_into_array(big_number) if len(big_array)-1 < number_of_digits: print "Your number of digits is bigger than the BIG number. Please check your arguments" start_index = 0 end_index = len(big_array) result = reduce(operator.mul, big_array[:number_of_digits]) for counter in range(number_of_digits, end_index, 1): if big_array[counter - number_of_digits] != 0: comparator = reduce(operator.mul, big_array[counter-number_of_digits:counter]) if(result < comparator): #print "Before"+str(result) result = comparator #print "After "+str(result) print "The largest mutliple is "+str(result) return result def put_digits_of_number_into_array(big_number): result = [] while big_number > 0: result.insert(0, big_number%10) big_number = big_number/10 return result if __name__ == "__main__": print "https://projecteuler.net/problem=9"
c43619a978aad128e3c11f0481741f8feb9dcbfc
Kew-Forest/Class-work
/groupingEx.py
333
3.5625
4
# thanks shanelynne from https://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/ import pandas as pd import dateutil # Load data from csv file data = pd.DataFrame.from_csv('phone_data.csv') # Convert date from string to date times data['date'] = data['date'].apply(dateutil.parser.parse, dayfirst=True)
1ce810f4fd043ba3ed5328eb4a3add424c79043d
ronjacobvarghese/Python_college
/sem-4/lab-2/Lab 02/Q06.py
2,639
4.09375
4
class Node: def __init__(self, data): self.data = data self.ref = None class LinkedList: def __init__(self): self.head = None def display(self): if self.head is None: print("List is empty") else: n = self.head while n is not None: print(n.data,end=" ") n = n.ref print() def add_begin(self, data): new_node = Node(data) new_node.ref = self.head self.head = new_node def add_end(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: n = self.head while n.ref is not None: n = n.ref n.ref = new_node def after_node(self, data, x): n = self.head while n is not None: if x == n.data: break n = n.ref if n is None: print("Node not present in Linked List") else: new_node = Node(data) new_node.ref = n.ref n.ref = new_node def delete_begin(self): if self.head is None: print("Linked list is empty") else: self.head = self.head.ref def delete_end(self): if self.head is None: print("Linked list is empty") elif self.head.ref is None: self.head = None else: n = self.head while n.ref.ref is not None: n = n.ref n.ref = None def delete_value(self, x): if self.head is None: print("LL is empty") return elif x == self.head.data: self.head = self.head.ref n = self.head while n.ref is not None: if n.ref.data == x: break n = n.ref if n.ref is None: print("Node is not present!") else: n.ref = n.ref.ref def k_value(self, x): if self.head is None: print("LL is empty") return elif x == self.head.data: print("Element found", self.head.data) n = self.head while n.ref is not None: if n.ref.data == x: break n = n.ref if n.ref is None: print("Element is not present!") else: while n.ref is not None: print(n.ref.data, " --> ", end="") n = n.ref a = LinkedList() a.add_begin(2) a.after_node(6, 2) a.after_node(8, 6) a.add_end(4) a.display() a.k_value(8)
10f7582a60287571e6e821fceb3c3f6b239e55a7
AlexandreCordaJunior/URI
/Grafo/uri1141.py
1,158
3.671875
4
def cultivando(lista, peso, i, num): if(peso[i] != 0): return peso[i] for j in range(i + 1, num): max = peso[i] if(lista[j].find(lista[i]) != -1): #print(lista[j] + " : " + lista[i]) temp = 1 + cultivando(lista, peso, j, num) if(temp > max): max = temp peso[i] = max #print("for : i: " + str(i) + " j: " + str(j)) #print(str(peso[i]) + " " + str(peso[j])) #max = 0 #for j in range(i + 1, num): # if(peso[j] > max and lista[j].find(lista[i]) != -1): # max = peso[j] #print("rec : i: " + str(i)) #print(str(peso[i])) return peso[i] while(True): num = int(input()) if(num == 0): break list = [] peso = [] for i in range(num): string = input() list.append(string) peso.append(0) list = sorted(list, key = lambda x: len(x)) max = 0 for i in range(num): temp = cultivando(list, peso, i, num) if(temp > max): max = temp #for i in range(len(peso)): # print(peso[i]) # print(list[i]) print(max + 1)
9c5cd40a0437e6087b2be270c423647d89cc1951
shiki7/leetcode
/0326: Power of Three/solution.py
240
3.625
4
class Solution: def isPowerOfThree(self, n: int) -> bool: num = 1 for i in range(0, 100000): if n == num: return True if n < num: return False num *= 3
24843d4999acd3fff65479b21b00ed8d499265ca
zalogarciam/CrackingTheCodeInterview
/Chapter 8/TowersOfHanoi.py
303
3.875
4
def hanoi_towers(n, source, buffer, destination): if n == 0: return hanoi_towers(n - 1, source, destination, buffer) print("Move disk", n, "from source", source, "to destination", destination) hanoi_towers(n - 1, buffer, source, destination) n = 3 hanoi_towers(n, '1', '2', '3')
e74a6e2ad34e4bdac12c0067656ba71cb9229d5a
slail/minimumWaitingTime
/main.py
1,446
4.125
4
def minimumWaitingTime(queries): """ You're given a non-empty array of positive integers representing the amounts of time that specific queries take to execute. Only one query can be executed at a time, but the queries can be executed in any order. A query's waiting time is defined as the amount of time that it must wait before its execution starts. In other words, if a query is executed second, then its waiting time is the duration of the first query; if a query is executed third, then its waiting time is the sum of the durations of the first two queries. Write a function that returns the minimum amount of total waiting time for all of the queries. For example, if you're given the queries of durations [1, 4, 5] , then the total waiting time if the queries were executed in the order of [5, 1, 4] would be (0) + (5) + (5 + 1) = 11 . The first query of duration 5 would be executed immediately, so its waiting time would be o, the second query of duration 1 would have to wait 5 seconds (the duration of the first query) to be executed, and the last query would have to wait the duration of the first two queries before being executed. Note: you're allowed to mutate the input array. """ queries.sort() min_wait = 0 for idx, duration in enumerate(queries): queriesLeft = len(queries) - (idx + 1) min_wait += duration * queriesLeft return min_wait
0bafc965590437a2bf30384a251b82c359a10c81
SharpBro/CodeWars
/codewars_svolti/duplicate_encode.py
1,020
4.125
4
""" The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. Examples "din" => "(((" "recede" => "()()()" "Success" => ")())())" "(( @" => "))((" """ def duplicate_encode(stringa): diz = {} #a blank dictionary stringa = stringa.lower() #case insensitive for carattere in stringa: if carattere in diz: diz[carattere] += 1 #add one if the element is in the dictionary else: diz[carattere] = 1#create a new key nuova = "" for carattere in stringa: if diz[carattere] > 1:#if the occurrence of the char is more than one nuova += ')'#add a closed parenthesis else: nuova += '('#add an open parenthesis return nuova miao("(( @")
60ae0acd1ae1672736a149977c8e21f387d941d8
edurflores/POO-U3EJ4
/claseEmpleadoContratado.py
1,478
3.734375
4
from datetime import date from claseEmpleado import Empleado class EmpleadoContratado(Empleado): __fechainicio = date __fechafin = date __cantHoras = 0 __valorHora = 50 # Variable de clase (50 por defecto) __sueldo = 0.0 # A calcular def __init__(self,docu,nom,direc,tel,fechaini,fechafin,cahoras): super().__init__(docu, nom, direc, tel) self.__fechainicio = fechaini self.__fechafin = fechafin if type(cahoras) is int: self.__cantHoras = cahoras self.__sueldo = self.__cantHoras * self.__valorHora @classmethod def SetValorHora(cls): val = float(input('Ingrese nuevo valor por hora:')) cls.__valorHora = val print('Valor por hora actualizado. Nuevo valor:',cls.__valorHora) def SetCantidadHoras(self,cant): self.__cantHoras += cant print('Se ha actualizado la cantidad de horas trabajadas.') print('Nuevo valor:',self.__cantHoras) self.ActualizaSueldo() def ActualizaSueldo(self): self.__sueldo = self.__cantHoras * self.__valorHora def GetSueldo(self): self.ActualizaSueldo() return self.__sueldo def GetFechaInicio(self): return self.__fechainicio def GetFechaFin(self): return self.__fechafin def GetCantidadHoras(self): return self.__cantHoras @classmethod def GetValorHora(cls): return cls.__valorHora
af5f912ccfde2e24c8d8792876a693dfce142db4
alago1/adv-code-2020
/src/day1.py
551
3.609375
4
import functools file = open('input/day1', 'r') nums = [int(x) for x in file.readlines()] def sum2_solver(vals, target): seen = set() for n in vals: if n in seen: return [n, target-n] seen.add(target - n) return False def sum3_solver(vals, target): for n in vals: t = sum2_solver(vals, target - n) if t: return [n] + t return False output = sum3_solver(nums, 2020) print(output) print("Product: ", functools.reduce(lambda a, b: a*b, output)) # 447 + 611 + 962
6f1ff8cec78d03ab5b3ca5493e40d7784ae3fb16
papadavis47/my_sandbox
/Treehouse Python Stuff/masterticket2.py
1,754
4.34375
4
TICKET_PRICE = 10 tickets_remaining = 100 # Run this code continuously until we run out of tickets while tickets_remaining >= 1: # Output how many tickets are remaining using the tickets_remaining variable print("There are {} tickets remaining.".format(tickets_remaining)) # Gather the user's name and assign it to a new variable user_name = input("What is your name? ") # Prompt the user by name and ask how many tickets they would like number_of_tickets = input("Hello {}! How many tickets would you like? ".format(user_name)) # Calculate the price ( number of tickets multiplied by the price ) and assign it to a variable number_of_tickets = int(number_of_tickets) customer_price = TICKET_PRICE * number_of_tickets # Output the price to the screen print("Your order will cost ${}.".format(customer_price)) # Prompt user if they want to proceed. Y/N? confirmation = input("Would you like to proceed with your purchase? Y/N: ") # If they want to proceed # Print out the screen "SOLD!" to confirm purchase # Gather credit card information and process it. if confirmation.lower() == "y": print("SOLD! You just purchased {} tickets!".format(number_of_tickets)) tickets_remaining -= number_of_tickets # And then decrement the tickets remaining by the number of tickets purchased # Otherwise . . . #Thank them by name. else: print("Thanks anyway, {}. Maybe next time!".format(user_name)) # Notify the user that the tickets are sold out print("Tickets are now sold out : )")
5d5061a333f1019a4820b8776af33cf2ef4984e0
lunar-r/sword-to-offer-python
/剑指offer/二叉树的下一个结点.py
1,419
3.640625
4
# -*- coding: utf-8 -*- """ File Name: 二叉树的下一个结点 Description : Author : simon date: 19-3-18 """ # -*- coding:utf-8 -*- class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None """ 中序遍历 左根右 第一道自己的原创解 感觉很有成就感~ 主要是活学活用了之前的状态码思想 """ class Solution: def GetNext(self, pNode): # write code here if not pNode: return # 获得根节点 pRoot = pNode while pRoot.next: pRoot = pRoot.next self.res = None def inOrder(root, state): if not root: return state # 为啥不能是 return -1 state = inOrder(root.left, state) if state == 1: #检查状态码2 self.res = root # 必须定义为 self类的属性才有用 state = 2 if root == pNode: # 找到目标节点之后 将状态码置成1 下一次的判断到状态码为1的节点就是需要return的节点 state = 1 if state == 2: # 加速递归的结束 后面的节点不用继续递归 return state state = inOrder(root.right, state) return state inOrder(pRoot, -1) return self.res
aa1ca5f83ac268c363c84b269de3fcbb0da0aa27
LeslieWilson/python_playground
/chapter-four/futv.py
576
3.984375
4
def main(): print "This program calculates the future value of an n-year investment." principal = input("Enter the initial principal: ") apr = input("Enter the annualized interest rate in decimal form: ") years = input("Enter the total number of years the investment will build: ") output = " Years Total \n-------------------\n" for i in range(years + 1): principal = principal * (1 + apr) output += " %-6d $%0.2f \n" % (i, principal) print output print "The amount in %d years is: $%0.2f" % (years, principal) main()
6b47cad25df6c5546032b673e1ac1ee1e2e10c16
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc090/A/4892085.py
88
3.5
4
s = [input() for _ in range(3)] for i in range(3): print(s[i][i], end='') print('')
3f00e274f7086f2c05c912df36348d0375332962
magda-zielinska/python-level1
/lists-slices.py
659
3.921875
4
list1 = [1] list2 = list1 list1[0] = 2 print(list2) #solution: slices: list3 = [2] list4 = list3[:] list3[0]= 4 print(list3) list6 = [10, 8, 6, 4, 2, 5, 9, 3] new_list = list6[1:3] # [start - count from the start 0, 1, 2.. : end - counting from the start but -1, because the # last value doent count, so 3 - 1= 2, the value 2 - 0, 1, 2 ] - start is the index of the first element included in the slice;- end is the index of the first element not included in the slice. print(new_list) list7 = [10, 8, 6, 4, 2] new_list2 = list7[1:-1] print(new_list2) list8 = [9, 7, 5, 3, 1] del list8[1:3] print(list8) list9 = [9, 7, 5, 3, 1] del list9[:] print(list9)
1bbe9f03bc288971df118b8adfb7855d52e14e4f
cielavenir/procon
/atcoder/tyama_atcodertenka1~2012qualbB.py
1,147
3.625
4
#!/usr/bin/python from __future__ import print_function import sys,re def snake2camel(orig): r=[] i=0 while i<len(orig): if orig[i]=='_': if i+1==len(orig) or orig[i+1]=='_' or '0'<=orig[i+1]<='9': return orig r.append(orig[i+1].upper()) i+=1 else: r.append(orig[i]) i+=1 return ''.join(r) def camel2snake(orig): r=[] for c in orig: if 'A'<=c<='Z': r.append('_') r.append(c.lower()) else: r.append(c) return ''.join(r) def convert(orig): s=orig start_underscore=0 end_underscore=0 while len(s)>0 and s[0]=='_': start_underscore+=1 s=s[1:] if not s: return orig if 'A'<=s[0]<='Z' or '0'<=s[0]<='9': return orig while s[-1]=='_': end_underscore+=1 s=s[:-1] if '_' in s: if any('A'<=c<='Z' for c in s): return orig return '_'*start_underscore+snake2camel(s)+'_'*end_underscore else: return '_'*start_underscore+camel2snake(s)+'_'*end_underscore for line in sys.stdin: print(convert(line.rstrip()))
4e93133f0130e1907d1aab0f9c687737bbd8d33a
85RM5Z/guessTheNumber
/guessTheNum.py
2,165
3.828125
4
import random import sys def guessTheNumber(): mini, maxi = input("Entrer la borne min et la borne max: ").split() try: mini = int(mini) maxi = int(maxi) except ValueError: print("La conversion de ce nombre est mal passée", file=sys.stderr) sys.exit() print("Borne minimale : ", mini) print("Borne maximale : ", maxi) nombre = random.randint(mini, maxi) guess = int(input("Saisissez un nombre entre {} et {} :".format(mini, maxi))) try: guess = int(guess) except ValueError: print("La conversion de ce nombre est mal passée", file=sys.stderr) sys.exit() cpt = 0 while not(guess == nombre): if guess > nombre: if guess > maxi: maxi = maxi raise Exception("La valeur que vous avez saisie est supérieur à la borne maximale") elif mini+1 != maxi and mini != maxi: maxi = guess-1 else: maxi = guess print("Le nombre", guess, "est trop grand") guess = int(input("Saisissez un nombre entre {} et {} :".format(mini, maxi))) try: guess = int(guess) except ValueError: print("La conversion de ce nombre est mal passée", file=sys.stderr) sys.exit() cpt = cpt + 1 else: if guess < mini: mini = mini raise Exception("La valeur que vous avez saisie est infèrieur à la borne minimale") elif guess+1 == maxi: mini = guess maxi = maxi+1 else: mini = guess+1 print("Le nombre", guess, "est trop petit") guess = int(input("Saisissez un nombre entre {} et {} :".format(mini, maxi))) try: guess = int(guess) except ValueError: print("La conversion de ce nombre est mal passée", file=sys.stderr) sys.exit() cpt = cpt + 1 print("Gagné! vous avez trouver le bon nombre au bout de", cpt, "essaye(s).") guessTheNumber()
534de227ab7411f6c194d183c6dddedf173c89f4
vladhondru25/scikit
/handwritten-digits-recogniser.py
912
3.6875
4
from PIL import Image import mnist import numpy as np from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix # Get dataset x_train = mnist.train_images() y_train = mnist.train_labels() x_test = mnist.test_images() y_test = mnist.test_labels() # Reshape the data from 2D images to 1D arrays x_train = x_train.reshape((-1,28*28)) x_test = x_test.reshape((-1,28*28)) # Rescale the data to be uniform x_train = x_train / 256 x_test = x_test / 256 # Define the model (optimiser, neural network architecture) clf = MLPClassifier(solver='adam', activation='relu', hidden_layer_sizes=(64,64)) # Training clf.fit(x_train, y_train) # Evaluating predictions = clf.predict(x_test) # Compute the confusion matrix conf_mat = confusion_matrix(y_test, predictions) print(conf_mat) # Compute accuracy acc = conf_mat.trace() / conf_mat.sum() print("Accuracy = {:.2f}%".format(100*acc))
f4dbd2054429612a595d3be6b8eb80c030d72b41
daniel-reich/turbo-robot
/iXabTtWEX8xegqFds_16.py
702
4.28125
4
""" Write a function that sorts a given list in an aletrnative fashion. The result should be a list sorted in ascending order (number then letter). Lists will contain equal amounts of integer numbers and single characters. ### Examples alternate_sort(["a", "b", "c", 1, 2, 3]) ➞ [1, "a", 2, "b", 3, "c"] alternate_sort([-2, "f", "A", 0, 100, "z"]) ➞ [-2, "A", 0, "f", 100, "z"] alternate_sort(["X", 15, 12, 18, "Y", "Z"]) ➞ [12, "X", 15, "Y", 18, "Z"] ### Notes N/A """ def alternate_sort(lst): x, y = [i for i in lst if isinstance(i, int)], [j for j in lst if isinstance(j, str)] return [x for y in [[a, b] for a, b in zip(sorted(x), sorted(y))] for x in y]
38f731cba0710f5802c6a96749f087b26ab1c025
rmodi6/scripts
/practice/Leetcode/3378_binary_tree_level_order_traversal_ii.py
877
3.875
4
# https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3378/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if root is None: return [] queue = [(root, 1)] ans = [] while queue: node, level = queue[0] queue = queue[1:] if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) if len(ans) < level: ans.append([node.val]) else: ans[-1].append(node.val) return reversed(ans)
77d68eef0e4ad5bc0e2e2495091c31a662c43ac2
karantza/AdventOfCode
/2016/Day16.py
585
3.515625
4
from string import maketrans space1 = 272 space2 = 35651584 input = "10111100110001111" def dragonCurve(a): tx = maketrans('01', '10') b = a[::-1].translate(tx) return a + '0' + b def checksumStep(x): pairs = [x[i:i+2] for i in range(0, len(x), 2)] return "".join(['1' if i[0] == i[1] else '0' for i in pairs]) def evaluate(input, space): while len(input) < space: input = dragonCurve(input) input = input[:space] cksum = input while True: cksum = checksumStep(cksum) if len(cksum) % 2 == 1: break print(cksum) evaluate(input, space1) evaluate(input, space2)
a119037ba422c42b02d664d48578cb4e005272f7
ianbooth12/python_crash_course
/chapter_4/4practice.py
1,960
4.5625
5
pizzas = ["pepperoni", "sausage", "cheese"] # Pizzas for pizza in pizzas: print(f"I like {pizza} pizza.") print("I really love pizza!") # Pizzas animals = ["cat", "dog", "hamster"] for animal in animals: print(f"I bet that a {animal} would make a great pet!") print("Now that I think about it, any of these pets are great!") # Animals numbers = list(range(1,21)) # Counting to Twenty for value in numbers: print(value) digits = [value for value in range(1,21)] print(digits) # Comprehensive lists can save lines of code million = [value for value in range(1,1000001)] # Comprehend larger lists odds = list(range(1,21,2)) # Odd Numbers threes = list(range(3,31,3)) # Threes for three in threes: print(three) cubes = [] # Cubes for value in range(1,11): cube = value**3 cubes.append(cube) print(cubes) cubec = [value**3 for value in range(1,11)] # Cube Comprehension print(cubec) # Comprehension can save many lines of code, use if comfortable animals.append("tiger") animals.append("horse") print(animals) print("The first animals I would think to adopt are:") # Slices print(animals[:3]) print("Three animals from the middle of my shortlist are:") print(animals[1:4]) print(animals[2:]) friend_pizzas = pizzas[:] # My pizzas, Your pizzas friend_pizzas.append("sausage") print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("My friend's favorite pizzas are:") for pizza in friend_pizzas: print(pizza) my_foods = ["pizza", "chicken", "ice cream"] # More Loops friend_foods = my_foods[:] my_foods.append("pasta") friend_foods.append("popsicles") print("My favorite foods are") for food in my_foods: print(food) print("My friend's favorite foods are:") for food in friend_foods: print(food) buffet_foods = ("wings", "chicken", "pizza", "cake", "bagels") # Tuples for food in buffet_foods: print(food) buffet_foods = ("wings", "turkey", "pizza", "ice cream", "toast") for food in buffet_foods: print(food)
f9a716f4704ca6d38e884f53a662bc3b83967ff8
neema80/python
/iter_tools.py
1,041
3.9375
4
# a great module to work with iterator import itertools # chain() list1 = [1,2,3,4,"a","b","c"] list2 = [100,200,300,"X","Y","Z"] print(list(itertools.chain(list1,list2))) # chain function makes an iterable of the arguments that we provide to it # count() # it iterates until we break the sequnce just like while True loop we have to be wise for i in itertools.count(10,2.5): if i <= 50: print(i) else: break # cycle() # just similar to count() we have to be careful to break the cycle # otherwise it would repeats infinately count = 0 for i in itertools.cycle(range(1,50,6)): if count <= 19: print(count , i) count += 1 else: break # filterfalse() # it is exactly opposite of filter() function and returns element where the iterator returns False # islice() # is similar to slicing but in a different manner list1 = list(range(10)) list1 = list1[2:9:2] # starting from 2 # end to 8 with step of 2 # just normal slicing print(list1) print(list(itertools.islice(range(10),2,9,2)))
dade176501cb8578855b4de29095653c5c2cf48e
DeanDamianus/PrAlPro.
/struktur kontrol kompleks.py
614
4.03125
4
print("=====Piramida setengah / full=====") baris = int(input("Silahkan memasukkan baris: ")) symbol = str(input("Masukkan simbol yang diinginkan (1 simbol untuk setengah piramida dan 2 simbol untuk full piramida: ")) jarak = baris - 1 for i in range (0,baris): for j in range (0,jarak): print(" ",end="") for k in range (0,i+1): print(symbol,end="") jarak = jarak - 1 print () jarak = 1 for i in range (jarak-1,0,-1): for j in range (0,jarak): print("",end="") for k in range (0,i+1): print(symbol,end="") jarak = jarak - 1 print()
ad4085bb7a09c877cca752a0eb1663c4a0f4ffa8
kb2020s/PyCharm_Homework
/python_script.py
270
4.21875
4
# Converting temperature to fahrenheit from celsius values # Temperature value in Celsius Celsius = 20.0 # Convert Temperature value to Fahrenheit Fahrenheit = (Celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(Celsius,Fahrenheit))
08e529279491018eb2bd86b50e9f2a972b0e2704
CalebKnight10/CS_260_7
/heap.py
638
3.65625
4
# Heap code class BinHeap: def __init__(self): self.heap_list = [0] self.current_size = 0 def perc_up(self, i): while i // 2 > 0: if self.heap_list[i] < self.heap_list[i // 2]: tmp = self.heap_list[i // 2] self.heap_list[i // 2] = self.heap_list[i] self.heap_list[i] = tmp i = i // 2 def insert(self, k): for item in k: self.heap_list.append(item) self.current_size = self.current_size + 1 self.perc_up(self.current_size) def __str__(self): return str(self.heap_list)
c72c03f19680487481cba3426a99d1560698d6af
yaseen-ops/python-100-days-of-course
/Beginner/day5/highScore.py
417
4.0625
4
student_scores = input("Enter the list of scores \n").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) highest_score = 0 for score in student_scores: if score > highest_score: highest_score = score print(f"Highest score in the class is : {highest_score}") # OR highest_score = max(student_scores) print(f"Highest score in the class is : {highest_score}")
6c1fd379fb02384c9a72d6e552bb504cea841cc2
svetoslavastoyanova/Python_Advanced
/Exam_Exercises/06.Function_Problem.py
207
3.640625
4
def get_magic_triangle(n): matrix = [] for row in range(1, n+1): for col in range(row): col = 0 matrix.append(col) return matrix print(get_magic_triangle(5))
748f4d7837894976df0d62ecf7a087302e528ba0
Archy2212/code-days-code100
/python/average.py
229
4.09375
4
n=int(input("Enter the number of element to be inserted")) a=[] for i in range(0,n): elem=int(input("Enter elements: ")) a.append(elem) avg=sum(a)/n print("Average of element",round(avg,2))
8fea1e6e7822a2d673e79cea5cba45925200f28e
grahamhendo/Fizzbuzz
/fizzbuzz.py
488
4.1875
4
# -*- coding: utf-8 -*- """ Spyder Editor This code lists the numbers from 1 to 100. If the number is divisible by 3 fizz is printed, if the number is divisible by 5 then buzz is printed. If the number is divisible by 3 and 5 then fizzbuzz is printed. """ for x in range(1, 101): fizz = x % 3 buzz = x % 5 if fizz == 0 and buzz == 0: print("fizzbuzz") elif fizz == 0: print("fizz") elif buzz == 0: print("buzz") else: print(x)
321ede70b7bae2f23e5c30672666935d7ded7b66
y-oksaku/Competitive-Programming
/AtCoder/abc/130c.py
159
3.53125
4
W , H , x , y = map(int,input().split()) area = W * H / 2. if 2 * x == W and 2 * y == H : var = '1' else : var = '0' print('{} {}'.format(area,var))
6f8120c6289fc4f9ff16798b7e22ba5063e9d9ab
malgorzatagwinner/Python
/ZADANIA_8/solve1.py
1,315
3.90625
4
#!usr/bin/env python3 # -*- coding: utf -8-*- import sys def solve1(a, b, c): """Rozwiązywanie równania liniowego a x + b y + c = 0. >>> solve1(0,0,0) Równanie wskazuje na całą płaszczyznę! >>> solve1(0,0,1) Równanie sprzeczne! >>> solve1(0,0,33) Równanie sprzeczne! >>> solve1(0,1,0) y = 0 >>> solve1(0,52, 0) y = 0 >>> solve1(1,0,0) x = 0 >>> solve1(52,0,0) x = 0 >>> solve1(1,0,1) x = -1.0 >>> solve1(5,0,1) x = -0.2 >>> solve1(0, 4, 8) y = -2.0 >>> solve1(2, 4, 8) y = -0.5x + -2.0 """ if a == 0: if b == 0: if c== 0: print("Równanie wskazuje na całą płaszczyznę!") return else: print("Równanie sprzeczne!") return else: if c==0: print("y = 0") return else: print("y = " + str((-c)/b )) return elif b == 0: if c == 0: print("x = 0") return else: print("x = " + str(-c/a )) return a = -a/b c = -c/b print("y = " + str(a) +"x + " +str(c)) if __name__ == '__main__': import doctest doctest.testmod()
b41422db685747072ccb5bfff7b55b8a6129545d
elsiormoreira/challenge_edabit_project
/01_very_easy/49_LEV4_same_number_unique_elem.py
322
3.84375
4
""" Write a function that returns True if two arrays have the same number of unique elements, and false otherwise. Examples same([1, 3, 4, 4, 4], [2, 5, 7]) ➞ True same([9, 8, 7, 6], [4, 4, 3, 1]) ➞ False same([2], [3, 3, 3, 3, 3]) ➞ True """ def same_num(arr1, arr2): return len(set(arr1)) == len(set(arr2))
30f9916750cc13c0331432f912f69bc106ce17c5
SzuKaiChen/Leetcode-solution
/720.Longest Word in Dictionary/Set.py
419
3.765625
4
class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ words.sort() word_set, longest_word = set(['']), '' for word in words: if word[:-1] in word_set: word_set.add(word) if len(word) > len(longest_word): longest_word = word return longest_word
f0e5d4c490d158871779c2aba1bb762c855ff5b5
chenjienan/python-leetcode
/116.populating-next-right-pointers-in-each-node.py
929
3.78125
4
# # @lc app=leetcode id=116 lang=python # # [116] Populating Next Right Pointers in Each Node # """ # Definition for a Node. class Node(object): def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ # can only use constant extra space if not root: return queue = collections.deque([root]) while queue: node = queue.popleft() # current node is fixing child nodes if node.left and node.right: node.left.next = node.right if node.next: node.right.next = node.next.left queue.append(node.left) queue.append(node.right) return root
f4eb62f843dd59413fe72b594af6df1db8a2c531
DevAVIJIT7/algo_programs_python
/graphs/adjacency_list_graph.py
559
4.03125
4
/** Creates a adjacency-list graph **/ from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add(self, key, value): self.graph[key].append(value) def get_graph(self): for node in self.graph: print("{0}".format(node), end="") for adjacency in self.graph[node]: print("-->{0}".format(adjacency), end="") print() g = Graph() g.add(1, 2) g.add(2, 3) g.add(1, 4) g.add(3, 5) g.add(3, 6) g.get_graph()
a0a904d1d8b73adea06b231e3d6666ecb284c4af
mmontpetit/HackerRank
/grading-students.py
331
3.609375
4
def gradingStudents(grades): # Write your code here givenGrade = [] n = int for i in range(len(grades)): n = grades[i] if (n % 5): t = (5 - n % 5) if(t<3): n = n + (5 - n % 5); if(n<38): n = grades[i] givenGrade.append(n)
5d94d85fa697e419d3151b53749c723e00d7e1fb
stevalang/Coding-Lessons
/SoftUni/Python Developmen/Python-Fundamentals/05_Functions/orders.py
603
4.21875
4
""" Write a function that calculates the total price of an order and prints it on the console. The function should receive one of the following products: coffee, coke, water, snacks; and a quantity of the product. The prices for a single piece of each product are: """ def find_price_per_unit(product, quantity): if product == 'coffee': return 1.5 * quantity if product == 'water': return 1 * quantity if product == 'coke': return 1.4 * quantity if product == 'snacks': return 2.0 * quantity print(f'{find_price_per_unit(input(), int(input())):.2f}')
1eea4429442d019fe46f43c560904f7319888f28
mattiazingaretti/EsercitazioniFondamenti2
/ESAMI/DOCS_NOTES/Fondamenti di Informatica II/espressioni.py
1,098
3.546875
4
#a^n b^n c^n d^n def abcd_n(n): espressione = 'aBCSd' base = 'abcd' inizio = 'aBCSd' if n == 1: print(base) return for i in range(n-2): espressione = espressione.replace('S', inizio) espressione = espressione.replace('S', base) while not espressione.islower(): espressione = espressione.replace('Ca', 'aC') espressione = espressione.replace('Cb', 'bC') espressione = espressione.replace('Cc', 'cc') espressione = espressione.replace('Ba', 'aB') espressione = espressione.replace('Bb', 'bb') print(espressione, int(len(espressione)/4)) abcd_n(10) def abc_n(n): espressione = 'aSBc' base = '' inizio = espressione if n == 0: print(base) return for i in range(n-1): espressione = espressione.replace('S', inizio) espressione = espressione.replace('S', base) i = 0 while not espressione.islower() and i<20: espressione = espressione.replace('Bc', 'bc') i+=1 print(espressione) #abc_n(5)
bdfb61fcff40972d10cbd3faee8537ea4f6da991
kikoken831/CSIT110
/Tutorials/demo.py
568
3.59375
4
import csv file_path = "test.csv" d:dict[str,list[dict[str,int]]] = {} with open(file_path) as file: reader = csv.DictReader(file) for row in reader: if row.get("stdn") in d: d[row.get("stdn")].append({row.get("subject"):int(row.get("cp"))}) else: d[row.get("stdn")] = [{row.get("subject"):int(row.get("cp"))}] for k,v in d.items(): print(f"Student {k}:") sum = 0 for x in v: for k,v in x.items(): sum += v print(f"{k:<10}{v:>7} cp") print(f"Total: {sum} cp")
87d06ae3fe1e5f68e8e965d41496c9f8fc6387ba
JahnaviPC/Python-Workshop
/ListOfTuplesOfRollNoInAscendingOrder.py
368
4.15625
4
Write python program to get a list of tuples of Rollno,Name for 5 students through keyboard and sort them Rollno wise ascending order a = [] for lam in range (5): name = input("Enter name:") roll = int(input("Enter roll no:")) a.append((roll,str(name))) a.sort() print (a) INPUT: Enter name:a Enter roll no:5 Enter name:s Enter roll no:1 [(1, 's'), (5, 'a')]
b9ee482ff36410461a16f2d8fd543704a3da92c5
phamhongnhung2501/Python-T3H
/lession 2/3.py
98
4.09375
4
name = input("What's your name?") if(name == "Bob" or name == "Alice"): print(f"Hello {name}")
42d8692ce53944414d2ad81f8feeddb0b37d45e6
erin-koen/Algorithms
/recipe_batches/recipe_batches.py
2,671
4.0625
4
#!/usr/bin/python import math """ Understand ---------- - receives two dictionaries, recipe and the ingredients available - returns the maximum number of batches you can make with the given ingredients, so it's the smallest number of ingredientKey/recipe key - need to confirm keys in the recipes dictionary exist in the ingredients dictionary. If in recipe and not in keys, return 0 Plan ---- - validate taht the ingedients keys are inclusive of the recipe keys. dictionary.keys() for both, figure out how to compare. Return 0 and a message if false. - Assuming all ingredients are present, query ingredient dictionary for each key in recipe dictionary, divide one by the other Execute ------- Analyze ------- Iterative example below. O(n^2) because it's a loop within a loop. I'm not sure how to go about doing this recursively because there's so much data manipulation that's needed. It seems like it'd be hard to do all that within a recursive loop. So maybe what needs to be done is - take the dictionaries and turn them into lists of tuples, then recurse against those lists somehow. """ def recipe_batches(recipe, ingredients): #only works if keys are identical, probably need a lower or uppercase thing here if recipe.keys() != ingredients.keys(): return 0 else: # transform dictionaries to lists of tuples recipe_list = recipe.items() ingredients_list = ingredients.items() # declare the batches variable, which is what will eventually be returned batches = 0 #check the tuples - for each tuple in the recipe list, find the one in the ingredients list that matches it, divide the the numbers recipe/ingredient (i/j) and set it equal to batches if it's larger than batches currently is for i in recipe_list: # declare variables for each part of the tuple against which we'll compare the ingredients list name = i[0] amount = i[1] # loop through ingredients list for j in ingredients_list: # validate that you're checking the correct tuple if j[0] == name: #figre out how many batches of that ingredient you've got ratio = math.floor(j[1]/amount) # if it's zero, you're done if ratio == 0: return 0 # if it's not zero, and you haven't yet altered the batches variable, set it equal to the ratio elif batches == 0 and ratio != 0: batches = ratio # if the ratio is smaller than batches (but greater than zero), reassign batches elif ratio < batches: batches = ratio return batches print(recipe_batches( { 'milk': 2 }, { 'milk': 200} ))
7af5949db52c39c4ab913599cadd9766c7c00bc3
ravijaya/oct15-2020
/basics/psdemosingleton.py
462
3.828125
4
"""demo for the metaclass to implement the singleton pattern""" class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class SingletonClass(metaclass=SingletonMeta): pass if __name__ == '__main__': s1 = SingletonClass() print(s1) s2 = SingletonClass() print(s2)
4c5965ceec4c26d14808d9739b65462873324e45
alesanchezr/pycon-chile
/structures/5-stack.py
351
3.515625
4
all_cards = ['2♦️', '5♥️', '6♣️', 'K♠️', 'A♠️', '3♥️', '2♠️'] print("This is your current stack: ", all_cards) print("Adding 9♣️") all_cards.append('9♣️') print("This is your current stack: ", all_cards) card = all_cards.pop() print("Deal this card: ", card) print("This is your current stack: ", all_cards)
150556af63273a31ddceb3f98f19513f7f633dbb
HayotbekAbdulazizov/python-basic-tutorial
/operators.py
655
3.9375
4
#int , str , float, bool # < , > , == , != , in ,not in, is,is not, and ,or , #print(10 > 5) # True #print(10 >= 10) # True #print(10 < 5) # False #print(10 <= 5) # False #print(10 == 10) # True #print(10 != 10) # False # s = 'salom' # print('b' in s) # False # print('s' in s) # True # print('s' not in s) # False # print('b' not in s) # True # x = y = [1,2] # print(x) # print(y) # print(x is y) #True aks holda False # print(x is not y) # False # x = 10 # y = [1,2] # print(x and y) birinchi true ni ushedi # print(x or y) birinchi false ni ushedi # <, > ,<=, >= , == , != , is ,is not , in , not in, and , or # Mantiqiy operatorlar >> not , and , or
18e36ce1304fad50679c066230d0279429851bed
mzmmohideen/CredozSample
/Excercise/pgm/emirp.py
645
3.875
4
""" __author__ = "mohideen" __created__ = "2019-11-05" __lastupdated__ = "2019-11-05" """ from __future__ import print_function def isprime(n): for i in range(2, n): if n % i == 0: return False return True def findEmirp(count): a = 1 emirp = [] while a: rev = int(str(a)[::-1]) if isprime(a) and rev != a and isprime(rev): # print("It is emirp", a) emirp.append(a) a+=1 if len(emirp) == count: a = 0 return emirp # for i in findEmirp(20): # print("Emirp = ", i) def readFile(): inp = raw_input("Enter File Path:") words = open(inp).read().split() for i in set(words): print("Words = ", i) readFile()
828207b3bfd5c38dc1902a6ca1254a298c836c98
Sniper970119/leetCode
/L0001~L0050/L0011.py
806
3.546875
4
# -*- coding:utf-8 -*- class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ weights = [[0 for _ in range(len(height))] for _ in range(len(height))] for i in range(1, len(weights)): for j in range(len(weights) - i): for k in range(j, j + i): if min(height[j], height[j + i]) * i < max(weights[j][k], weights[k][j + i]): weights[j][j + i] = max(weights[j][k], weights[k][j + i]) else: weights[j][j + i] = min(height[j], height[j + i]) * i return max(max(row) for row in weights) if __name__ == '__main__': height = [1, 8, 6, 2, 5, 4, 8, 3, 7] print(Solution().maxArea(height))
67c4b3ef2bba0242b95b991353ee2b8cf0e35129
chpaul/Leetcode
/053_MaximumSubarray.py
486
3.5625
4
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <=0: return 0; maxResult,curMax = nums[0], nums[0] for i in nums[1:]: curMax = max(i, (curMax+i)) maxResult = max(curMax, maxResult) return maxResult if __name__ == "__main__": solution = Solution() a = solution.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) print(a)
0595fbb6b45d373f8f1b35a8e9920ef617ada1dd
sotomaque/CSreview
/python/recursion/fib.py
899
3.75
4
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... # recurssive approach # O(2^n) time | O(n) space def fib(n): if n == 1: return 0 elif n == 2: return 1 else: return fib(n - 1) + fib(n - 2) # dynamic programming approach (bottom up) # O(n) time | O(n) space def fib_dp(n, cache = {1: 0, 2: 1}): if n in cache: return cache[n] else: cache[n] = fib_dp(n - 1, cache) + fib_dp(n - 2, cache) print(cache) return cache[n] # iterative solution # O(n) time | O(1) space def fib_iterative(n): lastTwo = [0, 1] counter = 3 while counter <= n: nextFib = lastTwo[0] + lastTwo[1] lastTwo[0] = lastTwo[1] lastTwo[1] = nextFib counter += 1 if n > 1: return lastTwo[1] else: return lastTwo[0] def test(): n = 5 print('the', n, 'th fib number is: ', fib_dp(n)) test()
cf48c2c0641a1d3c26edd79c2ad81c7686941296
rashmi1403/Spam_Detection_And_Sentiment_Analysis
/preprocess_spam.py
2,041
3.546875
4
from sys import argv from os import walk vocab_f = argv[1] #vocab file dir_p = argv[2] #path of directory - HAM output_f = argv[3] #output file outputfile = open(output_f, "w") #Add vocab file into a list vocab_list = [] filev = open(vocab_f, "r", encoding= "latin1") line = filev.readline() vocab_list.append("Rashmi") #So that we can access index from 1 for the words in vocab file while line: vocab_list.append(line.strip()) line = filev.readline() print("Finished loading vocab to list") #files has list of all files in the dir name passed as argument for dirname, dirnames, filenames in walk(dir_p): #print(filenames) filenames.sort() #print(filenames) for files in filenames: #print(files) fullname = dirname + "/" +files #print(fullname) filei = open(fullname, "r", encoding= "latin1") #print("File opened") #output_dictionary for each document output_d = {} #list of all lines in the file file_lines = [] line = filei.readline() while line: file_lines.append(line.strip()) line = filei.readline() #for each line split into tokens for line in file_lines: tokens = [] tokens = line.split(" ") for token in tokens: if(token in vocab_list): key = int(vocab_list.index(token)) val = output_d.get(key) if(val != None): output_d[key] = int(val) + 1 else: output_d[key] = 1 else: print("Word not in vocab list = " +token) #After the whole document is processed, write the dictionary to the output file output_res = [] for key in sorted(output_d): ostr = str(key) +":" + str(output_d[key]) output_res.append(ostr) #res = "SPAM " + " ".join(output_res) #Change this for dev data and comment below line res = " ".join(output_res) outputfile.write(res + "\n") filei.close() print("No of files processed = " +str(len(filenames))) filev.close() outputfile.close() print("Finished processing!")
e4564c47972c069fc53ed2b5104e93ea882dc496
sridhar086/Hackerrank-algorithms
/dynamic-programming/placing_parentheses.py
1,368
3.71875
4
# Uses python3 import math def evalt(a, b, op): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b else: assert False def split_expr(dataset): global operators global operands operators = list() operands = list() for i in range(len(dataset)): if i%2==0: operands.append(dataset[i]) else: operators.append(dataset[i]) print (operands) print (operators) #minmax(0,len(dataset),dataset) def minmax(i,j,dataset): print ("++++") for k in range(i,j,2): #print (type(k)) print (dataset[i:k] , dataset[k], dataset [k+1:j]) print ("++++") #write your code here return 0 def parantheses(str): global operators global operands n = math.ceil(len(str)/2) m = [[0 for i in range(n)] for i in range(n)] print (m) for i in range(len(operands)): m[i][i] = operands[i] print (m) for s in range(0,len(operands)-1): for i in range(0,n-s): j = i+s print ("operands ",s," inner loop ",i," tthe j is ",j) #minmax(i,j,s) if __name__ == "__main__": #str = input() str = "5-8+7*4-8+9" print (str) split_expr(str) parantheses(str) #print(get_maximum_value(str))
a96c1427894a6e1a64f4b05c2092fd2a4b79eb3e
MyHiHi/myLeetcode
/leetcode+牛客/judgeSquareSum判断是否存在两个整数 a 和 b,使得 a2 + b2 = c.py
894
3.8125
4
# -*- encoding: utf-8 -*- ''' @File : judgeSquareSum.py @Time : 2020/01/21 09:40:52 @Author : Zhang tao @Version : 1.0 @Desc : None ''' ''' 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 ''' class Solution: def judgeSquareSum(self, c: int) -> bool: a,b=0,int(c**0.5); res=a**2+b**2; while a<=b: if res==c:return True; elif res<c:a+=1; else:b-=1; res=a**2+b**2; return False class Solution: def judgeSquareSum(self, c: int) -> bool: if not c:return True for i in range(1, int(c**0.5)+1): r = (c-i*i)**0.5 k = int(r) if r**2 == k**2: return True return False
d378e9d6eff649413b46b8d24e8c85aa5581584c
dlm95/Highlight-Portfolio
/Academic Highlight/CSC 3340 Programming Languages/Lab7class.py
204
3.828125
4
#Lab 7 Michelle Lane prefixes = 'JKLMNOPQ' suffix = 'ack' suffix1 = 'uack' for letter in prefixes: if letter == 'O' or letter == 'Q': print(letter + suffix1) else: print(letter + suffix)
3c179f48f2b04a4512bc6bf2b260f301c61bc8c8
luk6xff/Pentesting
/scripts/arp_cache_spooffing.py
4,720
3.5
4
#!/usr/bin/env python import sys import socket import struct import binascii from datetime import datetime PY2 = sys.version_info[0] == 2 if PY2: raise Exception("Please use finally Python3.x version :)") '''==================== DESCRIPTION ====================''' #ARP (Address Resolution Protocol) is used to convert the IP address to its #corresponding Ethernet (MAC) address. When a packet comes to the Network layer #(OSI), it has an IP address and a data link layer packet that needs the MAC address #of the destination device. In this case, the sender uses the ARP protocol. #ARP PACKET FORMAT: ''' 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | HW Type = 0x0012 | Protocol = 0x0800 | +---------------+---------------+---------------+---------------+ | HW Len = 12 | Proto Len = 4 | Opcode | +---------------+---------------+---------------+---------------+ | | +- -+ | HW Address of Sender | +- -+ | | +---------------+---------------+---------------+---------------+ | Protocol Address of Sender | +---------------+---------------+---------------+---------------+ | | +- -+ | HW Address of Target | +- -+ | | +---------------+---------------+---------------+---------------+ | Protocol Address of Target | +---------------+---------------+---------------+---------------+ - HW Type: 0x0012 (Fibre Channel); - Protocol: 0x0800 (IPv4); - HW Len: 12 (Length in octets of the HW Address); - Proto Len: 4 (Length in octets of the Protocol Address); - Opcode: 0x0001 for ARP Request, 0x0002 for ARP Reply [ARP]; - HW Address of Sender: the HW Address (see section 8) of the Requester in an ARP Request, or the HW Address of the Responder in an ARP Reply; - Protocol Address of Sender: the IPv4 address of the Requester in an ARP Request, or that of the Responder in an ARP Reply; - HW Address of Target: set to zero in an ARP Request, and to the HW Address (see section 8) of the Requester in an ARP Reply; - Protocol Address of Target: the IPv4 address of the Responder in an ARP Request, or that of the Requester in an ARP Reply. ''' '''==================== DESCRIPTION-END ==================''' '''==================== USAGE ====================''' '''==================== USAGE-END ==================''' '''==================== GLOBAL SETTINGS ====================''' #victim WIN10_PC_IP= '192.168.1.100' WIN10_PC_MAC= '\x30\xb5\xc2\x11\xf8\x39' #gateway GATEWAY_IP='192.168.1.1' GATEWAY_MAC='\xd8\x5d\x4c\xff\xdb\x56' #attacker UBUNTU_LAPTOP_IP='192.168.1.102' UBUNTU_LAPTOP_MAC='\xc4\x17\xfe\x5b\x84\x83' CODE ='\x08\x06' HW_TYPE = '\x00\x01' PROTOCOL_TYPE = '\x08\x00' HW_LEN = '\x06' PROTOCOL_LEN = '\x04' OPCODE = '\x00\x02' '''==================== GLOBAL SETTINGS-END ==================''' def main(): s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) #LINUX #s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0800)) #WIN s.bind(("eth0",socket.htons(0x0800))) eth1 = WIN10_PC_MAC+UBUNTU_LAPTOP_MAC+CODE #for victim eth2 = GATEWAY_MAC+UBUNTU_LAPTOP_MAC+CODE # for gateway print("HERE") gateway_ip = socket.inet_aton(GATEWAY_IP) victim_ip = socket.inet_aton(WIN10_PC_IP) arp_packet_victim= eth1+HW_TYPE+PROTOCOL_TYPE+HW_LEN+PROTOCOL_LEN+OPCODE+UBUNTU_LAPTOP_MAC+gateway_ip+WIN10_PC_MAC+victim_ip arp_packet_gateway= eth2+HW_TYPE+PROTOCOL_TYPE+HW_LEN+PROTOCOL_LEN+OPCODE+UBUNTU_LAPTOP_MAC+victim_ip+GATEWAY_MAC+gateway_ip while(True): s.send(arp_packet_victim) s.send(arp_packet_gateway) if __name__ == '__main__': try: main() except Exception as e: print("[ERROR]: %s"%e)
2d84b5b7d3110a7268b27216b14f2014eb630c49
Kawaljeet18/Python-Programs
/TURN100.py
254
3.953125
4
#When will you turn 100 import datetime Name=input("Please Enter Your Name") Age=int(input("Please Enter Your Age")) Temp=100-Age Now=datetime.datetime.now() print("Current Year :",Now.year) Year=Now.year+Temp print("You Will Turn 100 in :",Year)
257c45f9815024dde3606d995ccfd142eb6f2332
0xjojo/Foundations-of-Python-Programming-Search-User-Scratch-Activecode-12.16.-Exercises
/Exercises.py
5,200
4.0625
4
#Write a function named num_test that takes a number as input. #If the number is greater than 10, the function should return “Greater than 10.” # If the number is less than 10, the function should return “Less than 10.” #If the number is equal to 10, the function should return “Equal to 10.” def num_test (x): y = "Greater than 10." n = "Less than 10." r = "Equal to 10." if (x > 10 ): return y if (x == 10): return r else : return n #Write a function that will return the number of digits in an integer. def numDigits(n): string = str (n) length = len (string) return length # your code here #Write a function that reverses its string argument. def reverse(astring): reversed = '' n = len (astring) - 1 #to avoide the problem of index for r in astring : reversed = reversed + astring[n] n = n-1 return reversed # your code here #Write a function that mirrors its string argument, generating a string containing the original string and the string backwards. def mirror(mystr): copy = mystr mirror = '' n = len (mystr) - 1 for r in mystr : mirror = mirror + mystr[n] n = n-1 collect = copy + mirror return collect # your code here #Write a function that removes all occurrences of a given letter from a string. def remove_letter(theLetter, theString): #n = len(theString) - 1 n = 0 without = '' for r in theString : if r == theLetter : n = n + 1 continue else : without = without + theString[n] n = n + 1 return without # your code here #Write a function replace(s, old, new) that replaces all occurences of old with new in a string s: def replace(s, old, new): y = '' s.split() for r in s : if r == old : r = new y = y+r return y # your code here #Write a Python function that will take a the list of 100 random integers between 0 and 1000 #and return the maximum value. (Note: there is a builtin function named max but pretend you cannot use it.) def maximum (lst) : ref = 0 for x in lst : if (x > ref ): ref = x return ref #Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs. For example, #sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29: def sum_of_squares(xs): sum = 0 for i in xs : i = i*i sum = sum + i return sum # your code here #Write a function to count how many odd numbers are in a list. def countOdd(lst): count = 0 for i in lst : remainder = i % 2 if remainder == 1 : count = count + 1 else : continue return count # your code here #Sum up all the even numbers in a list. import random def sumEven(lst): sumEv = 0 for n in lst : r = n % 2 if (r == 0): sumEv = sumEv + n else : continue return sumEv # your code here #Sum up all the negative numbers in a list. def sumNegatives(lst): ref = 0 sumNeg = 0 for r in lst : if r < 0 : sumNeg = sumNeg + r else : continue return sumNeg # your code here #Write a function findHypot. The function will be given the length of two sides # of a right-angled triangle and it should return the length of the hypotenuse. #(Hint: x ** 0.5 will return the square root, or use sqrt from the math module) def findHypot(a,b): Hypot = (a**2+b**2)**0.5 return Hypot # your code here #Write a function called is_even(n) that takes an integer as an argument and returns #True if the argument is an even number and False if it is odd. def is_even(n): r = n % 2 if r == 0: return True if r == 1: return False #your code here #Now write the function is_odd(n) that returns True when n is odd and False otherwise. def is_odd(n): r = n % 2 if r == 1: return True else : return False # your code here #Write a function is_rightangled which, given the length of three sides of a triangle, # will determine whether the triangle is right-angled. Assume that the third argument # to the function is always the longest side. It will return True# # if the triangle is right-angled, or False otherwise. #Hint: floating point arithmetic is not always exactly accurate, so it is not safe to test #floating point numbers for equality. If a good programmer wants to know whether x is equal or close enough to y, #they would probably code it up as def is_rightangled(a, b, c): #if the triangle is sqrt(a^2 + b^2)=c r = (a**2+b**2)**0.5 if (c == r) : return True elif ((c-r) < 0.001): return True elif ((r-c) < 0.001): return True else : return False # your code here
3af5f8ab48b048e2ceab2d3fd3dbbbde8f60ff0d
stevenwongso/Python_Fundamental_DataScience
/0 Python Fundamental/21.pangkatRekursif.py
181
3.671875
4
# recursive function def pangkat(x,y): if (y == 1): return x else: return x * pangkat(x, y-1) print(pangkat(2,3)) print(pangkat(3,3)) print(pangkat(10,5))
d62286f60863e4c55ec8c5176b03ee7419eca50a
jameswmccarty/AdventOfCode2015
/day7.py
5,907
3.875
4
#!/usr/bin/python """ --- Day 7: Some Assembly Required --- This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit. Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its inputs have a signal. The included instructions booklet describes how to connect the parts together: x AND y -> z means to connect wires x and y to an AND gate, and then connect its output to wire z. For example: 123 -> x means that the signal 123 is provided to wire x. x AND y -> z means that the bitwise AND of wire x and wire y is provided to wire z. p LSHIFT 2 -> q means that the value from wire p is left-shifted by 2 and then provided to wire q. NOT e -> f means that the bitwise complement of the value from wire e is provided to wire f. Other possible gates include OR (bitwise OR) and RSHIFT (right-shift). If, for some reason, you'd like to emulate the circuit instead, almost all programming languages (for example, C, JavaScript, or Python) provide operators for these gates. For example, here is a simple circuit: 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i After it is run, these are the signals on the wires: d: 72 e: 507 f: 492 g: 114 h: 65412 i: 65079 x: 123 y: 456 In little Bobby's kit's instructions booklet (provided as your puzzle input), what signal is ultimately provided to wire a? --- Part Two --- Now, take the signal you got on wire a, override wire b to that signal, and reset the other wires (including wire a). What new signal is ultimately provided to wire a? """ signals = {} def emulate(instructions): global signals while len(instructions) > 0: for inst in instructions: if "AND" in inst[0]: a,b = inst[0].split(" AND ") if a in signals: a = signals[a] else: try: a = int(a) except: a = None if b in signals: b = signals[b] else: try: b = int(b) except: b = None if a != None and b != None: signals[inst[1]] = a & b & 0xFFFF instructions.remove(inst) elif "OR" in inst[0]: a,b = inst[0].split(" OR ") if a in signals: a = signals[a] else: try: a = int(a) except: a = None if b in signals: b = signals[b] else: try: b = int(b) except: b = None if a != None and b != None: signals[inst[1]] = (a | b) & 0xFFFF instructions.remove(inst) elif "LSHIFT" in inst[0]: a,b = inst[0].split(" LSHIFT ") if a in signals: signals[inst[1]] = (signals[a] << int(b)) & 0xFFFF instructions.remove(inst) elif "RSHIFT" in inst[0]: a,b = inst[0].split(" RSHIFT ") if a in signals: signals[inst[1]] = (signals[a] >> int(b)) & 0xFFFF instructions.remove(inst) elif "NOT" in inst[0]: a = inst[0].replace("NOT ", '') if a in signals: signals[inst[1]] = ~signals[a] & 0xFFFF instructions.remove(inst) else: a = inst[0] if a in signals: signals[inst[1]] = signals[a] instructions.remove(inst) else: try: a = int(a) signals[inst[1]] = a instructions.remove(inst) except: continue def emulate_ovr(instructions): global signals while len(instructions) > 0: for inst in instructions: signals['b'] = 3176 if "AND" in inst[0]: a,b = inst[0].split(" AND ") if a in signals: a = signals[a] else: try: a = int(a) except: a = None if b in signals: b = signals[b] else: try: b = int(b) except: b = None if a != None and b != None: signals[inst[1]] = a & b & 0xFFFF instructions.remove(inst) elif "OR" in inst[0]: a,b = inst[0].split(" OR ") if a in signals: a = signals[a] else: try: a = int(a) except: a = None if b in signals: b = signals[b] else: try: b = int(b) except: b = None if a != None and b != None: signals[inst[1]] = (a | b) & 0xFFFF instructions.remove(inst) elif "LSHIFT" in inst[0]: a,b = inst[0].split(" LSHIFT ") if a in signals: signals[inst[1]] = (signals[a] << int(b)) & 0xFFFF instructions.remove(inst) elif "RSHIFT" in inst[0]: a,b = inst[0].split(" RSHIFT ") if a in signals: signals[inst[1]] = (signals[a] >> int(b)) & 0xFFFF instructions.remove(inst) elif "NOT" in inst[0]: a = inst[0].replace("NOT ", '') if a in signals: signals[inst[1]] = ~signals[a] & 0xFFFF instructions.remove(inst) else: a = inst[0] if a in signals: signals[inst[1]] = signals[a] instructions.remove(inst) else: try: a = int(a) signals[inst[1]] = a instructions.remove(inst) except: continue if __name__ == "__main__": # Part 1 Solution instructions = [] with open("day7_input", "r") as infile: for line in infile.readlines(): instructions.append(line.strip().split(" -> ")) emulate(instructions) print signals['a'] # Part 2 Solution instructions = [] signals = {} with open("day7_input", "r") as infile: for line in infile.readlines(): instructions.append(line.strip().split(" -> ")) emulate_ovr(instructions) print signals['a']
cb378b8a64a6fdee81ed0f2c42945506f111b670
ug2454/PythonPractice
/dice.py
178
3.53125
4
import random class Dice: def roll(self): roll1 = random.randint(1,6) roll2 = random.randint(1,6) return roll1,roll2 dice=Dice() print(dice.roll())
19cace90733eebc308c288bed4c444cee277e333
ryohang/java-basic
/python/LowestCommonAncesstor.py
715
3.828125
4
class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n1.left = n3 n1.right = n2 n3.left = TreeNode(5) n3.right = TreeNode(6) n2.right = TreeNode(9) def lowestCommonAncestor(root, p, q): if root == p or root == q: return root left = right = None if root.left: left = lowestCommonAncestor(root.left, p, q) if root.right: right = lowestCommonAncestor(root.right, p, q) if left and right: return root else: return left or right print(lowestCommonAncestor(n1, n2, n3).val)
e3032e13279484146087b81e3440a5c9f845ced6
Dpablook/Curso-de-Python3--Udemy
/Funciones Avanzadas/Lamba.py
300
4.125
4
#Una funcion Lambda es una funcion anonima #se puede ejecutar sin nombre #sirve para funciones mas simples # # Forma Traficional def suma(x,y): return(x+y) print(suma(2,5)) # Forma con Lambda i = lambda x,y: x+y print(i(5,10)) revertir = lambda cadena: cadena[::-1] print(revertir("Python"))
afc54e2b0eb5a422fe58062a6c556d5aa38983cc
rohitpawar4507/Zensar_Python
/Inheritance/Inher2.py
919
4.3125
4
# Multiple Inheritance # Father Class Created class Father: fathername ="" def show_father(self): print("Method from Parent Class") print("The father Name is ",self.fathername) # Mother Class Crated class Mother: mothername = "" def show_mother(self): print("Method from Parent class Mother") print("The Mother Name is ",self.mothername) # Son class inherits father and mother class class Son(Father,Mother): def show_parent(self): print("The father Name is ",self.fathername) print("The Mother Name is ",self.mothername) print("Creating child class object") s1=Son() print("Assigning value for father name and mother name") s1.fathername ='Harishchandra' s1.mothername='Rekha' print("Calling child class method") s1.show_parent() print("Calling mother class methods") s1.show_mother() print("Calling the Father class method") s1.show_father()
40c76219fa7559513ffc0082381a36d734df08b4
Keerthanavikraman/Luminarpythonworks
/recursion/pattern_prgming6.py
170
3.78125
4
# 000000 # 11111 # 2222 # 333 # 44 # 5 n=int(input("enter the number of rows")) for i in range(n+1): for j in range(i,n+1): print(i,end="") print()
8d505d06e4fcd38e27850725a5e8b1f3976c532b
GregorH97/HW070172
/L03/11.py
259
4.1875
4
print("This is a program that converts miles into kilometers") def main(): miles = eval(input("What is the distance in miles? ")) kilometers = miles*0.62 print("The distance in miles is", kilometers) main() input("Press enter to quit")
bf3049527af0f7e642fa6eda03568174828165f6
elvisliyx/python-learn
/learn-day2/string.py
1,100
4.03125
4
# -*- coding:utf-8 -*- name = "my name is elvis" print(name.capitalize()) print(name.count("a")) print(name.center(50,"-")) print(name.endswith("is")) print(name.expandtabs(tabsize=30)) print(name.find('name')) print(name.format(name='elvis',year=31)) print(name.format_map({'name':'elvis','year':12})) print('adfb123'.isalnum()) print('adfA'.isalpha()) print('1A'.isdecimal()) print('1A'.isdigit()) print('a 1A'.isidentifier())#判断是不是一个合法的标识符 print('22A'.islower()) print('33A'.isnumeric()) print('My Name is '.istitle()) print('My Name is '.isprintable()) print('My Name is '.isupper()) print(','.join(['1','2','3'])) print(name.ljust(50,'*')) print(name.rjust(50,'*')) print('Elvis'.lower()) print('Elvis'.upper()) print('\nElvis'.lstrip()) print('Elvis\n'.rstrip()) print(' Elvis'.strip()) p = str.maketrans("abcdef","123456") print("elvis li".translate(p)) print('elvis li'.replace('l','L',1)) print('elvis li'.rfind("i")) print('1+2+3+4'.split('+')) print('1+2\n3+4'.splitlines()) print('Elvis Li'.swapcase()) print('lvis li'.title()) print('elvis li'.zfill(50))
6c36a88cc30735dca6ac4ddb3d031492670e61a5
vemanand/pythonprograms
/opencv/1_read_image.py
994
4.28125
4
'''This program will read an image file and display the matrix You need to install opencv-python for this to work $pip install opencv-python Each image is returned as numpy arrary by opencv-python Notice that color image will have 3-D matrix where as grayscale image will have 2-D matrix''' import cv2 colorImage = cv2.imread("../resources/roses.jpg",1) #Read the image in RGB color format. 2nd parameter flag 1 indicates color image print(type(colorImage)) #Notice that image is returned as Numpy array print('Displaying color image matrix (3D)') print(colorImage) bwImage = cv2.imread("../resources/roses.jpg",0) #Read the image as grayscale or black&white image. 2nd parameter flat 0 indicates back&white image print('Displaying black and white image matrix (2d)') print(bwImage) #Some other functions of opencv print("Color image size = "+str(colorImage.shape)+ " Black&White image size = "+str(bwImage.shape)) #See that color image has 3 channels and grayscale image has 2 channels
2e6e8f9e56e7f857f53fc8597bd017649c380b8b
prof79/realpython-python-csv
/pandasreadcsv.py
912
4.03125
4
#!/usr/bin/env python3 # pandasreadcsv.py # https://realpython.com/python-csv import pandas FILENAME = 'hrdata.csv' FILENAME2 = 'hrdata2.csv' def main() -> None: print('File #1') print() # df = pandas.read_csv(FILENAME) # Make sure, the index column is the 'Name' column # Use date type for the 'Hire Date' column df = pandas.read_csv( FILENAME, index_col='Name', parse_dates=['Hire Date']) print(df) print() print() print('File #2') print() # Load a CSV file without header information fieldnames = ['Employee', 'Hired', 'Salary', 'Sick Days'] df2 = pandas.read_csv( FILENAME2, header=0, names=fieldnames, index_col=fieldnames[0], parse_dates=[fieldnames[1]] ) print(df2) if __name__ == '__main__': print() print() main() print() print()
10793c31029c047457b20054a8f28e63a1aca8b4
beneen/nobody-likes-a-for-loop
/string_manipulation/rotate_matrix.py
442
4.125
4
""" ----- Given an image represented by an NxN matrix, write a method to rotate the image by 90 degrees. can you do this in place? ----- """ def rotate_matrix(matrix): return [[matrix[row][column] for row in range(len(matrix) - 1, -1, -1)] for column in range(0, len(matrix[0]))] def main(): #hardcoded matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(rotate_matrix(matrix)) if __name__ == "__main__": main()
2f01e76f65fbd335e7c7b67e030098b63b3a1348
treasureb/Python
/class/createClass.py
732
4.03125
4
# -*- coding: utf-8 -*- #创建一个空类 class Person(object): pass #创建两个实例 guodong = Person() yiming = Person() #python是动态语言,可以动态添加属性 guodong.name = 'XiaoGuoDong' guodong.gender = 'Male' guodong.birth = '1996-9-16' yiming.birth = '1997-6-6' yiming.gender = 'Famale' yiming.grade = 2 #实例的属性可以像普通变量一样进行操作 yiming.grade = yiming.grade+1 print yiming.grade #------------------------------------------------ #练习 class Person(object): pass p1 = Person() p1.name = 'Bart' p2 = Person() p2.name = 'Adam' p3 = Person() p3.name = 'Lisa' L1 = [p1,p2,p3] L2 = sorted(L1,key=lambda x:x.name) print L2[0].name print L2[1].name print L2[2].name
36295670b311724c9ca72108a0e58f3e9a405754
JJJHolscher/zsb
/chessgame.py
19,397
3.8125
4
# chessgame.py # This file will play chess with a human. The program will suggest moves. It # does this using one of two decision-making algorithms: minimax and alphabeta. # Right now it uses alphabeta. # # By Jochem (11007729) and Reitze (11045442) on 8 june 2017 from group C from __future__ import print_function import sys # Helper functions # Translate a position in chess notation to x,y-coordinates # Example: c3 corresponds to (2,5) def to_coordinate(notation): x = ord(notation[0]) - ord('a') y = 8 - int(notation[1]) return x, y # Translate a position in x,y-coordinates to chess notation # Example: (2,5) corresponds to c3 def to_notation(coordinates): (x, y) = coordinates letter = chr(ord('a') + x) number = 8 - y return letter + str(number) # Translates two x,y-coordinates into a chess move notation # Example: (1,4) and (2,3) will become b4c5 def to_move(from_coord, to_coord): return to_notation(from_coord) + to_notation(to_coord) # Defining board states # These Static classes are used as enums for: # - Material.Rook # - Material.King # - Material.Pawn # - Side.White # - Side.Black class Material: Bisshop, Knight, Pawn, Queen, Rook, King = ['b', 'n', 'p', 'q', 'r', 'k'] class Side: White, Black = range(0, 2) # A chesspiece on the board is specified by the side it belongs to and the type # of the chesspiece class Piece: def __init__(self, side, material): self.side = side self.material = material if self.material == 'b': self.worth = 3 elif self.material == 'n': self.worth = 3 elif self.material == 'p': self.worth = 1 elif self.material == 'q': self.worth = 9 elif self.material == 'r': self.worth = 5 elif self.material == 'k': self.worth = 100 # A chess configuration is specified by whose turn it is and a 2d array # with all the pieces on the board class ChessBoard: def __init__(self, turn): # This variable is either equal to Side.White or Side.Black self.turn = turn self.board_matrix = None # Getter and setter methods def set_board_matrix(self, board_matrix): self.board_matrix = board_matrix # Note: assumes the position is valid def get_boardpiece(self, position): (x, y) = position return self.board_matrix[y][x] # Note: assumes the position is valid def set_boardpiece(self, position, piece): (x,y) = position self.board_matrix[y][x] = piece # Read in the board_matrix using an input string def load_from_input(self, input_str): self.board_matrix = [[None for _ in range(8)] for _ in range(8)] x = 0 y = 0 for char in input_str: if y == 8: if char == 'W': self.turn = Side.White elif char == 'B': self.turn = Side.Black return if char == '\r': continue if char == '.': x += 1 continue if char == '\n': x = 0 y += 1 continue if char.isupper(): side = Side.White else: side = Side.Black material = char.lower() piece = Piece(side, material) self.set_boardpiece((x,y),piece) x += 1 # Print the current board state def __str__(self): return_str = "" return_str += " abcdefgh\n\n" y = 8 for board_row in self.board_matrix: return_str += str(y) + " " for piece in board_row: if piece == None: return_str += "." else: char = piece.material if piece.side == Side.White: char = char.upper() return_str += char return_str += '\n' y -= 1 turn_name = ("White" if self.turn == Side.White else "Black") return_str += "It is " + turn_name + "'s turn\n" return return_str # Given a move string in chess notation, return a new ChessBoard object # with the new board situation # Note: this method assumes the move suggested is a valid, legal move def make_move(self, move_str): start_pos = to_coordinate(move_str[0:2]) end_pos = to_coordinate(move_str[2:4]) if self.turn == Side.White: turn = Side.Black else: turn = Side.White # Duplicate the current board_matrix new_matrix = [row[:] for row in self.board_matrix] # Create a new chessboard object new_board = ChessBoard(turn) new_board.set_board_matrix(new_matrix) # Carry out the move in the new chessboard object piece = new_board.get_boardpiece(start_pos) new_board.set_boardpiece(end_pos, piece) new_board.set_boardpiece(start_pos, None) return new_board def is_king_dead(self, side): seen_king = False for x in range(8): for y in range(8): piece = self.get_boardpiece((x, y)) if piece != None and piece.side == side and \ piece.material == Material.King: seen_king = True return not seen_king # This function should return, given the current board configuation and # which players turn it is, all the moves possible for that player # It should return these moves as a list of move strings, e.g. # [c2c3, d4e5, f4f8] def legal_moves(self): moves_list = [] piece_locs = self.get_own_pieces() for loc in piece_locs: piece = self.get_boardpiece(loc) if piece.material == Material.King: moves_list.extend(self.moves_king(loc)) elif piece.material == Material.Pawn: moves_list.extend(self.moves_pawn(loc)) elif piece.material == Material.Rook: moves_list.extend(self.moves_rook(loc)) elif piece.material == Material.Bisshop: moves_list.extend(self.moves_bisshop(loc)) elif piece.material == Material.Knight: moves_list.extend(self.moves_knight(loc)) elif piece.material == Material.Queen: moves_list.extend(self.moves_queen(loc)) return moves_list # returns a list of all move strings for a king at location loc # i.e [h5h6, h5g6, h5g5, h5g4, h5h4] (king is o the side of the board) def moves_king(self, loc): moves = [] x_dimension = [-1, 0, 1] y_dimension = [-1, 0, 1] for dx in x_dimension: for dy in y_dimension: moves.extend(self.explore_line(loc, dx, dy, one=True)) for move in range(len(moves)-1): if move == to_move(loc,loc): del moves[moves.index(move)] return moves # returns a list of all move strings for a pawn at location loc # i.e. [a1a2, b1b2, c3b4] # this should be dependand whose turn it is. def moves_pawn(self, loc): dy = 0 if self.turn == Side.White: dy = -1 else: dy = 1 if loc[1] + dy > 7 or loc[1] + dy < 0: return [] moves = [to_move(loc, (loc[0], loc[1] + dy))] x_dimension = [-1, 1] for dx in x_dimension: new_loc = (loc[0] + dx, loc[1] + dy) if 0 <= new_loc[0] <= 7 and self.get_boardpiece(new_loc): moves.append(to_move(loc, new_loc)) return moves # returns a list of all move strings for a rook at location loc # i.e. [a1a3, a2f2, ...] def moves_rook(self, loc): moves = [] x_dimension = [-1, 1] for dx in x_dimension: moves.extend(self.explore_line(loc, dx, 0)) y_dimension = [-1, 1] for dy in y_dimension: moves.extend(self.explore_line(loc, 0, dy)) return moves # returns a list of all move strings for a queen at location loc def moves_queen(self, loc): moves = [] x_dimension = [-1,0,1] y_dimension = [-1,0,1] for dx in x_dimension: for dy in y_dimension: if dx == dy == 0: continue moves.extend(self.explore_line(loc, dx, dy)) return moves # returns a list of all move strings for a bisshop at location loc def moves_bisshop(self, loc): moves = [] x_dimension = [-1,1] y_dimension = [-1,1] for dx in x_dimension: for dy in y_dimension: moves.extend(self.explore_line(loc, dx, dy)) return moves # returns a list of all move strings for a knight at location loc def moves_knight(self, loc): moves = [] x_dimension = [-2, -1, 1, 2] y_dimension = [-2, -1, 1, 2] for dx in x_dimension: for dy in y_dimension: if abs(dx) == abs(dy): continue moves.extend(self.explore_line(loc, dx, dy, one=True)) return moves # returns all move strings from a location by incrementing with dx and dy # untill the board edge, a friendly unit or an enemy unit is reached # one=True will cause only one increment to happen and is thus useful for # kings, knights (in the future) & pawns def explore_line(self, loc, dx, dy, one=False): moves = [] (newx, newy) = (loc[0] + dx, loc[1] + dy) while -1 < newx < 8 and -1 < newy < 8 and not one: piece = self.get_boardpiece((newx, newy)) if piece == None: moves.append(to_move(loc, (newx, newy))) elif piece.side == self.turn: break elif piece.side != self.turn: moves.append(to_move(loc, (newx, newy))) break newx += dx newy += dy if -1 < newx < 8 and -1 < newy < 8 and one: piece = self.get_boardpiece((newx, newy)) if piece == None: moves.append(to_move(loc, (newx, newy))) elif piece.side == self.turn: pass elif piece.side != self.turn: moves.append(to_move(loc, (newx, newy))) return moves # returns a list of all pieces of current side. def get_own_pieces(self): pos_w_piece = [] for x in range(8): for y in range(8): piece = self.get_boardpiece((x,y)) if piece and piece.side == self.turn: pos_w_piece.append((x,y)) return pos_w_piece # This function should return, given the move specified (in the format # 'd2d3') whether this move is legal # of legal_moves() def is_legal_move(self, move): if move in self.legal_moves(): return True else: return False # This static class is responsible for providing functions that can calculate # the optimal move using minimax class ChessComputer: # This method uses either alphabeta or minimax to calculate the best move # possible. The input needed is a chessboard configuration and the max # depth of the search algorithm. It returns a tuple of (score, chessboard) # with score the maximum score attainable and chessboardmove that is needed # to achieve this score. @staticmethod def computer_move(chessboard, depth, alphabeta=False): if alphabeta: inf = 99999999 min_inf = -inf return ChessComputer.alphabeta(chessboard, depth, min_inf, inf) else: return ChessComputer.minimax(chessboard, depth) # This function uses minimax to calculate the next move. Given the current # chessboard and max depth, this function should return a tuple of the # the score and the move that should be executed # NOTE: use ChessComputer.evaluate_board() to calculate the score # of a specific board configuration after the max depth is reached @staticmethod def minimax(chessboard, depth): best_move = '' best_score = 99999 enemy = Side.White if chessboard.turn == Side.White: enemy = Side.Black best_score = -best_score for move in chessboard.legal_moves(): new_chessboard = chessboard.make_move(move) score = ChessComputer.minimax_turn(new_chessboard, depth - 1) if enemy == Side.White and score < best_score: best_score = score best_move = move elif enemy == Side.Black and score > best_score: best_score = score best_move = move return best_score, best_move @staticmethod def minimax_turn(chessboard, depth): best_score = 99999 enemy = Side.White if chessboard.turn == Side.White: enemy = Side.Black best_score = -best_score if depth == 0 or chessboard.is_king_dead(chessboard.turn): return ChessComputer.evaluate_board(chessboard, depth) for move in chessboard.legal_moves(): new_chessboard = chessboard.make_move(move) score = ChessComputer.minimax_turn(new_chessboard, depth - 1) if enemy == Side.White and score < best_score: best_score = score elif enemy == Side.Black and score > best_score: best_score = score return best_score # This function uses alphabeta to calculate the next move. Given the # chessboard and max depth, this function should return a tuple of the # the score and the move that should be executed. # It has alpha and beta as extra pruning parameters # NOTE: use ChessComputer.evaluate_board() to calculate the score # of a specific board configuration after the max depth is reached @staticmethod def alphabeta(chessboard, depth, alpha, beta): best_move = '' best_score = beta enemy = Side.White if chessboard.turn == Side.White: enemy = Side.Black best_score = alpha for move in chessboard.legal_moves(): new_chessboard = chessboard.make_move(move) score = ChessComputer.alphabeta_turn(new_chessboard, depth - 1, alpha, beta) if enemy == Side.White and score < best_score: best_score = score best_move = move beta = best_score elif enemy == Side.Black and score > best_score: best_score = score best_move = move alpha = best_score return best_score, best_move @staticmethod def alphabeta_turn(chessboard, depth, alpha, beta): best_score = beta enemy = Side.White if chessboard.turn == Side.White: enemy = Side.Black best_score = alpha if depth == 0 or chessboard.is_king_dead(chessboard.turn): return ChessComputer.evaluate_board(chessboard, depth) for move in chessboard.legal_moves(): new_chessboard = chessboard.make_move(move) score = ChessComputer.alphabeta_turn(new_chessboard, depth - 1, alpha, beta) if enemy == Side.White and score < best_score: if score <= alpha: return alpha best_score = score beta = best_score elif enemy == Side.Black and score > best_score: if score >= beta: return beta best_score = score alpha = best_score return best_score # Calculates the score of a given board configuration based on the # material left on the board. Returns a score number, in which positive # means white is better off, while negative means black is better of @staticmethod def evaluate_board(chessboard, depth_left): score = 0 for x in range(8): for y in range(8): piece = chessboard.get_boardpiece((x,y)) if piece and not piece.side: score += piece.worth if piece and piece.side: score -= piece.worth if depth_left: score *= depth_left return score # This class is responsible for starting the chess game, playing and user # feedback class ChessGame: def __init__(self, turn): # NOTE: you can make this depth higher once you have implemented # alpha-beta, which is more efficient self.depth = 6 self.chessboard = ChessBoard(turn) # If a file was specified as commandline argument, use that filename if len(sys.argv) > 1: filename = sys.argv[1] else: filename = "board.chb" print("Reading from " + filename + "...") self.load_from_file(filename) def load_from_file(self, filename): with open(filename) as f: content = f.read() self.chessboard.load_from_input(content) def main(self): while True: print(self.chessboard) # Print the current score score = ChessComputer.evaluate_board(self.chessboard, 0) print("Current score: " + str(score)) # Calculate the best possible move new_score, best_move = self.make_computer_move() if best_move == '': # Recognise a tie. break print("Best move: " + best_move) print("Score to achieve: " + str(new_score)) print("") self.make_human_move() print('No further moves possible.') print('The game is a tie.') sys.exit(0) def make_computer_move(self): print("Calculating best move...") return ChessComputer.computer_move(self.chessboard, self.depth, alphabeta=True) def make_human_move(self): # Endlessly request input until the right input is specified while True: if sys.version_info[:2] <= (2, 7): move = raw_input("Indicate your move (or q to stop): ") else: move = input("Indicate your move (or q to stop): ") if move == "q": print("Exiting program...") sys.exit(0) elif self.chessboard.is_legal_move(move): break print("Incorrect move!") self.chessboard = self.chessboard.make_move(move) # Exit the game if one of the kings is dead if self.chessboard.is_king_dead(Side.Black): print(self.chessboard) print("White wins!") sys.exit(0) elif self.chessboard.is_king_dead(Side.White): print(self.chessboard) print("Black wins!") sys.exit(0) chess_game = ChessGame(Side.White) chess_game.main()
9eeb6c0c410e9979b6a02546f15fefdc297dd610
vaishnavi-ui/event-database-management
/Members.py
3,661
3.859375
4
from tkinter import * import sqlite3 connection = sqlite3.connect("Event_Management.db") conn= connection.cursor() def creatingTableCommitteeMembers(): global name,emailID,phoneNo,birthdate,course,branch,year,position,doj,cid #Creating table if it is not present conn.execute("CREATE TABLE IF NOT EXISTS MEMBERS(M_ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT NOT NULL,PHONE_NO INTEGER, DOB DATE,COURSE TEXT,BRANCH TEXT,YEAR INTEGER,POSITION TEXT,DOJ DATE,C_ID INTEGER,FOREIGN KEY (C_ID) REFERENCES COMMITTEE(C_ID))") #Inserting values to table conn.execute("INSERT INTO MEMBERS(NAME,PHONE_NO,DOB,COURSE,BRANCH,YEAR,POSITION,DOJ,C_ID) VALUES(?,?,?,?,?,?,?,?,?)",(name.get(),phoneNo.get(),birthdate.get(),course.get(),branch.get(),year.get(),position.get(),doj.get(),cid.get())) conn.execute("INSERT INTO COMMITTEE_MEMBERS(M_ID,C_ID) VALUES (?,?)",(conn.lastrowid,cid.get())) #Permanently saving the data to the database connection.commit() #Displaying the data on shell for convenince of user conn.execute("SELECT * FROM MEMBERS") for row in conn.fetchall(): print(row) def MembersGUI(): global name,emailID,phoneNo,birthdate,course,branch,year,position,doj,cid #Setting window dimensions t=Tk() t.title("Committee Members") t.geometry("500x370") t.configure(bg="black") l1=Label(t,text="Committee Members Details",font="Times 20 bold underline",bg="black",foreground="snow") l1.grid(row=0,column=0) #Defining LAbels Lname=Label(t,text="NAME",bg="black",foreground="snow",font="Baskerville 12 bold") LemailID=Label(t,text="EMAIL ID",bg="black",foreground="snow",font="Baskerville 12 bold") LphoneNo=Label(t,text="PHONE NUMBER",bg="black",foreground="snow",font="Baskerville 12 bold") Lbirthdate=Label(t,text="BIRTHDATE",bg="black",foreground="snow",font="Baskerville 12 bold") Lcourse=Label(t,text="COURSE",bg="black",foreground="snow",font="Baskerville 12 bold") Lbranch=Label(t,text="BRANCH",bg="black",foreground="snow",font="Baskerville 12 bold") Lyear=Label(t,text="YEAR",bg="black",foreground="snow",font="Baskerville 12 bold") Lposition=Label(t,text="POSITION",bg="black",foreground="snow",font="Baskerville 12 bold") Ldoj=Label(t,text="DATE OF JOINING",bg="black",foreground="snow",font="Baskerville 12 bold") Lcid=Label(t,text="COMMITTEE ID",bg="black",foreground="snow",font="Baskerville 12 bold") #Defining Entry Boxes name=Entry(t) emailID=Entry(t) phoneNo=Entry(t) birthdate=Entry(t) course=Entry(t) branch=Entry(t) year=Entry(t) position=Entry(t) doj=Entry(t) cid=Entry(t) #Adding Labels to window Lname.grid(row=1,column=0) LemailID.grid(row=2,column=0) LphoneNo.grid(row=3,column=0) Lbirthdate.grid(row=5,column=0) Lcourse.grid(row=6,column=0) Lbranch.grid(row=7,column=0) Lyear.grid(row=8,column=0) Lposition.grid(row=9,column=0) Ldoj.grid(row=10,column=0) Lcid.grid(row=11,column=0) #Adding Entry box to window name.grid(row=1,column=1) emailID.grid(row=2,column=1) phoneNo.grid(row=3,column=1) birthdate.grid(row=5,column=1) course.grid(row=6,column=1) branch.grid(row=7,column=1) year.grid(row=8,column=1) position.grid(row=9,column=1) doj.grid(row=10,column=1) cid.grid(row=11,column=1) #Recieving and passing all the values bSubmit=Button(t,text="Submit",command=creatingTableCommitteeMembers,font="Times 12 bold",activebackground="red") bSubmit.grid(row=12,column=1)
f5c34164c7d2125bf67f7dc582a4bd2c3fb9b263
wilfredarin/geeksforgeeks
/Graph/depth-first-traversal-for-a-graph.py
309
3.609375
4
#https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1/ def dfsHelp(g,k,visited): visited[k] = 1 print(k,end=" ") for i in g[k]: if not visited[i]: dfsHelp(g,i,visited) def dfs(g,N): visited = [0 for i in range(N)] dfsHelp(g,0,visited)
f503f1063ed794e9924a882b6ad5203e8e43380e
ivkumar2004/Python
/sample/compareTheTriplets.py
2,309
4.03125
4
''' Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]). The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2]. If a[i] > b[i], then Alice is awarded 1 point. If a[i] < b[i], then Bob is awarded 1 point. If a[i] = b[i], then neither person receives a point. Comparison points is the total points a person earned. Given a and b, determine their respective comparison points. Example a = [1, 2, 3] b = [3, 2, 1] For elements *0*, Bob is awarded a point because a[0] . For the equal elements a[1] and b[1], no points are earned. Finally, for elements 2, a[2] > b[2] so Alice receives a point. The return array is [1, 1] with Alice's score first and Bob's second. Function Description Complete the function compareTriplets in the editor below. compareTriplets has the following parameter(s): int a[3]: Alice's challenge rating int b[3]: Bob's challenge rating Return int[2]: Alice's score is in the first position, and Bob's score is in the second. Input Format The first line contains 3 space-separated integers, a[0], a[1], and a[2], the respective values in triplet a. The second line contains 3 space-separated integers, b[0], b[1], and b[2], the respective values in triplet b. Constraints 1 ≤ a[i] ≤ 100 1 ≤ b[i] ≤ 100 ''' #!/bin/python3 import math import os import random import re import sys # Complete the compareTriplets function below. def compareTriplets(a, b): lstResult = [0,0] for index,aValue in enumerate(a): bValue = b[index] if aValue == bValue: continue if aValue>bValue: lstResult[0] += 1 else: lstResult[1] += 1 return lstResult if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) result = compareTriplets(a, b) print(' '.join(map(str, result))) #fptr.write(' '.join(map(str, result))) #fptr.write('\n') #fptr.close()
fa32aa46ca44bb1699e8721aaacd7d67ff7e4626
bettybub/depaul
/CSC401/CSC401_final_P2.py
433
3.734375
4
''' CSC 401: Final exam Problem 2: Recursion - 25pts ''' s = "h e l l o" length = len(s) counter = 0 for i in range(0, length): if s[i] == " ": counter += 1 print("non-recursive: ", counter) ##### def spaces(s): length = len(s) if length == 1: # base case return 0 else: return (1 if s[0] == " " else 0) + spaces(s[1:]) print("recursive ",spaces(s))
2329eca7de9808affbadb0ba515d90a29d9ad92e
subodhss23/python_small_problems
/medium_problems/emphasis_the_words.py
617
4.09375
4
''' The challenge is to create the functionality of the title() method into a function called emphasise(). The title() method capitalises the first letter of every word and lowercases all of the other letters in the word.''' def emphasise(txt): new_lst = txt.split(' ') result_lst = [] if len(txt) == 0: return '' else: for i in range(len(new_lst) ): result_lst.append(new_lst[i][0].capitalize() + new_lst[i][1:].lower()) return (' ').join(result_lst) print(emphasise("hello world")) print(emphasise("GOOD MORNING")) print(emphasise("99 red balloons!"))
e21d4522a2c9da602205a7def3f6666e5ccee2da
mcampo2/python-exercises
/chapter_02/exercise_13.py
379
4.25
4
#!/usr/bin/env python3 # (Split digits) Write a program that prompts the user to enter a four-digit integer # and displays the number in reverse order. Here is a sample run: # Enter an integer: 3125 [Enter] # 3 # 1 # 2 # 5 number = eval(input("Enter an integer: ")) print(number // 1000) print(number % 1000 // 100) print(number % 100 // 10) print(number % 10 // 1)
67f1db517ea7670d5fc1eaad617de3acf3b5a391
CatalinAtanase/Hero-Game
/gameplay/utils.py
1,150
3.671875
4
import time # Check if the game is done def is_done(hero, beast, turn_number): return False if hero.health > 0 and beast.health > 0 and turn_number <= 20 else True def print_turn_number(turn_number): print(f''' ================================ TURN #{turn_number} ================================''' ) def game_intro(): print(''' ================================ WELCOME TO EMAGIA!!! ================================''' ) # Print the winner at the end of the game def declare_winner(hero, beast): winner = None if (hero.health > beast.health) and beast.health <= 0: winner = hero.name elif (hero.health < beast.health) and hero.health <= 0: winner = beast.name if winner: print(f''' ================================ The winner is {winner}!!! ================================''' ) else: print(f''' ================================ There's no winner. It's a draw. ================================''' ) def load_round(): input("\nPress enter to continue...")
4b0beabab52a04774e46a610bbb531f40dff238f
sdksfo/leetcode
/easy_20. Valid Parentheses.py
352
3.6875
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ hashmap, stack = {')': '(', '}':'{', ']': '['}, [] for char in s: if stack and hashmap.get(char, None) == stack[-1]: stack.pop() else: stack.append(char) return not stack
0debb8746e087a3dc773822aa9f483a035ea710a
noesterle/DailyProgrammerChallenges
/BlackJack/play.py
9,243
3.625
4
__author__ = 'nathan' import random class Player: def __init__(self, num): self.id = num self.hand = [] self.in_game = True self.busted = False def __str__(self): return self.id def print_deck(deck): for item in deck: string="" suit = "" if item % 4 == 0: suit = "Hearts" elif item % 4 == 1: suit = "Clubs" elif item % 4 == 2: suit = "Diamonds" elif item % 4 == 3: suit = "Spades" face = (item%13)+2 if face == 14: print(item, ":", "Ace of " + suit) elif face == 11: print(item, ":", "Jack of " + suit) elif face == 12: print(item, ":", "Queen of " + suit) elif face == 13: print(item, ":", "King of " + suit) else: print(item, ":", face, "of " + suit) def show_hand(person, game_over): string="" n = 0 for item in person.hand: suit = "" if item % 4 == 0: suit = "Hearts" elif item % 4 == 1: suit = "Clubs" elif item % 4 == 2: suit = "Diamonds" elif item % 4 == 3: suit = "Spades" face=((item%13)+2) if face == 14: face = "Ace" elif face == 13: face = "King" elif face == 12: face = "Queen" elif face == 11: face = "Jack" if person.id != USER and not game_over: if n == 0: string += "?, " n = 1 else: string+= str(face)+" of "+ suit +", " else: string+= str(face)+" of "+ suit +", " return string[:-2] def sum_hand(person,game_over): if person.id == USER or game_over: hand_value = 0 for card in person.hand: points = ((card % 13) + 2) if points > 13: hand_value += 11 elif points > 10: hand_value += 10 else: hand_value += points #for item in ACE: # if item in person.hand and hand_value > 21: # #You have an ace, and would bust if it counts as 11 points. num_aces = any_aces(person) while num_aces > 0 and hand_value > 21: hand_value -= 10 num_aces -= 1 return hand_value return "?" def hit(deck, person): new_card = deck.pop() person.hand.append(new_card) if (sum_hand(person,True) > 21): #print("BUST") person.busted = True person.in_game = False #return hand def stand(person): person.in_game = False #return in_game def double_down(): pass def split(): pass def surrender(): pass def deal(deck,players): for person in all_players: hit(deck,person) hit(deck, person) def view(players,game_over): for person in players: if person.id != DEALER: print("Player "+ str(person.id) + "\tHand value", sum_hand(person,game_over), "\tHand:", show_hand(person,game_over)) else: print("Dealer \tHand value", sum_hand(person,game_over), "\tHand:", show_hand(person,game_over)) def any_aces(player): ACE = [12,25,38,51] return len(set(ACE).intersection(player.hand)) def play(deck,players): player_num = 0 #Give every player a turn. while player_num < len(players): #print("Take a turn, player",player_num) #Make sure the player didn't bust. #if sum_hand(players[player_num],True) < 22: if((players[player_num].in_game)): #print("Player is in game.") #User's turn. if players[player_num].id == USER: #print("Player is user") view(players,False) action = "" #User decides what to do. while action.lower() != "hit" and \ action.lower() != "stand" and \ action.lower() != "double down" and \ action.lower() != "split" and \ action.lower() != "surrender": action = str(input("What would you like to do? You can 'hit' or 'stand'. ")) if action.lower() == 'hit': hit(deck,players[player_num]) elif action.lower() == 'stand': stand(players[player_num]) player_num += 1 elif action.lower() == 'double down': double_down() player_num += 1 elif action.lower() == 'split': split() player_num += 1 elif action.lower() == 'surrender': surrender() player_num += 1 #Dealer follows soft-hit rules #print("Dealer is player number",DEALER) #Dealer's turn. elif players[player_num].id==DEALER: #print("Player is dealer") score=(sum_hand(players[player_num],True)) #print("Dealer is playing.") if score < 17: hit(deck,players[player_num]) #print("Dealer hit with score less than 17") elif score == 17: num_aces = any_aces(players[player_num]) if num_aces > 0: hit(deck,players[player_num]) #print("Dealer hit with a soft 17") else: stand(players[player_num]) else: stand(players[player_num]) player_num += 1 #print("Dealer stands") #Other player's turn. else: #print("PLayer is bot") #Automated player plays if random.randint(0,22) > sum_hand(players[player_num],True): hit(deck,players[player_num]) else: stand(players[player_num]) player_num += 1 #Over 21 points. else: print("Player "+str(player_num)+" BUSTED") stand(players[player_num]) player_num += 1 #print(player_num) def players_playing(players): """ Determines if any players are currently playing. """ x = False for person in players: if person.in_game == True: x = True return x def winning(players): """ Prints out the result of each player vs Dealer. """ dealer_score = sum_hand(players[DEALER],True) #print("Is Dealer still in?",players[DEALER].busted) #print(players[DEALER].hand) for person in players: if person.id != DEALER: #print("Is player still in?",person.busted) player_score = sum_hand(person,True) if (players[DEALER].busted and not person.busted): print("PLayer",str(person.id),"beat the dealer, who busted!") elif dealer_score < player_score <= 21: if person.id == USER: print("You beat the dealer with a score of "+ str(player_score)+"!") else: print("Player " + str(person.id)+ " beat the dealer with a score of " + str(player_score) + "!") else: if person.id == USER: busted = "" if player_score > 21: busted = "You busted! " print(busted + "Better luck next time!") else: print("The dealer beat Player " + str(person.id)) if __name__ == '__main__': play_again = 0 while play_again == 0: #Set up deck. deck = [] for i in range(0, 52): deck.append(i) #print_deck(deck) #print("This is the deck.") random.shuffle(deck) #Game info from user. num_decks = 0 num_players = -1 while num_decks < 1: num_decks = int(input("How many decks do you want to play with? ")) deck *= num_decks while num_players < 0: num_players = int(input("How many other players are there? ")) + 1 DEALER = num_players USER = 0 #Setting up players and hands. x = 0 all_players = [] print("CREATING PLAYERS") while x < num_players + 1: person = Player(x) all_players.append(person) x += 1 print("DEALING") deal(deck, all_players) x = players_playing(all_players) #Play Game play(deck,all_players) print("GAME OVER") #View results (Score, Hand, won/lost to delaer.) view(all_players,True) winning(all_players) #Play again? again ="" while (again.lower()!="y" and again.lower()!="n"): again = input("Would you like to play again? (y/n)") if again.lower() == "y": play_again = 0 else: play_again = 1
056dd61e5807647c03bea850e400b1d21df5d848
GospodinJovan/raipython
/Easy Unpac.py
468
4.125
4
""""" Your mission here is to create a function that gets an tuple and returns a tuple with 3 elements - first, third and second to the last for the given array Input: A tuple, at least 3 elements long. Output: A tuple. easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7) easy_unpack((1, 1, 1, 1)) == (1, 1, 1) easy_unpack((6, 3, 7)) == (6, 7, 3)""""" def easy_unpack(t): tup2 = (t[0],t[2], t[-2]) return (tup2) beisp=(6,3,7) print (easy_unpack(beisp))
77c234abc65dc3f1c72da5efa699d2d4fdafa8b2
hjkim/hello-python
/BJ_2588.py
225
3.703125
4
# input은 입력되는 모든 것을 문자열로 취급한다. a = int(input()) b = input() #print(a[0], a[1], a[2]) m1 = a*int(b[2]) m2 = a*int(b[1]) m3 = a*int(b[0]) print(m1) print(m2) print(m3) print(m1+m2*10+m3*100)
ca8a15c8fdf092cbbc60a2f980ada86bcadab2ed
mig4/pygiggle
/src/pygiggle/hackerrank/alphabet_rangoli.py
941
3.6875
4
"""Alphabet Rangoli challenge from HackerRank.""" import string def rangoli(size: int) -> str: """Return an Alphabet Rangoli of specified [size].""" assert size <= len(string.ascii_lowercase) letters = string.ascii_lowercase[:size] mid_row = size num_rows = size * 2 - 1 rangoli_lines = [] for row in range(1, num_rows + 1): distance_from_mid = abs(mid_row - row) row_letters_right = letters[distance_from_mid:] # letters on the left are same as all but first on right reversed row_letters = ( list(reversed(row_letters_right[1:])) + list(row_letters_right) ) # pad row letters to size using `-` padding = ["-"] * (size - len(row_letters_right)) if padding: row_letters = padding + row_letters + padding row_str = "-".join(row_letters) rangoli_lines.append(row_str) return "\n".join(rangoli_lines)
6cbb58a5d6a1c6252552bd4aecd2d99b40863979
trorter/Test2_oy
/test/test_5.py
404
4.03125
4
fname = input("Enter file name: ") try: cfile = open(fname) except: print("File not found") quit() listofwords = list() for line in cfile: if not line.startswith("From"): continue if '2008' not in line: continue listofwords.append(line.split()[1]) for line in listofwords: print(line) print("\nThere were", len(listofwords), "lines in the file with From as the first word")
b6aab15cdb24c02f5594acd2cb26b25fcee0a137
ivekhov/python-project-lvl1
/brain_games/games/calc.py
822
3.953125
4
"""Game of brain-calc.""" import operator import random DESCRIPTION = 'What is the result of the expression?' OPERATORS = ('+', '-', '*') RANDOM_FROM = 1 RANDOM_TO = 25 def get_question_and_answer() -> (str, str): """ Get answer from user and calculate correct answer. Returns: str: question for user. str: correct answer. """ first = random.randint(RANDOM_FROM, RANDOM_TO) operation = random.choice(OPERATORS) second = random.randint(RANDOM_FROM, RANDOM_TO) if operation == '+': correct = operator.add(first, second) elif operation == '-': correct = operator.sub(first, second) elif operation == '*': correct = operator.mul(first, second) question = ' '.join([str(first), operation, str(second)]) return question, str(correct)
461bdfa4ba6c5641fa2e543282ba3b877d4a1649
vzhz/NYCtechtalentapplication
/decodeStrings.py
436
3.984375
4
###### # Question 2 -- decodeString(s): Given an encoded string, return its corresponding decoded # string. # # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets # is repeated exactly k times. Note: k is guaranteed to be a positive integer. # # For s = "4[ab]", the output should be decodeString(s) = "abababab" # For s = "2[b3[a]]", the output should be decodeString(s) = "baaabaaa" ######
f32e0c370a54961fefbac2dd0f77674f55bfd392
inderpal2406/python
/practice_programs/scripts/file_extension.py
1,468
4.375
4
#!/usr/bin/env python3 ############################################################################### # File : file_extension.py # Author : Inderpal Singh Saini <inderpal2406@gmail.com> # Created : 07 Nov, 2020 # Updated : 07 Nov, 2020 # Description : A script to accept a filename from the user and print the extension of that. # : The enhancement to enable the script to detect no file extension needs to be added. # : Maybe we can use str.rsplit(sep=".", maxsplit=1) function to add the enhancement. ################################################################################ # Import modules import os import platform import sys # Detect the OS and clear the screen accordingly. if platform.system()=="Windows": os.system("cls") elif platform.system()=="Linux": os.system("clear") else: print(f"The operating system couldn't be detected. Exiting script!") # Display purpose of script. print(f"The script will accept a filename and print its extension.") # Accept user input for filename with extension filename=input("Please enter the filename, (for example: name.txt): ") # Split the input filename based on dot/period as a delimiter . tmplist=filename.split(".") # The extension will be the last element of the list. extension=tmplist[-1] # Print the extension. print(f"The extension of file is: {extension}") # Single line implementation of above code is as below, #print(f"The extension of file is: {filename.split('.')[-1]}")
ce6fce0048748c1264460e8ab3c50685af032d4a
thekingslayer9794/Matrix-Calculator
/matrixMultiplication.py
1,844
4.46875
4
# Program to multiply two matrices using nested loops matrix1 =[] matrix2 = [] result = [] #function for taking user input of matrix. def matrixInput(R,C,matrix): print("Enter the entries rowwise:") for i in range(R): a =[] for j in range(C): a.append(int(input())) matrix.append(a) #function to make resultant matrix def matrixOutput(R,C,matrix): for i in range(R): a =[] for j in range(C): a.append(0) matrix.append(a) #function to calculate product of two matrix def prodOutput(X,Y,result): for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] #getting user's input for rows and columns for matrix 1. mat1_row = int(input ("Enter number of rows in matrix 1:")) mat1_col = int(input ("Enter number of columns in matrix 1:")) #getting user's input for rows and clumns for matrix 2. mat2_row = int(input ("Enter number of rows in matrix 2:")) mat2_col = int(input ("Enter number of columns in matrix 2:")) # for m*n and n*p if (mat1_col == mat2_row): print("For First Matrix:") matrixInput(mat1_row,mat1_col,matrix1) print("For Second Mtrix:") matrixInput(mat2_row,mat2_col,matrix2) print("Please verify both matrix :") print("matrix 1:",matrix1) print("matrix 2:",matrix2) a = input("press Y if correct else N:") if (a == 'Y'or a=='y'): matrixOutput(mat1_row,mat2_col,result) prodOutput(matrix1,matrix2,result) print(result) elif (a=='N' or a=='n'): print("please run the script once again") print("script is being terminated") else: print("Please enter the same no of columns and row in both matrix")
621ab604f55b1efa819b2ef09176389adb082a90
mikaelshall/python-challenge2
/PyBank/PyBank.py
1,862
3.5625
4
# Import Modules/Dependencies import os import csv #Files to load infile = os.path.join('/Users/mikaelshall/Desktop/unc-peace-data-pt-08-2020-u-c/02-Homework/02-Python/Instructions/PyBank/Resources/budget_data.csv') outfile = os.path.join("analysis", "pybank.txt") monthsTotal = 0 netTotal = 0 previousBudget = 0 changeTotal = 0 greatestIncrease = 0 greatestDecrease = 0 greatestIncreaseDate = "" greatestDecreaseDate = "" with open(infile) as csvFile: # print(csvFile.readline()) # csv_header = next(rows) csvFile.readline() rows = csv.reader(csvFile) changeCount = 0 change = 0 for row in rows: monthsTotal += 1 currentBudget = int(row[1]) netTotal += currentBudget if previousBudget != 0: change = currentBudget - previousBudget changeTotal += change changeCount += 1 print(change) previousBudget = currentBudget if change > greatestIncrease: greatestIncrease = change greatestIncreaseDate = row[0] if change < greatestDecrease: greatestDecrease = change greatestDecreaseDate = row[0] print(f"change count: {changeCount}") print(f"total of changes: {changeTotal}") # exit() # print(monthsTotal) # print(netTotal) # print(greatestIncreaseDate,greatestIncrease) # print(greatestDecreaseDate,greatestDecrease) # def print_results(results): # print(results) output = f""" Financial Analysis ---------------------------- Total Months: {monthsTotal} Total: ${netTotal:,} Average Change: ${changeTotal/changeCount:.2f} Greatest Increase in Profits: {greatestIncreaseDate} (${greatestIncrease:,}) Greatest Decrease in Profits: {greatestDecreaseDate} (${greatestDecrease:,}) """ # Call def print_results(results) # print_results(output) print(output)
18751c2a4ba89cb5575ce64ed38195b3c27ac822
zengzhiying/machine_learning
/deep_neural_network/neural_network.py
4,225
3.515625
4
# coding=utf-8 import numpy as np class NeuralNetwork(object): """简单的深度神经网络构建类 实现一个三层的神经网络(两层隐藏层) """ def __init__(self): # 学习速率 (多次调试选择使得损失函数下降最好的值) self.epsilon = 0.0155 # 隐藏层个数 self.hidden_layer_number = 2 # 隐藏层单元个数 self.hidden_number = 4 # 网络总层数 self.L = 3 # 初始化参数缩放倍数 self.init_zoom = 0.01 def train(self, X_train, Y_train, iterations_number=1000): """训练神经网络 Args: X_train: 训练样本集 n*m Y_train: 训练label 1*m iterations_number: 迭代次数 默认:1000 Returns: 直接更新网络参数 无返回值 """ # 随机初始化参数 self.W1 = np.random.randn(self.hidden_number, np.size(X_train, 0)) * self.init_zoom self.b1 = np.zeros((self.hidden_number, 1)) self.W2 = np.random.randn(self.hidden_number, self.hidden_number) * self.init_zoom self.b2 = np.zeros((self.hidden_number, 1)) self.W3 = np.random.randn(1, self.hidden_number) * self.init_zoom self.b3 = np.zeros((1, 1)) # 样本个数m m = X_train.shape[1] # 批量梯度下降 for i in xrange(iterations_number): # 前向传播 Z1 = self.W1.dot(X_train) + self.b1 # 4*n n*m => 4*m A1 = self.relu(Z1) Z2 = self.W2.dot(A1) + self.b2 # 4*4 4*m => 4*m A2 = self.relu(Z2) Z3 = self.W3.dot(A2) + self.b3 # 1*4 4*m => 1*m A3 = self.sigmod(Z3) # 反向传播 dZ3 = A3 - Y_train dW3 = 1.0/m * np.dot(dZ3, np.transpose(A2)) # 1*m m*4 => 1*4 db3 = 1.0/m * np.sum(dZ3, axis=1, keepdims=True) # 1*m => 1*1 dA2 = np.dot(np.transpose(self.W3), dZ3) # 4*1 1*m => 4*m dZ2 = dA2 * self.relu_derive(Z2) # 4*m 4*m => 4*m dW2 = 1.0/m * np.dot(dZ2, np.transpose(A1)) # 4*m m*4 => 4*4 db2 = 1.0/m * np.sum(dZ2, axis=1, keepdims=True) # 4*m => 4*1 dA1 = np.dot(np.transpose(self.W2), dZ2) # 4*4 4*m => 4*m dZ1 = dA1 * self.relu_derive(Z1) # 4*m 4*m => 4*m dW1 = 1.0/m * np.dot(dZ1, np.transpose(X_train)) # 4*m m*n => 4*n db1 = 1.0/m * np.sum(dZ1, axis=1, keepdims=True) # 4*n => 4*1 # 梯度下降更新参数 self.W1 -= self.epsilon * dW1 self.b1 -= self.epsilon * db1 self.W2 -= self.epsilon * dW2 self.b2 -= self.epsilon * db2 self.W3 -= self.epsilon * dW3 self.b3 -= self.epsilon * db3 if i % 10 == 0: print("迭代次数: %d loss: %g" % ((i + 1), self.loss_calculate(X_train, Y_train))) def loss_calculate(self, X, Y): """损失函数计算""" Z1 = self.W1.dot(X) + self.b1 A1 = self.relu(Z1) Z2 = self.W2.dot(A1) + self.b2 A2 = self.relu(Z2) Z3 = self.W3.dot(A2) + self.b3 A3 = self.sigmod(Z3) m = Y.shape[1] loss = -1.0/m * np.sum(Y * np.log(A3) + (1 - Y) * np.log(1 - A3)) return loss def predict(self, x): """对输入样本进行预测""" z1 = self.W1.dot(x) + self.b1 # 4*n n*1 => 4*1 a1 = self.relu(z1) z2 = self.W2.dot(a1) + self.b2 # 4*4 4*1 => 4*1 a2 = self.relu(z2) z3 = self.W3.dot(a2) + self.b3 # 1*4 4*1 => 1*1 a3 = self.sigmod(z3) return a3 def relu(self, x): """激活函数: ReLU 修正线性单元 """ return np.maximum(0, x) def sigmod(self, x): """输出层激活函数: sigmod""" return 1 / (1 + np.exp(-x)) def relu_derive(self, x): """ReLU函数导数""" x_copy = np.array(x) x_copy[x_copy >= 0] = 1 x_copy[x_copy < 0] = 0 return x_copy
0742a26aad010561814d33ef7952980b6a0a6a5f
ScatterBrain-I/MCLAPython
/2_SongCreator/2_PeterSongCreator.py
1,573
3.921875
4
# Program by Peter Niemeyer 2017/07/14 # MCLA Python / Mark Cohen # This program: # Gets inputs from user: 4 verses, a chorus, a repeat factor # Assembles inputs into list: V.1, Cx, V.2, Cx, V.3, Cx, V.4, Cx+1 all x2 # LEVEL-UP: # Verses are CAPITALIZED # Choruses are lowercased # A forbidden word 'cookies' is blocked out import NEMO # Mod file: 'userString', 'userInt' used # Gets input from user: 4 verseres --> assigns them to list 'versesNew' # Converts to Uppercase verses = ['first', 'second', 'third', 'fourth'] versesNew = [] for verse in verses: verse = NEMO.userString ("Enter the %s verse:" % verse) versesNew.append (verse.upper()) # Gets input from user: chorus and repeat factor ---> converts to lowercase chorus = NEMO.userString ("Enter the chorus:") chorus = chorus.lower() repeat = NEMO.userInt ("Enter the chorus repeat:") # Using list 'song', the verses from 'versesNew' are woven with the choruses song = [] for verse in versesNew: song.append (verse) song.append ((chorus + " ") * repeat) # Chorus #4 (located in index 7 is to be +1 of the repeat factor # song is to repeat (x2) but the extra "one more time" needs to be deleted # prints the song in it's list form song[7] = ((chorus + " ") * (repeat+1)) song.append('...one more time!...') song = song * 2 del song[17] print song print # prints song formatted properly while removing all occurances of the forbidden # word regardless of location in verse or chorus for versesChorus in song: print versesChorus.replace('COOKIES', '_______').replace('cookies', '_______')