blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1cf33f7de27fbe732b35bae1546c82d8556928a0
rebeccasmile1/algorithm
/homework1/test2.py
3,409
3.546875
4
def MaxmalRectangle(matrix): h = [] matrix2 = [] for i in range(0, len(matrix[0])): # 列 h.append(0) m = len(matrix) # 行数 n = len(matrix[0]) # 列数 print(m, n) max = 0 for i in range(0, m): h = [] for j in range(0, n): if i == 0: h.append(matrix[i][j]) else: if matrix[i][j] == 0: h.append(0) else: h.append(matrix[i - 1][j] + 1) matrix2.append(h) return max if __name__ == '__main__': matrix = [] temp_list = [] max = 0 while True: row = [] temp_list = input().split() if not temp_list: break # print(temp_list) for e in temp_list: row.append(int(e)) matrix.append(row) print(matrix) print(MaxmalRectangle(matrix)) # # # 全为1的,最大子矩阵中1的个数 # ''' # 1 0 1 1 # 1 1 1 1 # 1 1 1 0 # # # # ''' # import sys # # # def MaxmalRectangle(matrix): # h = [] # # for i in range(0, len(matrix[0])): # 列 # h.append(0) # m = len(matrix) # 行数 # n = len(matrix[0]) # 列数 # max = 0 # mat=[] # for i in range(0,m): # mat.append(matrix[i]) # # for i in range(0, m): # for j in range(0, n): # if i == 0: # h.append(matrix[i][j]) # else: # if matrix[i][j] == 0: # h.append(0) # else: # h.append(matrix[i - 1][j] + 1) # temp=LargestRecArea(h) # if temp>max: # max = temp # return max # # # def LargestRecArea(height): # if len(height) == 0: # return 0 # i = 1 # max = height[0] # stack = [] # # stack.append(0) # while i < len(height) or (i == len(height) and len(stack) > 0): # if i != len(height) and (len(stack) == 0 or height[i] > height[stack[-1]]): # stack.append(i) # i=i+1 # else:#弹出栈中大的 # top = height[stack.pop()] # if len(stack) > 0: # currMax = top * (i - stack[-1] - 1) # else: # currMax = top * i # if currMax>max: # max=currMax # # print(stack) # # # return max # # # # # def MaxmalRectangle2(matrix): # h = [] # matrix2=[] # for i in range(0, len(matrix[0])): # 列 # h.append(0) # m = len(matrix) # 行数 # n = len(matrix[0]) # 列数 # # print(m,n) # max = 0 # for i in range(0, m): # h = [] # for j in range(0, n): # if i == 0: # h.append(matrix[i][j]) # else: # if matrix[i][j] == 0: # h.append(0) # else: # h.append(matrix[i - 1][j] + 1) # matrix2.append(h) # # # for i in range(1,len(matrix2)): # return max # # if __name__ == '__main__': # matrix = [] # temp_list = [] # max = 0 # # while True: # # row = [] # temp_list = input().split() # if not temp_list: # break # # print(temp_list) # for e in temp_list: # row.append(int(e)) # matrix.append(row) # # print(matrix) # print(MaxmalRectangle(matrix))
85b70782db50a99ad55fc86179a6e5585b9185a7
marco-zietzling/advent-of-code-2020
/day12/day12.py
2,548
3.90625
4
print("advent of code 2020 - day 12") directions = ["N", "E", "S", "W"] current_ship_dir_index = 1 current_ship_pos_x1 = 0 current_ship_pos_y1 = 0 current_ship_pos_x2 = 0 current_ship_pos_y2 = 0 current_waypoint_pos_x = 10 current_waypoint_pos_y = 1 instructions = [] with open("input.txt") as file: for line in file: line = line.strip() instructions.append((line[:1], int(line[1:]))) def rotate_waypoint(rotation): global current_waypoint_pos_x global current_waypoint_pos_y old_x = current_waypoint_pos_x old_y = current_waypoint_pos_y if rotation == -1 or rotation == 3: current_waypoint_pos_x = - old_y current_waypoint_pos_y = old_x elif rotation == -2 or rotation == 2: current_waypoint_pos_x = - old_x current_waypoint_pos_y = - old_y elif rotation == -3 or rotation == 1: current_waypoint_pos_x = old_y current_waypoint_pos_y = - old_x else: print(f"unknown rotation encountered: {rotation}") for action, value in instructions: if action == "N": current_ship_pos_y1 += value current_waypoint_pos_y += value elif action == "S": current_ship_pos_y1 -= value current_waypoint_pos_y -= value elif action == "E": current_ship_pos_x1 += value current_waypoint_pos_x += value elif action == "W": current_ship_pos_x1 -= value current_waypoint_pos_x -= value elif action == "L": current_ship_dir_index = (current_ship_dir_index - (value // 90)) % 4 rotate_waypoint(- (value // 90)) elif action == "R": current_ship_dir_index = (current_ship_dir_index + (value // 90)) % 4 rotate_waypoint((value // 90)) elif action == "F": if directions[current_ship_dir_index] == "N": current_ship_pos_y1 += value elif directions[current_ship_dir_index] == "S": current_ship_pos_y1 -= value elif directions[current_ship_dir_index] == "E": current_ship_pos_x1 += value elif directions[current_ship_dir_index] == "W": current_ship_pos_x1 -= value current_ship_pos_x2 += value * current_waypoint_pos_x current_ship_pos_y2 += value * current_waypoint_pos_y else: print(f"invalid action: {action}") # result = 1441 print(f"part 1: distance to origin = {abs(current_ship_pos_x1) + abs(current_ship_pos_y1)}") # result = 61616 print(f"part 2: distance to origin = {abs(current_ship_pos_x2) + abs(current_ship_pos_y2)}")
984662890c19916591461f9e3e953ed05281f8b8
sripathyfication/bugfree-octo-dangerzone
/techie-delight/sockets/echo_server.py
1,491
3.9375
4
#/usr/bin/python ''' A simple tcp server/client application socket is an ipaddress/port. Server operations: create socket bind to serveraddress(ip,port) listen(1) recv sendall close ''' import socket import sys class Server: def __init__(self,ip_address,port): print " Setting up tcp server.." self.ip_address = ip_address self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_address = (self.ip_address,self.port) self.sock.bind(self.server_address) def start(self): self.sock.listen(1) while True: print >>sys.stderr," waiting for a connection" connection,client_address = self.sock.accept() try: print sys.stderr," accepted connection from ", client_address while True: data = connection.recv(16) print >>sys.stderr, ".. got data::", data if not data: print >>sys.stderr, "..no data from client ", client_address break else: connection.sendall(data) print >>sys.stderr, ".. sending data back" break finally: connection.close() if __name__ == '__main__': server = Server('localhost',10001) server.start()
7247c6980220808b6d9ff0b4f2edb619575e1ee7
DevParapalli/SchoolProjects_v2
/33_sum_diagonals_matrix.py
1,143
4.25
4
"Write a Program to showSum of Diagonals (major and minor) in Two Dimensional List" MATRIX = [] def create_matrix(): global MATRIX row_n = int(input("Enter Dimension (Square Matrix Only):")) for i in range(row_n): MATRIX.append([]) # add new row for j in range(row_n): MATRIX[i].append(int(input(f"Enter Value for ROW {i} COL {j}: "))) # print the matrix for row in MATRIX: print(row) def calc_diagonals(): global MATRIX primary_diag = 0 secondary_diag = 0 _len = len(MATRIX) for i in range(_len): primary_diag += MATRIX[i][i] secondary_diag += MATRIX[i][_len - i - 1] return primary_diag, secondary_diag def main(): create_matrix() diag_p, diag_s = calc_diagonals() print(f"Primary Diagonal: {diag_p} \nSecondary Diagonal: {diag_s}") if __name__ == "__main__": main() __OUTPUT__ = """ Enter Dimension (Square Matrix Only):2 Enter Value for ROW 0 COL 0: 1 Enter Value for ROW 0 COL 1: 2 Enter Value for ROW 1 COL 0: 3 Enter Value for ROW 1 COL 1: 4 [1, 2] [3, 4] Primary Diagonal: 5 Secondary Diagonal: 5 """
21e65ea4897ba065108f685e84c576f58942506a
zhanary/leetcode-python
/0083-28ms.py
572
3.765625
4
In Python, every value is a reference, you can say a pointer, to an object. Objects cannot be values. Assignment always copies the value; two such pointers point to the same object. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): cur = head while cur: while cur.next and cur.next.val == cur.val: cur.next = cur.next.next cur = cur.next return head
a160d3f4a86943ca9081c8174e809c98fbfa8184
catechnix/python_1
/generator.py
881
4.34375
4
""" *a function become a generator if it contains a yield *generators return a generator object when called *no code is executed when a generator is called *iterating (or calling next() on the generator object executes all the code until the first yield *once the yield is reached, the execution is paused and a value is returned. *when another value is requested and the execution is resumed and the code executed until the next yield *once the end of the function is reached, StopIteration is raised to signal that there are no more values def gfibo(num): """Generate num fibonacci numbers""" fst, snd = 0, 1 for x in range (num): yield fst fst,snd = snd, fst+snd >>>gfibo(10) generator object ... #no code is executed when calling generator >>>list(_) [0,1,1,2,3,5,8,13,21,34] >>> for f in gfibo(10): print(f,end=' ') 0,1,1,2,3,5,8,13,21,34 """
250f8fa9da16e9fc7beb0eed48ee84536996c940
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/_06_Glob_Example.py
2,011
4.125
4
""" Purpose Use UNIX shell rules to find filenames matching a pattern. look for a list of files on the file system with names matching a pattern. To create a list of filenames that all have a certain extension, prefix, or any common string in the middle """ #Buat folder dan file contoh import os if not os.path.exists("dir/subdir"): os.makedirs("dir/subdir") if not os.path.exists("dir/subfold"): os.makedirs("dir/subfold") for i in ["dir/file.txt", "dir/file1.txt", "dir/file2.txt", "dir/filea.txt" ,"dir/fileb.txt", "dir/subdir/subfile.txt", "dir/subdir/subfile2.txt", "dir/subfold/subfile2.txt"]: if not os.path.exists(i): print i , "= file" folderna = os.path.dirname(i) if not os.path.exists(folderna): os.makedirs(folderna) f = open(i, "w") f.write(i) f.close() #contoh penggunaan glob """ The pattern matches every path name (file or directory) in the directory "dir" tanpa memasukan subdirektory """ import glob print "contoh awal =========================================" for name in glob.glob('dir/*'): print name """ To list files in a subdirectory, the subdirectory must be included in the pattern. """ print "search for subdir =========================================" print 'Named explicitly:' for name in glob.glob('dir/subdir/*'): print '\t', name print 'Named with wildcard:' for name in glob.glob('dir/*/*'): print '\t', name """ A question mark ( ? ) is another wildcard character. It matches any single character in that position in the name. """ print "? wild card =========================================" for name in glob.glob("dir/file?.txt"): print name """ Use a character range ( [a-z] ) instead of a question mark to match one of several characters. This example finds all files with a digit in the name before the extension. """ print "character range =========================================" for name in glob.glob('dir/*[0-9].*'): print name
88f4c10311b0bac17c6111b92b343b50019a09fc
Ashmita-bhattacharya/programming-pancake
/scripts/percentage_calc.py
459
4.25
4
print ("Percentage calculator") print ("---------------------") print ("") m = float(input("Maths: ")) s = float(input("Science: ")) e = float(input("English: ")) print ("") percentage = ( (m + s + e) / 300 ) * 100 print ("Your percentage is ",percentage) if percentage >= 60: print ("You got 1st division") elif percentage >= 45: print ("You got 2nd division") elif percentage >= 30: print ("You got 3rd division") else: print ("You did not clear")
710b2cd95ba46fa4fa15ace554ef41a8fcea0442
CandiceDiao/Candice_Python
/DataStructureForLetcoode/link_structure.py
791
4.28125
4
""" 链表 常用操作 """ ###创建链表 from collections import deque #使用队列创建链表 linkedlist = deque() ###尾部添加元素 #时间复杂度:O(1) linkedlist.append(1) linkedlist.append(2) linkedlist.append(3) ###中间添加元素 #时间复杂度:O(N) linkedlist.insert(2,99) print(linkedlist) ###访问元素 #时间复杂度:O(N) element = linkedlist[2] # 99 print(element) ##搜索元素 #时间复杂度:O(N) index = linkedlist.index(99) #2 print(index) ##更新元素 #时间复杂度:O(N) linkedlist[2]=88 #[1,2,88,3] print(linkedlist) ###删除元素 #时间复杂度:O(N) #删除指定索引处的值 del linkedlist[2] #删除某个值 linkedlist.remove(88) ###长度 #时间复杂度:O(1) length = len(linkedlist)
932d93e11b5e404793a7e0412090867929ccb3aa
ljrdemail/AID1810
/PythonBasic/Day10/execDemo.py
262
3.671875
4
x = 100 y = 200 s = ''' print("hello") z=x+y print(z) #如果你用eval 就不能a=x+y 因为用了赋值表达式 ''' print(exec(s)) print(z) #跑完之后z 也有了 等同于放在代码中直接执行 所以你在里面修改 x y 的话 x y 会受影响
f5d8ade2f73c66905bf39700254f53eedc817bbc
kronkanok/workshop_2
/operators/comparison.py
267
3.984375
4
x = 10 y = 12 print("x > y is", x > y) #output: False print("x < y is", x < y) #output: True print("x == y is", x == y) #output: False print("x != y is", x != y) #output: True print("x >= y is", x >= y) #output: False print("x >= y is", x >= y) #output: True
bc492442f5a52806b9c6c004d2a9822b9d45cb6a
keviv202/Python-Code
/power of 2.py
155
3.984375
4
import math def power(s): if (math.log(s,2).is_integer()): print ("Is power of 2") else: print("It is not power of 2") power(18)
c7aefda49884826dc2e74635ff1e0209dd21d2d1
rainavyas/Phone_Distance_Grader
/convert_legacy_pickle.py
1,133
3.796875
4
''' convert a pickle file saved from python2 into a pickle file that can be read from python3 ''' import pickle import dill def convert(input_file, output_file): # Convert Python 2 "ObjectType" to Python 3 object dill._dill._reverse_typemap["ObjectType"] = object with open(input_file, 'rb') as f: pkl = pickle.load(f, encoding="latin1") pickle.dump(pkl, open(output_file, 'wb')) ''' #input_file = '/home/alta/BLTSpeaking/grd-kk492/mfcc13/GKTS4-D3/grader/BLXXXgrd02/data/BLXXXgrd02.pkl' input_file = '/home/alta/BLTSpeaking/grd-graphemic-vr313/speech_processing/merger/adversarial/gradient_attck_mfcc_model/mypkl.pkl' output_file = '/home/alta/BLTSpeaking/exp-vr313/data/mfcc13/GKTS4-D3/grader/BLXXXgrd02/BLXXXgrd02.pkl' ''' #input_file = '/home/alta/BLTSpeaking/grd-kk492/mfcc13/GKTS4-D3/grader/BLXXXeval3/data/BLXXXeval3.pkl' input_file = '/home/alta/BLTSpeaking/grd-graphemic-vr313/speech_processing/merger/adversarial/gradient_attck_mfcc_model/mypkleval.pkl' output_file = '/home/alta/BLTSpeaking/exp-vr313/data/mfcc13/GKTS4-D3/grader/BLXXXeval3/BLXXXeval3.pkl' convert(input_file, output_file)
8b1f081faa1587e58b291cbd53e159977a86122b
vgaicuks/ethereum-address
/ethereum_address/utils.py
1,020
3.5625
4
import re from Crypto.Hash import keccak def is_checksum_address(address): address = address.replace('0x', '') address_hash = keccak.new(digest_bits=256) address_hash = address_hash.update(address.lower().encode('utf-8')).hexdigest() for i in range(0, 40): # The nth letter should be uppercase if the nth digit of casemap is 1 if ((int(address_hash[i], 16) > 7 and address[i].upper() != address[i]) or (int(address_hash[i], 16) <= 7 and address[i].lower() != address[i])): return False return True def is_address(address): if not re.match(r'^(0x)?[0-9a-f]{40}$', address, flags=re.IGNORECASE): # Check if it has the basic requirements of an address return False elif re.match(r'^(0x)?[0-9a-f]{40}$', address) or re.match(r'^(0x)?[0-9A-F]{40}$', address): # If it's all small caps or all all caps, return true return True else: # Otherwise check each case return is_checksum_address(address)
f08067f1554b6ddcc1f1432125320393ef81e79c
kwasiansah/coffee_machine
/coffee_machine.py
5,060
4.125
4
class MyCoffee: water = 400 milk = 540 beans = 120 dis_cup = 9 money = 550 def __init__(self, user): self.user = user self.es_water = 250 self.es_beans = 16 self.es_money = 4 self.la_water = 350 self.la_milk = 75 self.la_beans = 20 self.la_money = 7 self.ca_water = 200 self.ca_milk = 100 self.ca_beans = 12 self.ca_money = 6 def buy(self): if self.user == "buy": print() print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") cof = input("> ") if cof == "1": if MyCoffee.water < self.es_water: print("Sorry, not enough water!") elif MyCoffee.beans < self.es_beans: print("Sorry, not enough beans!") elif MyCoffee.dis_cup < 1: print("Sorry, not enough disposable cups!") else: MyCoffee.water = MyCoffee.water - self.es_water MyCoffee.beans = MyCoffee.beans - self.es_beans MyCoffee.dis_cup = MyCoffee.dis_cup - 1 MyCoffee.money = MyCoffee.money + self.es_money print("I have enough resources, making you a coffee!") elif cof == "2": if MyCoffee.water < self.la_water: print("Sorry, not enough water!") elif MyCoffee.milk < self.la_milk: print("Sorry, not enough milk!") elif MyCoffee.beans < self.la_beans: print("Sorry, not enough beans!") elif MyCoffee.dis_cup < 1: print("Sorry, not enough disposable cups!") else: MyCoffee.water = MyCoffee.water - self.la_water MyCoffee.milk = MyCoffee.milk - self.la_milk MyCoffee.beans = MyCoffee.beans - self.la_beans MyCoffee.dis_cup = MyCoffee.dis_cup - 1 MyCoffee.money = MyCoffee.money + self.la_money print("I have enough resources, making you a coffee!") elif cof == "3": if MyCoffee.water < self.ca_water: print("Sorry, not enough water!") elif MyCoffee.milk < self.ca_milk: print("Sorry, not enough milk!") elif MyCoffee.beans < self.ca_beans: print("Sorry, not enough beans!") elif MyCoffee.dis_cup < 1: print("Sorry, not enough disposable cups!") else: MyCoffee.water = MyCoffee.water - self.ca_water MyCoffee.milk = MyCoffee.milk - self.ca_milk MyCoffee.beans = MyCoffee.beans - self.ca_beans MyCoffee.dis_cup = MyCoffee.dis_cup - 1 MyCoffee.money = MyCoffee.money + self.ca_money print("I have enough resources, making you a coffee!") def fill(self): if self.user == "fill": print("Write how many ml of water do you want to add:") add_water = int(input("> ")) print("Write how many ml of milk do you want to add:") add_milk = int(input("> ")) print("Write how many grams of coffee beans do you want to add:") add_beans = int(input("> ")) print("Write how many disposable cups of coffee do you want to add:") add_dis = int(input("> ")) MyCoffee.water = MyCoffee.water + add_water MyCoffee.milk = MyCoffee.milk + add_milk MyCoffee.beans = MyCoffee.beans + add_beans MyCoffee.dis_cup = MyCoffee.dis_cup + add_dis MyCoffee.money = MyCoffee.money def take(self): if self.user == "take": print(f"I gave you ${MyCoffee.money}") if MyCoffee.money > 0: MyCoffee.money = MyCoffee.money - MyCoffee.money def remaining(self): if self.user == "remaining": print() print("The coffee machine has:") print(f"{MyCoffee.water} of water") print(f"{MyCoffee.milk} of milk") print(f"{MyCoffee.beans} of coffee beans") print(f"{MyCoffee.dis_cup} of disposable cups") if MyCoffee.money == 0: print(f"{MyCoffee.money} of money") else: print(f"${MyCoffee.money} of money") def main_menu(): global condition print() print("Write action (buy, fill, take, remaining, exit):") user = input("> ") if user == "exit": condition = False main = MyCoffee(user) main.buy() main.fill() main.take() main.remaining() condition = True while condition: main_menu()
3c5d9ae445180b6c591bd19a731fe2d5c4b907e5
fedpre/cse210
/week2-tictactoe/tic-tac-toe.py
7,349
4.1875
4
# Assignment "Tic-Tac-Toe" by Federico Pregnolato # Create a Tic-Tac-Toe game to play in Python import math from typing import Counter def main(): grid_squared = int(input('How many squares do you want on your grid? ')) max_val = grid_squared**2 n_digits = int(math.log10(max_val)) + 1 grid = create_grid(grid_squared) draw_grid(grid, n_digits) game_finished = False; incorrect_number = True player_x = 'X' player_o = 'O' is_finished = False number_chosen = [] while game_finished != True: x_selection = int(input(f"x's turn to choose a square (1-{max_val}): ")) while incorrect_number != False: if x_selection < 1 or x_selection > max_val: incorrect_number = True x_selection = int(input(f"Incorrect value. Please choose a value between 1 and {max_val}: ")) elif x_selection in number_chosen: incorrect_number = True x_selection = int(input(f"Value already chosen. Please choose a value between 1 and {max_val} not already chosen: ")) else: incorrect_number = False number_chosen.append(x_selection) updated_grid = change_element(x_selection, grid, player_x) draw_grid(updated_grid, n_digits) status = status_checker(updated_grid, player_x, player_o, max_val) if status == 'player_x': print(f"Congratulations player X! You won the game") game_finished = True break elif status == 'player_o': print(f"Congratulations player X! You won the game") game_finished = True break elif status == 'draw': print('Draw. Thanks for playing the game.') game_finished = True break incorrect_number = True o_selection = int(input(f"o's turn to choose a square (1-{max_val}): ")) while incorrect_number != False: if o_selection < 1 or o_selection > max_val: incorrect_number = True o_selection = int(input(f"Incorrect value. Please choose a value between 1 and {max_val}: ")) elif o_selection in number_chosen: incorrect_number = True o_selection = int(input(f"Value already chosen. Please choose a value between 1 and {max_val} not already chosen: ")) else: incorrect_number = False number_chosen.append(o_selection) updated_grid = change_element(o_selection, grid, player_o) draw_grid(updated_grid, n_digits) status = status_checker(updated_grid, player_x, player_o, max_val) if status == 'player_x': print(f"Congratulations player X! You won the game") game_finished = True elif status == 'player_o': print(f"Congratulations player O! You won the game") game_finished = True elif status == 'draw': print('Draw. Thanks for playing the game.') game_finished = True incorrect_number = True def create_grid(n_rows_cols=3): rows = [] k = 1 for _ in range(n_rows_cols): new_row = [] for __ in range(n_rows_cols): new_row.append(k) k += 1 rows.append(new_row) return rows def draw_grid(grid_array, n_digits): print() for row in grid_array: for element in row: print(f"{element:{n_digits}}", end=' ') print('|', end = ' ') print() if n_digits == 1: print('--', end = '') for _ in range(len(row)): if _ == range(len(row))[-1]: continue print('+---', end = '') print() else: print('---', end = '') for _ in range(len(row)): if _ == range(len(row))[-1] and n_digits >= 2: continue print('+----', end = '') print() print() def change_element(number, grid_array, player): for row in grid_array: for element in row: if number == element: element_index = row.index(element) row[element_index] = player return grid_array def status_checker(grid_array, player_x, player_o, max_val): result1 = horizontal_checker(grid_array, player_x, player_o) result2 = vertical_checker(grid_array, player_x, player_o) result3 = lr_diagonal_checker(grid_array, player_x, player_o) result4 = rl_diagonal_checker(grid_array, player_x, player_o) result5 = draw_checker(grid_array, player_x, player_o, max_val) if result1 != None: return result1 elif result2 != None: return result2 elif result3 != None: return result3 elif result4 != None: return result4 elif result5 != None: return result4 else: return None def horizontal_checker(grid_array, player_x, player_o): player_x_counter = 0 player_o_counter = 0 for row in grid_array: for element in row: if element == player_x: player_x_counter += 1 elif element == player_o: player_o_counter += 1 if player_x_counter == len(row): return 'player_x' elif player_o_counter == len(row): return 'player_o' else: player_o_counter = 0 player_x_counter = 0 return None def vertical_checker(grid_array, player_x, player_o): i = 0 counter_x = 0 counter_o = 0 for i in range(len(grid_array)): for j in range(len(grid_array)): if grid_array[j][i] == player_x: counter_x += 1 elif grid_array[j][i] == player_o: counter_o += 1 if counter_x == len(grid_array): return 'player_x' elif counter_o == len(grid_array): return 'player_o' counter_x = 0 counter_o = 0 return None def lr_diagonal_checker(grid_array, player_x, player_o): i = 0 counter_x = 0 counter_o = 0 for i in range(len(grid_array)): if grid_array[i][i] == player_x: counter_x += 1 elif grid_array[i][i] == player_o: counter_o += 1 if counter_x == len(grid_array): return 'player_x' elif counter_o == len(grid_array): return 'player_o' return None def rl_diagonal_checker(grid_array, player_x, player_o): i = 0 counter_x = 0 counter_o = 0 for i in range(len(grid_array)): if grid_array[i][(len(grid_array)-1)-i] == player_x: counter_x += 1 elif grid_array[i][i] == player_o: counter_o += 1 if counter_x == len(grid_array): return 'player_x' elif counter_o == len(grid_array): return 'player_o' return None def draw_checker(grid_array, player_x, player_o, max_val): accumulator = 0 for row in grid_array: for element in row: if element == player_x or element == player_o: accumulator += 1 if accumulator == max_val: return 'draw' else: return None if __name__ == '__main__': main()
3155a38c8284c686f0ac8989c05cefb5ba32cbe2
AndrewLu1992/lintcodes
/119_edit-distance/edit-distance.py
988
3.515625
4
# coding:utf-8 ''' @Copyright:LintCode @Author: hanqiao @Problem: http://www.lintcode.com/problem/edit-distance @Language: Python @Datetime: 16-06-08 10:02 ''' class Solution: # @param word1 & word2: Two string. # @return: The minimum number of steps. def minDistance(self, word1, word2): # write your code here if word1 is None or word2 is None: return 0 m = len(word1) n = len(word2) f = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(m + 1): f[i][0] = i for j in range(n + 1): f[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): if word1[i - 1] == word2[j - 1]: f[i][j] = min(f[i - 1][j - 1], f[i - 1][j] + 1, f[i][j - 1] + 1) else: f[i][j] = min(f[i - 1][j - 1] + 1, f[i - 1][j] + 1, f[i][j - 1] + 1) return f[m][n]
13b9d2d5d35df6935394d20a3bda71b60f259f10
JeffreybVilla/100DaysOfPython
/Beginner Day 4 Random & Lists/All50states.py
1,499
4.4375
4
# WITHOUT LISTS state1 = "Delaware" state2 = "Pennyslvania" state3 = "New Jersey" food1 = "Strawberries" food2 = "Spinach" print(f"{state1}, {state2}, {state3}, {food1}, {food2}\n\n\n") # WITH LISTS states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"] print(f"{states_of_america}\n\n\n") # To print first state print(states_of_america[0]) # To print third state print(states_of_america[2]) # To print last state in list print(states_of_america[-1]) # To change data of list states_of_america[1] = "pencilvania" print(f"{states_of_america[1]}") # Append/Add element to end of list (queue) # Use append function to add SINGLE item states_of_america.append("JeffreyLand") print(f"\n\n\n{states_of_america}") # Extend/Add element to end of list (queue) # Use append function to add MULTIPLE item states_of_america.extend(["DadLand", "PhoebeLand","MomLand"]) print(f"\n\n\n{states_of_america}")
6ffe2765ef035f6eac5b922600692ac742aa8aa3
ajskdlf64/Bachelor-of-Statistics
/2019 - 02/[응용통계학과] 빅데이터분석활용/anacondatest.py
413
3.53125
4
# Library import numpy as np import math from matplotlib import pyplot as plt # Error Check print("Hello Anaconda!") # Sine Graph for matplotlib n = 100 sintheta = [ math.sin(theta) for theta in np.random.uniform(0, np.pi, n)] pplot = plt.plot(sintheta) plt.axhline(y=0.5, color='r') plt.title("Sin Values of Uniform Random Number") plt.ylabel('Value') plt.xlabel('Number of Trials') plt.grid(True) plt.show()
3d8cce506aaf60964864bae1c1ab8f3a842a2ae3
ghazalerfani/MyMovie
/Simple_Regression_Models.py
9,516
3.796875
4
# Python Project - Section A2 Group 1 - MyMovie ##This is the Simple_Regression_Models script. This script contains the functionality of 3 traditional regression methods over different variables. ## Made by Shayne Bement, Jeff Curran, Ghazal Erfani, Naphat Korwanich, and Asvin Sripraiwalsupakit ## Imported by myMovie import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from math import sqrt ##### %matplotlib qt, if graphs are inline ##### ## Linear Regression model with 1 continuous variable and 23 dummy variables def LinearRegression(df, inputList): ##### Obtaining Inputs from main ##### modelInput = inputList #[Genre, MPAA, Budget, BookBool, AwardBool] movieDF = df #[Title, Year, Distributor, Genre, MPAA, Budget, Worldwide Gross, Average Rating, BookBool, AwardBool] ##### Loading the data for the Linear Regression Model ##### indepMovieDF = pd.DataFrame(movieDF, columns=['Genre', 'MPAA', 'Production_Budget', 'Book_Based', 'award_winning']) depMovieDF = pd.DataFrame(movieDF, columns=['Worldwide_Gross']) genreDummy = pd.get_dummies(indepMovieDF['Genre']) indepMovieDF = indepMovieDF.join(genreDummy) indepMovieDF = indepMovieDF.drop(columns=['Genre']) mpaaDummy = pd.get_dummies(indepMovieDF['MPAA']) indepMovieDF = indepMovieDF.join(mpaaDummy) indepMovieDF = indepMovieDF.drop(columns=['MPAA']) ##### Generating the user input DataFrame ##### ###print(indepMovieDF.head()) userInputDF = indepMovieDF[:1] for col in userInputDF.columns: userInputDF[col].values[:] = 0 userInputDF.at[0, 'Production_Budget'] = modelInput[2] userInputDF.at[0, 'Book_Based'] = modelInput[3] userInputDF.at[0, 'award_winning'] = modelInput[4] userInputDF.at[0, modelInput[0] ] = 1 #Genre userInputDF.at[0, modelInput[1] ] = 1 #MPAA ###print(indepMovieDF.head()) ##### Creating Linear Regression Model ##### ### Generating training data ### indepTrain, indepTest = train_test_split(indepMovieDF, test_size=0.25) #set test size? depTrain, depTest = train_test_split(depMovieDF, test_size=0.25) #set test size? ### Training Regression Model ### regr = linear_model.LinearRegression() regr.fit(indepTrain, depTrain) depPrediction = regr.predict(indepTest) ### Calculating RMSE ### RMSE = int(sqrt(mean_squared_error(depPrediction, depTest))) ### Making the prediction with Sample inputs ### userInputList = userInputDF.iloc[0,:].tolist() predGross = int(regr.predict([userInputList])) ### Some Discussion on Error ### # ============================================================================= # fullDF = depMovieDF.join(indepMovieDF) # variables = ['Worldwide_Gross', 'Production_Budget'] # # corr_matrix = fullDF.corr() # print(corr_matrix['Worldwide_Gross'].sort_values(ascending=False)) # # pd.plotting.scatter_matrix(fullDF[variables], figsize=(12, 8)) # plt.show() # ============================================================================= return predGross, RMSE #end LinearRegression ## Logistical Regression with 1 continuous variable and 23 dummy variables def LogisticRegression(df, inputList): ##### Obtaining Inputs from main ##### modelInput = inputList #[Genre, MPAA, Budget, BookBool, AwardBool] movieDF = df #[Title, Year, Distributor, Genre, MPAA, Budget, Worldwide Gross, Average Rating, BookBool, AwardBool] ##### Loading the data for the Linear Regression Model ##### indepMovieDF = pd.DataFrame(movieDF, columns=['Genre', 'MPAA', 'Production_Budget', 'Book_Based', 'award_winning']) depMovieDF = pd.DataFrame(movieDF, columns=['Worldwide_Gross']) genreDummy = pd.get_dummies(indepMovieDF['Genre']) indepMovieDF = indepMovieDF.join(genreDummy) indepMovieDF = indepMovieDF.drop(columns=['Genre']) mpaaDummy = pd.get_dummies(indepMovieDF['MPAA']) indepMovieDF = indepMovieDF.join(mpaaDummy) indepMovieDF = indepMovieDF.drop(columns=['MPAA']) ##### Generating the user input DataFrame ##### userInputDF = indepMovieDF[:1] for col in userInputDF.columns: userInputDF[col].values[:] = 0 userInputDF.at[0, 'Production_Budget'] = modelInput[2] userInputDF.at[0, 'Book_Based'] = modelInput[3] userInputDF.at[0, 'award_winning'] = modelInput[4] userInputDF.at[0, modelInput[0] ] = 1 #Genre userInputDF.at[0, modelInput[1] ] = 1 #MPAA ##### Creating Linear Regression Model ##### ### Generating training data ### indepTrain, indepTest = train_test_split(indepMovieDF, test_size=0.25) #set test size? depTrain, depTest = train_test_split(depMovieDF, test_size=0.25) #set test size? ### Training Regression Model ### logReg = linear_model.LogisticRegression() logReg.fit(indepTrain, depTrain.values.ravel()) depPrediction = logReg.predict(indepTest) ### Calculating RMSE ### RMSE = int(sqrt(mean_squared_error(depPrediction, depTest))) ### Making the prediction with Sample inputs ### userInputList = userInputDF.iloc[0,:].tolist() predGross = int(logReg.predict([userInputList])) ### Some Discussion on Error ### # ============================================================================= # fullDF = depMovieDF.join(indepMovieDF) # variables = ['Worldwide_Gross', 'Production_Budget'] # # corr_matrix = fullDF.corr() # print(corr_matrix['Worldwide_Gross'].sort_values(ascending=False)) # # pd.plotting.scatter_matrix(fullDF[variables], figsize=(12, 8)) # plt.show() # ============================================================================= return predGross, RMSE #end LogisticRegression ## Simplified Linear Regression model with 1 continuous variable def BudgetOnlyRegression(df, inputList): ##### Obtaining Inputs from main ##### modelInput = inputList[2] #[Genre, MPAA, Budget, BookBool, AwardBool] movieDF = df #[Title, Year, Distributor, Genre, MPAA, Budget, Worldwide Gross, Average Rating, BookBool, AwardBool] ##### Loading the data for the Linear Regression Model ##### budgetDF = pd.DataFrame(movieDF, columns=['Production_Budget']) depMovieDF = pd.DataFrame(movieDF, columns=['Worldwide_Gross']) ##### Generating the user input DataFrame ##### userInputDF = budgetDF[:1] for col in userInputDF.columns: userInputDF[col].values[:] = 0 userInputDF.at[0, 'Production_Budget'] = modelInput ##### Creating Linear Regression Model ##### ### Generating training data ### budgetTrain, budgetTest = train_test_split(budgetDF, test_size=0.25) #set test size? depTrain, depTest = train_test_split(depMovieDF, test_size=0.25) #set test size? ### Training Regression Model ### budgetRegr = linear_model.LinearRegression() budgetRegr.fit(budgetTrain, depTrain) budgetPrediction = budgetRegr.predict(budgetTest) ### Calculating RMSE ### RMSE = int(sqrt(mean_squared_error(budgetPrediction, budgetTest))) ### Making the prediction with Sample inputs ### userInputList = userInputDF.iloc[0,:].tolist() predGross = int(budgetRegr.predict([userInputList])) ### Some Discussion on Error ### # ============================================================================= # fullDF = depMovieDF.join(budgetDF) # variables = ['Worldwide_Gross', 'Production_Budget'] # # corr_matrix = fullDF.corr() # print(corr_matrix['Worldwide_Gross'].sort_values(ascending=False)) # # pd.plotting.scatter_matrix(fullDF[variables], figsize=(12, 8)) # plt.show() # ============================================================================= return predGross, RMSE #end BudgetOnlyRegression ##if testing the script individually this will run. if __name__ == "__main__": modelInput = ['Comedy', 'PG-13', 50000000, 1, 0] movieDF = pd.read_csv(r'FullOutput.csv') grossEarnings, errorTerm = LinearRegression(movieDF, modelInput) logGrossEarnings, logErrorTerm = LogisticRegression(movieDF, modelInput) budgetEarnings, budgetErrorTerm = BudgetOnlyRegression(movieDF, modelInput) print('\n\033[4mLinear Regression Model\033[0m') print('Projected Budget: ', "${:,}".format(modelInput[2])) print('Predicted Gross Budget: ', "${:,}".format(grossEarnings)) print('predicted Root Mean Squared Error: ', "${:,}".format(errorTerm)) print('\n\033[4mLinear Regression Model (Budget Only)\033[0m') print('Projected Budget: ', "${:,}".format(modelInput[2])) print('Predicted Budget Gross Budget: ', "${:,}".format(budgetEarnings)) print('predicted Budget Root Mean Squared Error: ', "${:,}".format(budgetErrorTerm)) print('\n\033[4mLogistic Regression Model\033[0m') print('Projected Budget: ', "${:,}".format(modelInput[2])) print('Predicted Gross Budget: ', "${:,}".format(logGrossEarnings)) print('predicted Root Mean Squared Error: ', "${:,}".format(logErrorTerm))
98dfa255d3f9c8768ad518506330cf238a8d6e00
aliwo/swblog
/_drafts/disk_control3.py
744
3.5625
4
from queue import PriorityQueue def solution(jobs): ''' 채점 시간을 보니 최소 n log n 안에는 끝나야 한다. for 문이 한 번 회전 할 때 마다 job 은 종료되어야 한다. 로직을 정리하면 다음과 같다. 1. 큐에서 새로운 작업을 뽑아낸다. 2. 큐에 아무것도 없으면?? job 의 실행 중에 n 개의 새로운 작업이 들어온다. n 개의 작업은 큐에 추가. 마지막 job 의 실행 중에는 새로운 작업이 들어오지 않는다. ''' answer = 0 p_que = PriorityQueue(maxsize=500) jobs.sort() i = 0 for job in jobs: pass return answer / len(jobs) print(solution([[0, 3], [1, 9], [2, 6]])) # 9
19bdaa200f30a380e71d3daca76fe2722957cd38
bodunadebiyi/datastructure_and_algorithms
/MergeSort.py
594
4.09375
4
def merge(left, right, A): i = 0 j = 0 k = 0 while k < len(A): if i >= len(left) and j < len(right): A[k] = right[j] j += 1 elif j >= len(right) and i < len(left): A[k] = left[i] i += 1 elif left[i] < right[j]: A[k] = left[i] i += 1 elif left[i] > right[j]: A[k] = right[j] j += 1 k += 1 def mergesort(arr): size = len(arr) if size < 2: return midpoint = round(size/2) left = arr[:midpoint] right = arr[midpoint:] mergesort(left) mergesort(right) merge(left, right, arr)
9aaa8e7a195a18a8c95cd1dceedb64487eca04a7
Ashtalakshmimano/Lakshmi
/Arm.py
188
3.59375
4
lower=int(input()) upper=int(input()) for num in range(lower,upper+1): order=len(str(num)) temp=num sum=0 while (temp>0): rem=temp%10 sum=sum+rem**order temp//=10 if(num==sum): print(num)
f044bdda5876e31b138529c6822aca61ebd110fb
ZhiyuSun/leetcode-practice
/301-500/403_青蛙过河.py
1,465
3.6875
4
""" 一只青蛙想要过河。 假定河流被等分为若干个单元格,并且在每一个单元格内都有可能放有一块石子(也有可能没有)。 青蛙可以跳上石子,但是不可以跳入水中。 给你石子的位置列表 stones(用单元格序号 升序 表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一块石子上)。 开始时, 青蛙默认已站在第一块石子上,并可以假定它第一步只能跳跃一个单位(即只能从单元格 1 跳至单元格 2 )。 如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1 个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/frog-jump 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List # 2021.03.30 这种困难题毫无任何思路 class Solution: def canCross(self, stones: List[int]) -> bool: n, s = len(stones), set(stones) dp = [set() for _ in range(n)] dp[0].add(0) for i in range(n): cur = stones[i] for j in range(i): need = cur - stones[j] if need - 1 in dp[j] or need + 1 in dp[j] or need in dp[j]: dp[i].add(need) return len(dp[-1]) > 0
1e7afef369681d6846854c0d8dbbc28316922a10
quentin-auge/bookings_report
/bookings_report/transform.py
2,097
3.921875
4
from datetime import date, datetime from typing import Tuple def parse_amount_and_currency(raw_amount: str) -> Tuple[float, str]: """ Parse raw amount string into float amount and currency. Args: raw_amount: raw amount string Returns: Amount and currency Raises: :exc:`NotImplementedError` on invalid currency (not ending with `€` or starting with `£`). :exc:`NotImplementedError` on invalid amount (comma and dot decimal separator accepted). Examples: >>> parse_amount_and_currency('12,34 €') (12.34, '€') >>> parse_amount_and_currency('£12.34') (12.34, '£') """ raw_amount = raw_amount.strip() error_msg = f"Cannot parse amount '{raw_amount}'" # Parse currencu if raw_amount.startswith('£'): currency = '£' raw_amount = raw_amount[1:] elif raw_amount.endswith('€'): currency = '€' raw_amount = raw_amount[:-1] else: raise NotImplementedError(f'{error_msg}: unrecognized currency') # Parse amount try: amount = float(raw_amount.replace(',', '.')) except ValueError: raise NotImplementedError(f"{error_msg}: unrecognized amount '{raw_amount}'") return amount, currency def parse_date(raw_date: str) -> date: """ Parse '%d-%m-%Y' and '%d/%m/%Y' formatted dates indifferently. Args: raw_date: raw date string Returns: Parsed date Raises: :exc:`NotImplementedError` on invalid date format. Examples: >>> parse_amount_and_currency('21/03/2015') date(2015, 3, 21) >>> parse_amount_and_currency('21-03-2015') date(2015, 3, 21) """ raw_date = raw_date.strip() try: parsed_date = datetime.strptime(raw_date, '%d-%m-%Y').date() except ValueError: try: parsed_date = datetime.strptime(raw_date, '%d/%m/%Y').date() except: raise NotImplementedError(f"Cannot parse date '{raw_date}' as '%d-%m-%Y' or '%d/%m/%Y'") return parsed_date
e1af8e8554288b7fdf710402c3d3cf9a0723ffa9
KJeanpol/Tarea3-Anpi
/Parte 2/animacion.py
1,433
3.71875
4
import edo2 from sympy import sympify import matplotlib.pyplot import numpy as np def evalFuncion(): """ Aproximar la solucion de la funcion dada en el codigo. Salidas: [X,Y]: Matriz con los vectores de las soluciones de X y Y evaluadas en la funcion """ a=1 X=[] Y=[] funcion = "(sin(6-x))*((sin(5)*(x**(1/2)))**-1)" f = sympify(funcion) for i in range(0,5000): #Valor maximo 5000, pues es suficiente para mostrar su comportamiento segun los evaluados en edo2 X += [a + (i*10**-3)] Y += [f.subs({'x':X[i]})] return[X,Y] def animacion(): p = "-1/x" q = "(1/(4*x**2))-1" f = "0" y0 = 1 yn = 0 a = 1 b = 6 paso=0 legendas=[] matplotlib.pyplot.title("Funciones") puntos=evalFuncion() matplotlib.pyplot.plot(puntos[0],puntos[1]) legendas.append('Funcion Inicial') matplotlib.pyplot.legend( legendas, loc=1) matplotlib.pyplot.pause(2) for i in range(1,4): # Solo ejecuta 3 iteraciones, pues mas de esas, la pc no es capaz de computarlos, pues maneja numeros punto flotantes muy grandes legendas.append("Iteracion: "+ str(i)) paso = 10**-i x = edo2.edo2(p,q,f,paso,a,b,y0,yn) matplotlib.pyplot.plot(x[0], x[1]) matplotlib.pyplot.legend( legendas, loc=1) matplotlib.pyplot.pause(2) matplotlib.pyplot.show() animacion()
a044d4314e494effdbb0daef06b0df7c0a8b7bb1
Erqiao/Hello-World
/list.py
249
3.78125
4
total = 0 for i in range(1,100): if i%3 == 0 or i%5 ==0: total += i print total sum = 0 i = 0 list1 = list(range(1, 100)) while i < len(list1): if list1[i]%3 == 0 or list1[i]%5 == 0: sum += list1[i] i += 1 print sum
97a20ffe1ee71acb84a88936e245fb3baca58146
jefferson206/destravando-python
/exercicio05/exercicio05.py
354
3.625
4
from listaExercicio.uteis.util import Util def main(): Util().enunciado('PEÇA AO USUÁRIO PARA DIGITAR UM NÚMERO REAL E IMPRIMA A QUINTA PARTE DESTE NÚMERO.') valor = float(input(f'Digite um numero real: ').replace(',', '.')) print('\nA quinta parte de {} é de: {} '.format(valor, (valor*(1/5)))) if __name__ == '__main__': main()
7c666f85f8faef80fc4fa152d07e9b2551f216f4
innorev14/my-very-first-repo
/hello.py
70
3.5625
4
for i in range(1,12): if i % 2 == 0: print("Hello world")
bbf55396225a24a267f1d3c988d1532b55fbd449
teamdaemons/100daysofcode
/Day21/Multiplayer/snake_game.py
2,052
3.609375
4
from turtle import Screen import time from snake import Snake from food import Food from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) snake = Snake("cyan") snake2 = Snake("red") food = Food() scoreboard = Scoreboard() scoreboard2 = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") screen.onkey(snake2.up, "w") screen.onkey(snake2.down, "s") screen.onkey(snake2.left, "a") screen.onkey(snake2.right, "d") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) snake.move() snake2.move() # Detect collision with food if snake.head.distance(food) < 15: food.refresh() scoreboard.increase_score() if snake2.head.distance(food) < 15: food.refresh() scoreboard2.increase_score2() # Detect collision with wall player 1 if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: x = snake.head.xcor() y = snake.head.ycor() if x > 280: snake.segments[0].goto(-280, y) elif x < -280: snake.segments[0].goto(280, y) elif y > 280: snake.segments[0].goto(x, -280) elif y < -280: snake.segments[0].goto(x, 280) # Detect collision with wall player 2 if snake2.head.xcor() > 280 or snake2.head.xcor() < -280 or snake2.head.ycor() > 280 or snake2.head.ycor() < -280: # x2 = snake2.head.xcor() # y2 = snake2.head.ycor() # if x2 > 280: # snake2.segments[0].goto(-280, y2) # elif x2 < -280: # snake2.segments[0].goto(280, y2) # elif y2 > 280: # snake2.segments[0].goto(x2, -280) # elif y2 < -280: # snake2.segments[0].goto(x2, 280) game_is_on = False scoreboard.game_over() screen.exitonclick()
0a2dd0ed370a6ab14016ebb8175d55652a67d1be
fernandavincenzo/exercicios_python
/26-50/042_TiposTriângulos.py
551
4.03125
4
r1 = float(input('Digite o comprimento da primeira reta: ')) r2 = float(input('Digite o comprimento da segunda reta: ')) r3 = float(input('Digite o comprimento da terceira reta: ')) if r2<r1+r3 and r1<r2+r3 and r3<r1+r2: if r1==r2==r3: print('Estas retas conseguem formar um triângulo Equilátero!') elif r1!=r2!=r3: print('Essas retas conseguem formar um triângulo Escaleno!') else: print('Essas retas conseguem formar um triângulo Isósceles!') else: print('Essas retas não podem formar um triângulo...')
11813ed89eb6a97a46a72bf1c8a3623d94c8c56e
dowookims/ProblemSolving
/swea/stack2/stack2_3.py
526
3.65625
4
import sys sys.stdin = open("sample_input3.txt", "r") # 1 가위 2 바위 3 보 def div_list(case): if len(case[0])== 1 or len(case[0])==2: return return div_list([[case[0:idx], case[idx+1:len(case)]]]) for TC in range(1, int(input())+1): N = int(input()) t = 0 while True: t +=1 if N == 1: break else: N = N//2 case = list(map(int, input().split())) idx = len(case) // 2 a = [case[0:idx],case[idx+1:len(case)]] print(div_list(a))
efb3d2a97789aa8ef2b51d1d5bb5c11a6e89a19a
bainco/bainco.github.io
/course-files/lectures/lecture15 -old/creature.py
1,024
3.640625
4
from tkinter import Canvas import utilities def make_creature(canvas, center, size=100, my_tag='creature', my_fill='hotpink'): radius = size / 2 # just a demo of how you might think about making your creature: left_eye_pos = (center[0] - radius / 4, center[1] - radius / 5) right_eye_pos = (center[0] + radius / 4, center[1] - radius / 5) eye_width = eye_height = radius / 10 # IMPORTANT that I'm tagging each of the shapes that makes up my "make_creature" # with the tag that the user passed in: utilities.make_circle(canvas, center, radius, color=my_fill, tag=my_tag) utilities.make_oval(canvas, left_eye_pos, eye_width, eye_height, color='black', tag=my_tag) utilities.make_oval(canvas, right_eye_pos, eye_width, eye_height, color='black', tag=my_tag) utilities.make_line(canvas, [ (center[0] - radius / 2, center[1] + radius / 3), (center[0], center[1] + radius / 1.2), (center[0] + radius / 2, center[1] + radius / 3) ], curvy=True, tag=my_tag)
ae18a0f125b2c9ee0ec80f8b07694ad14ab882e4
YashiSinghania/test_repo
/ifelse9.py
455
4.4375
4
# Write a program to check if a triangle can be formed using the given lengths of 3 sides. # HINT: For example, if the sides are 10, 24, and 67, then you cannot make a triangle # because 10+24 is not greater than or equal to 67. a= int(input("first side of triangle")) b= int(input("second side of triangle")) c= int(input("third side of triangle")) if a+b>=c and b+c>=a and a+c>=b: print("triangle possible") else: print("triangle not possible")
39c68268a82e307f66b1d45b930d93175eeaf866
ShivamBhosale/100DaysOfCode
/Day51/generator.py
654
3.765625
4
import sys def mygenerator(n): for x in range(n): yield x ** 3 values = mygenerator(100) for x in range(1,10): print(next(values)) print("Size: {} bytes".format(sys.getsizeof((values)))) def infinite_sequences(): result = 1 while True: yield result result += 5 values2 = infinite_sequences() for i in range(1,10): print(next(values2)) print("Size: {} bytes".format(sys.getsizeof((values2)))) def iter_sequences(num): flag = 1 while True: yield flag flag *= 10 num = int(input("Enter a number: ")) values3 = iter_sequences(num) for j in range(1,10): print(next(values3))
76f1ab579654437cdee38b1071b9bc3b84e286a9
pepitogrilho/learning_python
/xSoloLearn_basics/files/text_analyzer_01.py
902
3.671875
4
# -*- coding: utf-8 -*- """ v1 """ filepath = "C:\\GitHub\\learning_python\\files\\text_analyzer_01_file_example.txt" with open(filepath) as f: text = f.read() print(text) """ v2 """ def count_char(text, char): count=0 for c in text: if c == char: count+=1 return count filepath = "C:\\GitHub\\learning_python\\files\\text_analyzer_01_file_example.txt" with open(filepath) as f: text = f.read() num_veces_01 = count_char(text,"e") print(num_veces_01) """ v3 """ def count_char(text, char): count_all=0 count_found=0 for c in text: count_all+=1 if c == char: count_found+=1 return 100*(count_found/count_all) filepath = "C:\\GitHub\\learning_python\\files\\text_analyzer_01_file_example.txt" with open(filepath) as f: text = f.read() num_veces_01 = count_char(text,"e") print(num_veces_01)
8e3b1ce44ef1b37205a9afb6b241aef115230b75
shaneweisz/DLOGs
/models/2D-CNN/preprocessing_utils_2d_cnn.py
3,944
3.515625
4
import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.utils import to_categorical DEFAULT_FILE_SUFFIX = "14_10000" # Dataset with 10 classes, 10000 packets in each DEFAULT_DATA_PATH = f"/Users/chiratidzomatowe/DLOGs/preprocessing/data/{DEFAULT_FILE_SUFFIX}" MAX_BYTE_VALUE = 255 def read_in_data(data_path=DEFAULT_DATA_PATH, file_suffix=DEFAULT_FILE_SUFFIX): """ Returns df_train, df_val, df_test corresponding to the csv at the specified file path. e.g. data_path = "../../data/" and file_suffix = "12_10000" for data stored in folder `data` named with `12_10000` suffix. Example usage: df_train, df_val, df_test = read_in_data() """ df_train = pd.read_csv(f"{data_path}/train_{file_suffix}.csv") df_val = pd.read_csv(f"{data_path}/val_{file_suffix}.csv") df_test = pd.read_csv(f"{data_path}/test_{file_suffix}.csv") return df_train, df_val, df_test def preprocess_2d_cnn(df_train, df_test, df_val): """ Takes in train, val, and test data frames with columns "label" and 1480 further columns with each byte from an IP payload. Returns numpy arrays: X_train, y_train, X_val, y_val, X_test, y_test X_train is of shape (m, 40, 37, 1) (m training examples, which are 40 x 37, with 1 depth layer) y_train is of shape (m, k) (m training examples, one hot-encoded label with k classes) Example usage: (X_train, y_train), (X_val, y_val), (X_test, y_test) = preprocess_2d_cnn(df_train, df_test, df_val) """ # 1) Make copies so that that preprocessing changes leave original data frames unchanged df_train_copy = df_train.copy() df_val_copy = df_val.copy() df_test_copy = df_test.copy() # 2) Mask first 20 bytes df_train_copy[df_train_copy.columns[1:21]] = 0 df_val_copy[df_val_copy.columns[1:21]] = 0 df_test_copy[df_test_copy.columns[1:21]] = 0 # 3) Create X_train, y_train, X_val, y_val, X_test, y_test X_train, y_train = df_train_copy.drop( 'label', axis=1), df_train_copy["label"] X_val, y_val = df_val_copy.drop('label', axis=1), df_val_copy["label"] X_test, y_test = df_test_copy.drop('label', axis=1), df_test_copy["label"] # 4) Normalize the data X_train /= MAX_BYTE_VALUE X_val /= MAX_BYTE_VALUE X_test /= MAX_BYTE_VALUE # 5) Reshape the data for CNN X_train = X_train.values.reshape(X_train.shape[0], 40, 37, 1) X_val = X_val.values.reshape(X_val.shape[0], 40, 37, 1) X_test = X_test.values.reshape(X_test.shape[0], 40, 37, 1) # 6) Encode labels as integers y_train = y_train.astype('category').cat.codes.values y_val = y_val.astype('category').cat.codes.values y_test = y_test.astype('category').cat.codes.values # 7) One hot encode y_train = to_categorical(y_train) y_val = to_categorical(y_val) y_test = to_categorical(y_test) return (X_train, y_train), (X_val, y_val), (X_test, y_test) def create_tf_datasets(X_train, y_train, X_val, y_val, X_test, y_test): """ Example usage: train_dataset, val_dataset, test_dataset = create_tf_datasets(X_train, y_train, X_val, y_val, X_test, y_test) """ train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)) val_dataset = tf.data.Dataset.from_tensor_slices((X_val, y_val)) test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test)) return train_dataset, val_dataset, test_dataset def test(): # Read in the data df_train, df_val, df_test = read_in_data() # Create (X_train, y_train), (X_val, y_val), (X_test, y_test) (X_train, y_train), (X_val, y_val), (X_test, y_test) = preprocess_2d_cnn(df_train, df_test, df_val) # TF datasets train_dataset, val_dataset, test_dataset = create_tf_datasets( X_train, y_train, X_val, y_val, X_test, y_test) if __name__ == "__main__": test()
6484e95a8a6af9d616a8ffb06fcb9b117ee1df0f
Susmitha95/Internstudy
/firstprogram_add.py
67
3.578125
4
x=int(raw_input("enter x:")) y=int(raw_input("enter y")) print x+y
7be5e79042c9379d35066f2354799f97e626591f
lokeshsenthilkumar/leetcode
/word-search/word-search.py
781
3.6875
4
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: r = len(board) ; c = len(board[0]) def dfs(i,j,w): if w == len(word): return True if i<0 or j<0 or i>=r or j>=c or board[i][j]!=word[w] or (i,j) in path: return False t = board[i][j] board[i][j] = '#' res = dfs(i-1,j,w+1) or dfs(i+1,j,w+1) or dfs(i,j-1,w+1) or dfs(i,j+1,w+1) board[i][j] = t return res for i in range(r): for j in range(c): if dfs(i,j,0): return True return False
33974da521f14195d8beae7d9ec0694fbff4aae0
LenHu0725/02_JZOffer-Notebook
/题目05:替换空格.py
1,708
3.796875
4
# -*- coding: utf-8 -*- """ 名称: 替换空格 题目: 请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 测试: 输入包括空格(空格在最前 在最后 在中间 多个连续空格) 输入字符串没有空格 特殊输入(空指针 空字符串 只有一个空格 多个连续空格) """ class Solution_1: def __init__(self): pass def replaceSpace(self, s): return '%20'.join(s.split(' ')) class Solution_2: def __init__(self): pass def replaceSpace(self, s): return s.replace(' ', '%20') class Solution_3: def __init__(self): pass def replaceSpace(self, s): """ 遍历一次字符 从后到前排序 【重点掌握从后向前赋值 保护内存】 时间复杂度N(n) 空间复杂度(n) 输入 - s: 一段字符串 输出 - s: 替换空格的字符串 """ # S1: 获得字符串长度 与空格数量 s = list(s) spaceCount = 0 for e in s: if e==' ': spaceCount+=1 p1 = len(s)-1 # S2: 倒序赋值list s += [None]*2*spaceCount p2 = len(s)-1 while (p1 >= 0): if s[p1]!=' ': s[p2] = s[p1] p2 -= 1 else: s[p2-2] = '%' s[p2-1] = '2' s[p2] = '0' p2 -= 3 p1 -= 1 return ''.join(s)
5582f7fcbb9b7e2f0ed2beaf91ae5fab18e342c7
dzanto/asynchrony
/async_with_gen.py
531
3.53125
4
from time import sleep queue = [] def counter(): counter = 0 while True: print(counter) counter += 1 yield def bang(): counter = 0 while True: if counter % 3 == 0: print('Bang') counter += 1 yield def main(queue): while True: task = queue.pop(0) next(task) queue.append(task) sleep(0.5) if __name__ == '__main__': cnt = counter() ban = bang() queue.append(cnt) queue.append(ban) main(queue)
e85d1e88616ffe6f1058bd8374e47a36b604c636
huangm96/Algorithms
/rock_paper_scissors/rps.py
868
3.921875
4
#!/usr/bin/python """ player: 1:3 3**1 r p s player: 2:9 3**2 rr rp rs pr pp ps sr sp ss player: 3 : 27 3**3 """ import sys def rock_paper_scissors(n): # if n = 1 [['rock'], ['paper'], ['scissors']] # if n = 2, add [['rock'], ['paper'], ['scissors']] to the item in n(1), if n == 0: return [[]] elif n == 1: return [['rock'], ['paper'], ['scissors']] else: arr = [[]] * 3 ** n returned_arr = rock_paper_scissors(n - 1) x=0 for i in range(len(returned_arr)): arr[x] = returned_arr[i] + ["rock"] x += 1 arr[x] = returned_arr[i] + ["paper"] x += 1 arr[x] = returned_arr[i] + ["scissors"] x += 1 return arr if __name__ == "__main__": if len(sys.argv) > 1: num_plays = int(sys.argv[1]) print(rock_paper_scissors(num_plays)) else: print('Usage: rps.py [num_plays]')
7b434d0fcfbc062849a0983ae63397374fe0cbf5
NBlanchar/exercism
/word-count/word_count.py
741
3.59375
4
import string def count_words(sentence): sentence = sentence.lower() for puntuacion in string.punctuation: if(puntuacion != "'"): sentence = sentence.replace(puntuacion, " ") sentence = sentence.replace('\n', ' ').replace('\t', ' ') sentence = sentence.replace(' ', ' ') sentence = sentence.split(" ") resultado = {} for x in range(len(sentence)): palabra = sentence[x] if(palabra.count("'") > 1): sentence[x] = palabra.replace("'", "") for palabra in sentence: if(palabra.count("'") > 1): palabra = palabra.replace("'", "") if palabra != '': resultado[palabra] = sentence.count(palabra) return resultado
99f8e2320cc83eeb12e3ceaca11069b86980bfb9
srininara/pykidz
/sessions/session-7-loops/code/while_ice_cream.py
585
3.890625
4
icecream_flavors = ['vanilla', 'chocolate', 'mint chocolate', 'chocolate chip', 'cookie dough'] fruits = ['apple', 'banana', 'fig', 'mango', 'orange'] flavor_index = 0 print('The combination are:') while flavor_index < len(icecream_flavors): fruit_index = 0 flavor = icecream_flavors[flavor_index] flavor_index += 1 if flavor == 'mint chocolate': continue while fruit_index < len(fruits): fruit = fruits[fruit_index] fruit_index += 1 if fruit == 'banana': continue print(f"{flavor} - {fruit}") print("Good bye!")
0c0f2128b0ea9cbe59babbaa6ea7a44aded6b69f
Jabuf/projecteuler
/problems/problem10/Problem10.py
579
3.59375
4
""" https://projecteuler.net/problem=10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from locals import * TWO_MILLIONS = 2000000 def solution(): current_prime = 2 sum_primes = 0 primes = [current_prime] while current_prime < TWO_MILLIONS: sum_primes += current_prime current_prime = find_next_prime(primes) primes.insert(len(primes), current_prime) return sum_primes with Timer() as timed: print(solution()) print("Seconds taken: {0}".format(timed.elapsed))
658600a522b7823875b27a1d145338692faec934
Oksana1-prog/Python_06.02
/ua/univer/lesson01/lesson01_homework/Homework_chapter_3.py
5,064
4.40625
4
# 1. День недели. Программа должн вывести сообщение об ошибке, если пользователь вводит сообшение вне диапозона x = int(input("Введите число: ")) if x >= 1 and x < 8: print('Зачение лежит в допустимом диапозоне') else: print('Зачение лежит в недопустимом диапозоне') # 2. Площать прямоуголников: вывести сообщение площадь какого прямоуголника больше или сообщить об ошибке length_1 = int(input("Введите длину первого прямоуголника: ")) width_1 = int(input("Введите ширину первого прямоуголника: ")) length_2 = int(input("Введите длину второго прямоуголника: ")) width_2 = int(input("Введите ширину второго прямоуголника: ")) square_1=length_1*width_1 square_2=length_2*width_2 if square_1 > square_2: print("Площадь первого прямоуголника больше") if square_2 > square_1: print("Площадь второго прямоуголника больше") if square_1 == square_2: print("Площадь прямоугольников равна") # 3. Классификатор возраста: age = int(input("Введите Ваш возраст: ")) if age <= 1: print("Младенец") if age > 1 and age <= 13: print("Ребенок") if age >= 13 and age <= 20: print("Подросток") if age > 20 : print("Взрослый") # 4. Римские цифры number = int(input("Введите число: ")) if number == 1: print("I") else: if number == 2: print("II") else: if number == 3: print("III") else: if number == 4: print("IV") else: if number == 5: print("V") else: if number == 6: print("VI") else: if number == 7: print("VII") else: if number == 8: print("VIII") else: if number == 9: print("XI") else: if number == 10: print("X") else: print("Неизвестно") #5. Масса и вес Если вес тела больше 500 Н - тело слишком тяжелое, меньше 100 - тело слишком лгкое weight = float(input("Введите массу тела: ")) weight_newton=weight*9.8 if weight_newton > 500: print("Тело слишком тяжелое") elif weight_newton < 100: print("Тело слишком легкое") else: print("В пределах нормі") #6.Волшебные даты month = int(input("Введите месяц в числовой форме: ")) day = int(input("Введите день: ")) year = int(input("Введите двузначный год: ")) product_of_numbers=month*day if product_of_numbers == year: print("Данная дата является волшебной: ") else: print("Дата не является волшебной") # 7. Цветовой микшер сolor_1 = input("Введите название одного цвета с маленькой буквы: ") сolor_2 = input("Введите название второго цвета с маленькой буквы: ") if сolor_1 == "красный" and сolor_2 == "синий" or сolor_1 =="синий" and сolor_2 == "красный": print("фиолетовый") elif сolor_1 == "красный" and сolor_2 == "желтый" or сolor_1 =="желтый" and сolor_2 == "красный": print("оранжевый") elif сolor_1 == "синий" and сolor_2 =="желтый" or сolor_1 =="желтый" and сolor_2 == "синий": print("зеленый") else: print("ошибка") # 8. Калькулятор сосисок для пикника people = int(input('kolvo ludei? ')) hotdog_na_chel = int(input('skolko hotdogov kagdomy? ')) all_hotdogs = people * hotdog_na_chel if all_hotdogs <= 10: sos_upak = 1 bul_upak = 1 sos_ostal = 10 - allhotdogs bul_ostal = 8 - allhotdogs elif all_hotdogs > 10: upak_sos = (all_hotdogs // 10) + 1 < +1 про который говорил upak_bul = (all_hotdogs // 8) + 1 < +1 про который говорил sos_ostal = upak_sos * 10 - all_hotdogs bul_ostal = upak_bul * 10 - all_hotdogs print(upak_sos, upak_bul, sos_ostal, bul_ostal)
ea64b622e024b4a411a93daa297ab8e903807c55
tiaedmead/Data_24_repo
/OOP/Tic_Tac_Toe.py
1,308
3.859375
4
class Board: def __init__(self): self.cells = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " ",] def display(self): print(" %s | %s | %s " %(self.cells[1], self.cells[2], self.cells[3])) print("-----------") print(" %s | %s | %s " % (self.cells[4], self.cells[5], self.cells[6])) print("-----------") print(" %s | %s | %s " % (self.cells[7], self.cells[8], self.cells[9])) def update_cell(self, cell_num, player): if self.cells[cell_num] == " ": self.cells[cell_num] = player def is_winer(self, player): if self.cells[1] == player and self.cells[2] == player and self.cells[3] == player: return True board = Board() print("Welcome to tic-tac-toe") def refresh_game(): board.display() print("\n") while True: refresh_game() x_move = int(input("Player X. Please choose from 1-9 >>> ")) print("\n") board.update_cell(x_move, "X") refresh_game() if board.is_winer("X"): print("X WINS!") play_again = input("Would you like to play again? (Y/N) >>> ").upper() if play_again == "Y": continue else: break o_move = int(input("Player O. Please choose from 1-9 >>> ")) board.update_cell(o_move, "O")
f0637adf6dd650834cf68b540a626312075f9e00
rodumani1012/PythonStudy
/Python/Python01_Type/string.py
892
3.8125
4
# 문자 # ''(single quotation) ""(double quotation) 차이 없다. # \ : escape sequence 라고 부름. a='a\nb\'\s' print(a) b="a\nb's" print(b) # ''' 내용 ''' # ''' 3개는 안에 있는 엔터나 공백을 다 포함시켜줌. c=''' a b c d e''' print(c) # """ d="""a b c d """ print(d) # 섞어서 ex="""Weather you're new to programming or an experienced developer, it's easy to learn and use Python.""" print(ex) ex2='''Python Insider by the Python Core Developers is licensed under a 'Creative' "Commons" Attribution-NonCommercial-ShareAlike 3.0 Unported License. Based on a work at blog.python.org.''' print(ex2) # 참고 ''' 이 안에 주석을 쓰는 사람도 있다. 출력만 안하면 되기 때문이다. ''' # 문자열 더하기, 문자열 곱하기 s1 = 'Hello, ' s2 = 'World' s3 = '!' print(s1+s2+s3) print(s1+s2+(s3*10))
577dd61501a776dd2399b70ebf20aff4763924cd
yachu0721/Introduction-to-data-sciencl
/Week10/IDS_20200508_2.py
461
3.59375
4
# variable vs. values: 1-on-multiple ( 1 對 多 ) weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] print(len(weekdays)) #觀察長度 lucky_numbers = [7, 24, 5566] print(lucky_numbers) lucky_numbers.append(87) #新增資料至末端 print(lucky_numbers) lucky_numbers.pop() #將最末端資料拋出 print(lucky_numbers) my_fav_group = lucky_numbers.pop() print(lucky_numbers) print(my_fav_group) #讀出拋出的最末端資料
daf9a4787874e5b32017aff437fbfbfa14dd491a
nagireddy96666/Interview_-python
/Reverse_String&List.py
692
3.609375
4
"""1. this is using negitive index""" s="hai this is lakshma reddy" a=s[::-1] print a ," 1st" """@@@@2nd method""" l=s.split() print l r="\t".join(reversed(l)) print r ,"2nd" """@@@3rd method""" z="".join((s[i] for i in range(len(s)-1,-1,-1))) print z """@@@4th method""" def krish(s): if len(s) <= 1: return s return krish(s[1:]) + s[0] s ="reddy" print krish(s) """@@@5""" my_string = "Hello World" for x in range(len(my_string)): print my_string[len(my_string)-x-1] """@@@6""" for x in range(len(my_string), 0, -1): print my_string[x-1] print range(6,0,-1) """List leverse """ l=[1,2,3,4,5,6] l1=[] for i in range((len(l)-1),-1,-1): l1.append(l[i]) print l1
9b8bd42dbc1464a307ff7bff78e53a876b812e64
njcssa/njcssa-python-practice-probs
/misc/instructorlistsanswers.py
2,277
4.03125
4
####################################################################################### # 1.1 # Loop through this list using a for loop and print all the values. list1 = [2, 4, 6, 8, 10, 12] for i in range(len(list1)): print(list1[i]) ####################################################################################### # 1.2 # Change all the values in the list to 0 using a for loop and then print the changed # list. list1 = ["dog", "cat", True, 1, 5, 0, 2, False, 1.2] for i in range(len(list1)): list1[i] = 0 print(list1) ####################################################################################### # 1.3 # Divide all the values in the list by 5. Then print the changed list. list1 = [5, 10, 15, 20, 25, 30, 35, 40] for i in range(len(list1)): list1[i] = list1[i] / 5 print(list1) ####################################################################################### # 1.4 # Loop through the list and change all values divisible evenly divisible by 3 into # "fizz", all values evenly divisible by 5 into "buzz", and all values evenly divisible # by both into "fizzbuzz" list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] for i in range(len(list1)): if list1[i] % 5 == 0 and list1[i] % 3 == 0: list1[i] = "fizzbuzz" elif list1[i] % 5 == 0: list1[i] = "buzz" elif list1[i] % 3 == 0: list1[i] = "fizz" print(list1) ####################################################################################### # 1.5 # Add ten strings to an empty list using a for loop empty_list = [] for i in range(10): empty_list.append("hi") ####################################################################################### # 1.6 # Add all numbers in the age list that are between 0 and 18 exclusive into the child # list. Move all numbers greater than 18 into the adult list. Delete the numbers you move. age_list = [1, 2, 44, 5, 18, 19, 25, 9, 11, 47, 32, 4, 6, 8, 20] adult_list = [] child_list = [] for i in range(len(age_list)-1, -1, -1): if age_list[i] < 18: child_list.append(age_list[i]) del age_list[i] else: adult_list.append(age_list[i]) del age_list[i] print(age_list) print(adult_list) print(child_list)
a290b0f8fceb02aeaf0704160bb27319c00b1771
omrikiei/mina-payout-script
/Currency.py
4,620
3.71875
4
# Credit: https://github.com/MinaProtocol/coda-python-client from enum import Enum class CurrencyFormat(Enum): """An Enum representing different formats of Currency in coda. Constants: WHOLE - represents whole coda (1 whole coda == 10^9 nanocodas) NANO - represents the atomic unit of coda """ WHOLE = 1 NANO = 2 class CurrencyUnderflow(Exception): pass class Currency(): """A convenience wrapper around interacting with coda currency values. This class supports performing math on Currency values of differing formats. Currency instances can be added or subtracted. Currency instances can also be scaled through multiplication (either against another Currency instance or a int scalar). """ @classmethod def __nanocodas_from_int(_cls, n): return n * 1000000000 @classmethod def __nanocodas_from_string(_cls, s): segments = s.split('.') if len(segments) == 1: return int(segments[0]) elif len(segments) == 2: [l, r] = segments if len(r) <= 9: return int(l + r + ('0' * (9 - len(r)))) else: raise Exception('invalid coda currency format: %s' % s) def __init__(self, value, format=CurrencyFormat.WHOLE): """Constructs a new Currency instance. Values of different CurrencyFormats may be passed in to construct the instance. Arguments: value {int|float|string} - The value to construct the Currency instance from format {CurrencyFormat} - The representation format of the value Return: Currency - The newly constructed Currency instance In the case of format=CurrencyFormat.WHOLE, then it is interpreted as value * 10^9 nanocodas. In the case of format=CurrencyFormat.NANO, value is only allowed to be an int, as there can be no decimal point for nanocodas. """ if format == CurrencyFormat.WHOLE: if isinstance(value, int): self.__nanocodas = Currency.__nanocodas_from_int(value) elif isinstance(value, float): self.__nanocodas = Currency.__nanocodas_from_string(str(value)) elif isinstance(value, str): self.__nanocodas = Currency.__nanocodas_from_string(value) else: raise Exception('cannot construct whole Currency from %s' % type(value)) elif format == CurrencyFormat.NANO: if isinstance(value, int): self.__nanocodas = value else: raise Exception('cannot construct nano Currency from %s' % type(value)) else: raise Exception('invalid Currency format %s' % format) def decimal_format(self): """Computes the string decimal format representation of a Currency instance. Return: str - The decimal format representation of the Currency instance """ s = str(self.__nanocodas) if len(s) > 9: return s[:-9] + '.' + s[-9:] else: return '0.' + ('0' * (9 - len(s))) + s def nanocodas(self): """Accesses the raw nanocodas representation of a Currency instance. Return: int - The nanocodas of the Currency instance represented as an integer """ return self.__nanocodas def __str__(self): return self.decimal_format() def __repr__(self): return 'Currency(%s)' % self.decimal_format() def __add__(self, other): if isinstance(other, Currency): return Currency(self.nanocodas() + other.nanocodas(), format=CurrencyFormat.NANO) else: raise Exception('cannot add Currency and %s' % type(other)) def __sub__(self, other): if isinstance(other, Currency): new_value = self.nanocodas() - other.nanocodas() if new_value >= 0: return Currency(new_value, format=CurrencyFormat.NANO) else: raise CurrencyUnderflow() else: raise Exception('cannot subtract Currency and %s' % type(other)) def __mul__(self, other): if isinstance(other, int): return Currency(self.nanocodas() * other, format=CurrencyFormat.NANO) elif isinstance(other, Currency): return Currency(self.nanocodas() * other.nanocodas(), format=CurrencyFormat.NANO) else: raise Exception('cannot multiply Currency and %s' % type(other))
e7fac3b77f9786ef9bbbe8aa9e2532f692f91239
shraddhakandale/python1
/fibonaccis series.py
355
3.65625
4
# 0 1 1 2 3 5 8 13 21 def fib(n): a = 0 b = 1 if n<=0: print("invalid series") elif n==1 : print(a) else: print(a) print(b) for i in range(2,n): c = a+b a = b b = c #if c < 100: print(c) fib(int(input("enter number")))
53305441e20aecad5ec9f1d90a89af24d50b82c8
neuraloverflow/Learn-python-ex
/ex12.py
169
3.6875
4
name = raw_input("What's your name? ") place = raw_input("Where are you from? ") print "Wow, cool! Your name is %r and you come from %r!\n\tFantastic!" % (name, place)
c05d970a3da14a7af8cc932ad93bad296e4086c0
Rishant96/Expert-Python
/Chapter_2-below_classes/List_n_Tuples.py
1,624
4.34375
4
# print(dir(tuple()), "\n") # print(dir(list())) """ Python Idioms for lists """ """ 1 - Python list 'Comprehension' """ evens = [] for i in range(10): if i % 2 == 0: evens.append(i) print(f'using c style for loop,\n{evens}\n') # ---------------------------------------------- evens = [i for i in range(10) if i % 2 == 0] print(f'using python comprehension,\n{evens}\n') """ 2 - Usiing the built-in function 'enumerate' """ print("Using old school counter variable 'i',\n") i = 0 for element in ['one', 'two', 'three']: print(i, element) i += 1 print("\n") # ---------------------------------------------- print("Getting the count using the 'enumerate' function,\n") for i, element in enumerate(['one', 'two', 'three']): print(i, element) print("\n") """ 3 - Using 'zip' to aggregate elements from multiple lists """ print("Showcasing 'zip',") for item in zip([1, 2, 3], [4, 5, 6]): print(item) print('\n') print("Reversing 'zip',") for item in zip(*zip([1, 2, 3], [4, 5, 6])): print(item) print("\n") """ 4 - Sequence unpacking """ first, second, third = "foo", "bar", 100 print(first) print(second) print(third) print("\n") # Unpacking allows you to capture multiple elements in a single expression # using starred expressions, as long as it can be interpreted unambiguosly first, second, *rest = 0, 1, 2, 3 print(first) print(second) print(rest) print("\n") # starred expresiion to capture middle of the sequence first, *inner, last = 0, 1, 2, 3 print(first) print(inner) print(last) print("\n") # nested unpacking (a, b), (c, d) = (1, 2), (3, 4) print(a, b, c, d)
b23da6f37918bd817e05f30c85854af66f9f87aa
Ltrahair/IntroProgramming-Labs
/working_with_objects.py
1,962
3.8125
4
class Product: def __init__(self,productName,productPrice,productQuantity): self.productName=productName self.productPrice=productPrice self.productQuantity=productQuantity def isThatMany(self,n): if n>self.productQuantity: return False else: return True def totalCost(self,n): return self.productPrice*n def removeProducts(self,n): self.productQuantity-=n products= [Product("Ultrasonic range finder",2.50,4) ,Product("Servo motor",14.99,10) ,Product("Servo controller",44.95,5) ,Product("Microcontroller Board",34.95,7) ,Product("Laser range finder",149.99,2) ,Product("Lithium polymer battery",8.99,8)] def printStock(): print() print("Available Products") print("------------------") for i in range(0,len(products)): if products[i].productQuantity > 0: print(str(i)+")",products[i].productName, "$", products[i].productPrice) print() def main(): cash = float(input("How much money do you have? $")) while cash > 0: printStock() vals = input("Enter product ID and quantity you wish to buy: ").split(" ") if len(vals)<1: continue if vals[0] == "quit": break prodId = int(vals[0]) count = int(vals[1]) if products[prodId].isThatMany(count): if cash >= products[prodId].totalCost(count): products[prodId].removeProducts(count) cash -= products[prodId].totalCost(count) print("You purchased", count, products[prodId].productName+".") print("You have $", "{0:.2f}".format(cash), "remaining.") else: print("Sorry, you cannot afford that product.") else: print("Sorry, we are sold out of", products[prodId].productName) main()
047998ca0b449021a85c293ab026bd9bad7de0ca
ECGonzales/Pythonpractice
/ex36.py
3,972
4.28125
4
#To try to do while I am away at momma's. #Create a game like the one from exercise 35. Use lists(ex 32,33,34), functions(sheet), #and modules(ex 13) from sys import exit #Define how you die in game def dead(explain): print explain, "That sucks!" exit(0) #Define how you win def win(explain): print explain, "You win!" exit(0) #define start of game def start(): print "You and a friend are about to head out on a road trip." print """It will be the greatest journey ever. However you and your friend never discussed where you were going. Which direction will you choose to travel in north or south?""" choice = raw_input(">>") if choice == "north" or choice == "N": northpath() elif choice == "south" or choice == "S": southpath() else: print "You only have those choices." #*****************Going north******************************************************** def northpath(): print "Alright northeast or northwest?" choice = raw_input(">>") if choice == "northeast" or choice == "NE": dead("You crash into a snow bank and die.") elif choice == "northwest" or choice == "NW": print "Ok. You were traveling along all hapiliy and then ..." print "You hit a pot hole and get a flat tire." print "There is a gas station 2 miles away that does repairs." print "Your buddy says he has AAA and would prefer to call them." print "Do you call AAA or walk to the gas station?" choice = raw_input(">>") if "AAA" in choice: print "Your buddy lost his AAA card." print "He needs to look up the number on his phone." AAAproblem() elif "gas station" in choice: gasstaion() else: dead("Well it took you too long to agree on what to do. Bear attacks.") else: print "testing2" #AAA def AAAproblem(): print "Do you guys have cell service here?" choice = raw_input(">>") if choice == "yes": print "There are two numbers that show up:" numbers = ["1-800-995-2247", "1-800-937-4245"] print numbers print "which number do you call?" choice = raw_input(">>") if choice == numbers[1]: print "That number is no longer in service." print "After you get off the phone you see a strange van." print "On the side is says 'Rare pokemon inside'." print "Your friend walks over while playing Pokemon Go." print "You join too." dead("Well that kidnapping was simple!") elif choice == numbers[0]: print "Hello how can we help you?:" AAAcall() else: print "incorrect number" AAAproblem() elif choice == "no": print "Well I guess you have to walk to the gas station" gasstation() else: print "Not an option." #AAA call def AAAcall(): choice = raw_input(">>") if "flat" or "tire" in choice: print "We will send a truck out right away." print "When AAA gets there, you ask if they can drop you off after the car is taken to the shop." print " Mandy, the AAA agent says 'No problem!'" print "You get dropped off at a 5 star cabin resort." win("Wow what a trip!") else: print "I'm sorry could you repeat that" AAAcall() #Gas Station def gasstation(): print "Following the crooked road down the way you see a sign," print "that says 'Now entering Town of Schuyler.'" print "Once you get to the gas station you really have to pee." print "The cashier hands you the key and says it is around back." print "As you close the bathroom door you see something strange run by." print "what do you do?" choice = raw_input(">>") if "run" in choice: print "They caught you." dead("Umm you look so tasty. You're dinner!") elif "hide" in choice: print "Your friend is worried. You have been gone for a long time." print "He walks towards the bathroom" dead("A machte cuts though his neck. You're next!") else: dead("Death by a massive turd!") #**************************going South************************************************** def southpath(): print "Now you are heading down I-95" start()
b5692d96188cd922c631811b5806dc74358ccb09
marcelo-py/Exercicios-Python
/exercicios-Python/desaf054.py
400
3.9375
4
from datetime import date total = 0 total2 = 0 for c in range(1,8): nascimento = int(input('Ano de nascimento da {}º pessoa'.format(c))) idade = nascimento + 18 if date.today().year - nascimento >= 18 : total += 1 else: total2 += 1 print('Há um total de {} pessoas menores de idade'.format(total2)) print('Há um total de {} pessoas maiores de idade'.format(total))
bbf53b5dd1c922d438a75489ffa30168003e8130
mjwakex/Country-guesser
/Main files/countries.py
2,003
3.8125
4
import csv, random, os, time score = 0 lives = 5 dict = {} with open("countries.csv", mode="r") as f: reader = csv.reader(f) dict_from_csv = {rows[0].replace('\xa0', '').lower():rows[1].lower() for rows in reader} def cls(): os.system("cls") def captial_guess(): global lives, score while lives != 0 : result = random.choice(list(dict_from_csv.keys())) print(result) answer = input("What is the capital of this country : ").lower() if answer == dict_from_csv[result]: print("You got it right!") score += 1 time.sleep(2) cls() else: lives -= 1 print(f"You got it wrong...\nThe correct answer is {dict_from_csv[result]}\nYou have {lives} remaining") time.sleep(2) cls() if lives == 0: print(f"You are out of lives, your score was {score}") def country_guess(): global lives, score while lives != 0 : result = random.choice(list(dict_from_csv.values())) print(result) answer = input("This is the capital of what country : ").lower() for key, value in dict_from_csv.items(): if result == value: correct = key if answer == correct: print("You got it right!") score += 1 time.sleep(2) cls() else: lives -= 1 print(f"You got it wrong...\nThe correct answer is {correct}\nYou have {lives} remaining") time.sleep(2) cls() if lives == 0: print(f"You are out of lives, your score was {score}") def intro(): option = int(input("Press (1) for capital game mode\nPress (2) for country game mode\nOption:")) while option != 1 and option != 2: option = int(input("Press (1) for capital game mode\nPress (2) for country game mode\nOption:")) if option == 1: captial_guess() else: country_guess() intro()
05391c71b2656f23cf74706f94d9e6e3ed5b56ba
famaxth/Way-to-Coding
/MCA Exam Preparations/Python/3 sum of squares of the digits in the odd position.py
318
3.90625
4
def main(): sum=0 iter=0 number = int(input("Enter a number to check Krishnamoorthy number : ")) num_string = str(number) for each in num_string: iter = iter + 1 if(iter%2==1): sum = sum + int(each)* int(each) print("sum is : ",sum) while True: main()
6602067a98581268fdcdef8731d4a8f990574a71
bilginyuksel/clighter
/clighter/core/dimension.py
479
4.09375
4
class Dimension: def __init__(self, height: int, width: int) -> None: """ Construct dimension object. Dimension is useful when you deal with scene. `height` can be seen as the distance from the starting point of some `y` point in coordinate system. `width` can be seen as the distance from the starting point of some `x` point in coordinate system. """ self.height = height self.width = width
b47f70ee1b356085e3a8bb4e0756e1bf5f4e0619
Estefa29/Ejercicios_con_Python
/Vectores y matrices/ejercicios_matrices.py
8,999
4.03125
4
# Realice un algoritmo que permita diseñar un sudoku, donde se debe de ingresar # inicialmente la posición aleatoria de los valores con los cuales se va iniciar, # luego deberá comenzar el juego y validar las jugadas, si excede el valor total por # columnas o filas deberá emitir un mensaje de error. import numpy as np def check_sudoku(grid): """ Return True if grid is a valid Sudoku square, otherwise False. """ for i in range(9): # j, k index top left hand corner of each 3x3 tile j, k = (i // 3) * 3, (i % 3) * 3 if len(set(grid[i,:])) != 9 or len(set(grid[:,i])) != 9\ or len(set(grid[j:j+3, k:k+3].ravel())) != 9: return False return True sudoku = """245327698 839654127 672918543 496185372 218473956 753296481 367542819 984761235 521839764""" # Turn the provided string, sudoku, into an integer array grid = np.array([[int(i) for i in line] for line in sudoku.split()]) print(grid) if check_sudoku(grid): print('cuadricula valida') else: print('cuadricula invalida') # Realice un algoritmo que permita hacer un ahorcadito, # la matriz permitirá almacenar las palabras, se recomienda que las palabras tengan # el mismo tamaño para evitar reasignar el valor o tamaño de la matriz. import random AHORCADO = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | / | | =========''', ''' +---+ | | O | /|\ | / \ | | ========='''] palabras = 'valoracion aprenderpython comida juego python web imposible variable curso volador cabeza reproductor mirada escritor billete lapicero celular valor revista gratuito disco voleibol anillo estrella'.split() def buscarPalabraAleat(listaPalabras): palabraAleatoria = random.randint(0, len(listaPalabras) - 1) return listaPalabras[palabraAleatoria] def displayBoard(AHORCADO, letraIncorrecta, letraCorrecta, palabraSecreta): print(AHORCADO[len(letraIncorrecta)]) print ("") fin = " " print ('Letras incorrectas:', fin) for letra in letraIncorrecta: print (letra, fin) print ("") espacio = '_' * len(palabraSecreta) for i in range(len(palabraSecreta)): if palabraSecreta[i] in letraCorrecta: espacio = espacio[:i] + palabraSecreta[i] + espacio[i+1:] for letra in espacio: print (letra, fin) print ("") def elijeLetra(algunaLetra): while True: print ('Adivina una letra:') letra = input() letra = letra.lower() if len(letra) != 1: print ('Introduce una sola letra.') elif letra in algunaLetra: print ('Ya has elegido esa letra ¿Qué tal si pruebas con otra?') elif letra not in 'abcdefghijklmnopqrstuvwxyz': print ('Elije una letra.') else: return letra def empezar(): print ('Quieres jugar de nuevo? (Si o No)') return input().lower().startswith('s') print ('A H O R C A D O') letraIncorrecta = "" letraCorrecta = "" palabraSecreta = buscarPalabraAleat(palabras) finJuego = False while True: displayBoard(AHORCADO, letraIncorrecta, letraCorrecta, palabraSecreta) letra = elijeLetra(letraIncorrecta + letraCorrecta) if letra in palabraSecreta: letraCorrecta = letraCorrecta + letra letrasEncontradas = True for i in range(len(palabraSecreta)): if palabraSecreta[i] not in letraCorrecta: letrasEncontradas = False break if letrasEncontradas: print ('¡Muy bien! La palabra secreta es "' + palabraSecreta + '"! ¡Has ganado!') finJuego = True else: letraIncorrecta = letraIncorrecta + letra if len(letraIncorrecta) == len(AHORCADO) - 1: displayBoard(AHORCADO, letraIncorrecta, letraCorrecta, palabraSecreta) print ('¡Se ha quedado sin letras!\nDespues de ' + str(len(letraIncorrecta)) + ' letras erroneas y ' + str(len(letraCorrecta)) + ' letras correctas, la palabra era "' + palabraSecreta + '"') finJuego = True if finJuego: if empezar(): letraIncorrecta = "" letraCorrecta = "" finJuego = False palabraSecreta = buscarPalabraAleat(palabras) else: break # este ejercicio lo modifique de internet # Realice un algoritmo que permita realizar un triqui de 3*3 # es necesarias todas las validaciones. from collections import deque turno = deque(["0", "X"]) tablero = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "], ] def mostrar_tablero(): print("") for fila in tablero: print (fila) def actualizar_tablero(posicion, jugador): tablero[posicion[0]][posicion[1]] = jugador def rotar_turno(): turno.rotate() return turno[0] def procesar_posicion(posicion): fila, columna = posicion.split(",") return [int(fila)-1, int(columna)-1] def posicion_correcta(posicion): if 0 <= posicion[0] <= 2 and 0 <= posicion[1] <= 2: if tablero[posicion[0]][posicion[1]] == " ": return True return False def ha_ganado(j): #compara las filas del tablero if tablero[0] == [j,j,j] or tablero[1] == [j,j,j] or tablero[2] == [j,j,j]: return True #compara las columnas elif tablero[0][0] == j and tablero[1][0] == j and tablero[2][0] == j: return True elif tablero[0][1] == j and tablero[1][1] == j and tablero[2][1] == j: return True elif tablero[0][2] == j and tablero[1][2] == j and tablero[2][2] == j: return True #compara las diagonales elif tablero[0][0] == j and tablero[1][1] == j and tablero[2][2] == j: return True elif tablero[0][2] == j and tablero[1][1] == j and tablero[2][0] == j: return True return False def juego(): mostrar_tablero() jugador = rotar_turno() while True: posicion = input("Juega {}, elige una posicion (fila, columna) de 1 a 3. 'salir' para salir".format(jugador)) if posicion == 'salir': print ("Adios!!!") break try: posicion_l = procesar_posicion (posicion) except: print ("Error, posicion {} no es válida. ".format(posicion)) continue if posicion_correcta(posicion_l): actualizar_tablero(posicion_l, jugador) mostrar_tablero() if ha_ganado(jugador): print ("Jugador de {} ha ganado!!!".format(jugador)) break jugador = rotar_turno() else: print ("Posicion {} no válida".format(posicion)) juego() # tabla de multiplicación y que se pueda llenar sola de la tabla del 1 al 14 for i in range(1, 15): for j in range(1, 11): print(f'{i} x {j} = {i * j}') # Realice un algoritmo que permita obtener el valor de cada uno de los vehículos # teniendo la siguiente tabla de información. # vehiculos=[renault=0,chevrolet=0,mazda=0,audi=0,flat=0,toyota=0] # precio=[MazdaPrecio=70000000,RenultPrecio=56000000,ChevroletPrecio=64000000, # AudiPrecio=170000000,FlatPrecio=79000000,ToyotaPrecio=80000000] # descuento[MazdaDes=0.10,RenultDes=0.20,ChevroletDes=0.11,AudiDes=0.10,FlatDes=0.7,ToyotaDes=0.12] # Mazda=0 # Renult=0 # Chevrolet=0 # Audi=0 # Flat=0 # Toyota=0 MazdaPrecio=70000000 RenultPrecio=56000000 ChevroletPrecio=64000000 AudiPrecio=170000000 FlatPrecio=79000000 ToyotaPrecio=80000000 MazdaDes=0.10 RenultDes=0.20 ChevroletDes=0.11 AudiDes=0.10 FlatDes=0.7 ToyotaDes=0.12 Vehiculo = input("Ingrese el vehiculo que desea comprar: ") if(Vehiculo=="Mazda" or "mazda"): print("Valor a pagar: ", MazdaPrecio - MazdaDes ) elif(Vehiculo=="Renult" or "renult"): print("Valor a pagar: ", RenultPrecio - RenultDes ) elif(Vehiculo=="Chevrolet" or "chevrolet"): print("Valor a pagar: ", ChevroletPrecio - ChevroletDes ) elif(Vehiculo=="Audi" or "audi"): print("Valor a pagar: ", AudiPrecio - AudiDes ) elif(Vehiculo=="Flat" or "flat"): print("Valor a pagar: ", FlatPrecio - FlatDes ) elif(Vehiculo=="Toyota" or "toyota"): print("Valor a pagar: ", ToyotaPrecio - ToyotaDes ) else: print("Por favor ingresa un valor valido") # lo intente hacer con una lista pero no supe # Se tiene una matriz con un tamaño para 100 registro de correos que le llega a un usuario # donde se almacena un código consecutivo, la fuente (correo del remitente), el asunto # y la descripción del correo y la fecha correos=[] for i in range(100): datos=(input("Ingrese asunto, descripción del correo y la fecha: ")) correos.append(datos) print(correos) correos.reverse() print(correos) # https://www.youtube.com/watch?v=w0LqU99RRy8&t=281s
d13c158a4f14d436ef8493aa106b9961c0de4108
rcanaan/Functional-Programming-in-Python
/תרגיל 3/ex3q5.py
530
3.75
4
#Rinat Canaan 207744012 #ex 3 question 5 def m(n): f = lambda i: i/(i+1) #the wanted equation def recursiveSumFunc(k): if k == 0: return 0 else: return recursiveSumFunc(k - 1) + f(k) return recursiveSumFunc(n) def main(): n = abs(int(input("Enter a Number: "))) print("the sum is: ", m(n), "\n") """ output: Enter a Number: >? 3 the sum is: 1.9166666666666665 the item: 1 = 0.5 the item: 2 = 1.1666666666666665 the item: 3 = 1.9166666666666665 helpFunc result: """
6f7dbb3c039f0defc8c0800ae0a7c9457d7ee0b7
prajaktaaD/Basic-Python1
/add.py
107
3.765625
4
a=int(input("enter val of a:")) b=int(input("enter val of b:")) sum=a+b print("sum=",sum) print(type(sum))
597f25d6a5127e310c4c39dbaf52404bf3657152
Nora-Wang/Leetcode_python3
/Dynamic Programming/背包问题/01背包/416. Partition Equal Subset Sum.py
1,754
3.625
4
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5, 11, 5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. 解析: 实际上就是求是否存在子数组,使得子数组的和等于整个数组和的1/2。考虑用动规,看成是0-1背包问题的一种变形,dp[i][j]表示考虑前i个数字, 是否存在子数组和为j。 转移方程为dp[i][j] = dp[i-1][j] | dp[i-1][j-nums[i]](即不选第i个数字或者选第i个数字) 可以用滚动数组进行优化。 时间复杂度: O(MN). M是数组元素和,N是数组元素个数 参考链接:https://www.acwing.com/solution/LeetCode/content/6416/ code: ''' step 1: set find a subset that sum is target(all_sum // 2) dp[i][j]: i means the previous i numbers; j means curt subset sum dp[i][j]表示考虑前i个数字,是否存在子数组和为j step 2: attribute count step 3: pick it or not pick it dp[i] -> dp[i - 1][j], dp[i - 1][j - nums[i]] ''' class Solution: def canPartition(self, nums: List[int]) -> bool: all_sum = sum(nums) if all_sum % 2: return False target = all_sum // 2 dp = [0] * (target + 1) dp[0] = 1 for i in range(0, len(nums)): for j in range(target, nums[i] - 1, -1): dp[j] |= dp[j - nums[i]] return dp[target]
fb275aa50dcbb302b41ae1e2b257a79d1e728d7e
Aasthaengg/IBMdataset
/Python_codes/p02963/s991598209.py
112
3.578125
4
S = int(input()) x2 = 10**9 x3 = (x2 - S%x2) % x2 y3 = (S + x3) // x2 print('0 0 {} 1 {} {}'.format(x2,x3,y3))
4939763f263e98bb7dd1f78ebdaae9ec3b7e356d
Kimbsy/feed-me
/src/meal.py
740
3.796875
4
#!/usr/bin/python from ingredient import Ingredient class Meal: """The Meal class contains the name of the meal as well as a list of required Ingredients. """ def __init__(self, options): self.ingredients = [] self.hydrate(options) def hydrate(self, options): self.name = options['name'] if 'ingredients' in options.keys(): for ingredient_data in options['ingredients']: ingredient = Ingredient(ingredient_data) self.ingredients.append(ingredient) def show(self, string): string = string + self.name + ':' + '\n' for ingredient in self.ingredients: string = ingredient.show(string) return string
d08f70e1711874ed57fbdc089835155e4d98bd57
beechundmoan/python
/caesar_8.py
1,359
4.3125
4
""" All of our previous examples have a hard-coded offset - which is fine, but not very flexible. What if we wanted to be able to encode a bunch of different strings with different offsets? Functions have a great feature for exactly this purpose, called "Arguments." Arguments are specific parameters that we can set when we call a function, and they're super versatile. """ def encode_string(character_offset): string_to_encode = input("Please enter a message to encode! [ PRESS ENTER TO ENCODE ] :") string_to_encode = string_to_encode.upper() output_string = "" no_translate = "., ?!" # We don't need the following line, because we've defined it as an argument. #character_offset = 6 for character in string_to_encode: if character in no_translate: new_character = character else: ascii_code = ord(character) new_ascii_code = ascii_code + character_offset if new_ascii_code > 90: new_ascii_code -= 25 new_character = chr(new_ascii_code) output_string += new_character print(output_string) print("Welcome to our second Caesar Cipher script") print("Let's call our first argumented function!") # Those parentheses might make a little more sense now... encode_string(3) encode_string(18) encode_string(1) # Notice that we can now specify an offset of zero, which doesn't encode at all! encode_string(0)
d425a9a9632134d1822e95cbb631492176be15b8
lynhyul/Coding_test
/프로그래머스/간단한문제/행렬의덧셈.py
1,145
3.53125
4
# 문제 설명 # 행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. # 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요. # 제한 조건 # 행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다. # 입출력 예 # arr1 arr2 return # [[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]] # [[1],[2]] [[3],[4]] arr1 = [[3,4,5],[5,6,7]] arr2 = [[4,5,6],[7,8,9]] # print(arr1[0][1]+arr1[0][1]) # 4+4 = 8 print(arr1[0][1]) # 4 //0번째 행에서 1번째열 def solution(arr1,arr2) : answer = [[]for x in range(len(arr2))] # 세로크기 for i in range(len(arr1)) : #가로크기 for j in range(len(arr1[i])) : answer[i].append(arr1[i][j] + arr2[i][j]) return answer print(solution(arr1,arr2)) # 다른 사람 풀이 def sumMatrix(A,B): answer = [[c + d for c, d in zip(a, b)] for a, b in zip(A,B)] return answer # 아래는 테스트로 출력해 보기 위한 코드입니다. print(sumMatrix([[1,2], [2,3]], [[3,4],[5,6]]))
24c8a810c6d4dfc8359331ac7d38942d82e213fc
ChristopherRogers1/IntroProgramming-Labs
/madlib.py
216
3.578125
4
noun = input("Enter a noun: ") verb = input ("Enter a verb: ") adj = input ("Enter an adjective: ") place = input ("Enter a place: ") print ("Take your " + adj + " " + noun + " and " + verb + " it at the " + place)
bfc963779e73a678577112c764d44057e52b3fd2
Scribbio/pYdioms
/Other/Corpera.py
1,328
3.53125
4
from nltk.corpus import CategorizedPlaintextCorpusReader import nltk, string, numpy reader = CategorizedPlaintextCorpusReader(r'\Users\JoeDi\Desktop\MSC\Idioms Corpera', r'.*\.txt', cat_pattern=r'(\w+)/*') print(reader.categories()) print(reader.fileids()) from random import randint File = reader.fileids() fileP = File[randint(0, len(File)-1)] print(fileP) for w in reader.words(fileP): print(w + ' ', end='') if (w is '.'): print() #https://sites.temple.edu/tudsc/2017/03/30/measuring-similarity-between-texts-in-python/ from sklearn.feature_extraction.text import CountVectorizer import nltk, string, numpy sss = "Because there is no easy way to decide how two words, two documents are related. All we have is sequence of letters " \ "or strings if you prefer. So how to find a relationship between two words? If you want to decide how two documents related, " \ "how to figure that out? It cant be done without having any other data." sss2 = " If you want to decide how two documents related, how to figure that out? It cant be done without having any other data." \ "If you have some other parameter, it can be converted into plot or statistical methods can be applied. " \ "In order to create that parameter, document is first vectorized." documents = [sss, sss2]
0826ca74846594df618664de35ae8f6ad0fef43f
DropthaBeatus/PythonTutorialForStudent
/BinTree.py
2,712
3.953125
4
import random #TODO make sure to flatten binary tree to linked list #TODO find least common ancestor of binary tree nods #TODO Convert a binary tree to its sum tree(each node is the sum of its children) # 1--2---5--6--19--0--2-20-13-15-3-5-32-1-3-7-6-8 #16 class Node: data = 0 def __init__(self, data): self.data = int(data) self.right = None self.left = None def add_left(self,data): self.left = Node(data) def add_right(self,data): self.right = Node(data) class BinTree: def __init__(self,data): self.root = Node(data) def add_Node_Order(ele, node): if node.data <= ele: if node.left is None: node.add_left(ele) else: add_Node_Order(ele, node.left) else: if node.right is None: node.add_right(ele) else: add_Node_Order(ele, node.right) def print_all_nodes(node): if node.left is not None: print(node.data) print_all_nodes(node.left) if node.right is not None: print(node.data) print_all_nodes(node.right) def height(node): if node is None: return 0 else: # Compute the height of each subtree lheight = height(node.left) rheight = height(node.right) # Use the larger one if lheight > rheight: return lheight + 1 else: return rheight + 1 def printLevelOrder(root): h = height(root) for i in range(1, h + 1): printGivenLevel(root, i) # Print nodes at a given level def printGivenLevel(root, level): if root is None: return if level == 1: print(root.data, end=" ") elif level > 1: printGivenLevel(root.left, level - 1) printGivenLevel(root.right, level - 1) #TODO link left node as prev node to make doubly linked list def flatten(root): if root != None or root.left != None or root.right != None: return tmp_node = root.right root.right = root.left root.left = None move_node = root.right while(move_node.right != None): move_node = move_node.right move_node.right = tmp_node flatten(root.right) def inorder(root): # Base condition if (root == None): return inorder(root.left) print(root.data, end=' ') inorder(root.right) tree = BinTree(50) x = 0 print(tree.root.data) print() print() while x < 50: test = random.randint(0,101) add_Node_Order(test, tree.root) x+=1 inorder(tree.root) flatten(tree.root) inorder(tree.root)
b49e540b3c56972c34ef859bc1f1d554677bfa65
shcqupc/hankPylib
/leetcode - 副本/S0033_1103_distributeCandies.py
1,722
3.65625
4
''' 分糖果 II 输入:candies = 7, num_people = 4 输出:[1,2,3,1] 解释: 第一次,ans[0] += 1,数组变为 [1,0,0,0]。 第二次,ans[1] += 2,数组变为 [1,2,0,0]。 第三次,ans[2] += 3,数组变为 [1,2,3,0]。 第四次,ans[3] += 1(因为此时只剩下 1 颗糖果),最终数组变为 [1,2,3,1]。 ''' class Solution(object): def distributeCandies(self, candies, num_people): """ :type candies: int :type num_people: int :rtype: List[int] """ n = 0 a = 0 ln = 0 ans = [0 for x in range(num_people)] while True: if n == candies: return ans elif n > candies: a = candies - n + a if ln >= num_people: ans[ln % num_people] += a else: ans[ln] += a return ans else: a += 1 n += a if n > candies: a = candies - n + a n = candies if ln >= num_people: ans[ln % num_people] += a else: ans[ln] += a ln += 1 def distributeCandies2(self, candies: int, num_people: int) -> List[int]: ans = [0] * num_people i = 0 while candies != 0: ans[i % num_people] += min(i + 1, candies) candies -= min(i + 1, candies) i += 1 return ans s = Solution() print(s.distributeCandies(7, 4)) print(s.distributeCandies(10, 3)) print(s.distributeCandies(0, 3)) print(s.distributeCandies(1, 3)) print(s.distributeCandies(1, 3))
397c41f65c6efc16407b8b480e75285901e9e27a
johnson365/python
/Design Pattern/Decorator.py
1,020
3.6875
4
from abc import ABCMeta, abstractmethod class Component: __metaclass__ = ABCMeta @abstractmethod def operation(self): pass class ConcreteComponent(Component): def operation(self): print('The operation of concrete component!') class Decorator(Component): def setComponent(self, component): self.component = component def operation(self): if self.component != None: self.component.operation() class ConcreteDecoratorA(Decorator): def operation(self): self.component.operation() self.__addedState = 'new State' print('Implementation of concrete decorator A!') class ConcreteDecoratorB(Decorator): def operation(self): self.component.operation() self.__addedBehavior() print('Implementation of concrete decorator B!') def __addedBehavior(self): print('self.__addedBehavior()') if __name__ == '__main__': c = ConcreteComponent() d1 = ConcreteDecoratorA() d2 = ConcreteDecoratorB() d1.setComponent(c) d2.setComponent(d1) d2.operation()
7c03130606656cf0b69e09ace9967a1c02c5ee9b
anubhavv1998/Python-While
/armstrong.py
237
3.90625
4
num=int(input('Enter no. to check if it is armstrong or not ')) sum=0 temp=num while temp>0: digit=temp%10 sum=sum+digit**3 temp=temp//10 if num==sum: print('%d is armstrong'%(num)) else: print('%d is not armstrong'%(num))
05593838c86beabfeca6bdcb740e1eeff8e64b34
plasmatic1/Py-Generator
/param_parser.py
1,644
3.53125
4
import random import re def process_param(param): """ Processes the value in the `vars` section in a case config. Generally they are kept untouched except for these extended data types x~y : Random (uniform) number between `x` and `y` (An integer if both `x` and `y` are integers, otherwise it is a float) x:y : Range from `x` to `y` with +1 increment. Note that these are standard python ranges x:y:z : Range from `x` to `y` with `+z` increment :param param: The parameter to process :return: The processed parameter """ if isinstance(param, str): spl = param.split('~') if len(spl) == 2: if _is_int(spl[0]) and _is_int(spl[1]): return random.randint(int(spl[0]), int(spl[1])) elif _is_number(spl[0]) and _is_number(spl[1]): return random.uniform(float(spl[0], float(spl[1]))) spl = param.split(':') if 2 <= len(spl) <= 3: if all(spl, _is_int): return range(*map(int, spl)) return param return param def _is_number(str_): """ Checks if str_ is a number (either float or int) :param str_: The string to check :return: Whether it is a float """ return _is_int(str_) or _is_float(str_) def _is_float(str_): """ Checks if str_ is a float :param str_: The string to check :return: Whether it is a float """ return bool(re.match('[+-]?\d+\.\d*$', str_)) def _is_int(str_): """ Checks if str_ is an int :param str_: The string to check :return: """ return bool(re.match('[+-]?\d+$', str_))
5956f9c5593a91286c63ec95b3acdf7bb6d7ea3d
guilhermefsc/Curso-em-V-deo---Python
/Mundo 1/ex007 - media aritmetica.py
188
3.78125
4
n1 = float(input('Primeira nota do aluno: ')) n2 = float(input('Segunda nota do aluno: ')) media = (n1+n2)/2 print('A média entre {:.1f} e {:.1f} é igual a {:.1f}.'.format(n1,n2,media))
b4881cab6161034d1d89dcaf19e46e10ec55f48e
hieuvp/learning-python
/advanced-tutorials/exception-handling/example.py
591
3.8125
4
def do_stuff_with_number(number): print("number = %s" % number) def catch_this(): # This list only has "3" numbers in it numbers = (11, 22, 33) # Iterate over "5" numbers for index in range(5): try: number = numbers[index] do_stuff_with_number(number) # Raised when accessing a non-existing index of a list except IndexError: # After reaching the end of "numbers", # we just want the rest to be interpreted as a "0" number = 0 do_stuff_with_number(number) catch_this()
55eed8180584350667ebf02679f8c2c30a1f1893
tariksetia/Algx-Practice
/sorting/partition.py
1,481
4.03125
4
def partition (start, end, data): pivot = start lo, hi = start, end while True: while data[pivot] >= data[lo] and lo < end: lo += 1 while data[pivot] < data[hi] and hi >start: hi -= 1 if hi<=lo : break data[hi], data[lo] = data[lo], data[hi] # This statement comes after the check data[hi], data[pivot] = data[pivot], data[hi] #hi is the pivor return hi # Hi is the pivot def three_way_partition(start, end, data): pivot = start lt = start gt = end i = start + 1 while i <= gt: if data[i] < data[pivot]: data[i], data[lt] = data[lt], data[i] i, lt = i+1, lt+1 elif data[i] > data[pivot]: data[i], data[gt] = data[gt], data[i] gt -= 1 elif data[i] == data[pivot]: i += 1 return (lt,gt) def partition_event_odd(data): data = list(data) low, high = 0, len(data)-1 while low < high: while data[low]%2 == 0 and low < high: low += 1 while data[high]%2 ==1 and low <high: high -=1 if low<high: data[low],data[high] = data[high],data[low] low += 1 high -= 1 return data if __name__ == '__main__': a= [3,2,5,2,6,23,5,34,23,5,324,3421,1235,456,324] print(partition_event_odd(a)) b=[1,0,2,0,1,0,2,2,1,0,0,1,1,2,0,0,2]
866f03082ba16e28f7deb5a2c42ad32930b3fc78
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 3 Conditional/assn_3.3.py
795
4.4375
4
# 3.3 # Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following # table: # Score Grade # >= 0.9 A # >= 0.8 B # >= 0.7 C # >= 0.6 D # < 0.6 F # If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85. try: score = float(raw_input("Please Enter a Value between 0.0 and 1.0:")) except: print "Thats not a value between 0.0 and 1.0, Please try again" quit() #if except runs quit the program if 0.9 <= score <= 1.0: print 'A' elif 0.8 <= score < 0.90: print 'B' elif 0.7 <= score < 0.80: print 'C' elif 0.6 <= score < 0.70: print 'D' elif 0.0 <= score < 0.60: print 'F' else: print "some other error"
69dbd41a9424dcd06c8556dc197b3e175406cda9
mmcgee26/PythonProjects
/7_2.py
1,089
3.796875
4
def toBin(n): # base case if n <= 1: return str(n) return toBin(n//2) + str(n % 2) print(toBin(14)) ## print nth Fibonacci number : Using loop technique def fib(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a print (fib(5)) ## print nth Fibonacci number : Using recursion def fibR(n): if n==1 or n==2: return 1 return fibR(n-1)+fibR(n-2) print (fibR(5)) def hanoi(num, _from, _by, _to): # base condition, when n == 1, move 1 disk from A to C, which is same as printing the disk move if num == 1: print("from {} to {} : move disk {}".format(_from, _to, num)) return # pattern for the minimal moves hanoi(num-1, _from, _to, _by) # move n-1 disks from A to B print("from {} to {} : move disk {}".format(_from, _to, num)) # move 1 disk from A to C (print the disk move) hanoi(num-1, _by, _from, _to) # move n-1 disks from B to C hanoi(3, 'A', 'B', 'C')
073f212117191e2ffb980faf2cc2599c62edf4ac
misohan/Udemy
/Test_udemy.py
1,419
4.375
4
# numbers = 1, 2, 3, data type integer # strings = "ahoj", data type string # lists = [], can be changed # tuples = (), can not be changed # dictionary = {}, key values multiplication = 2.005*50 print(multiplication) divison = 401/4 print(divison) exponent = 10.01249219725040309**2 print(exponent) addition = 100+0.25 print(addition) substraction = 100.5-0.25 print(substraction) # What is the value of the expression 4 * (6 + 5) # 44 first = 4 * (6 + 5) print(first) # What is the value of the expression 4 * 6 + 5 # 29 second = 4 * 6 + 5 print(second) # What is the value of the expression 4 + 6 * 5 # 34 third = 4 + 6 * 5 print(third) # What is the type of the result of the expression 3 + 1.5 + 4? # expression = 8.5, it is a float # Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below: s0 = 'hello' # Print out 'e' using indexing print(s0[1]) # Reverse the string 'hello' using slicing: s1 = 'hello' # Reverse the string using slicing print(s1[::-1]) # Given the string hello, give two methods of producing the letter 'o' using indexing. s2 ='hello' # Print out the 'o' # Method 1: print(s2[-1]) # Method 2: print(s2[4]) # Build this list [0,0,0] two separate ways. # Method 1: # Method 2: # Reassign 'hello' in this nested list to say 'goodbye' instead: list3 = [1,2,[3,4,'hello']] for i in list3: list3[2][2] = 'goodbye' print(list3)
ded75bf0e0dd84a7789a756dfcfa34afa46bbbd1
test-for-coocn/test-back
/pyton/Histogram_1.py
807
3.78125
4
import matplotlib.pyplot as mpt import math def sqr(x): return x * x data = [66, 59, 62, 64, 63, 68, 65, 59, 68, 64, 65, 51, 67, 64, 83, 59, 61, 62, 57, 72, 65, 64, 54, 60, 53, 65, 67, 60, 53, 79, 74, 53, 61, 68, 75, 50, 57, 55, 66, 56, 55, 61, 70, 71, 49, 69, 70, 80, 73, 72] n = len(data) # The number of scores print("n =%d"%n) print("Data...") i = 1 for x in data: print("%5d:"%i + " %f"%x) i+=1 mpt.title("Histogram") # The title of the histogram mpt.xlabel("Score") # The label of the x-axis mpt.ylabel("Frequency") # The label of the y-axis mpt.hist(data, bins = 10) # Making the histogram mpt.show() # Show the histogram
90468094eba93a44725707f532797ed506a41723
EoghanDelaney/Problem-Sets
/primes.py
1,213
4.46875
4
## In this instance I have used the following link to help me in this question. ## https://www.programiz.com/python-programming/examples/prime-number ## I have adapted it to read the way I would want it. ## The core of this question is how to calculate a prime number & having reviewed the above link it is clear - something that is divisible by only itself and one! value = int(input("Please enter a positive integer: ")) # as previous questions the try element is to determine whether the user inputted a positive integer try : number = int(value) if number > 1: for i in range(2,number): ## for i in range 2,3,4,5,6....number - up to but not including number if (number%i)==0: ## we then divide our number chosen by the above range, loop through number/2../3../4 and so on up to number/(number-1), If any of these are true we have a number that divides into our chosen number ## And this cant be the case! A zero remainder would mean it evenly devides print(number, " is not a prime number!") break else: print(number, " is a prime number!") except ValueError: print("This is not a integer!")
e10e469c265b93ffbd98399baa040a58875d0179
jonathansayer/airport_challenge_python
/airport_unittest.py
1,482
3.546875
4
import unittest from mock import Mock from airport import Airport class AirportTest(unittest.TestCase): def test(self): self.assertTrue(True) def test_airport_capacity(self): airport = Airport() self.assertEqual(airport.capacity,20) def test_airport_land_plane(self): airport = Airport() plane = Mock() airport.land_plane(plane) plane.land.assert_called_once_with() def test_airport_storing_planes(self): airport = Airport() plane = Mock() airport.land_plane(plane) self.assertEqual(airport.planes,[plane]) def test_airport_take_off_plane(self): airport = Airport() plane = Mock() weather = Mock() weather.stormy.return_value = False airport.planes = [plane] airport.release_plane(plane,weather) plane.take_off.assert_called_once_with() def test_airport_release_plane(self): airport = Airport() plane = Mock() weather = Mock() weather.stormy.return_value = False airport.land_plane(plane) airport.release_plane(plane,weather) self.assertEqual(airport.planes,[]) def test_stormy_weather(self): airport = Airport() plane = Mock() weather = Mock(stormy=True) airport.planes = [plane] self.assertEqual(airport.release_plane(plane,weather), "Weather is Stormy") if __name__ == '__main__': unittest.main()
fabc10712901d09eb22d6cfb4e3fe24e50b43aca
JonSeijo/project-euler
/problems 70-79/problem_75.py
2,133
3.859375
4
# Problem 75 # Singular integer right triangles """ It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L <= 1,500,000 can exactly one integer sided right angle triangle be formed? """ import math Lmax = 1500000 triangles = {} ps = [] """ https://en.wikipedia.org/wiki/Farey_sequence https://en.wikipedia.org/wiki/Pythagorean_triple farey_function generates a and b coprimes. If a and b aren't both odd, then the euclid's formula will generate a _primitive_ pythagorean triplet From the primitive triplets, I get every posible triplet by multiplying by a natural k, Then I count the results that were generated only once """ def farey_function(n): a, b, c, d = 0, 1, 1, n while (c <= n): k = int((n + b) / d) a, b, c, d = c, d, (k*c-a), (k*d-b) # If a and b aren't both odd, if (a % 2 == 1 and b % 2 == 1): continue # a < b # Euclid's formula: generate a _primitive_ pythagorean triplet x1 = b*b - a*a x2 = 2*a*b x3 = b*b + a*a L = x1 + x2 + x3 if (L <= Lmax): ps.append(L) farey_function(10000) # ps has the primitive triplets, I want to get every one so multiply by k for p in ps: k = 1 while (k*p <= Lmax): saved_value = triangles.get(k*p, 0) triangles[k*p] = saved_value + 1 k += 1 rta = 0 # answer is the amount of Ls that are made from only oone combination for l, cant in triangles.items(): if (cant == 1): rta += 1 print("rta: " + str(rta))
d6be744cfb739c1c72df25b46651170a18d59142
LacThales/tic-tac-toe-in-python
/tic-tac-toe.py
4,770
4
4
import sys #para sair do programa explicacao = ''' //// Sobre o jogo: //// Automaticamente você será o 1º Jogador e começará sendo o X, mas pode optar por ser o 2º Jogador (e ser o O (bola)), só deixar seu amigo começar jogando :D. Quando for sua vez, digite o número correspondente à linha e coluna no tabuleiro para fazer sua jogada nela. Por exemplo, digamos que você queira jogar na linha 1, coluna 1, você começara no canto superior esquerdo. | | X | 2 | 3 _____|_____|_____ | | 4 | 5 | 6 _____|_____|_____ | | 7 | 8 | 9 | | ''' tabuleiro= [ [0,0,0], [0,0,0], [0,0,0] ] def start(): print(explicacao) while True: comecar = int(input("Digite 1 para iniciar o jogo: ")) if comecar == 1: global tabuleiro #----------------------- tabuleiro em formato de matriz, sempre com 0, para sempre que reiniciar, poder posicionar o X(xis) e o O(bola) novamente ----------------------- tabuleiro= [ [0,0,0], [0,0,0], [0,0,0] ] jogo() else: print("Escrita inválida, reinicie o jogo.") sys.exit(0) # ---------- sair do jogo ----------- def show(): #----------------------- OBS.: range até 3 pois o jogo se baseia em um quadrado 3x3 ----------------------- #----------------------- Linha. ----------------------- #----------------------- Os jogadores no cód sempre serão alternados de 1 e -1, mesmo que no print apareça player 1 e 2 ------------------------- for linha in range(0, 3): #----------------------- Coluna ----------------------- for coluna in range(0, 3): if tabuleiro[linha][coluna] == 0: print(" _ ", end=' ') #----------------------- End=' ' para fazer com que o print do tabuleiro fique um do lado do outro 3x3 _ _ _ ----------------------- elif tabuleiro[linha][coluna] == 1: print(" X ", end=' ') elif tabuleiro[linha][coluna] == -1: print(" O ", end=' ') print() def jogo(): chances=0 while vencedor() == 'continue': print("\nPlayer ", chances%2 + 1, ' :D ') show() linha = int(input("Digite uma linha: ")) if linha > 3 or linha < -2: print("Linha inválida.") break coluna = int(input("Digite uma coluna: ")) if coluna > 3 or coluna < -2: print("Coluna inválida.") break if tabuleiro[linha-1][coluna-1] == 0: # -------- Uma obs sobre o if a seguir: se vc digitar linha 0, aparecerá na 3º linha, se digitar linha -1, aparecerá na 2º linha e se digitar -2, aparecerá na 1º linha ------- if(chances%2+1)==1: tabuleiro[linha-1][coluna-1]=1 #----- Player 1 ------ else: tabuleiro[linha-1][coluna-1]=-1 #----- Player 2 ------ else: print("Lugar ocupado.") # ---------- se o player oponente digitar um lugar ocupado aparecerá essa mensagem, e será voltado uma jogada ---------- chances -=1 if vencedor() == 1: print("Player ", chances%2 + 1," venceu! :D ") start() # ------ reiniciar o game ------- chances +=1 def vencedor(): #----------------------- Verificar as linhas ----------------------- for linha in range(0, 3): verif_venc = tabuleiro[linha][0]+tabuleiro[linha][1]+tabuleiro[linha][2] #----------------------- Sempre comparando com as somas = 3 pois o jogo acaba assim que somar 3 lados seguidos e certos ----------------------- if verif_venc==3 or verif_venc ==-3: return 1 #------------------------ Retornar 1 para vencedor e então ir para a linha 71 ----------------------- #----------------------- Verificar as colunas ----------------------- for coluna in range(0, 3): verif_venc = tabuleiro[0][coluna]+tabuleiro[1][coluna]+tabuleiro[2][coluna] if verif_venc==3 or verif_venc ==-3: return 1 #----------------------- Diagonal não usei for pois ele pega 1 por 1 no range ----------------------- #----------------------- Verificar as diagonais ----------------------- diagonal_e = tabuleiro[0][0]+tabuleiro[1][1]+tabuleiro[2][2] diagonal_d = tabuleiro[0][2]+tabuleiro[1][1]+tabuleiro[2][0] if diagonal_e==3 or diagonal_e==-3: return 1 if diagonal_d==3 or diagonal_d==-3: return 1 return 'continue' #---------------- serve para que caso n haja vencedor o jogo continue rodando ------------------- start()
d31871ada59d0bdba396bb7bcc8a88278816c5b8
jiewu-stanford/leetcode
/79. Word Search.py
2,275
3.5
4
''' Title : 79. Word Search Problem : https://leetcode.com/problems/word-search/description/ ''' ''' recursive DFS helper function Reference: https://leetcode.com/problems/word-search/discuss/27660/Python-dfs-solution-with-comments ''' class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not board: return False for i in range(len(board)): for j in range(len(board[0])): if self.helper(board, i, j, word): return True return False def helper(self, board, i, j, word): if not word: return True if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]: return False tmp, board[i][j] = board[i][j], '$' # marked as visited to avoid going back and used twice res = self.helper(board, i+1, j, word[1:]) or self.helper(board, i-1, j, word[1:]) or \ self.helper(board, i, j+1, word[1:]) or self.helper(board, i, j-1, word[1:]) board[i][j] = tmp return res ''' instead of searching for characters on neighboring positions, find the positions and check whether they are adjacent Reference: https://leetcode.com/problems/word-search/discuss/27751/Clean-Python-Solution ''' from collections import defaultdict class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not board: return False char2pos = defaultdict(list) for i in range(len(board)): for j in range(len(board[0])): char2pos[board[i][j]].append((i, j)) return self.isFound(char2pos, word, set()) def isFound(self, char2pos, word, used, lastPos=None): if not word: return True for c in char2pos[word[0]]: if c in used or (lastPos and not self.isValid(c,lastPos)): continue # lastPos and not self.isValid(c,lastPos) is used for repeated characters used.add(c) if self.isFound(char2pos, word[1:], used, c): return True used.remove(c) # get ready for checking the next occurrence return False def isValid(self, pos1, pos2): return (pos1[0]==pos2[0] and abs(pos1[1]-pos2[1])==1) or (pos1[1]==pos2[1] and abs(pos1[0]-pos2[0])==1)
b3f71da0b452458ef26a6bae95a3ca9ae3234b2d
Josh7GAS/Oficina
/Python/list.py
224
3.890625
4
#Give me 10 names to add and print names = [] print("Give me 10 names to add and show on my list") for count in range(10): print("Give me the " + str(count + 1) + "th name") names.append(input()) print(names)
aa3d1759bc2c74c61b7d2a6838fad051c3dfe3e8
JaderSouza/exercicios
/ex 035 - analise de triangulos. v1.0.py
788
4.09375
4
print('=-='*20) print('Analisando seguimentos para formar um triangulo') print('=-='*20) l1 = float(input('Digite o primeiro seguimento: ')) l2 = float(input('Dgite o segundo seguimento: ')) l3 = float(input('Digite o valor do terceiro seguimento: ')) # SIMPLIFICANDO OS IF'S (CONDIÇÕES). if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2: print('os valores digitados podem formar um triangulo.') else: print('os valores digitados não podem formar um triangulo.') #REPETINDO OS IF'S... '''if l2 < l1 + l3: print('os valores digitado podem formar um triangulo.') if l3 < l1 + l2: print('os valores digitado podem formar um triangulo.') if l1 < l2 + l3: print('os valores digitados não podem formar um triangulo.') ''' print('=-='*20)
87dce6d51ee32b2af497cba2ed9bcbdd5db936df
EdmundHorsch/StockTrading
/test_functions.py
9,728
3.78125
4
# Evaluation function and back-testing methods and simulations import get_data as gd import indicators as ind import random import math import matplotlib as mpl import matplotlib.pyplot as plt ''' Evaluate a symbol and decide buy/sell/sit overnight RETURNS: buy, sell - buy: how much money to invest in this symbol - sell: how many shares to sell INPUT: - cash: amount of cash avaiable to invest on this symbol - invested: the amount of shares of this symbol that we currently own - bought_at: the price-per-share of this symbol when we last bought shares - table: the table of data for this symbol ''' def evaluate_symbol(cash, invested, bought_at, table): # buy: how much money to invest in the symbol # sell: how many shares to sell buy = 0.0 sell = 0.0 # variables for indicators/prices macd = table['MACD'] macd_hist = table['MACD_Hist'] macd_signal = table['MACD_Signal'] a_up = table['Aroon Up'] a_down = table['Aroon Down'] b_up = table['Real Upper Band'] b_mid = table['Real Middle Band'] b_low = table['Real Lower Band'] obv = table['OBV'] # calculations: # look for buy siganl when CCI moves from negative/near-zero to above 100 if (invested == 0): #if (ind.cci(20, table) > 100) and (ind.cci(20, table[1:]) < 10): # buy = cash if (a_up[0] > 70) and (a_down[0] < 30): buy = cash if (invested > 0): if (bought_at < ind.sma(4, 'close', table)) or (bought_at > ind.sma(2, 'high', table)): sell = invested return buy, sell #end def ''' Simulate evaluation function over time. a.k.a. "backtesting". Splits money evenly bewteen symbols and invests independently. Loops through each symbol and simulates whole time period. RETURNS: the total percentage gained/lost after evaluating all symbols over the time period INPUT: - list_syms: list of symbols to be looked at / invested in - a: start day - b: end day ''' def sim_past(list_syms, a, b): start_money = 100 allowance = float(start_money) / float(len(list_syms)) percents = dict.fromkeys(list_syms, 0.0) start = a end = b super_totals = [0.0] * (end-start) # set up chart #x = range(end-start) #fig, axs = plt.subplots(2) #iterate through symbols: for symbol in list_syms: #set up this symbol's table table = gd.get_table(symbol) #print(symbol, len(table)) if len(table) < (end): start = 0 end = len(table) - 30 table = table[start:end+30] # allows you to look 15 days back, on day one # set up variables cash = allowance invested = 0.0 bought_at = 0.0 buy = 0.0 sell = 0.0 # keep track of cash, owned shares, and closing price of each day money = [0.0] * (end-start) shares = [0.0] * (end-start) price = [0.0] * (end-start) i = 0 # go through days. "day" counts down. for day in range(end-start, 0, -1): #simulate buy/sell at beginnning of day #buy if buy > 0.0 : invested = invested + (float(buy) / table.iloc[day]['open']) cash = cash - float(buy) bought_at = table.iloc[day]['open'] buy = 0.0 #sell if sell > 0 : invested = invested - float(sell) cash = cash + (float(sell) * table.iloc[day]['open']) bought_at = 0.0 sell = 0.0 #evaluate and determine buy/sell for the morning buy, sell = evaluate_symbol(cash, invested, bought_at, table[day:]) # update lists keeping track money[i] = cash shares[i] = invested price[i] = table['close'][day] super_totals[i] += money[i] + (shares[i] * price[i]) i += 1 #end for #chart this symbol's journey, adjusted for sharing of initial cash totals = [(money[i] + (shares[i] * price[i])) * len(list_syms) for i in range(len(money))] #axs[0].plot(x, totals, ls='-', label=symbol+" total value") #evaluate cash + owned_shares*price at this point CLOSE PRICE percents[symbol] = cash + (invested * table['close'][0]) #end for # finalize the chart #axs[0].plot(x, super_totals, ls='-.', c='k', label="total value") #axs[0].legend(loc=6) #plt.savefig("multiple.png") # calculate statistics and return tot_mon = sum(percents.values()) t = 0.0 for y in percents.values(): t += y mean = t/len(list_syms) s = 0.0 for x in percents.values(): s += pow((x - mean), 2) stdev = 0.0 if len(list_syms) == 1: stdev = 0 else: stdev = math.sqrt(s / (len(list_syms)-1)) #print("Mean:", round(mean, 3), "| Std.Dev.:", round(stdev, 3)) # plot histogram of individual gains/losses: #n, bins, patches = axs[1].hist(percents.values(), bins=10) #axs[1].xlabel("Gain/Loss (% of original investment)") #axs[1].ylabel("Frequency") #axs[1].title("Return of investment (%) after"+str(end-start)+"days, from "+str(len(list_syms))+" symbols.") #plt.savefig("sim_past.png") return super_totals[end-start-1] - 100 #end def ''' Simulate evaluation function over time. a.k.a. "backtesting". Only looks at one symbol and simulates over time period. Prints two graphs to "one_symbol_detailed.png". One of total value of assets (cash + value of owned shares), and one of the price of the symbol. RETURNS: The percentage of money gained/lost after this simulation INPUT: - symbol: list of symbols as strings to be considered for investment - a: start day - b: end day ''' def one_symbol_detailed(symbol, a, b): start = a end = b totals = [0.0] * (end-start) # set up chart plt.figure(0) x = range(end-start) fig, axs = plt.subplots(2) #set up this symbol's table table = gd.get_table(symbol) #print(symbol, len(table)) if len(table) < (end): start = 0 end = len(table) - 30 table = table[start:end+30] # allows you to look 30 days back, on day one # set up variables cash = 100 invested = 0.0 bought_at = 0.0 buy = 0.0 sell = 0.0 # keep track of cash, owned shares, and prices (hig, low, typical) of each day money = [0.0] * (end-start) shares = [0.0] * (end-start) high = [0.0] * (end-start) low = [0.0] * (end-start) tp = [0.0] * (end-start) i = 0 # go through days. "day" counts down. for day in range(end-start, 0, -1): #simulate buy/sell at beginnning of day #buy if buy > 0 : invested = invested + (float(buy) / table.iloc[day]['open']) cash = cash - float(buy) bought_at = table.iloc[day]['open'] buy = 0.0 #sell if sell > 0 : invested = invested - float(sell) cash = cash + (float(sell) * table.iloc[day]['open']) bought_at = 0.0 #evaluate and determine buy/sell for the morning buy, sell = evaluate_symbol(cash, invested, bought_at, table[day:]) # update lists keeping track money[i] = cash shares[i] = invested high[i] = table['high'][day] low[i] = table['low'][day] tp[i] = (high[i] + low[i] + table['close'][day]) / 3 totals[i] += money[i] + (shares[i] * tp[i]) i += 1 #end for axs[0].plot(x, totals, ls='-') #axs[0].title(label="Cash + value of owned shares by day") #chart the price of the stock axs[1].plot(x, high, ls="-") axs[1].plot(x, low, ls="-") axs[1].plot(x, tp, ls="-") #axs[1].title(label="Price of "+symbol) plt.savefig("one_symbol_detailed.png") plt.show() #return the percentage of money gained/lost after this simulation return totals[len(totals)-1] - 100 #end def ''' Run evaluation function on list of symbols for a certain amount of trials, where each trial uses a random stretch of "days" trading days, and present statistics about the results. Prints a histogram of the trials' results to "experiment.png" RETURNS: data, mean, stdev - data: List of results of each trial. A result is the percentage gained/lost - mean: average of sample - stdev: standard deviation of sample INPUT: - ls: list of symbols as strings - trials: number of trials to complete - days: the number of trading days ''' def rand_sims(ls, trials, days): data = [0.0] * trials for i in range(trials): a = random.randint(0, 700-days) pct = sim_past(ls, a, a + days) data[i] = pct print("Trial", i+1, "complete") #end for # statistics: mean = float(sum(data)) / float(len(data)) s = 0.0 for x in data: s += pow((x-mean), 2) #end for var = 0.0 if (trials == 1): var = 0.0 else: var = s / (trials - 1) stdev = math.sqrt(var) # plot data plt.figure(1) n, bins, patches=plt.hist(data, bins=10) plt.xlabel("Gain/Loss (% of original investment)") plt.ylabel("Frequency") plt.title(str(trials)+" trials; Return of investment (%) after"+str(days)+"days.") plt.savefig("experiment.png") plt.show() return data, mean, stdev #end def
330a622f11a65258af937bbdfd14714579a62ffc
impacta-ADS/python
/decimal2binario.py
507
3.84375
4
''' TRANSFORMAR BINÁRIO EM DECIMAL ''' continuar=True contador=0 numeroDecimal=0 while continuar: numeroBinario=int(input("Digite um número binario:")) numeroBinarioInicial=numeroBinario if numeroBinario>0: continuar=False while (numeroBinario!=0): resto=numeroBinario%10 numeroDecimal=numeroDecimal+resto*(2**contador) numeroBinario=numeroBinario//10 contador+=1 print(f"O número binário {numeroBinarioInicial} é igual a {numeroDecimal} em base decimal")
69f428aabe854675e64e095960d3574eff7fe7af
vidyasagarr7/DataStructures-Algos
/Karumanchi/Queue/Rearrange.py
647
3.96875
4
from Karumanchi.Queue import Queue def rearrange(input_que): temp_que = Queue.Queue1() is_length_odd = True if input_que.size%2 ==1 else False mid = input_que.size//2 for i in range(mid): temp_que.enqueue(input_que.dequeue()) while not temp_que.is_empty(): input_que.enqueue(temp_que.dequeue()) input_que.enqueue(input_que.dequeue()) if is_length_odd: input_que.enqueue(input_que.dequeue()) return input_que if __name__=="__main__": que = Queue.Queue1() for i in range(11,22): que.enqueue(i) rearrange(que) while not que.is_empty(): print(que.dequeue())
bcf7ad8906384ff92c93bd58a2356ccb6470a454
jailukanna/Notes
/Note Pad ++/Troubleshooting/Time calculator.py
410
3.671875
4
while True: speed= input("Enter the speed of video: ") if speed =="quite": break duration = input("Enter the video duration in h:min formate: ") duration = duration.split(':') exact_time = int(duration[0])*60+int(duration[1]) finale_time = (1/float(speed))*exact_time print(f"Finale view time is : {int(finale_time)}min .\nYou saved {int(exact_time-finale_time)}min.")
1206ab0afdafa2c50e3f0a63c3fbe3953617dd61
harrylee0810/TIL
/swexpert/python01/6251.py
256
3.984375
4
# for문을 이용해 아래와 같이 별(*)을 표시하는 프로그램을 만드십시오. # 출력: # * # ** # *** # **** # ***** a = int(input()) for i in range(1, a+1): blank = ' '*(a-i) star = '*'*i print(blank, star, sep='')
e9fc665f3a29ef8d7eaa2b3b365beb7b25915c56
think-TL/python-code
/chapter2/Test2_11.py
567
3.59375
4
def general(general): add = [] for i in range(5): add.append(int(raw_input("input number"))) count = 0 for i in add: count += i if general == 1: print count else: print float(count) / len(add) while True: print "five--sum --1" print "five--avg --2" print "break --X" try: sel = int(raw_input("Please select a")) if sel == 1: general(1) elif sel == 2: general(2) else: print "input error" except ValueError: break
bf11aa74d28aea5f3f8564f135bd7d54f9c2dc6c
ppalves/desafios-de-programacao
/aula-6-3/b.py
146
3.578125
4
n = int(input()) l = 0 r = 0 commands = input() for letter in commands: if letter == "L": l+=1 else: r+=1 print(l + r + 1)
e07ca24c85058507cafbaf33bfccf6d846726e2a
hirekatsu/MyNLTKBOOK
/ch03_06.py
1,802
3.515625
4
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division import nltk, re, pprint from nltk import word_tokenize print(""" ---------------------------------------------------------------------- 3.6 Normalizing Text ---------------------------------------------------------------------- """) raw = """DENNIS: Listen, strange woman lying in ponds distributing swords is no basis for a system of government. Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony.""" tokens = word_tokenize(raw) print("Stemmers") porter = nltk.PorterStemmer() lancaster = nltk.LancasterStemmer() print([porter.stem(t) for t in tokens]) print([lancaster.stem(t) for t in tokens]) print("-" * 40) class IndexedText(object): def __init__(self, stemmer, text): self._text = text self._stemmer = stemmer self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text)) def concordance(self, word, width=40): key = self._stem(word) wc = int(width/4) for i in self._index[key]: lcontext = ' '.join(self._text[i-wc:i]) rcontext = ' '.join(self._text[i:i+wc]) ldisplay = '{:>{width}}'.format(lcontext[-width:], width=width) rdisplay = '{:{width}}'.format(rcontext[:width], width=width) print(ldisplay, rdisplay) def _stem(self, word): return self._stemmer.stem(word).lower() porter = nltk.PorterStemmer() grail = nltk.corpus.webtext.words('grail.txt') text = IndexedText(porter, grail) text.concordance('lie') print("-" * 40) print("Lemmatization") wnl = nltk.WordNetLemmatizer() print([wnl.lemmatize(t) for t in tokens]) print("-" * 40)
aa0c06c041d77490f0a8a1bc4233db4aadd4aee6
crouther/data-parsing
/netflix/netflixListParser.py
1,278
3.515625
4
################################################################################ # # Myles Crouther # Netflix List Parser # ################################################################################ import re, json # Variables titles = [] extractedTxt = [] array = [] key = "\"fallback-text\"" # First seperate txt file by line with open("his-netflix-list.html", "r") as ins: for line in ins: array.append(line) # Checks if line has instances of the variable "key" in the "inputString" def hasKey(inputString): arr = [m.start() for m in re.finditer(key, inputString)] return arr # Returns the next in-line Title of "fallback-Text" images in an html line def findTitle(str, start): init = start + 16 for x in range(init, len(str)): if str[x] == "<": return str[init:x] # Loops through array (html file), reads each line for matching key values for y in range(0,len(array)): temp = hasKey(array[y]) if len(temp) > 0: for z in range(0,len(temp)): extractedTxt.append(findTitle(array[y],temp[z])) # Prints My List in Text Form (Title's Only) to console print(extractedTxt) # Save Data (Netflix Titles) formatted to json file with open('data.json', 'w', encoding='utf-8') as f: json.dump(extractedTxt, f, ensure_ascii=False, indent=4)
18dbd7ff0e659b5d8bc965c9619ba03d3ac4ab16
kailash-manasarovar/A-Level-CS-code
/challenges/conversion_hex_to_binary.py
1,418
4.03125
4
hex_number = input("Please enter 2 digit hex number") denary_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] denary_result = 0 bin_result = "" def convert(hex_digit): if hex_digit in denary_numbers: return int(hex_digit) elif hex_digit == "A": return 10 elif hex_digit == "B": return 11 elif hex_digit == "C": return 12 elif hex_digit == "D": return 13 elif hex_digit == "E": return 14 elif hex_digit == "F": return 15 def hex_to_bin(denary_result): binary_result = "" if denary_result > 15: print("out of range") if denary_result >= 8 and denary_result < 16: binary_result += "1" denary_result = denary_result - 8 else: binary_result += "0" if denary_result >= 4 and denary_result < 8: binary_result += "1" denary_result = denary_result - 4 else: binary_result += "0" if denary_result >= 2 and denary_result < 4: binary_result += "1" denary_result = denary_result - 2 else: binary_result += "0" if denary_result >= 1 and denary_result < 2: binary_result += "1" denary_result = denary_result - 1 else: binary_result += "0" return binary_result for i in hex_number: denary_result = convert(i) bin_result += hex_to_bin(denary_result) print(bin_result)