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
379a6098c0af188573fee0867ce1517de11c3ff9
ShinAKS/coursera-ds-algorithms
/Data Structures/week1/check_brackets_in_code/check_brackets.py
722
3.65625
4
# python3 def balance_check(s): opening = set('([{') closing=set(')]}') matches = set([ ('(',')'), ('[',']'), ('{','}') ]) stack = [] j=[] for i in range(len(s)): if s[i] in opening: stack.append(s[i]) j.append(i) elif s[i] in closing: if len(stack) == 0: return i+1 last_open = stack.pop() if (last_open,s[i]) not in matches: return i+1 else: j.pop() if len(stack)==0: return 'Success' else: return (j[0]+1) s=input() print(balance_check(s))
6a40619df2a5a7080f960b106564124c708abb4d
mohammadr63/python3
/Reverse.py
125
3.859375
4
def Reverse(lst): return [ele for ele in reversed(lst)] # Driver Code lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst))
f677209fcccb10fb511c5a3f0950270f5072bcfd
amitkac/PythonAtom
/OOPS/classMethod.py
457
3.5
4
# x = 9 class Add(object): # class variable x = 20 def __init__(self, x): self.x = x def addMethod(self, y): return self.x+y # class method--as convention we need to use cls @classmethod def addClass(self, y): return self.x+y # static method takes variable defined in main function # static doesn't take anything from self @staticmethod def addStatic(x, y): return x+y
5e834b91dd6cff6d5f0560c1f64d65708e9f0f5f
Semosky/Simeon
/Day 5.py
721
3.984375
4
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> simeon=[1,2,3,4,5] >>> simeon_sq=[] >>> for num in simeon: new_num=num**2 simeon_sq.append(new_num) >>> print(simeon_sq) [1, 4, 9, 16, 25] >>> is_eve=[] >>> is_even=[] >>> is_odd=[] >>> is_a_factor_of_3=[] >>> for num in simeon_sq: if num % 3==0 SyntaxError: invalid syntax >>> is_even=[] >>> is_odd=[] >>> is_a_factor_of_3=[] >>> for num in simeon_sq: if num % 3==0: is_a_factor_of_3.append(num) elif num % 2==0: is_even.append(num) else: is_odd.append(num) >>> print(is_a_factor_of_3, is_even, is_odd) [9] [4, 16] [1, 25] >>>
0f8dddd231e8306d9fe105b307e234e2097d89a4
jrog20/hailstones
/hailstones.py
471
4.1875
4
""" File: hailstones.py """ import math def main(): n = int(input('Enter a number: ')) count = 0 while n != 1: if n % 2 == 0: print(n, 'is even, so I take half:', n//2) n //= 2 count += 1 else: print(n, 'is odd, so I make 3n + 1:', n * 3 + 1) n = (n * 3) + 1 count += 1 print('This process took', count, 'steps to reach 1') if __name__ == '__main__': main()
369aee3c8c025dc3a4b3eb72be4aa67cf7c6d93d
Frankyyoung24/SequencingDataScientist
/Algrithms/week3/editDistance_question.py
2,862
3.5625
4
""" 1. Rows of the dynamic programming matrix are labeled with the bases from P and columns with bases from T 2. Elements in the first Row are set to 0 3. Elements in the first column are set to 0, 1, 2..., as for edit distance 4. Other elements are set in the same way as elements of a standard edit distance matrix 5. The minimal value in the bottom row is the edit distance of the closet match between P and T Parse the human chromosome 1. Adapt the editDistance function. """ from collections import defaultdict from overlap import overlap def main(): chr = readGenome('chr1.GRCh38.excerpt.fasta') p = 'GCTGATCGATCGTACG' print("Question 1: %d" % editDistance(p, chr)) p = 'GATTTACCAGATTGAG' print("Question 2: %d" % editDistance(p, chr)) seq, qual = readFastq('ERR266411_1.for_asm.fastq') edge, suffix = overlap_graph(seq, 30) print("Question 3: ", edge) print("Qusetion 4: ", suffix) def readGenome(filename): genome = '' with open(filename, 'r') as f: for line in f: if not line[0] == '>': genome += line.rstrip() return genome def readFastq(filename): sequences = [] qualities = [] with open(filename, 'r') as fh: while True: fh.readline() seq = fh.readline().rstrip() fh.readline() qual = fh.readline().rstrip() if len(seq) == 0: break sequences.append(seq) qualities.append(qual) return sequences, qualities def editDistance(x, y): D = [] for i in range(len(x) + 1): D.append([0] * (len(y) + 1)) # Initialize first row and column of matrix for i in range(len(x) + 1): D[i][0] = i for i in range(len(y) + 1): D[0][i] = 0 # Fill in the rest of the matrix for i in range(1, len(x) + 1): for j in range(1, len(y) + 1): distHor = D[i][j - 1] + 1 distVer = D[i - 1][j] + 1 if x[i - 1] == y[j - 1]: distDiag = D[i - 1][j - 1] else: distDiag = D[i - 1][j - 1] + 1 D[i][j] = min(distHor, distVer, distDiag) # Edit distance is the vcalue in the bottom right corner of the matrix # return D[-1][-1] return min(D[-1]) def overlap_graph(reads, k): # make index index = defaultdict(set) # remember the defaultdict function for read in reads: for i in range(len(read) - k + 1): index[read[i:i + k]].add(read) # make praph graph = defaultdict(set) for r in reads: for o in index[r[-k:]]: if r != o: if overlap(r, o, k): graph[r].add(o) edges = 0 for read in graph: edges += len(graph[read]) return (edges, len(graph)) if __name__ == '__main__': main()
0c87fc0842a16583f2604bb3ffd2581c8fa951ab
Andrew325/cs114
/SpaceDungeon.py
891
3.578125
4
print('Welcome to Space Dungeon') print('Please enter your name.') Name = input() print('Welcome, ' + Name + '.' ' Please select a class from the choices below.') print('Soldier - Trained fighters with formal military training. High attack and lower magic average.') print('Mercenary - Skillful warriors for hire. with relatively average attack and magic abilities.') print('Wizard - Magic users with high degrees of intelligence and power.') print('Knight - Armored fighters with a code of honor.') print('Technician - Skilled engineers with technical based combat abilities and expertise.') Class = input() print('Now allocate points towards attack and magic power out of 100 total points.') print('Points for Attack') Attack = input() print('Points for Magic') Magic = input() print('You have chosen to be a ' + Class + ' with ' + Attack + ' attack power and ' + Magic + ' magic power.')
715b9ac719c17759e3c5c36c9dfec72225ea6d1a
chamdodari2/python_study
/chap05/variable_param.py
203
4.21875
4
def print_n_times(n,*values): for i in range(n): for value in values: print(value) print() print_n_times(3,"안녕하세요","즐거운","파이썬 프로그래밍")
7db8bf224244a1b0d14a9b6f94728e7841f3a740
Codeded87/Css_practice
/DataScience/System of linearEquation.py
151
3.515625
4
import numpy A = np.matrix("3,1,2;3,2,5;6,7,8") print(A) b = np.matrix("2,-1,3").transpose() print(b) solve = numpy.linalg.solve(A,b) print(solve)
81d734997beb8d6aaa228f347516ac0d8c2e943b
ulisseslimaa/SOLUTIONS-URI-ONLINE-JUDGE
/Solutions/1014_Consumo.py
73
3.828125
4
X= int(input()) Y=float(input()) CM = X/Y print('%.3f' %CM, 'km/l')
73adeacd4c9e609d95b124057f3aaaadf653f745
chenshanghao/LeetCode_learning
/Problem_123/learning_solution.py
1,218
3.921875
4
# First assume that we have no money, so buy1 means that we have to borrow money from others, # we want to borrow less so that we have to make our balance as max as we can(because this is negative). # sell1 means we decide to sell the stock, after selling it we have price[i] money and we have to give back the money we owed, # so we have price[i] - |buy1| = prices[i ] + buy1, we want to make this max. # buy2 means we want to buy another stock, we already have sell1 money, # so after buying stock2 we have buy2 = sell1 - price[i] money left, we want more money left, so we make it max # sell2 means we want to sell stock2, we can have price[i] money after selling it, # and we have buy2 money left before, so sell2 = buy2 + prices[i], we make this max. class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ sell1, sell2 = 0, 0 buy1, buy2 = float('-inf'), float('-inf') for i in range(len(prices)): buy1 = max(buy1, -prices[i]) sell1 = max(sell1, buy1 + prices[i]) buy2 = max(buy2, sell1 - prices[i]) sell2 =max(sell2, buy2 + prices[i]) return sell2
638db1a9e357f46a3a1da123784a8bae350fb6f1
ztcxdu/just_for_fun
/pi.py
717
3.59375
4
# -*- coding: utf-8 -*- from __future__ import division import time import sys time1=time.time() ################算法根据马青公式计算圆周率#################### number = int(input('请输入想要计算到小数点后的位数n:')) number1 = number+10 b = 10**number1 x1 = b*4//5 x2 = b// -239 he = x1+x2 number *= 2 for i in range(3,number,2): x1 //= -25 x2 //= -57121 x = (x1+x2) // i he += x print(i) pai = he*4 pai //= 10**10 paistring=str(pai) result=paistring[0]+str('.')+paistring[1:len(paistring)] print(result) time2=time.time() zero = 0 one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 seven = 0 eight = 0 nine = 0 print('总共耗时:' + str(time2 - time1) + 's')
f09f1c6abeb78e9b6e3a42755ec8148a38926fdb
process/euler
/src/52/52.py
288
3.734375
4
#!/usr/bin/env python def are_permutations(nums): num_chars = [tuple(sorted([d for d in str(n)])) for n in nums] num_set = set(num_chars) return len(num_set) == 1 # Main Code # n = 1 while True: if are_permutations([n, 2*n, 3*n, 4*n, 5*n, 6*n]): print n break n += 1
a87fafe1722129bcb12985fb9939ed1ec94028c5
RishabhBhatnagar/Snake-Game-Text
/guiMain.py
979
3.890625
4
from tkinter import Tk, Label import textRes from tkinter.font import Font def create_labelBoard(root): # Creating the labelBoard labelBoard = Label(root, text="Hello World", anchor='nw') labelBoard.pack(fill='both') # Setting the font(monospace) # Custom font my_font = Font(family='Consolas', size=15) labelBoard.config(font=my_font) # Setting the text # Works # labelBoard.config(text=textRes.textBoard) # Alternate labelBoard.config(text=textRes.array2D_to_string(textRes.init_list2D())) # Set background color as red labelBoard.config(bg='red') labelBoard.config(highlightthickness=6) labelBoard.config(relief='solid') # Setting location in grid labelBoard.grid(row=0, column=0) def create_root(): root = Tk() # Setting size root.geometry("400x400+100+100") create_labelBoard(root) # Runs the window root.mainloop() if __name__ == '__main__': create_root()
fa1a387120ab727fd20272b5a9dea6f0cb787417
Here2Huynh/Thirteen-Card-Game
/checkInstantWin.py
3,514
3.5625
4
#check for instant module # there are 3 conditions for instant win # 1. 4 2's # 2. dragon # 3. 6 pairs and a single card import sys from collections import Counter def check_for_four_twos_instant_win(list_of_players): """ """ #4 2's #check for the presence of 4 2's and different suits #check for all 13 cards are still in hand #all cards have different values for player in list_of_players: #player.show_hand() #print len(list_of_players) four_twos_counter = 0 for card in player.Hand: #print card #print four_twos_counter and if there is 13 cards in your hand if card['display'] == '2S' and card['value'] == 49 and len(player.Hand) == 13: four_twos_counter += 1 elif card['display'] == '2C' and card['value'] == 50 and len(player.Hand) == 13: four_twos_counter += 1 elif card['display'] == '2D' and card['value'] == 51 and len(player.Hand) == 13: four_twos_counter += 1 elif card['display'] == '2H' and card['value'] == 52 and len(player.Hand) == 13: four_twos_counter += 1 #print four_twos_counter if four_twos_counter == 4: print 'Player ' + str(player.get_ID())+ " got an instant win with four 2's!" #set next game's first player to this player #add and subtract points #restart game #player.sort_hand() player.show_hand() return True sys.exit() def check_for_six_pairs_instant_win(list_of_players): """ """ # 6 pairs #check if there is 13 cards in card FIRST for player in list_of_players: if len(player.Hand) == 13: pair_count = 0 pair_list = [] for card in player.Hand: pair_list.append(card['display'][0]) #print '6_doubles_pair_list= ' + str(pair_list) #print 'Counter(pair_list) = ' + str(Counter(pair_list)) counter_list = Counter(pair_list).items() #print 'counter_list = ' + str(counter_list) for item in counter_list: #print item[1] if item[1] == 2: pair_count += 1 elif item[1] == 3: pair_count += 1 elif item[1] == 4: pair_count += 2 #print 'pair_count = ' + str(pair_count) #print '' if pair_count == 6: print 'Player ' + str(player.get_ID()) + ' got an instant win with 6 pairs!' player.show_hand() #set next game's first player to this player #add and subtract points #restart game return True sys.exit() def check_for_dragon_instant_win(list_of_players): """ """ #dragon #check if there is 13 cards first dragon_list = ['3', '4', '5', '6', '7', '8', '9', '1', 'J', 'Q', 'K', 'A'] for player in list_of_players: if len(player.Hand) == 13: pair_list = [] for card in player.Hand: pair_list.append(card['display'][0]) print 'dragon_compare_list= ' + str(pair_list) print '' if set(dragon_list).issubset(pair_list) == True: print 'Player ' + str(player.get_ID()) + ' got an instant win with a dragon!' return True sys.exit()
c8fd7db325a6b22e3afd4530368110467aa312a7
ANamelessDrake/jblib
/jblib/conversion/convert_module.py
1,641
3.515625
4
""" Module to convert various data 11/07/2016 - Created 02/03/2019 - Converted to make python3 compatible def convert_time_from_seconds(seconds_given) Converts seconds into minutes/hours. def IP2Int(ip) Converts an IPv4 address to a interger - This is useful to store IP addresses in databases def Int2IP(ipnum) Converts an interger back to an IPv4 address def urlcode(url, encode=False) Wrapper for urllib.parse.quote and urllib.parse.unquote. From urllib docs - Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of URL. https://docs.python.org/3.1/library/urllib.parse.html?highlight=urllib#urllib.parse.quote """ import urllib.parse version = '1.1' def convert_time_from_seconds(seconds_given): if seconds_given == "N/A": return seconds_given else: m, s = divmod(seconds_given, 60) h, m = divmod(m, 60) total_time = "%d:%02d:%02d" % (h, m, s) return total_time def IP2Int(ip): if '.' in str(ip): o = list(map(int, ip.split('.'))) res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3] return res else: return ip def Int2IP(ipnum): o1 = int(ipnum / 16777216) % 256 o2 = int(ipnum / 65536) % 256 o3 = int(ipnum / 256) % 256 o4 = int(ipnum) % 256 return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals() def urlcode(url, encode=False): if encode: # Convert string to URL safe return urllib.parse.quote(url) else: # Convert string to human readable return urllib.parse.unquote(url)
74dd80c0ad638cf464805d0efa764a484ebf81e9
damodardikonda/Python-Basics
/Python3/KeyWord_Arg.py
304
3.796875
4
def calc(x,y): add = x+y sub = x-y mul = x*y return add , sub , mul t = calc(x=100,y = 50) for c in t: print(c) x = calc(y=50,x = 100) for c in x: print(c) l = calc(100,y = 50) for c in l: print(c) ''' a = calc(x=100, 50) #Not Allowed for c in a: print(c) '''
416af836898c0e6ac624ce655e0b31cb899bf87e
kevinmc14159/book_directory
/frontend.py
4,201
3.84375
4
from tkinter import * import backend def add_command(): """Insert entry via button.""" backend.insert(title_text.get(), author_text.get(), year_text.get(), isbn_text.get()) listing.delete(0, END) listing.insert(END, (title_text.get(), author_text.get(), year_text.get(), isbn_text.get())) def view_command(): """View entries via button.""" listing.delete(0, END) for row in backend.view(): listing.insert(END, row) def update_command(): """Update entry via button.""" backend.update(selected_tuple[0], title_text.get(), author_text.get(), year_text.get(), isbn_text.get()) def delete_command(): """Delete entry via button.""" backend.delete(selected_tuple[0]) def search_command(): """Search entry via button.""" listing.delete(0, END) for row in backend.search(title_text.get(), author_text.get(), year_text.get(), isbn_text.get()): listing.insert(END, row) def get_selected_row(event): """Pre-fill fields for selected entry.""" global selected_tuple index = listing.curselection()[0] selected_tuple = listing.get(index) entry1.delete(0, END) entry1.insert(END, selected_tuple[1]) entry2.delete(0, END) entry2.insert(END, selected_tuple[2]) entry3.delete(0, END) entry3.insert(END, selected_tuple[3]) entry4.delete(0, END) entry4.insert(END, selected_tuple[4]) window = Tk() window.wm_title("Book Directory") # Labels for entry fields. label1 = Label(window, text = "Title") label1.grid(row = 0, column = 0) label2 = Label(window, text = "Author") label2.grid(row = 0, column = 2) label3 = Label(window, text = "Year") label3.grid(row = 1, column = 0) label4 = Label(window, text = "ISBN") label4.grid(row = 1, column = 2) # Entry Fields. title_text = StringVar() entry1 = Entry(window, textvariable = title_text) entry1.grid(row = 0, column = 1) author_text = StringVar() entry2 = Entry(window, textvariable = author_text) entry2.grid(row = 0, column = 3) year_text = StringVar() entry3 = Entry(window, textvariable = year_text) entry3.grid(row = 1, column = 1) isbn_text = StringVar() entry4 = Entry(window, textvariable = isbn_text) entry4.grid(row = 1, column = 3) # List all data. listing = Listbox(window, height = 6, width = 35) listing.grid(row = 2, column = 0, rowspan = 6, columnspan = 2) # Scrollbar. scroller = Scrollbar(window) scroller.grid(row = 2, column = 2, rowspan = 6) # Configure scrollbar for Listbox. listing.configure(yscrollcommand = scroller.set) scroller.configure(command = listing.yview) listing.bind('<<ListboxSelect>>', get_selected_row) # Buttons for various operations on data. button1 = Button(window, text = "View All", width = 12, command = view_command) button1.grid(row = 2, column = 3) button2 = Button(window, text = "Search Entry", width = 12, command = search_command) button2.grid(row = 3, column = 3) button3 = Button(window, text = "Add Entry", width = 12, command = add_command) button3.grid(row = 4, column = 3) button4 = Button(window, text = "Update Selected", width = 12, command = update_command) button4.grid(row = 5, column = 3) button5 = Button(window, text = "Delete Selected", width = 12, command = delete_command) button5.grid(row = 6, column = 3) button6 = Button(window, text = "Close", width = 12, command = window.destroy) button6.grid(row = 7, column = 3) # Keep window open until closed. window.mainloop()
adc3d0acc1c61c877a67e092ee46dd532e610d92
wleepang/learn
/learn_multiprocessing.py
1,680
4.03125
4
#!/usr/bin/env python """ A script to explore parallelization via the multiprocessing package Python :: 3 Python :: 3.6 """ import os import multiprocessing as mp import time def expensive(value, results=None, index=None): proc = mp.current_process() print('{}[{}]: working on index {} value {}'.format(proc.name, os.getpid(), index, value)) time.sleep(2) result = value*2 if results: results[index] = result else: return result if __name__ == "__main__": # there are two basic methods for using multiple processes over an iterable # list of data: # 1. spawning a process for each element in the list # 2. using a process pool to work on the data # for the most control, processes can be generated explicitly # with data communication handled as needed data = range(8) print('--- Example 1 ---') with mp.Manager() as manager: procs = [] results = manager.list([None]*len(data)) for index, value in enumerate(data): proc = mp.Process(target=expensive, args=(index, results, index)) procs.append(proc) proc.start() for proc in procs: proc.join() print(results) # the above uses a Manager() to store the return values from each function # evaluation. this can also be done (more easily) using a Pool print('--- Example 2 ---') with mp.Pool(processes=len(data)) as pool: print(pool.map(expensive, data)) # limiting the pool size keeps resource utilization in check print('--- Example 3 ---') with mp.Pool(processes=4) as pool: print(pool.map(expensive, data))
ee477db80e26673411ee0435e167569775756c53
davelau0918/Tic-Tac-Toe
/main.py
4,039
3.875
4
playerTurn = True def TicTacToe(): board = [1, 2, 3, 4, 5, 6, 7, 8, 9] MagicSquare = [4, 9, 2, 3, 5, 7, 8, 1, 6] def getE(i, type): #type = 0 means to show on the actual board and type = 1 means to show for the help box if(type == 0): if(board[i] == "X" or board[i] == "O"): return(board[i]) else: return(" ") if(type == 1): if(board[i] == "X" or board[i] == "O"): return("-") else: return(board[i]) def PrintBoard(): print("") print("", getE(0, 0), "|", getE(1, 0), "|", getE(2, 0), " ", getE(0, 1), "|", getE(1, 1), "|", getE(2, 1)) print("---|---|---", " ", "---|---|---") print("", getE(3, 0), "|", getE(4, 0), "|", getE(5, 0), " ", getE(3, 1), "|", getE(4, 1), "|", getE(5, 1)) print("---|---|---", " ", "---|---|---") print("", getE(6, 0), "|", getE(7, 0), "|", getE(8, 0), " ", getE(6, 1), "|", getE(7, 1), "|", getE(8, 1)) print("") def GetNumber(player): while True: number = input("Choose a box for " + player + ": ") try: number = int(number) if number in range(1, 10): return number else: print("Gimme a valid number! -_-") except ValueError: print("I need a number! :|") continue def CheckWin(thisBoard): count = 0 for x in range(9): for y in range(9): for z in range(9): if x != y and y != z and z != x: if thisBoard[x] == "X" and thisBoard[y] == "X" and thisBoard[z] == "X": if MagicSquare[x] + MagicSquare[y] + MagicSquare[z] == 15: return 1 if thisBoard[x] == "O" and thisBoard[y] == "O" and thisBoard[z] == "O": if MagicSquare[x] + MagicSquare[y] + MagicSquare[z] == 15: return -1 for v in range(9): if(thisBoard[v] == "X" or thisBoard[v] == "O"): count += 1 if(count == 9): return 0 return 5 def Turn(player): n = GetNumber(player) if(board[n-1] == "X" or board[n-1] == "O"): print("But this box is occupied. Try another box?") Turn(player) else: board[n-1] = player def miniMax(current, depth, isMaximizing): rVal = 0 newB = current[:] score = CheckWin(newB) if(depth == 0): if(score == 5): return 0 return score if(score != 5): return score if(isMaximizing): minVal = -10 for i in range(9): if(newB[i] != "X" and newB[i] != "O"): newB[i] = "X" rVal = miniMax(newB, depth-1, not isMaximizing) if(rVal > minVal): minVal = rVal newB[i] = i+1 return minVal if(not isMaximizing): maxVal = 10 for i in range(9): if(newB[i] != "X" and newB[i] != "O"): newB[i] = "O" rVal = miniMax(newB, depth-1, not isMaximizing) if(rVal < maxVal): maxVal = rVal newB[i] = i+1 return maxVal def AITurn(): newB = board[:] winBox = 0 minVal = -10 print("Good turn, thinking......") for i in range(9): if(newB[i] != "X" and newB[i] != "O"): newB[i] = "X" receivedVal = miniMax(newB, 6, False) if(receivedVal > minVal): minVal = receivedVal winBox = i newB[i] = i+1 board[winBox] = "X" end = 5 playerX = not playerTurn while end == 5: end = CheckWin(board) PrintBoard() if(end == -1): print("Congratulations! Player \'O\' wins") elif (end == 1): print("Congratulations! Player \'X\' wins") elif (end == 0): print("The game ends in a tie!") if(end == 5): if(playerX): AITurn() else: Turn("O") playerX = not playerX while True: TicTacToe() inp = input("Play again? Y/N: ") if (inp.lower() == "y"): print("Let's go again!\n") playerTurn = not playerTurn else: break
967189d107c3a7d4c1f8e896e19b8eb3fc3dfa1b
mpusio/Teoria_Grafow
/Laboratorium4/Alghoritm_LF.py
3,859
3.53125
4
# Koloruje graf na minimalna ilosc kolorow # Skrypt do zmiany: # COMMAND="python2 Alghoritm_LF.py $1" # pobranie danych z flagami lub bez nich: import sys result = sys.argv[1] #flagi -c, -ch if '/' in result: #jezeli nic nie podales, bedzie sciezka arg = sys.argv[1] else: arg = sys.argv[2] f = open(arg, mode='r') a = f.read() a = a.split() edg_list = [int(item) for item in a] f.close() #klasa graf class Graph: def __init__(self, list_neighbors): self.list_neighbors = list_neighbors def ColorGraph(self): """Przeszukuje graf w glab, sprawdza czy jest spojny""" def bubble_sort(l): for item in range(len(l) - 1): # dl 5 [0,1,2,3,4] if l[item] > l[item + 1]: l[item], l[item + 1] = l[item + 1], l[item] bubble_sort(l) return l def list_edges(): """Zwraca nowa liste z parami wierzcholkow (krawedziami grafu): [(v1,v2),(v1,v3),...]""" list_neighbors = list(self.list_neighbors) list_edg = zip(list_neighbors[::2], list_neighbors[1::2]) return list_edg def neighbors_v(v): """"Zwraca liste sasiadow danego wierzcholka""" neigbors_v = [] for pairs in l_edg: if pairs[0] == v: neigbors_v.append(pairs[1]) elif pairs[1] == v: neigbors_v.append(pairs[0]) return set(neigbors_v) def check_color(all_neigh): """Sprawdz kolory sasiadow""" for v, c in vertices_colors: if v in all_neigh: try: l_colors.remove(c) #jezeli juz kolor zostal odjety except ValueError: pass def give_color(act_v): """Daj kolor dla aktualnego wierzcholka""" vertices_colors.append((act_v, l_colors[0])) def sort_by_degrees(l_neigh): """Oddaje nowa, posortowana liste po stopniach wierzcholkow""" list_v = [] degree_and_v = [] for v in set(l_neigh): degree = len(neighbors_v(v)) degree_and_v.append((degree, v)) degree_and_v = bubble_sort(degree_and_v) for pair in degree_and_v[::-1]: list_v.append(pair[1]) return list_v def colored(): """Kolejne kolorowanie LF""" colored_list = [] for v, c in vertices_colors: colored_list.append(c) return colored_list def chromatic_number(): """Liczb chromatyczna""" chromatic_list = [] for v, c in vertices_colors: chromatic_list.append(c) return len(set(chromatic_list)) l_ver = bubble_sort(list(set(self.list_neighbors))) # [0,1,2,3,4,5] l_edg = list_edges() # [(0,1),(0,4),(1,2),(1,4),(1,5),(2,3),(3,4),(3,5),(4,5)] l_deg = sort_by_degrees(self.list_neighbors) # [4,1,5,3,2,0] actual_vertices = self.list_neighbors[0] vertices_colors = [] # struktura [(v, c)], czyli [(vertices, color)] while l_deg != []: l_colors = range(len(l_ver)) actual_vertices = l_deg[0] check_color(neighbors_v(actual_vertices)) give_color(actual_vertices) l_deg.remove(actual_vertices) if '-ch' in result: print "Liczba chromatyczna: ", chromatic_number() return " " if '-c' in result: print "Lista kolorowania: ", colored() return " " else: print "Lista kolorowania: ", colored() print "Liczba chromatyczna: ", chromatic_number() return " " graf1 = Graph(edg_list) print graf1.ColorGraph()
0e8fac3aeb2f57516c16775fbf92fa8c1b4b31a1
zone31/Advent-of-Code-2020
/Days/7/Python/run.py
3,097
3.765625
4
#!/usr/bin/env python3 import os import re import sys #######################Helping functions########################### def data_parser(filepath): """ We parse each line , and create a dict with the base case, and then a list containing the amount of suitcases in that case. """ tmp = open(filepath).read().split('\n') ret = {} for element in tmp: name, others = element.split(' bags contain ') parsed_values = {} for value in [re.sub(r' bags?.?', '', x) for x in others.split(', ')]: if value == 'no other': continue parsed_values[value.split(' ', 1)[1]] = int(value.split(' ')[0]) ret[name] = parsed_values return ret def inverse_graph(g): """ Inverse a acrylic suitcase graph. """ ret = {} for name, elements in g.items(): if name not in ret: ret[name] = {} for element, value in elements.items(): if element not in ret: ret[element] = {} ret[element][name] = value return ret def node_visits_unique(g, node_name): """ Recursively get the unique nodes we hit, when traversing the suit case graph at node 'node_name' """ node = g[node_name] vals = set(node.keys()) for new_node in node.keys(): vals |= node_visits_unique(g, new_node) return vals def node_visits_count(g, node_name): """ Like the recursive function, but return the amount of suitcases seen from that node. """ node = g[node_name] vals = 1 for new_node, value in node.items(): vals += value * node_visits_count(g, new_node) return vals #########################Main functions############################ def solver_1star(d): """ Inverse the suitcase graph, and get the unique node visits. """ inv_g = inverse_graph(d) visits = node_visits_unique(inv_g, 'shiny gold') return len(visits) def solver_2star(d): """ Count all the notes visited from the shiny gold suitcase. """ return node_visits_count(d, 'shiny gold') - 1 ##############################MAIN################################# def main(): """Run the program by itself, return a tuple of star1 and star2.""" dirname = os.path.dirname(__file__) input_source = os.path.join(dirname, '..', 'input1.txt') # Make list, since the generator has to be used multiple times d = data_parser(input_source) return (solver_1star(d), solver_2star(d)) def day_name(): """Get the date name from the folder.""" file_path = os.path.dirname(__file__) day_path = os.path.normpath(os.path.join(file_path, '..')) return os.path.basename(day_path) if __name__ == "__main__": star1, star2 = main() if len(sys.argv) == 2: arg = sys.argv[1] if arg == '1': print(star1) elif arg == '2': print(star2) else: day = day_name() print(f"Day {day} first star:") print(star1) print(f"Day {day} second star:") print(star2)
4c133ecacfc7edde562441d18c293e375b3d36bc
andreluismoreira/Codigos-em-Python
/lista01questao02.py
218
4.03125
4
print('----Transfomação de Temperaturas----') Celcius = int(input("Digite a temperatura em Celcius: ")) Formula = (9*Celcius+160)/5 print( 'A Temperatura em celcius e {} em farenheiten e {}'.format(Celcius,Formula))
0cc2e54a1ceda2bfffe8eac1558cc2190dfbee50
mandark97/Search-Methods-Course
/Uninformed Search/src/cell.py
715
3.65625
4
class Cell(object): def __init__(self, x, y, dist=0, road=[]): self.x = x self.y = y self.dist = dist self.road = road.copy() self.road.append(self) def __eq__(self, cell): if cell: return self.x == cell.x and self.y == cell.y # else: # return def __repr__(self): return f"({self.x}, {self.y}, {self.dist})" def move(self, movement): x, y = movement return Cell(self.x + x, self.y + y, self.dist + 1, self.road) def is_valid(self, dim, visited): return self.x >= 0 and self.x < dim and \ self.y >= 0 and self.y < dim and \ visited[self.x][self.y] == None
1945273b89526452432881bf925fc10c50d467ce
vermouth1992/Leetcode
/python/623.add-one-row-to-tree.py
2,584
3.765625
4
# # @lc app=leetcode id=623 lang=python3 # # [623] Add One Row to Tree # # https://leetcode.com/problems/add-one-row-to-tree/description/ # # algorithms # Medium (53.10%) # Total Accepted: 71.3K # Total Submissions: 134.2K # Testcase Example: '[4,2,6,3,1,5]\n1\n2' # # Given the root of a binary tree and two integers val and depth, add a row of # nodes with value val at the given depth depth. # # Note that the root node is at depth 1. # # The adding rule is: # # # Given the integer depth, for each not null tree node cur at the depth depth - # 1, create two tree nodes with value val as cur's left subtree root and right # subtree root. # cur's original left subtree should be the left subtree of the new left # subtree root. # cur's original right subtree should be the right subtree of the new right # subtree root. # If depth == 1 that means there is no depth depth - 1 at all, then create a # tree node with value val as the new root of the whole original tree, and the # original tree is the new root's left subtree. # # # # Example 1: # # # Input: root = [4,2,6,3,1,5], val = 1, depth = 2 # Output: [4,1,1,2,null,null,6,3,1,5] # # # Example 2: # # # Input: root = [4,2,null,3,1], val = 1, depth = 3 # Output: [4,2,null,1,1,3,null,null,1] # # # # Constraints: # # # The number of nodes in the tree is in the range [1, 10^4]. # The depth of the tree is in the range [1, 10^4]. # -100 <= Node.val <= 100 # -10^5 <= val <= 10^5 # 1 <= depth <= the depth of tree + 1 # # # # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode: if depth == 1: new_root = TreeNode(val=val, left=root) return new_root # find all the nodes at depth curr_row = [root] for _ in range(depth - 2): next_row = [] while len(curr_row) > 0: curr_node = curr_row.pop() if curr_node.left is not None: next_row.append(curr_node.left) if curr_node.right is not None: next_row.append(curr_node.right) curr_row = next_row for node in curr_row: new_left_node = TreeNode(val=val, left=node.left) new_right_node = TreeNode(val=val, left=None, right=node.right) node.left = new_left_node node.right = new_right_node return root
70dffc4febbf96ab2170bd87c822227c97ffd526
TheJericle/Recipizer
/core/Ingredient_Class.py
2,049
3.921875
4
#!/usr/bin/env python # -*- coding: utf8 -*- # ****************************************** # ** RECIPIZER ** # ** © 2017 ** # ****************************************** # Ensure Python 3 compatibility from __future__ import absolute_import, division, print_function # ----------------------------------------------------------------- class Ingredient(object): def __init__(self, name="", quantity=0, unit=""): self._name = name self._quantity = quantity self._unit = unit def __eq__(self, other): if self.name != other.name: return False return True def __mul__(self, value): if not isinstance(value, int): raise TypeError("An ingredient can only be multiplied by an integer or a float") else: self._quantity *= value return self @property def name(self): return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError("Pretty sure the name of the ingredient should be a string...") else: self._name = value @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): if not isinstance(value, float): raise TypeError("Try using a float for the quantity") else: self._quantity = value @property def unit(self): return self._unit @unit.setter def unit(self, value): if not isinstance(value, str): raise TypeError("Try using a string for the unit...") else: self._unit = value def inverse_parser(self): output = self.name + "\t" + str(self.quantity) + "\t" + self.unit return output def parser(self, v_str): self.name = v_str[0] self.quantity = float(v_str[1]) self.unit = v_str[2] # -----------------------------------------------------------------
07e2422cf8cec89b4528475e990dbf669fdf9a40
Nirperm/MachineLearning_Python
/NLP_100knock/chapter1/07.py
327
3.515625
4
""" 07. テンプレートによる文生成 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ. さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ. """ template = lambda x, y, z: print('{0}時の{1}は{2}'.format(x, y, z)) template(12, "気温", 22.4)
2b770384c4e009c2c2423756e0630f83573076fa
MaRTeKs-prog/Self-Taught
/Ch 14/python_ex265.py
166
4.03125
4
x = 10 if x is None: print('x equals None :(') else: print("x isn't None") x = None if x is None: print('x equals None :(') else: print("x isn't None")
92b5b79f0c30fa34919daf6f64db3792e9aea69e
verisimilitude20201/dsa
/Sorting/Bubble_Sort/Array/bubble_sort.py
2,975
3.65625
4
""" Approach -------- Pass 0: 0 to N - 1 0 [3, 4, 1, 19, 21, 17, 18, 2] # Compare 3 and 4, 3 < 4 so don't swap 1 [3, 1, 4, 19, 21, 17, 18, 2] # Compare 4 and 1, 4 < 1 so swap 2 [3, 1, 4, 19, 21, 17, 18, 2] # Compare 4 and 19, 4 < 19 so don't swap 3 [3, 1, 4, 19, 21, 17, 18, 2] # Compare 19 and 21, 19 < 21 so don't swap 4 [3, 1, 4, 19, 17, 21, 18, 2] # Compare 17 and 21, 21 < 17 so swap 5 [3, 1, 4, 19, 17, 18, 21, 2] # Compare 21 and 18, 21 < 18 so swap 6 [3, 1, 4, 19, 17, 18, 2, 21*] # Compare 21 and 2, 21 < 2 so swap, now 21 is largest element and is fixed. Pass 1: 0 to N - 2 7 [1, 3, 4, 19, 17, 18, 2, 21*] # Compare 3 and 1, 3 < 1 so swap 8 [1, 3, 4, 19, 17, 18, 2, 21*] # Compare 3 and 4, 3 < 4 so don't swap 9 [1, 3, 4, 19, 17, 18, 2, 21*] # Compare 4 and 19, 4 < 19 so don't swap 10 [1, 3, 4, 17, 19, 18, 2, 21*] # Compare 19 and 17, 19 < 17 so swap 11 [1, 3, 4, 17, 18, 19, 2, 21*] # Compare 19 and 18, 19 < 18 so swap 12 [1, 3, 4, 17, 18, 2, 19*, 21*] # Compare 19 and 2, 19 < 2 so swap, now 19 is second-largest element and is fixed. Pass 2: 0 to N - 3 13 [1, 3, 4, 17, 18, 2, 19*, 21*] # Compare 1 and 3, 1 < 3 so don't swap 14 [1, 3, 4, 17, 18, 2, 19*, 21*] # Compare 3 and 4, 3 < 4 so don't swap 15 [1, 3, 4, 17, 18, 2, 19*, 21*] # Compare 4 and 17, 4 < 17 so don't swap 16 [1, 3, 4, 17, 18, 2, 19*, 21*] # Compare 17 and 18, 17 < 18 so don't swap 17 [1, 3, 4, 17, 2, 18*, 19*, 21*] # Compare 18 and 2, 18 < 2 so swap, now 18 is third-largest element and is fixed. Pass 3: 0 to N - 4 18 [1, 3, 4, 17, 2, 18*, 19*, 21*] # Compare 1 and 3, 1 < 3 so don't swap 19 [1, 3, 4, 17, 2, 18*, 19*, 21*] # Compare 3 and 4, 3 < 4 so don't swap 20 [1, 3, 4, 17, 2, 18*, 19*, 21*] # Compare 4 and 17, 4 < 17 so don't swap 21 [1, 3, 4, 2, 17*, 18*, 19*, 21*] # Compare 17 and 2, 17 < 2 so swap, 17 is the fourth largest number and is fixed Pass 4: 0 to N - 5 21 [1, 3, 4, 2, 17*, 18*, 19*, 21*] # Compare 1 and 3, 1 < 3 so dont swap 22 [1, 3, 4, 2, 17*, 18*, 19*, 21*] # Compare 3 and 4, 3 < 4 so dont swap 23 [1, 3, 2, 4*, 17*, 18*, 19*, 21*] # Compare 4 and 2, 4 < 2 so swap, 4 is the fifth largest number and is fixed Pass 5: 0 to N - 6 24 [1, 3, 2, 4*, 17*, 18*, 19*, 21*] # Compare 1 and 3, 1 < 3 so don't swap 25 [1, 2, 3*, 4*, 17*, 18*, 19*, 21*] # Compare 1 and 3, 3 < 2 so swap, 3 is the sixth largest number and is fixed Pass 6: 0 to N - 7 26 [1*, 2*, 3*, 4*, 17*, 18*, 19*, 21*] # Compare 1 and 3, 1 < 3 so don't swap, 1 and 3 are also fixed now. Time complexity -------------- Time: O(N^2) Space: O(1) """ def bubble_sort(A): current_pass = 1 i = 0 N = len(A) while i < N - current_pass: for j in range(N - current_pass): if A[j] >= A[j + 1]: temp = A[j] A[j] = A[j + 1] A[j + 1] = temp current_pass += 1 A = [3, 4, 1, 19, 21, 17, 18, 2] bubble_sort(A) print(A)
be2cfd9e87f54b23f2197911f4cd2e341ae87e53
ricwtk/result-ai-a1-202104
/players/Group14Player1/player.py
7,754
3.578125
4
# Node class for each position on the maze class Node(): def __init__(self, parent=None, state=None): self.ID = None self.parent = parent self.state = state self.expansionsequence = -1 self.children = [] self.actions = [] self.removed = False self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.state == other.state def addChildren(self, children): self.children.append(children) class Player(): name = "Banana2" group = "Banana" members = [ ["Sarah Low Ren Ern", "18122614"], ["Low Jun Jie", "19041409"], ["sean Suraj Nathan", "17003807"], ["Mukesh Rajah", "19028281"] ] informed = True def __init__(self, setup): # setup = { # maze_size: [int, int], # static_snake_length: bool # } self.setup = { "maze_size": setup["maze_size"], "static_snake_length": setup["static_snake_length"] } def run(self, problem): # problem = { # snake_locations: [[int,int],[int,int],...], # current_direction: str, # food_locations: [[int,int],[int,int],...], # } self.problem = { "snake_locations": problem["snake_locations"], "current_direction": problem["current_direction"], "food_locations": problem["food_locations"] } # create a virutal maze for the function depending on the settings nrow = self.setup["maze_size"][0] ncol = self.setup["maze_size"][1] e = [] maze = [] for i in range(ncol): e.append(0) for i in range(nrow): maze.append(e) temp_s = self.problem["snake_locations"][0] temp_e = self.problem["food_locations"][0] start = (temp_s[0], temp_s[1]) end = (temp_e[0], temp_e[1]) # Create initial and end node initial_node = Node(None, start) initial_node.g = initial_node.h = initial_node.f = 0 end_node = Node(None, end) end_node.g = end_node.h = end_node.f = 0 # Initialize both frontier and explored frontier = [] explored = [] solution = [] # Add the initial node to frontier frontier.append(initial_node) frontierloop = 0 # lecturer added # Loop until you find the end while len(frontier) > 0: if frontierloop > 1000: # lecturer added raise Exception("frontier loop > 1000") # lecturer added frontierloop += 1 # lecturer added print(frontierloop, end=" ") # lecturer added # Get the current node in the frontier with lowest f value first_node = frontier[0] first_index = 0 for i, nodes in enumerate(frontier): if nodes.f < first_node.f: first_node = nodes first_index = i # Pop current node off frontier, add to explored frontier.pop(first_index) explored.append(first_node) # Return solution and search tree if reached goal if first_node == end_node: path = [] reversed_path = [] current = first_node while current is not None: path.append(current.state) current = current.parent reversed_path = path[::-1] # Reversed path for i in range(len(reversed_path)): if i == 0: continue elif reversed_path[i][0] - reversed_path[i-1][0] == 1: solution.append("e") elif reversed_path[i][0] - reversed_path[i-1][0] == -1: solution.append("w") elif reversed_path[i][1] - reversed_path[i-1][1] == 1: solution.append("s") elif reversed_path[i][1] - reversed_path[i-1][1] == -1: solution.append("n") search_tree = [] temp_tree = [] for i in range(len(reversed_path)): if i == 0: first = Node(None, reversed_path[0]) first.ID = i + 1 first.expansionsequence = i + 1 first.addChildren(i + 2) temp_tree.append(first) else: previous = Node(None, reversed_path[i - 1]) previous.ID = i rest = Node(previous.ID, reversed_path[i]) rest.ID = i + 1 rest.expansionsequence = i + 1 if i == range(len(reversed_path))[-1]: useless = i # A holder with no purpose for if reach last node else: rest.addChildren(i + 2) for e in range(i): rest.actions.append(solution[e]) temp_tree.append(rest) for e in temp_tree: a = { "id": e.ID, "state": e.state, "expansionsequence": e.expansionsequence, "children": e.children, "actions": e.actions, "removed": e.removed, "parents": e.parent } search_tree.append(a) print() # lecturer added return solution, search_tree # Generate children children = [] for directions in [(0, -1), (0, 1), (-1, 0), (1, 0)]: # All n, s, e, w # Get node position node_position = (first_node.state[0] + directions[0], first_node.state[1] + directions[1]) # Make sure node position within range of the maze size if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0: continue # Prevent snake from biting itself if [node_position[0], node_position[1]] in self.problem["snake_locations"]: continue new_node = Node(first_node, node_position) children.append(new_node) # Loop through children for child in children: # Child is on the explored list for explored_child in explored: if child == explored_child: continue # Create the f, g, and h values child.g = first_node.g + 1 child.h = ((child.state[0] - end_node.state[0]) ** 2) + ((child.state[1] - end_node.state[1]) ** 2) child.f = child.g + child.h # Child is already in the frontier for open_node in frontier: if child == open_node and child.g > open_node.g: continue # Else add the child to the open list frontier.append(child) if __name__ == "__main__": p1 = Player({ "maze_size": [10,10], "static_snake_length": True }) sol, st = p1.run({'snake_locations': [[0, 5]], 'current_direction': 'e', 'food_locations': [[6, 7]]}) print("Solution is:", sol) print("Search tree is:") print(st)
bdcf70a0c25217b0ebbe9b63ade9c53a612f085c
ongsuwannoo/PSIT-61
/Week 10/Difference.py
537
3.640625
4
"""Difference""" def main(first, second): """try""" set_first = [] set_second = [] for _ in range(first): member_first = int(input()) set_first.append(member_first) set_first = set(set_first) for _ in range(second): member_second = int(input()) set_second.append(member_second) set_second = set(set_second) set_total = set_first - set_second set_total = list(set_total) set_total = sorted(set_total) print(*set_total, end=' ') main(int(input()), int(input()))
0b660578de7d213533f9231b5e2d84d840d52725
kylerlmy/pythonpractice
/src/basic_control.py
1,197
4.0625
4
## 控制流 number=12 guess=12#int(input('Enter an integer:')) if guess==number: #新块在这里开始23 print('congradulation ,you guessed it.') #块结束 elif guess<number: #另一代码块 print('No,it is little higher than that') #end block else: print('No,it is a littler lower than that') print('Done') ### for 循环 ,for循环与 C# 中的 foreach 循环相似。 for i in list(range(1,5)): #或者 for i in range(1,5) range应该实现了枚举器功能 print(i) else: print('the for loop is over') ### while 语句 number=12 running=False while running: guess=int(input('Enter an integer:')) if guess==number: #新块在这里开始23 print('congradulation ,you guessed it.') running=False #块结束 elif guess<number: #另一代码块 print('No,it is little higher than that') #end block else: print('No,it is a littler lower than that') print('Done') ### continue while True: s=input('Enter something: ') if s=='quit': break if len(s)<3: print('too small') continue print('input is of sufficient length')
6b8a8bdf5152c31cc24e448b29a03cd28632737a
E-Armstrong/practiceCode
/Python/stringsInParentheses.py
1,687
4.09375
4
"""You have string like this "abc(def) (xyz) ((mno))" Find the deepest nested string in parenthesis. So in this case mno Anoher scenario will be "aaa(bbb(ccc)(ddd))" This should return ['ccc','ddd'] """ def stringsInParenth (stringX): parenthLevel = 0 highestValueParenth = 0 finalResult = [] tempResult = [] tempDictionary = [] for char in stringX: if char is "(": if tempResult is not []: tempString = "" for letter in tempResult: tempString += letter tempDictionary.append([parenthLevel, tempString]) tempResult = [] parenthLevel += 1 if char is ")": if tempResult is not []: tempString = "" for letter in tempResult: tempString += letter tempDictionary.append([parenthLevel, tempString]) tempResult = [] parenthLevel -= 1 if (parenthLevel > 0) and (char is not "(") and (char is not ")"): tempResult.append(char) if parenthLevel is not 0: return "Not equal amount of matching parenthesis." for keyPair in tempDictionary: if int(keyPair[0]) > highestValueParenth: highestValueParenth = int(keyPair[0]) for keyPair in tempDictionary: if keyPair[0] is highestValueParenth: finalResult.append(keyPair[1]) return finalResult print(stringsInParenth("abc(def) (xyz) ((mno))")) print(stringsInParenth("aaa(bbb(ccc)(ddd))")) print(stringsInParenth("aaa(bbb((ccc))(ddd))")) print(stringsInParenth("aaa(bbb(ccc)((ddd)))"))
23a43d4e2666a982259cba9d832fbe98f5450590
mayaragualberto/URIOnlineJudge
/Python/1008.py
113
3.53125
4
NF=int(input()) HT=int(input()) VH=float(input()) print("NUMBER =",NF) print("SALARY = U$ {:.2f}".format(HT*VH))
19d599d71cfb5bb22718b0c4cb6511162a939ee8
arun-p12/project-euler
/p0001_p0050/p0010.py
588
3.859375
4
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all prime numbers below 2,000,000 ''' import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# import sys sys.path.append('../') import common as c number = 2000000 print("sum of primes = ", sum(c.prime_list_generator(number, False))) ########## end of main routine ########### t = time.time() - t # and now, after the routine print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t * 1000000))
4b4f5692083afa11c93a48a3ef4a9d730ca1ad40
jayohhhh/IntroToProg-Python-Mod08
/Assignment08_Starter.py
8,167
3.640625
4
# ------------------------------------------------------------------------ # # Title: Assignment 08 # Description: Working with classes # ChangeLog (Who,When,What): # RRoot,1.1.2030,Created started script # RRoot,1.1.2030,Added pseudo-code to start assignment 8 # Jonathan Ou, 5/30/20, Modified code to product class # Jonathan Ou, 5/31/21, added code to IO class # Jonathan Ou, 5/31/21, added code to Main Script Body # ------------------------------------------------------------------------ # # Data -------------------------------------------------------------------- # strFileName = 'products.txt' lstOfProductObjects = [] objFile = None # An object that represents a file strStatus = "" class Product(object): """Stores data about a product: properties: product_name: (string) with the products's name product_price: (float) with the products's standard price methods: """ def __init__(self, product_name, product_price): self.__product_name = '' self.__product_price = '' self.product_name = product_name self.product_price = product_price @property def product_name(self): return str(self.__product_name).title() @product_name.setter def product_name(self, name): if not name.isnumeric(): self.__product_name = name else: raise Exception("Names can't be numbers") @property def product_price(self): return float(self.__product_price) @product_price.setter def product_price(self, value: float): try: self.__product_price = float(value) # cast to float except ValueError: raise Exception("Prices must be numbers") # -- Methods -- def to_string(self): return self.__str__() def __str__(self): return self.product_name + "," + str(self.product_price) # Data -------------------------------------------------------------------- # # Processing ------------------------------------------------------------- # class FileProcessor: """Processes data to and from a file and a list of product objects: methods: save_data_to_file(file_name, list_of_product_objects): read_data_from_file(file_name): -> (a list of product objects) """ pass @staticmethod def read_data_from_file(file_name: str): """ Reads data from a file into a list of object rows :param file_name: (string) with name of file :return: (list) of object rows """ list_of_rows = [] try: file = open(file_name, "r") for line in file: prod = line.split(",") row = Product(prod[0],prod[1]) list_of_rows.append(row) file.close() except Exception as e: print("There was a general error!") print(e, e.__doc__, type(e), sep='\n') return list_of_rows @staticmethod def save_data_to_file(file_name: str, list_of_objects: list): """ Write data to a file from a list of object rows :param file_name: (string) with name of file :param list_of_objects: (list) of objects data saved to file :return: (bool) with status of success status """ success_status = False try: file = open(file_name, "w") for row in list_of_objects: file.write(row.__str__() + "\n") file.close() success_status = True except Exception as e: print("There was a general error!") print(e, e.__doc__, type(e), sep='\n') return success_status # Processing ------------------------------------------------------------- # # Presentation (Input/Output) -------------------------------------------- # class IO: # TODO: Add docstring """ performs input/output tasks methods: print_menu_tasks() input_menu_choice() print_current_product_data() input_product_data() input_yes_no_choice() input_press_to_continue() """ # TODO: Add code to show menu to user @staticmethod def print_menu_tasks(): """ Display a menu of choices to the user :return: nothing """ print(''' Menu of Options 1) Show Current Products 2) Add New Product Details 3) Save Data to File 4) Exit Program ''') print() # TODO: Add code to get user's choice @staticmethod def input_menu_choice(): """ Gets the menu choice from a user :return: string """ choice = input("Which option would you like to perform? [1 to 4] - ").strip() print() # Add an extra line for looks return choice # TODO: Add code to show the current data from the file to user @staticmethod def print_current_product_data(lstOfProductObjects): print("******* The current Product details are: *******") for row in lstOfProductObjects: print(str(row.product_name) + "," + str(row.product_price)) print("*******************************************") # TODO: Add code to get product data from user @staticmethod def input_product_data(): name = str(input("What is your new product? - ").strip()) price = float(input("What is your product price - ").strip()) prod = Product(product_name=name, product_price=price) print() return prod @staticmethod def input_yes_no_choice(message): """ Gets a yes or no choice from the user :return: string """ return str(input(message)).strip().lower() @staticmethod def input_press_to_continue(optional_message=''): """ Pause program and show a message before continuing :param optional_message: An optional message you want to display :return: nothing """ print(optional_message) input('Press the [Enter] key to continue.') # Presentation (Input/Output) -------------------------------------------- # # Main Body of Script ---------------------------------------------------- # # TODO: Add Data Code to the Main body # Load data from file into a list of product objects when script starts # Show user a menu of options # Get user's menu option choice # Show user current data in the list of product objects # Let user add data to the list of product objects # let user save current data to file and exit program # Step 1 - When the program starts, Load data from products.txt. lstOfProductObjects = FileProcessor.read_data_from_file(strFileName) # read file data while (True): IO.print_menu_tasks() # Shows menu strChoice = IO.input_menu_choice() # Get menu option # Step 4 - Process user's menu choice if strChoice.strip() == '1': # show current products IO.print_current_product_data(lstOfProductObjects) # Show current data in the list/table IO.input_press_to_continue(strStatus) continue # to show the menu elif strChoice == '2': # add new product details lstOfProductObjects.append(IO.input_product_data()) IO.input_press_to_continue(strStatus) continue # to show the menu elif strChoice == '3': # Save Data to File strChoice = IO.input_yes_no_choice("Save this data to file? (y/n) - ") if strChoice.lower() == "y": FileProcessor.save_data_to_file(strFileName, lstOfProductObjects) IO.input_press_to_continue(strStatus) else: IO.input_press_to_continue("Save Cancelled!") continue # to show the menu elif strChoice == '4': # Exit Program print("Goodbye!") break # and Exit # Main Body of Script ---------------------------------------------------- #
a34daa79c05adcba8f511dc31f5940aea2332380
spatialaudio/python-sounddevice
/examples/play_file.py
2,394
3.546875
4
#!/usr/bin/env python3 """Load an audio file into memory and play its contents. NumPy and the soundfile module (https://python-soundfile.readthedocs.io/) must be installed for this to work. This example program loads the whole file into memory before starting playback. To play very long files, you should use play_long_file.py instead. This example could simply be implemented like this:: import sounddevice as sd import soundfile as sf data, fs = sf.read('my-file.wav') sd.play(data, fs) sd.wait() ... but in this example we show a more low-level implementation using a callback stream. """ import argparse import threading import sounddevice as sd import soundfile as sf def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '-l', '--list-devices', action='store_true', help='show list of audio devices and exit') args, remaining = parser.parse_known_args() if args.list_devices: print(sd.query_devices()) parser.exit(0) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[parser]) parser.add_argument( 'filename', metavar='FILENAME', help='audio file to be played back') parser.add_argument( '-d', '--device', type=int_or_str, help='output device (numeric ID or substring)') args = parser.parse_args(remaining) event = threading.Event() try: data, fs = sf.read(args.filename, always_2d=True) current_frame = 0 def callback(outdata, frames, time, status): global current_frame if status: print(status) chunksize = min(len(data) - current_frame, frames) outdata[:chunksize] = data[current_frame:current_frame + chunksize] if chunksize < frames: outdata[chunksize:] = 0 raise sd.CallbackStop() current_frame += chunksize stream = sd.OutputStream( samplerate=fs, device=args.device, channels=data.shape[1], callback=callback, finished_callback=event.set) with stream: event.wait() # Wait until playback is finished except KeyboardInterrupt: parser.exit('\nInterrupted by user') except Exception as e: parser.exit(type(e).__name__ + ': ' + str(e))
df0b7d92fdbd2b0f634f29951e86879a52a4992e
mmanley42/learn_tests
/python/computor_v1/computor_v1_1/my_pars_stuff.py
3,016
3.5
4
import re import argparse from my_math import is_all_float class pars_class(): """docstring for pars_class.""" def __init__(self, str_check=None, pattern_tab=None, change_tab=None, split_tab=None): self.strch = str_check self.patts = pattern_tab self.subs = change_tab self.splits = split_tab def reshape_string(self, s, pattern=' +', sub=' ', msg=None): tmp = re.sub(pattern, sub, s) if tmp: return tmp if msg != None: print ('No patterns found in string') return s def chars_cmp_str(self, s, cmp): tmp = re.search(cmp, s) if tmp == None: print (s, cmp) print ('Wrong character in equation, -help for more details') exit () def for_computor_v1(self, s): s = self.reshape_string(s, self.patts[0]) #s = self.reshape_string(s, '(?<=\ *-*)([xX])(?=\ \+*-*\Z?)', 'x^1', 'go') self.chars_cmp_str(s, self.strch) print 'Parsed string < ' + s + ' >' s = self.reshape_string(s, self.patts[1], self.subs[0]) s = self.reshape_string(s, self.patts[2], self.subs[1]) tab_l = s.split(self.splits[0]) tab_r = tab_l[1] tab_l = tab_l[0].split(self.splits[1]) tab_r = tab_r.split(self.splits[1]) return tab_l, tab_r class numerical_pars(): """docstring for numerical_pars.""" def __init__(self, tab_l, tab_r): self.tl = tab_l self.tr = tab_r def fraction_shit(self, s): #if re.search('((\d+\.\d+/\d+\.\d+)|(-\d+\.\d+/-\d+\.\d+))|((-\d+\.\d+/\d+\.\d+)|(\d+\.\d+/-\d+\.\d+)|(-\d+/-\d+)|(\d+/\d+)|(-\d+/\d+)|(\d+/-\d+))', s): # print ('Fraction shit :\n', s) if re.search('-*\d+\.*\d*/-*\d+\.*\d*', s): print 'Fraction shit :\n', s a = re.search('\A-*\d+\.*\d*', s) b = re.search('(?<=/)-*\d+\.*\d*(?=\D)', s) a = float(a.group()) b = float(b.group()) print '------> A', a, '<-> B', b, '<-> A/B', float(a / b) # print ('------>', a, b, float(a / b)) tmp = str(a / b) s = re.sub('-*\d+\.*\d*/*-*\d+\.*\d*', tmp, s) print 'My floated version', s, '\n' # print ('My floated version', s) return s return s def already_simplfied(self, s): if re.search('(\d+\D\^\d+)|(-\d+\D\^\d+)', s) != None: if re.search('(\d+\D\^0)|(-\d+\D\^0)', s) != None: s = re.sub('\D\^0', '', s) print 'Already simplified' # print ('Already simplified') return s def simplification(self, s): if self.already_simplfied(s) != None: s = self.already_simplfied(s) return s s = self.fraction_shit(s) if re.search('((\d+ *\** *-*\D\^?(?=\d*)))', s) != None: if re.search('\D\^0', s) != None: s = re.sub(' *\** *\D\^0', '', s) else: s = re.sub(' *\** *', '', s) return s elif is_all_float(s) == True: return s elif re.match('(\+* *-*\D\^\d+)', s) != None: if s[-1] == '0': s = '1' return s else: print ('Error of some sort') exit() def simplify(self, tab): i = 0 while i < len(tab): tab[i] = self.simplification(tab[i]) i += 1 return tab def started(self, tab_l, tab_r): tab_l = self.simplify(tab_l) tab_r = self.simplify(tab_r) return tab_l, tab_r
7f92e571be834a1546c3d95cc67fac332265e2b6
byrpatrick/Pico_Placa
/venv/Source/Pico_Placa.py
1,435
3.9375
4
from datetime import time import calendar def getDay(date): dayNumber = calendar.weekday(date.year, date.month, date.day) days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return (days[dayNumber]) class Pico_Placa(): def __init__(self, rulesPP = {"Monday":[1,2], "Tuesday":[3,4], "Wednesday":[5,6], "Thursday":[7,8], "Friday":[9,0]}, picoHours = [[time(7, 0), time(9, 30)],[time(16, 0), time(19, 30)]] ): self.__rulesPP = rulesPP self.__picoHours = picoHours def isPicoHour(self, timeGiven): for picoH in self.__picoHours: if (timeGiven >= picoH[0] and timeGiven <= picoH[1]): return True return False def canBeOnRoad(self, lastDigit, date, timeGiven): day = getDay(date) # It's weekend anyone can be on road, enjoy your journey!! if day in ["Saturday", "Sunday"]: return "The car can be on road." # When the time is right, you can drive!! # If isn't a pico hour you can drive. if not self.isPicoHour(timeGiven): return "The car can be on road." # Isn't weekend and is a pico hour. Can I drive? for k, v in self.__rulesPP.items(): if (day == k) and (lastDigit in v): return "The car can't be on road." return "The car can be on road."
5d8aa04e2e91d98df938d7fd35db72cd94e9bb21
elzilcho666/pyukplatelookup
/reg_lookup.py
729
3.5
4
#/usr/bin/python import sys import sqlite3 regDB = sqlite3.connect('UK_prefixes.db') reg = sys.argv[1] region = (reg[:2],) cur = regDB.cursor() cur.execute("select * from Reg_current where prefix =?", region) row = cur.fetchone() print "Car registered at %s, %s" % (row[1], row[2]) if int(reg[-2:]) > 50: year = str(int(reg[-2:]) - 49) prevyear = str(int(year) - 1) if len(year) == 1: year = "0" + year prevyear = "0" + prevyear print "The car was registered between 1st September 20%s and 28th/29th Febuary 20%s" % (prevyear, year) else: year = reg[-2:] print "The car was registered between 1st March and 31st August 20%s" % (year) #for row in rows: # print "Car registered in %s, %s" % (row['city'], row['region'])
b6a17a27501cc76405131901e6ae95d1947c5fce
aSrivastaava/Python
/25-07-2018/venv/Number_Game.py
307
4
4
import random while(5>1): think = random.randint(1, 10) num = int(input("I'm thinking of a number in range 1 to 10, Can you guess it??...\n")) question = input("Enter your Question: ") if(num == think): print("Lucky Guess....") else: print("I know you are a dumb...")
c3ac15d425b6ff17331eb994aa52ff60c129bc4e
lizzzcai/leetcode
/python/bit_manipulation/0421_Maximum_XOR_of_Two_Numbers_in_an_Array.py
1,534
3.59375
4
''' 16/09/2020 421. Maximum XOR of Two Numbers in an Array - Medium Tag: Bit Manipulation, Trie Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. Could you do this in O(n) runtime? Example: Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28. ''' from typing import List # Solution class Solution1: def findMaximumXOR(self, nums: List[int]) -> int: ''' https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/91049/Java-O(n)-solution-using-bit-manipulation-and-HashMap O(n) ''' max_result, mask = 0, 0 for i in range(31, -1, -1): mask = mask | (1 << i) hset = set() for num in nums: num_left = num & mask hset.add(num_left) try_greedy = max_result | (1 << i) for num_left in hset: num_right = num_left ^ try_greedy if num_right in hset: max_result = try_greedy break return max_result # Unit Test import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_testCase(self): for Sol in [Solution1()]: func = Sol.findMaximumXOR self.assertEqual(func([3, 10, 5, 25, 2, 8]), 28) if __name__ == '__main__': unittest.main()
c4f31c5ad1ea93b7c548097a0b5e168edd745185
minatverma/project-euler
/largest_prime_factor.py
1,089
3.734375
4
# coding=utf-8 # Problem Statement # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? import os import sys import re import timeit def larget_prime_factor(number): start = timeit.default_timer() factor_list = list() div = 2 while div**2 < number : if number % div == 0: number = number / div if div not in factor_list: factor_list.append(div) else: div = div + 1 if number not in factor_list: factor_list.append(number) print '\n Factor List = ', factor_list stop = timeit.default_timer() print 'Time : ', start - stop if __name__ == "__main__": print "\nThis utility helps in finding disctinct factors of a number" print "To end session press 1 !!" try: session = True while session: print "\nEnter your number" number = raw_input() if number.isdigit(): if int(number) == 1: session = False else: larget_prime_factor(int(number)) else: print number, " is not a valid number.please try again.else print 1 to exit" continue except Exception: pass
65163e63c3495fa837d8d3ae7cb0f3a320b63bed
djpaguia/SeleniumPythonProject1
/Demo/PythonDictionary.py
1,360
4.34375
4
# There are 4 Collection data types in Python # List | Tuple | Set | Dictionary # List - [] - ordered | indexed | changeable | duplicates # Tuple - () - ordered | indexed | unchangeable | duplicates # Set - {} - unordered | unindexed | no duplicates # Dictionary - {K:V} - unordered | indexed | changeable | no duplicates my_dict = { "class" : "animal", "name" : "giraffe", "age" : 10 } print(my_dict) print(my_dict["name"]) # Prints value of the key = "name" print(my_dict.get("name")) # Prints value of the key = "name" print(my_dict.values()) # Prints all Values for x in my_dict: print(x) # Prints all Keys. for x in my_dict: print(my_dict[x]) # Prints all Values. for x,y in my_dict.items(): # Prints all keys and values print(x, y) my_dict["name"] = "elephant" # Updates value of existing Key print(my_dict) my_dict["color"] = "grey" # Adds a new key and value since the key is previously non-existent. print(my_dict) my_dict.pop("color") # Removes key "color" and its value from the Dictionary print(my_dict) my_dict.popitem() # Removes last item from the dictionary. print(my_dict) del my_dict["class"] print(my_dict) my_dict.clear() print(my_dict) del my_dict
f338336ac6ae23bb85173918d74b8d06c0cecc08
VIGribkov/communis_math
/py_samples/snowy_fractal.py
434
3.65625
4
import turtle as t def go_snowy(length): if length < 5: t.forward(length) else: go_snowy(length/3) t.left(60) go_snowy(length/3) t.right(120) go_snowy(length/3) t.left(60) go_snowy(length/3) t.color('red', 'yellow') t.speed(100) t.begin_fill() for _ in 0, 1, 2: go_snowy(250) t.right(120) t.end_fill() t.exitonclick() t.mainloop() t.done()
3497a39a3f808c90e2adf11e2d635359bd861ecd
tolgazorlu/CodePractices
/day2/day2_part2.py
795
3.75
4
def testInput(testFile): arr = [] test = open(testFile, "r") for i in test: arr.append(i) test.close() return arr def validPassword(arr): count = 0 for i in range(len(arr)): c = 0 List = (arr[i].split("-")) minNumber = int(List[0]) maxNumberList = List[1].split(": ") password = maxNumberList[1].split("\\") password = password[0] maxNumberList = maxNumberList[0].split(" ") maxNumber = int(maxNumberList[0]) letter = maxNumberList[1] if((password[minNumber-1] == letter) and (password[maxNumber-1] == letter)): count = count + 1 return count arr = testInput("test.txt") print(validPassword(arr))
6281d3a0f3f1cec4094d7244306bc1f82633afe0
PetoriousBIG/DailyProblems
/CrackingTheCodingInterviewProblems/PalindromePermutations.py
1,306
4.15625
4
# Problem Description: # # Palindrome Permutation - Given a string, write a function to check if it is a permutation of a palindrome. # A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters # The palindrome does not need to be limited to just dictionary words. # # EXAMPLE - Input: "Tact Coa" Output: True (via "taco cat", "atco cta", and others) # Solution note: a palindrome can only have at most one character with an odd number of instances within the string # The same holds for a permutation of a palindrome def isPermutationOfPalindrome(text): textNoWhiteSpace = text.replace(" ", "") textFormatted = textNoWhiteSpace.lower() lettersInText = {} oddCount = 0 for i in range(0, len(textFormatted)): char = textFormatted[i] if char in lettersInText: lettersInText[char] += 1 else: lettersInText[char] = 1 for key in lettersInText: if lettersInText[key] % 2 == 1: oddCount += 1 return oddCount < 2 def main(): print("Testing 'Tact Coa', expected output is true") print(isPermutationOfPalindrome("Tact Coa")) print("Testing 'bhhhbi', expected output is false") print(isPermutationOfPalindrome("bhhhbi")) main()
b4c33243c0fa8fa135404530abbaf54b7da28f8d
VRER1997/leetcode_python
/easy/014 Longest Common Prefix.py
648
3.515625
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return '' res = strs[0] for i in range(len(strs)): res = self.getTwoWordCommomPrefix(res, strs[i]) return res def getTwoWordCommomPrefix(self, x, y): res, i = '', 0 while i < len(x) and i < len(y): if x[i] == y[i]: res += x[i] else: break i += 1 return res if __name__ == '__main__': s = Solution() s.getTwoWordCommomPrefix("fl", "fl")
b38954105c9127d258431e3c72686b213a3bd8c7
cyberbono3/euler-exercises
/eulerexercises/euler-23-non abundant sums.py
1,197
3.890625
4
# abundant number is number the sum of divisors exceeds the number # all integers grater tan 28123 can be written as the sum of 2 abundant numbers # find th sum of al positiive integers which can not be written as the sum of two abundant numbers # write the function that checks if numbers are # generator comprehension of sum of the numbes that are not abundandant # 1) lsit of all abundant numbers #sum of divisors def divisors_sum(n): result = sum(int(i) for i in range(1, n) if n % i == 0) return result def is_abundant(n): return divisors_sum(n)>n x=100 abundant_numbers = [int(i) for i in range(12,28123) if is_abundant(i)] print("List of abundant numbers: " + str(abundant_numbers)) def can_be_sum_of_abundant(x): x_list =[] for i in (a for a in abundant_numbers if a <x): for j in (a for a in abundant_numbers if a <x): if i + j == x: print(" " + str(i) + " + " + str(j) + "=" + str(x) ) return True return False result = sum(int(i) for i in range (1,28123) if not can_be_sum_of_abundant(i)) print("result: " + str(result)) #result = sum(int(i) for i in range(1,28123) if not abundant_sum(i))
ec3b454d818c78e2a9ae0725fe6178dddc291ec6
jogspokoen/hangman
/hangman.py
4,134
3.625
4
from random import choice import csv # separating text strings is good practice, e.g. for translation purposes MESSAGES = { 'welcome': 'Welcome to the HangMan game!', 'name': 'What is your name?', 'guess_invitation': 'Your guess: ', 'not_letter': 'This is not a single letter. Please be careful when you type. It\'s violent game, after all.', 'already_revealed': 'This letter is already revealed. No need to double-check, trust me', 'already_wasted': 'You already tried with this letter, with no luck. Leave it alone.', 'lucky_guess': 'You was lucky this time! Keep guessing!', 'unlucky_guess': 'Nice try, but you was wrong, and this is one step closer to the edge', 'attempts_left': 'You have {} attempts left!', 'epic_win': 'You won! Such a lucky day for you. Go buy some lottery.', 'epic_fail': 'We need to talk.\n' 'Just sit back and listen.\n' 'It\'s not about you, it\'s about me.\n' 'You have no more attempts.\n' 'This is the end of this game.\n' 'Bye.\n' } def get_input(text): return input(text) class HangmanGame: wordlist = ['3dhubs', 'marvin', 'print', 'filament', 'order', 'layer'] choosen_word = None failed_attemts_left = 5 players_name = None highscore_file = 'highscore.csv' def __init__(self): self.choosen_word = choice(self.wordlist) self.prepare() def prepare(self): self.current_state = ['_' if self.is_letter(_) else _ for _ in self.choosen_word] self.failed_ateempts_letters = set() def is_letter(self, char): return 97 <= ord(char) <= 122 def start_game(self): print(MESSAGES['welcome']) self.players_name = get_input(MESSAGES['name']).lower() self.step() def step(self): # print current state print(' '.join(self.current_state)) print(MESSAGES['attempts_left'].format(self.failed_attemts_left)) # ask for input step_letter = get_input(MESSAGES['guess_invitation']).lower() # process input result = self.process_input(step_letter) print(MESSAGES[result]) print('') if not result.startswith('epic'): self.step() def process_input(self, l): # only letters a-z allowed if len(l) != 1: return 'not_letter' if not self.is_letter(l): return 'not_letter' if l in self.current_state: return 'already_revealed' if l in self.failed_ateempts_letters: return 'already_wasted' if l in self.choosen_word: self.current_state = [c if l == c else self.current_state[i] for i, c in enumerate(self.choosen_word)] if '_' not in self.current_state: return self.finalize_win() return 'lucky_guess' else: self.failed_attemts_left -= 1 self.failed_ateempts_letters.add(l) if self.failed_attemts_left == 0: return self.finalize_fail() return 'unlucky_guess' def show_highscore(self): # saving current record with open(self.highscore_file, 'a') as f: csv.writer(f).writerows([[self.players_name, self.failed_attemts_left]]) with open(self.highscore_file, 'r') as f: # grouping highscore by player's name score = dict() for t in csv.reader(f): score[t[0]] = max(score.get(t[0], 0), int(t[1])) # show standings formatter = '|%-16s| %-5s|' print(' %-16s %-5s ' % ('_' * 16, '_' * 5)) print(formatter % ('Name', 'Score')) print(formatter % ('‾' * 16, '‾' * 5)) for k in sorted(score, key=score.get, reverse=True): print(formatter % (k, score[k])) print(' %-16s %-5s ' % ('‾' * 16, '‾' * 5)) def finalize_win(self): self.show_highscore() return 'epic_win' def finalize_fail(self): return 'epic_fail' if __name__ == '__main__': HangmanGame().start_game()
2bc79b368abd6169525d357d1c3cda64d0e73617
xiaomingxian/python_base
/1.xxm/day10_python高级/Demo1_深拷贝.py
1,650
4.0625
4
# c是深拷贝 a = ['aaa'] b = a print(id(a)) print(id(b)) import copy # 对只读类型不管用---- c = copy.deepcopy(a) d = copy.copy(a) print(id(c)) print(id(d)) print('a is b?', a is b) print('a is c?', a is c) print('a is d?', a is d) print('----------------- copy and deepcopy --------------------') list1 = [1, 2] list2 = [2, 3] list3 = [list1, list2] co = copy.copy(list3) dc = copy.deepcopy(list3) print('copy()内部元素是否深拷贝', '\t不是' if (co[0] is list1) else '\t是') # 内部元素还是浅拷贝----类似于java的clone接口 print('deepcopy()内部元素是否深拷贝', '\t不是' if (dc[0] is list1) else '\t是') list3.append(['o', 't']) print(list3) print(co) # copy实现的是表面深拷贝 def change(list): # list[0]=9 list = [4, 4, 4, ] pass change(list1) print(list1) print("------------------- 元组测试 --------------") l1 = [1, 2] y1 = (2, 3, l1) cy = copy.copy(y1) print(id(y1), id(cy)) print(y1 == cy) dcy = copy.deepcopy(y1) print(id(y1), id(dcy)) print('-------------------- other ---------------') x = [1, 2] yz = [x, 2] cc = yz[:] print(cc) print(id(cc), id(yz)) # 切片是浅拷贝 print(id(yz[0]), id(cc[0])) # 切片 # https://blog.csdn.net/xpresslink/article/details/77727507 print('------------字典(与java中的map相同 元素的位置也是key的哈希) 同样适用于以上拷贝结论 -----------') dic = {'a': x, 'b': 2} dic2 = copy.copy(dic) # print('copy:', id(dic), id(dic2), ' 内部元素:', id(dic['a']), id(dic2['a'])) dic3 = copy.deepcopy(dic) print('deepcopy:', id(dic), id(dic3), ' 内部元素:', id(dic['a']), id(dic3['a']))
acf6c02b6e521bcbeb5d7aa81a23d6fb41ed3b75
name-chichi/KDT-BigData
/03_numpy_pandas/pandas/pan05.py
596
3.53125
4
import pandas as pd data = {'subject': ['math', 'comp', 'phys', 'chem'], 'score': [100, 90, 85, 95], 'students': [94, 32, 83, 17]} print(data, '\n') df = pd.DataFrame(data, columns=['subject', 'score', 'students', 'class']) df['class2'] = [1, 2, 3, 4] df.index = ['one', 'two', 'three', 'four'] print(df, '\n') print(df.columns) print(df.index, '\n') print(df['subject'], '\n') print(df.subject, '\n') # df2 = df[['score','class2']] # print(df2) print(df[['subject', 'score']], '\n') print(df.loc['two', 'score': 'class'], '\n') print(df.loc['two', ['score', 'students', 'class2']], '\n')
0d1bb1235ae434f22de34897530aa7c98513f759
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter5-Functions/P5.6.py
506
4.1875
4
# Write a function # def countVowels(string) # that returns a count of all vowels in the string string . Vowels are the letters a, e, i, o, # and u, and their upper case variants. # FUNCTIONS def countVowels(string): numVowels = 0 vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U") for i in range(len(string)): if string[i] in vowels: numVowels += 1 return numVowels def main(): string = str(input("Enter a string: ")) print("Vowels: ", countVowels(string)) # PROGRAM RUN main()
e967e22b5f71e882da5fab622c007b19cc9800a1
shaozucheng/python3Demo
/example/函数式编程.py
480
3.78125
4
""" 函数式编程 """ def f(x): return x * x mList = list(range(10)) r = map(f, mList) print(list(r)) """ filter() 函数过滤 """ def is_add(x): return x % 2 == 1 list(filter(is_add, [1, 2, 4, 5, 6, 9, 10, 15])) print(list(filter(is_add, list(range(100))))) print(list(filter(is_add, [1, 2, 3, 4, 5]))) """ sorted 排序 """ print("-------------------------------------------------------") print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
7463ae1757748b90c2d837cf938adc6ecbac811c
alexdemarsh/gocode
/webserver-1.py
2,235
3.84375
4
''' Build out a webserver. The code below will accept and return basic http requests. After starting the script you can test it out by going to http://localhost:8888/ in your browser. In the terminal you will see a response like this. GET /favicon.ico HTTP/1.1 Host: localhost:8888 Connection: keep-alive Accept: */* .... .... The first line of the http verb (action) and the desired file. Second part of the first line is the file or resource requested. After that is the body of the request. **** Test your code after each step **** Phase one: Basic web server 1) Extend the program by parsing the http request (request) to parse out the http verb from the request. The verb is the first part of the first line. Lines are seperated by \r\n so recommend using .split('\r\n') 2) Extend webserver to be able to get the file for request. The second part of the first line. 3) Create a directory called views 4) In views create two new files index.html and about.html 5) Enter some basic html into those two files. 6) Using the filename filter out /favicon.ico requests 7) If a request comes in for "/" return views/index.html file data 8) If a request comes in for "/about.html" return the data in views/about.html ''' import socket HOST, PORT = '', 8888 VIEWS_DIR = "./views" def run_server(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) listen_socket.listen(1) print 'Serving HTTP on port %s ...' % PORT while True: client_connection, client_address = listen_socket.accept() request = client_connection.recv(4096) line = request.split('\r\n')[0] verb = lines.split(' ')[0] f = lines.split(' ')[1] if f == '/favicon/ico': filename = read_data("views/index.html") elif f == '/': filename = read_data("views/about.html") if not request: continue http_response = """\ HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n %s """ % filename client_connection.sendall(http_response) client_connection.close() run_server()
51fec9203ed6dbc8b2af80ba75927bdaedf06d5b
kritebh/python-101
/arithmetic_num(3).py
176
3.96875
4
# Artithmetic operations on Number num1 = 11 num2 = 5 print(num1+num2) print(num1-num2) print(num1*num2) print(num1/num2) print(num1//num2) print(num1%num2) print(4**2) # 4^2
eabd2bf83a6632530e717190d15a8f903d2e6c46
dshelts/FutureInteractions
/Presentation_10-17-13/ClassesFile.py
5,307
4.15625
4
#classes file #Andrew Shelton #-----BALL CLASS---------------------------------------------------------- class Ball(): def __init__(self, image, size=(50, 50), pos=(0, 0), bounds=(350, 350)): #Initializer method for Ball class self.image = image #sets the image of the ball self.sizeX, self.sizeY = size self.x, self.y = pos # puts the ball in the starting position self.width, self.height = size # gives the ball its size self.xBound, self.yBound = bounds # sets the boundaries for where the ball can go in the screen self.vX = 0 #sets the initial velocity of the ball in the horizontal to 0 self.vY = 0 #sets the inital velocity of the ball in the vertical to 0 self.state = 0 # 0 = x direction, 0 = y direction def bounce(self): self.x += self.vX #updates the x coordinate self.y += self.vY #updates the y coordinate self.checkBounds()#calls the Ball class checkbounds method return (self.x, self.y) #returns the new location def checkBounds(self): #The update method for the Ball class if self.y >= self.yBound: self.y = self.yBound-1 if self.state == 0: self.state = 1 else: self.state = 0 self.vY = -self.vY if self.x >= self.xBound: self.x = self.xBound self.vX = -self.vX elif self.y<=0:#changes 10/31/13 #ceiling bind self.y = self.yBound+1 if self.state == 1: self.state = 0 else: self.state = 1 self.vY = -self.vY#end changes elif self.x <= 0: self.x = 0 self.vX = -self.vX self.vY += .2 # Gravity self.vX *= .995 # Friction def resetGravity(): self.vY = 0 self.vX = 0 def grabBall(self, pos): self.x, self.y = pos self.resetGravity() self.checkBounds() return(self.x, self.y) def surrounds(self, pointer_pos): #surrounds method checks to see if your finger is holding the ball x, y = pointer_pos #position of the pointer if x < (self.x + self.width) and x > (self.x) and y < (self.y + self.height) and y > (self.y): #if the pointer is the image box #if statement to check to see if your finger and the ball share the same coordinates #returns a boolean return True def updateV(self, velocity): newVX = velocity[0] newVY = -velocity[1] vScalar = float(8)/400 self.vX = newVX * vScalar self.vY = newVY * vScalar #-----BALL CLASS END------------------------------------------------------ #-----HAND CLASS---------------------------------------------------------- class Hand(): def __init__(self, image, size=(50, 50), pos=(0, 0), bounds=(350,350)): self.image = image #initializer for the Hand class #initializer for the Hand class self.hx, self.hy = pos #sets the initial position of the hand self.width, self.height = size #sets the size of the ball self.xBound, self.yBound = bounds #sets the boundaries of the ball within the screen self.hx = 0 #sets hand in the horizontal to 0 self.hy = 0 #sets hand in the verticle to 0 #-----HAND CLASS END------------------------------------------------------ #-----PORTAL CLASS-------------------------------------------------------- class Portal(): def __init__(self, image, size, pos, state, bounds): '''Key for image corners self.y, x = top left self.y, self.sizeX = bot left self.sizeY, x = top right self.sizeY, self.sizeX = bot right ''' self.image = image self.sizeY, sizeX = size#bottom right corner self.x, self.y = pos#y,x top left corner self.state = state#direction of movement 1^, 0down self.width, self.height = bounds#the full size of screen def swap(self, ballPos): return self.samePlace(ballPos) def samePlace(self, pointer_pos):#change x, y = pointer_pos if (abs(self.x - x) < 50) and (abs(self.y - y) < 50): return True else: return False def directionCheck(self): if self.checkOutOfBounds(): self.state += 1 if self.state > 3: self.state = 0 if state == 0: self.vX = 1 self.vY = 0 if state == 1: self.vX = 0 self.vY = 1 if state == 2: self.vX = -1 self.vY = 0 if state == 3: self.vX = 0 self.vY = -1 def move(self): #self.directionCheck() #print "move self.y, self.sizeY", self.y, self.sizeY #print "move self.height", self.height if self.y <= 0: self.state = 0 return self.down() elif (self.y+self.sizeY+20)>= self.height: self.state = 1 return self.up() else: if self.state == 0: return self.down() if self.state == 1: return self.up() def down(self): self.y += 2 #print"down x,y", self.x, self.y return(self.x, self.y) def up(self): self.y -= 2 #print"up, x,y", self.x, self.y return(self.x, self.y) def checkOutOfBounds(self): #Checkes if self.x or self.y is out of bounds and puts it in bounds if it is. #also sets booleon to true if at one of the edges so it can change direction if self.x >= self.xBound: self.x = self.xBound return True elif self.y >= self.yBound: self.y = self.yBound return True elif self.y <= 0: self.x = 0 return True elif self.x <= 0: self.y = 0 return True #def teleport(self, portal2) #if self.samePlace(): #take ball set it to the location of portal2 #------ END portal Class----------------------------------------------------------------------------------
f10db0d4358be621d846849358ecd477f5aeddea
tjcapo/sandbox1
/automate_the_boring_stuff/guess_the_number.py
432
3.875
4
import random, sys def roll_dice(): roll = random.randint(1,7) return roll def roll_loop(): while ans == 'y': print(roll_dice()) break print('Roll the dice? y/n') ans = input() if ans == 'y': print('You rolled ' + str(roll_dice())) print('Roll again?') input() elif ans == 'n': print('...goodbye...') sys.exit() else: print('...invalid entry...') sys.exit()
4dfd50c6156093fc234d6cc30bf437bc67ad44da
GeorgeVince/DAND_Interview_Prep
/Fundementals/credit_card_mask.py
637
3.984375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 8 19:58:47 2017 @author: georg Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it. Your task is to write a function maskify, which changes all but the last four characters into '#'. """ # return masked string def maskify(cc): if len(cc) < 4: return cc cc = ("#" * (len(cc) - 4)) + cc[len(cc) - 4:len(cc)] return cc print(maskify("absdcabc"))
83dd7b96b7b21386b759ac34fb0182e1dbaf5dc1
robertodermato/Banco
/Banco/Contas.py
5,275
3.6875
4
from abc import ABCMeta, abstractmethod from Banco.Erros import * from Banco.Moeda import * class ContaBancaria (metaclass=ABCMeta): """Classe abstrata da conta bancária""" quantidade_contas = 0 @classmethod def status_contas(cls): return cls.quantidade_contas @classmethod def incrementa_qtidade_contas(cls): cls.quantidade_contas += 1 def __enter__(self): return self def __exit__(self, *args): return True def __init__(self, numero, nome, cpf, balanco): erro = False if numero <0 or numero > 9999: raise NumeroDeContaInvalido(numero) erro = True else: self.numero = numero if len(nome)>=50: raise NomeInvalido(nome) erro = True else: self.nome = nome if cpf <0 or cpf > 999_999_999_99: raise CPFInvalido(cpf) erro = True else: self.cpf = cpf self.balanco = Moeda(balanco) if erro == False: ContaBancaria.incrementa_qtidade_contas() def __str__(self): return "A conta de número " + str(self.numero) + " em nome de " + self.nome + " CPF - " + str(self.cpf) + " possui R$ " + str(self.balanco) def deposito (self, valor): if valor < 0: raise ValorMonetarioNegativo(valor) else: self.balanco = self.balanco + valor print ("Depósito de " + str(valor) + " realizado com sucesso.") def saque (self, valor): if valor < 0: raise ValorMonetarioNegativo(valor) elif valor > self.balanco: raise SaldoInsuficiente(valor) else: self.balanco = self.balanco - valor print ("Saque de " + str(valor) + " realizado com sucesso.") def saque_verboso(objeto, valor): print("Saque verboso de", objeto.nome, "- CPF:", objeto.cpf, "- Número da conta:", objeto.numero, "- Saldo:", objeto.balanco, "- Rendimento:", objeto.taxa_de_rendimento) objeto.saque(valor) print("Saldo final:", objeto.balanco) @property def saldo (self): return self.balanco @saldo.setter def saldo (self, novo_balanco): self.balanco = novo_balanco @abstractmethod def consulta_rendimento (self, dias): pass class ContaCorrente(ContaBancaria): quantidade_contas = 0 @classmethod def incrementa_qtidade_contas(cls): cls.quantidade_contas += 1 def __init__(self, numero, nome, cpf, balanco, limite): self.taxa_de_rendimento = 0.01 super().__init__(numero, nome, cpf, balanco) # limite precisa ser menor ou igual a zero if limite <= 0: self.limite=limite else: raise LimitePrecisaSerNegativo(limite) ContaCorrente.incrementa_qtidade_contas() def saque (self, valor): if valor < 0: raise ValorMonetarioNegativo(valor) elif valor > (self.balanco + abs(self.limite)): raise SaqueAcimaDoLimite(valor) else: self.balanco = self.balanco - valor print ("Saque de " + str(valor) + " realizado com sucesso.") def consulta_rendimento (self, dias): return ((self.balanco * self.taxa_de_rendimento)/30)*dias def __str__(self): return super().__str__() + ". É uma conta do tipo Conta Corrente com limite de " + str(self.limite) class ContaInvestimento(ContaBancaria): quantidade_contas = 0 @classmethod def incrementa_qtidade_contas(cls): cls.quantidade_contas += 1 def __init__(self, numero, nome, cpf, balanco, risco): super().__init__(numero, nome, cpf, balanco) self.risco = risco.strip().lower() ContaInvestimento.incrementa_qtidade_contas() self.taxa_de_rendimento = 0 #print ("testando rendimento", risco) if risco == " baixo" or risco == " Baixo": #print ("Risco baixo rendimento") self.taxa_de_rendimento = 0.1 if risco == " médio" or risco == " medio" or risco == " Medio" or risco == " Médio": #print("Risco médio rendimento") self.taxa_de_rendimento = 0.25 if risco == " alto" or risco == " Alto": #print("Risco alto rendimento") self.taxa_de_rendimento = 0.5 def consulta_rendimento (self, dias): return ((self.balanco * self.taxa_de_rendimento)/30)*dias def __str__(self): return super().__str__() + ". É uma conta do tipo Conta Investimento com risco " + self.risco class ContaPoupanca(ContaBancaria): quantidade_contas = 0 @classmethod def incrementa_qtidade_contas(cls): cls.quantidade_contas += 1 def __init__(self, numero, nome, cpf, balanco, taxa_de_rendimento): super().__init__(numero, nome, cpf, balanco) self.taxa_de_rendimento=taxa_de_rendimento ContaPoupanca.incrementa_qtidade_contas() def consulta_rendimento (self, dias): return ((self.balanco * self.taxa_de_rendimento)/30)*dias def __str__(self): return super().__str__() + ". É uma conta do tipo Conta Poupança com taxa de rendimento de " + str(self.taxa_de_rendimento)
fe359ace9b46246a521c8bf31f83a7201116f530
UncleBob2/MyPythonCookBook
/matplotlib 3D/plot legend savefig show.py
973
3.546875
4
import csv import numpy as np from collections import Counter from matplotlib import pyplot as plt plt.style.use("fivethirtyeight") with open('data.csv') as csv_file: csv_reader = csv.DictReader(csv_file) language_counter = Counter() for row in csv_reader: language_counter.update((row)['LanguagesWorkedWith'].split(';')) ''' # row = next(csv_reader) # print(row['LanguagesWorkedWith'].split(';')) from collections import Counter c=Counter(['Python', 'JavaScript']) print(c) c.update(['C++', 'Python']) print(c) c.update(['C++', 'Python']) print(c) ''' # print(language_counter.most_common(15)) languages = [] popularity = [] for item in language_counter.most_common(15): # we could use zip to languages.append(item[0]) popularity.append(item[1]) # print(languages) # print(popularity) plt.barh(languages, popularity) plt.title("Most Popular Languages") plt.xlabel("Number of People Who use") plt.tight_layout() plt.show()
6c4466b074112f0f234f11bfbe94ca4afe9b03b3
TRUSTMEIMDEAD/MelodyNote
/MelodyNote.py
6,216
3.5625
4
from enum import Enum class NoteSign(Enum): """Ноты""" C = 1 D = 2 E = 3 F = 4 G = 5 A = 6 H = 7 class MusicalMood(Enum): """Лады""" minor = 1 major = 2 """Класс нотной тетради""" class MelodyNote: """Инициализация нотной тетради""" def __init__(self, songs=None): if songs is None: songs = [] self.songs = songs self.status = False def __lshift__(self, other): """Перегрузка <<""" if not self.status: raise Exception('The note is closed') self.songs.append(Song(other)) return self def show_songs(self): """Вывод названий песен""" for i in self.songs: print(i.title) def __getitem__(self, i): """Взять элемент по индексу obj[i]""" if not self.status: raise Exception('The note is closed') return self.songs[i] def __iter__(self): self.status = True """Передача управления на итерацию по песне""" yield from iter(self.songs) self.status = False def __enter__(self): """Перегрузка enter метода менеджера контекста""" self.status = True return self def __exit__(self, exception_type, exception_val, trace): """Перегрузка exit метода менеджера контекста""" self.status = False """Класс песни""" class Song: """Инициализация песни""" def __init__(self, title, notes: list = None): if notes is None: notes = [] self.notes = notes self.title = title def __lshift__(self, other: str): """Перегрузка <<""" self.notes.append(Note(NoteSign[other])) return self def play_song(self): """Проигрывание песни""" print('Start playing a song!') for i in self.notes: i.show_note() print() print('The song is not playing anymore.') def change_mood(self, mood: MusicalMood, start: int = 0, end: int = -1): """Смена настроя нот в диапазоне от start до end""" if end == -1: end = len(self.notes) for i in range(start, end): self.notes[i].change_note_mood(mood) def __getitem__(self, i): """Взять элемент по индексу obj[i]""" return self.notes[i] def __iter__(self): """Возвращаеим итератор for note in song: print(note) #Выводятся ноты из песни """ return iter(self.notes) @property def mood_count(self): """Cчетчик мажорных нот""" return len(list(filter(lambda x: x.mood == 'major', self.notes))) def __lt__(self, other): """ Перегрузка < """ return len(self.notes) < len(other.notes) or \ (self.mood_count < other.mood_count and len(self.notes) == len(other.notes)) def __gt__(self, other): """ Перегрузка > """ return len(self.notes) > len(other.notes) or \ (self.mood_count > other.mood_count and len(self.notes) == len(other.notes)) def __eq__(self, other): """ Перегрузка == """ return self.mood_count == other.mood_count and len(self.notes) == len(other.notes) """Класс ноты""" class Note: """Инициализация ноты""" def __init__(self, sign, mood=MusicalMood.major): self.__sign = sign self.mood = mood @property def sign(self): """Защита перезаписи знака ноты""" return self.__sign def show_note(self): """Вывести ноту""" if self.mood == MusicalMood.major: print(self.sign.name, end=' ') else: print(self.sign.name.lower(), end=' ') def change_note_mood(self, mood: MusicalMood): """Меняем настрой ноты""" self.mood = mood def __gt__(self, other): """ Перегрузка > """ return self.sign.value > other.sign.value or \ (self.mood.value > other.mood.value and self.sign == other.sign) def __lt__(self, other): """ Перегрузка < """ return self.sign.value < other.sign.value or \ (self.mood.value < other.mood.value and self.sign == other.sign) def __eq__(self, other): """ Перегрузка == """ return self.mood.value == other.mood.value and self.sign == other.sign note1 = Note(NoteSign.C, MusicalMood.major) note2 = Note(NoteSign.D, MusicalMood.major) note3 = Note(NoteSign.E, MusicalMood.minor) note4 = Note(NoteSign.F, MusicalMood.minor) note5 = Note(NoteSign.G, MusicalMood.major) note6 = Note(NoteSign.A, MusicalMood.minor) note7 = Note(NoteSign.H, MusicalMood.major) song1 = Song("FirstSong", [note2, note1, note6, note5, note5, note3, note4, note5, note1, note7, note5, note4, note1, note2, note1, note2, note2, note1, note6, note5, note6, note5, note5, note3]) song2 = Song("SecondSong", [note1, note1, note4, note7, note4, note5, note1, note2, note1, note4, note3, note2, note1, note4, note5, note6, note5, note1, note2, note1, note1, note2, note1, note4, note3, note2]) song3 = Song("TrirdSong", [note3, note6, note4, note2, note7, note1, note7, note5, note5, note4, note6, note7, note6, note5, note7, note4, note6, note7, note3, note6, note4, note2, note7]) my_melody_note = MelodyNote([song1, song2, song3]) with my_melody_note as note: note[1].play_song() print(my_melody_note[2][1].sign.name) my_melody_note.show_songs() my_melody_note << 'Song4' my_melody_note.show_songs() my_melody_note.songs[2].play_song() my_melody_note.songs[2].change_mood(MusicalMood.minor) my_melody_note.songs[2].play_song() print(note6 < note1) print(song1 > song2) my_melody_note[2] << 'C'
36d8b5349b2f6f4ab5ea9229fae30963db4073b2
fbw618/arduino-python-talk
/read-analog.py
1,382
3.5625
4
import asyncio import sys from pymata_express.pymata_express import PymataExpress # Setup a pin for analog input and monitor its changes async def the_callback(data): """ A callback function to report data changes. :param data: [pin, current reported value, pin_mode, timestamp] """ print(f"analog callback data: {data[1]} ", end='\r') async def analog_in(my_board, pin): """ This function establishes the pin as an analog input. Any changes on this pin will be reported through the call back function. Also, the differential parameter is being used. The callback will only be called when there is difference of 5 or more between the current and last value reported. :param my_board: a pymata_express instance :param pin: Arduino pin number """ await my_board.set_pin_mode_analog_input(pin, callback=the_callback, differential=5) # run forever waiting for input changes while True: await asyncio.sleep(1) # get the event loop loop = asyncio.get_event_loop() # instantiate pymata_express board = PymataExpress() try: # start the main function loop.run_until_complete(analog_in(board, 0)) except (KeyboardInterrupt, RuntimeError): loop.run_until_complete(board.shutdown()) sys.exit(0)
95a3e964fe159d8cba8721719faa83923997eab2
drowergit/shiyanlou-code
/jump7.py
130
3.65625
4
i = 0 while i<100: i += 1 if i % 7 == 0 or i % 10 == 7 or i in range(70, 80): continue else: print(i)
f24ded121d0dae7dceec51fde19e62ba88dd5ae9
finewink/programmers_python
/stack/printer.py
551
3.59375
4
import collections def solution(priorities, location): answer = 0 queue = collections.deque(range(len(priorities))) while queue : index = queue.popleft() exists = False for i in queue : if priorities[index] < priorities[i] : queue.append(index) exists = True break else : exists = False if not exists : answer += 1 if index == location : break return answer
cf019c00e874542d7effb5ddbd403b92dc6b2101
aarushirai1997/pythonlearn
/aar12.py
93
3.984375
4
a=str(input("enter the no\n")) rev_string=a[::-1] if a==rev_string: print("Palindrome")
cb0ec5537cd75850d129ed0cba3ce4d6ceda8995
kailastone/dsc-mod-2-project-v2-1-onl01-dtsc-ft-041320
/functions.py
2,612
3.875
4
import locale import numpy as np import matplotlib.pyplot as plt def get_binary_column(dfName, colName, qual_for_false): """ Iterate through a column to append an additional binary (T/F) column to a DataFrame dfName = Name of Pandas DataFrame to pull information from colName = Name of column from DataFrame to pull information from qual_for_false = condition where value is <= qual_for_false returns a binary 0, else 1 """ newCol = [] for val in dfName[colName]: if val <= qual_for_false: newCol.append('0') else: newCol.append('1') return newCol def get_means(values, dfName, colName): mean_list = [] for val in values: this_df = dfName.loc[dfName[colName]==val] mean_price = np.mean(this_df['price']) price_change_per_val = mean_price/len(this_df[colName]) mean_list.append(price_change_per_val) return (mean_list) def get_mean_diff(values, dfName, colName): list = get_means(values, dfName, colName) sum_list = sum(list) av_mean = round(sum_list/len(list), 2) print(av_mean) return #LISTS def get_av_val(dfName, values, colName): val_list = [] for val in values: this_df = dfName.loc[dfName[colName] == val] mean_grade = round(np.mean(this_df['grade']), 2) val_list.append(mean_grade) return(val_list) def get_av_diff(dfName, values, colName): val_list = get_av_val(dfName, values, colName) diff = [] i = 1 while i < len(val_list): diff.append(val_list[i] - val_list[(i-1)]) i+=1 sum_list = sum(diff) av_list = round(sum_list/len(diff), 2) return av_list #PLOTTING Simple Linear Regression def calc_slope(xs,ys): m = (((np.mean(xs)*np.mean(ys)) - np.mean(xs*ys)) / ((np.mean(xs)**2) - np.mean(xs*xs))) return m def best_fit(xs,ys): m = calc_slope(xs,ys) c = np.mean(ys) - m*np.mean(xs) return m, c def reg_line (m, c, xs): return [(m*x)+c for x in xs] def plot_scatter_lin_reg(X, Y, regression_line, colName, Ycol): plt.scatter(X,Y,color='#003F72', label="Data points") plt.plot(X, regression_line, label= "Regression Line") plt.title(colName + ' vs. ' + Ycol) plt.ylabel(Ycol) plt.xlabel(colName) plt.legend() plt.show() return def get_sim_lin_reg(dfName, Ycol, subset): for col in subset: X, Y = dfName[col], dfName[Ycol] m, c = best_fit(X, Y) regression_line = reg_line(m, c, X) plot_scatter_lin_reg(X, Y, regression_line, col, Ycol) return
e518a198316af2466728681c97bcf0a503b5e8f2
pradip026/general_ideas_python
/pythonjune2019/function0/tut25.py
2,124
4.0625
4
# def outer(num1): # def inner(num1): # return num1+1 # # num2=inner(num1) # print(num1,num2) # # # outer(4) # # # def factorial_recursive(n): # if n==1: # return 1 # # else: # return(n*factorial_recursive(n-1)) # # # print(factorial_recursive(5)) # # #print(help(str)) # str1=str("Kathmandu,NEPAL") # str4="N" # str2=str1.__add__('Nepal') # print(str2) # str3=str2.__sizeof__() # print(str3) # print(str1.__str__()) # # print(str1.capitalize()) # a=(str1.casefold()) # b=(str4.casefold()) # # if a==b: # print('True') # else: # print('False') # # print(str1.count(str4)) # # # print(str1.encode()) # # print(str1.endswith('NEPAL')) # print(str1.find('N')) # li=[] # str1="what is your name" # def hello(msg): # print(str1.count(msg)) # i=0 # while msg in str1: # # if msg in str1: # # str1.find(msg) # ind=str1.index(msg) # i=ind+1 # li.append(ind) # continue # # hello("a") # print(li) val=input("Enter a character or string you want to Search: ") val=val.casefold() li=[] str1="""This project intends to make a communication and information exchange environment for teachers and students. This platform will only solely focus on interaction between teacher and students for better learning environment. This project will help teachers to find jobs and also helps connecting teachers and students. This web platform will enable more interactive teaching and learning environment among the users.""" str1=str1.casefold() b=len(str1) def check(msg): if msg in str1 and len(msg)>=1: start = 0 for x in range(start,b): a=str1.find(msg,start) if a==-1: break li.append(a) start = a + 2 elif msg in str1 and len(msg)==1: for index,item in enumerate(str1): if item==msg: a=index li.append(a) else: print("Not Found") check(val) print(li)
61bafc8700302e45e8ca3e3e2c18f510fb9e9ed2
svitliachok07/GL-Test-Sum-Numbers
/sumNum.py
589
3.578125
4
def sumNum(): sumList = [] plusMinus = "" with open("number.txt") as file: lines = file.readlines() lines = [line.rstrip() for line in lines] for line in lines: plusMinus = "" if line == "": continue if line[0] == "+" or line[0] == "-": plusMinus = line[0][0] line = line[1:] if line.replace(".", "", 1).isdigit(): if plusMinus == "-": line = plusMinus + line sumList.append(float(line)) return sum(sumList) sumNum()
0c8fc4f41cb5b7b193b969a85f50aa3dd8296756
taylorrees/studybook
/test/test.py
1,459
3.859375
4
#Author: Thomas Sweetman import shelve import csv class Test: """ This class manages the creation, monitoring and usage of Test, a Test consists of Questions in multiple choice or other question class. """ def __init__(self, testID): self._id = testID self.questions = [] self.results = {} self.resultcsv = 'results/' + testID + '.csv' def getStatus(self, studentID): """ this method returns true if the student has completed the test. """ if studentID in self.students: return True else: return False def setResult(self, studentID, mark): """ this method sets the result of a completed test. """ print(self.results) self.results[studentID] = mark self.store() with open(self.resultcsv, 'w', newline = '') as csvfile: writer = csv.writer(csvfile, delimiter=',') for _id in self.results.keys(): writer.writerow([_id, self.results[_id]]) csvfile.close() def getResult(self, studentID): """ this method returns the result of a previously completed test. """ return self.results[studentID] def takeTest(self): """ this method presents the user with the test to be taken. """ def add(self, detail, answers): """ this method adds a question to the test. """ self.questions.append((detail, answers)) def store(self): try: store = shelve.open('test/store', 'w') except Exception: store = shelve.open('test/store', 'n') store[self._id] = self store.close()
cb3427736bf1846631e4c551e9bfe38bd3f902e4
allenz16/automate_the_boring_stuff_with_python
/c7_8_strong_pass_detection.py
393
3.875
4
# strong password detection import re # create password regex passRegex = re.compile(r'(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}') # capture a password and verify it while True: password = input('please input your password : ') mo1 = passRegex.search(password) if mo1 is not None: print('nice password') break else: print('bad password') print('done')
6f0a3183caec33f22f47cec6d7b9f3c44f3b9b12
antonylu/leetcode2
/Python/500_keyboard-row.py
1,160
4.03125
4
""" https://leetcode.com/problems/keyboard-row/description/ Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. American keyboard Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet. """ class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ # Approach #1, use set() # # O(n), 78% key1 = set("qwertyuiop") key2 = set("asdfghjkl") key3 = set("zxcvbnm") ans = [] for w in words: ws = set(w.lower()) if ws <= key1 or ws <= key2 or ws <= key3: ans.append(w) return ans if __name__ == '__main__': s = Solution() tc = [["Hello", "Alaska", "Dad", "Peace"]] an = [["Alaska", "Dad"]] for i in range(len(tc)): print (s.findWords(tc[i])) #assert(s.findWords(tc[i]) == an[i])
77fd41c956123afa6f718829039f43e8f29ff666
goosetherumfoodle/marie_challenge
/problems/loops.py
1,872
3.703125
4
## MAPPING (taking a collection and building a new collection of the same size) # from a list 1-50, build a list with those numbers doubled # from a list of ['a', 'B', 'C', 'd', 'E', 'F', 'g'], build a list # where the cases are flipped (upper to lower, lower to upper) # from a list ['horse', 'cat', 'trash', 'apriori', 'kevin'], # and a dictionary {'cat': 3 , 'button': 'fog', 'trash': 'balloons'} # build a new list, based off the first, where each element is either the # value corresponding to the key in the dictionary, or Nothing # CATAMORPHISM (destruction) (taking a collection and building a non-collection) # from a list 1-50, get the sum of all the elements # from a list 1-50, get the product of all the elements # from a list [1,6,2,4,2,9,11,4,8], get the maximum element (this only works for positive numbers) # from a list [-1,-6,-2,-4,-2,-9,-11,-4,-8], get the maximum element (if I don't know what's in the list) # from the same list as the above, get the minumum element # from a list 1-50, get the sum of all the even elements # FILTERING (taking a collection and returning a collection of the same size or smaller) # from a list 1-50, get a list of just the even elements # from a list 1-50, get a list of all the elements divisible by 3 # from a list of a-z, get a list of the consonants # NESTED LOOPS # for a list of lists of numbers [[1, 2, 3, 4], [60, 61, 62, 63], [101, 102, 103, 104]] # create a list of lists of only even numbers # eg: [[2, 4], [60, 62], [102, 104]] # flattening a nested list. For a list of lists of 10 (1-10, 11-20, 21-30, 31-40, 41-50), # flatten the list to a list of 1-50 # from the lists a-c, and 1-3, generate a list of their cartesian products. # (One way to do it would be to build 2-tuples, which would look like: # [('a',1), ('a',2), ('a',3), ('b',1), ('b',2), ('b',3), ('c',1), ('c',2), ('c',3)]
ebb8399a35875d06bc6b38df6349e1f33e67ab99
PrinceNathaniel/leetcode
/079Word-Search.py
1,004
3.515625
4
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ visited = [[False for j in range(len(board[0]))] for i in range(len(board))] for i in range(len(board)): for j in range(len(board[0])): if self.recur(board,word,0,i,j,visited): return True return False def recur(self, board, word, cur, i, j, visited): if len(word) == cur: return True if i<0 or i >= len(board) or j<0 or j>=len(board[0]) or visited[i][j] or board[i][j] != word[cur]: return False visited[i][j] = True res = self.recur(board, word, cur+1, i -1, j, visited) or \ self.recur(board, word, cur+1, i +1, j, visited) or\ self.recur(board, word, cur+1, i , j-1, visited) or\ self.recur(board, word, cur+1, i , j+1, visited) visited[i][j] = False return res
5df17f7ac4f928e71421a6eebdbd018244156d48
KIRANKUMAR-ENUGANTI/Python
/python_basics/teranary_operature.py
769
3.8125
4
#teranary operator n = 9 print("Hello") if n==9 else print("Goodbye") m='hello' if n<9 else 'goodbey' print(m) n=n+1 if n==9 else n+5 print(n) #nested teranary operator n = 9 print("Hello") if n==9 else print("Goodbye") if n==5 else print('good day') m='hello' if n<9 else 'goodbey' if n==5 else 'good day' print(m) #we cannot use any assignment/inplace_operator in conditional expression # n = 9 # try: # n+=1 if n == 9 else n+=5 if n == 5 else n=10 # print(n) # except: # print("raised SyntaxError: invalid syntax") #since its showing the error no useof try and except blocks still the code termenates incorrectly # but we can use the arithemetic operations and assign the result to a var n = 9 n=n+1 if n==9 else n+5 if n==5 else 10 print(n)
5c125dc1f5d78145108f1c2373bb43902c37e205
qmnguyenw/python_py4e
/geeksforgeeks/python/basic/19_16.py
3,608
4.25
4
Reading an excel file using Python Using xlrd module, one can retrieve information from a spreadsheet. For example, reading, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. **xlrd** module is used to extract data from a spreadsheet. Command to install xlrd module : pip install xlrd **Input File:** ![Sample excel file](https://media.geeksforgeeks.org/wp-content/uploads/excel- file.png) **Code #1:** Extract a specific cell ## Python3 __ __ __ __ __ __ __ # Reading an excel file using Python import xlrd # Give the location of the file loc = ("path of file") # To open Workbook wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # For row 0 and column 0 print(sheet.cell_value(0, 0)) --- __ __ Output : 'NAME' **Code #2:** Extract the number of rows ## Python3 __ __ __ __ __ __ __ # Program to extract number # of rows using Python import xlrd # Give the location of the file loc = ("path of file") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) # Extracting number of rows print(sheet.nrows) --- __ __ Output : 4 **Code #3:** Extract the number of columns ## Python3 __ __ __ __ __ __ __ # Program to extract number of # columns in Python import xlrd loc = ("path of file") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # For row 0 and column 0 sheet.cell_value(0, 0) # Extracting number of columns print(sheet.ncols) --- __ __ Output : 3 **Code #4 :** Extracting all columns name ## Python3 __ __ __ __ __ __ __ # Program extracting all columns # name in Python import xlrd loc = ("path of file") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # For row 0 and column 0 sheet.cell_value(0, 0) for i in range(sheet.ncols): print(sheet.cell_value(0, i)) --- __ __ Output : NAME SEMESTER ROLL NO **Code #5:** Extract the first column ## Python3 __ __ __ __ __ __ __ # Program extracting first column import xlrd loc = ("path of file") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) for i in range(sheet.nrows): print(sheet.cell_value(i, 0)) --- __ __ Output : NAME ALEX CLAY JUSTIN **Code #6:** Extract a particular row value ## Python3 __ __ __ __ __ __ __ # Program to extract a particular row value import xlrd loc = ("path of file") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) print(sheet.row_values(1)) --- __ __ Output : ['ALEX', 4.0, 2011272.0] Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
d9ee0517e4c1de000a9cbdf08675bf2887e908d2
yoowonsuk/python
/practice/if_positive.py
103
3.9375
4
def main(): num = int(input("input int: ")) if num > 0: print("it's positive") main()
acff409e376b48c1f386e46b6077cc9a469fa97b
gnou/Data-Structures
/Basic/tree-height.py
2,135
3.5625
4
# python3 import sys, threading sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class Node: def __init__(self, data): self.data = data self.children = [] def add_child(self, obj): self.children.append(obj) def height(self): if len(self.children) == 0: return 1 else: children_height = [] for child in self.children: children_height.append(child.height()) return max(children_height) + 1 class Tree: def read(self): self.n = int(sys.stdin.readline()) self.nodes = [] for num in range(self.n): node = Node(num) self.nodes.append(node) self.parents = list(map(int, sys.stdin.readline().split())) for index, parent in enumerate(self.parents): node = self.nodes[index] if parent != -1: parent_node = self.nodes[parent] parent_node.add_child(node) else: self.root = node def compute_height(self): return self.root.height() class TreeHeight: def read(self): self.n = int(sys.stdin.readline()) self.parent = list(map(int, sys.stdin.readline().split())) def compute_height(self): # Replace this code with a faster implementation maxHeight = 0 for vertex in range(self.n): height = 0 i = vertex while i != -1: height += 1 i = self.parent[i] maxHeight = max(maxHeight, height); return maxHeight; def main(): tree = Tree() tree.read() print(tree.compute_height()) threading.Thread(target=main).start()
450d2731e04068099ccfe61ebfad3b70e295eb83
hupadhyay/learnPython
/inheritance/simple_inheritance.py
424
3.78125
4
class Parent(object): def __init__(self): print("Parent class initialized.") def parentFun(self): print("Parent class function") class Child(Parent): def __init__(self): Parent.__init__(self) print("Child class initialized") def childFun(self): print("Child class function") # Create object of child mychild = Child(); mychild.childFun(); mychild.parentFun();
eae035ae705cb4fd5299b2ef7cdc801c253244c8
qinysy/Learning-python
/ex5.py
463
3.953125
4
#!/usr/bin/env python3 #coding: utf-8 #__author:qinzhang #计算密集型任务 import threading import time def foo(n): ret=0 for i in range(n): ret+=1 print(ret) def bar(n): ret=1 for i in range(1,n): ret*=i print(ret) s=time.time() foo(10000000) bar(100000) #t1=threading.Thread(target=foo,args=(100000000,)) #t1.start() #t2=threading.Thread(target=foo,args=(100000000,)) #t2.start() #t1.join() #t2.join() print("cost time:",time.time()-s)
c33062fb7075b84ea604f45810a15dda354fa26d
RicardoPereiraIST/Design-Patterns
/Behavioral Patterns/Mediator/example.py
764
3.75
4
class Node: def __init__(self, v): self.value = v class List: def __init__(self): self.arr = [] def add_node(self, node): self.arr.append(node) def traverse(self): for i in self.arr: print(i.value, end=' ', flush=True) print() def remove_node(self, value): size = len(self.arr) for i in range(size): if self.arr[i].value == value: self.arr.pop(i) break def main(): lst = List() one, two, three, four = Node(11), Node(22), Node(33), Node(44) lst.add_node(one) lst.add_node(two) lst.add_node(three) lst.add_node(four) lst.traverse() lst.remove_node(44) lst.traverse() lst.remove_node(22) lst.traverse() lst.remove_node(11) lst.traverse() if __name__ == "__main__": main()
6f40d2943a0683595b014afa05dd98c302555d45
pschafran/Notes
/scripts/PURC_countBarcodes.py
6,114
3.53125
4
#! /usr/bin/python ## 2019 September 2 ## Last updated 2019 September 23 ## Peter W. Schafran ## This script takes barcode sequences and searches for and counts them in a sequence file. ## Reports number of each barcode found at forward, reverse, combined (sum of forward + reverse), and paired (for sequences with forward and reverse barcodes). ## With PURC_map_file.txt it will also supply sample names to barcode matches. ## Barcodes that occur frequently but not assigned to any sample may be PCR error or wrong barcode added to sample ## Files: (1) PURC_barcode_file.fasta ## (2) PURC_map_file.txt ## (3) CCS sequence file(s) ### Usage: PURC_countBarcodes.py PURC_barcode_file.fasta PURC_map_file.txt CCS_Sequence_File_1.fasta[.fastq] CCS_Sequence_File_2.fasta[.fastq]... usage=''' Input Files: 1. PURC_barcode_file.fasta 2. PURC_map_file.txt 3. CCS sequence file(s) Usage: PURC_countBarcodes.py PURC_barcode_file.fasta PURC_map_file.txt CCS_Sequence_File_1.fasta[.fastq] CCS_Sequence_File_2.fasta[.fastq]... ''' try: from Bio.Seq import Seq from Bio import SeqIO from Bio.Alphabet import generic_dna except: print "ERROR: BioPython not installed" import sys if len(sys.argv) == 1: print "!" *10 print "ERROR: No files provided" print "!" *10 sys.exit(usage ) ### read in PURC Barcode File purc_barcode_file = open(sys.argv[1], "r") purcBarcodeDict = {} purcBarcodeLength = [] for line in purc_barcode_file: if ">" in line: BCname = line.strip("\n") elif ">" not in line: purcBarcodeDict[line.strip("\n")] = BCname purcBarcodeLength.append(len(line.strip("\n"))) purc_barcode_file.close() if len(set(purcBarcodeLength)) > 1: print "!" * 10 print "ERROR: Barcodes not all same length" print "!" * 10 sys.exit() else: purcBarcodeLength = purcBarcodeLength[0] ### check for dupe barcodes (reverse complements) for key in purcBarcodeDict: revComp = Seq(key, generic_dna) revComp = revComp.reverse_complement() if revComp in purcBarcodeDict.keys(): print "WARNING: %s [%s] and %s [%s] are reverse complements!" %(purcBarcodeDict[key], key, purcBarcodeDict[revComp], revComp) ### read in PURC Map File purc_map_file = open(sys.argv[2], "r") purcMapDict = {} for line in purc_map_file: splitline = line.strip("\n").split("\t") purcMapDict[splitline[2]] = [splitline[0],splitline[1]] purc_map_file.close() ### Loop through input sequence files for file in sys.argv[3:]: FbarcodeDict = {} RbarcodeDict = {} CombinedBarcodeDict = {} PairedBarcodeDict = {} fastaDict = {} totalseqs = 0 key = 0 ### parse fastq if ".fastq" in file or ".fq" in file: SeqIO.convert(file, "fastq", "PacBioBarcodes.temp.fasta", "fasta") infile = open("PacBioBarcodes.temp.fasta", "r") ### parse fasta elif ".fasta" in file or ".fa" in file: infile = open(file, "r") ### continue processing -- read fasta into dict to deal with interleaved format for line in infile: if ">" in line: while key != 0: joinLine = "".join(fastaDict[key]) fastaDict[key] = joinLine key = 0 key = line.strip("\n") totalseqs += 1 fastaDict[key] = [] if totalseqs == 1000: print "1k seqs processed..." if totalseqs == 10000: print "10k seqs processed..." if totalseqs == 50000: print "50k seqs processed..." if totalseqs == 100000: print "100k seqs processed..." if totalseqs == 250000: print "250k seqs processed..." if totalseqs == 500000: print "500k seqs processed..." if totalseqs == 750000: print "750k seqs processed..." if totalseqs == 1000000: print "1M seqs processed..." if ">" not in line: stripLine = line.strip("\n").upper() fastaDict[key].append(stripLine) joinLine = "".join(fastaDict[key]) fastaDict[key] = joinLine print "%s seqs processed...DONE" %(totalseqs) ### parse fastaDict to read barcodes for key in fastaDict.keys(): Fbarcode = fastaDict[key][0:purcBarcodeLength] endBC = fastaDict[key][-purcBarcodeLength:] endBC = Seq(endBC, generic_dna) Rbarcode = endBC.reverse_complement() Pairedbarcode = Fbarcode + Rbarcode try: FbarcodeDict[Fbarcode] += 1 except: FbarcodeDict[Fbarcode] = 1 try: RbarcodeDict[Rbarcode] += 1 except: RbarcodeDict[Rbarcode] = 1 try: CombinedBarcodeDict[Fbarcode] += 1 except: CombinedBarcodeDict[Fbarcode] = 1 try: CombinedBarcodeDict[Rbarcode] += 1 except: CombinedBarcodeDict[Rbarcode] = 1 try: PairedBarcodeDict[Pairedbarcode] += 1 except: PairedBarcodeDict[Pairedbarcode] = 1 ### output results Foutfile = open("Forward_PacBio_Barcodes.csv", "w") for key in FbarcodeDict.keys(): Foutfile.write("%s,%s\n" %(key, FbarcodeDict[key])) Foutfile.close() Routfile = open("Reverse_PacBio_Barcodes.csv", "w") for key in RbarcodeDict.keys(): Routfile.write("%s,%s\n" %(key, RbarcodeDict[key])) Routfile.close() Combinedoutfile = open("Combined_PacBio_Barcodes.csv", "w") for key in CombinedBarcodeDict.keys(): Combinedoutfile.write("%s,%s\n" %(key, CombinedBarcodeDict[key])) Combinedoutfile.close() Pairedoutfile = open("Paired_PacBio_Barcodes.csv", "w") ### compare PURC barcodes to barcodes from CCS sequence file for key in PairedBarcodeDict.keys(): if key[0:purcBarcodeLength] in purcBarcodeDict: FBCname = purcBarcodeDict[key[0:purcBarcodeLength]] else: try: FBCreversed = purcBarcodeDict[key[0:purcBarcodeLength]] FBCname = FBCreversed.reverse_complement() + "_reversed" except: FBCname = "N/A" if key[purcBarcodeLength:] in purcBarcodeDict.keys(): RBCname = purcBarcodeDict[key[purcBarcodeLength:]] else: try: RBCreversed = purcBarcodeDict[key[purcBarcodeLength:]] RBCname = RBCreversed.reverse_complement() + "_reversed" except: RBCname = "N/A" sample = "No sample match!" for mapKey in purcMapDict.keys(): if FBCname.strip(">") in purcMapDict[mapKey] and RBCname.strip(">") in purcMapDict[mapKey]: sample = mapKey Pairedoutfile.write("%s,%s,%s,%s,%s,%s\n" %(sample, key[0:purcBarcodeLength], key[purcBarcodeLength:], FBCname.strip(">"), RBCname.strip(">"), PairedBarcodeDict[key])) Pairedoutfile.close()
4175618fb4963eeec7450eb8809c7f5ee63975f3
hs929kr/study-algorithm
/basic_algorithm1/12_even_and_odd.py
132
3.796875
4
def solution(num): answer = '' if num==0 or num%2==0: answer="Even" else: answer="Odd" return answer
68aa8b354998aa6e67d92d05f3f578daf8210a0e
crisjulyancolesco/Assignment2
/ApplesOranges.py
169
3.859375
4
print('Quantity of Apples:') Apple = int(input()) print('Quantity of Oranges:') Orange = int(input()) Amount = Apple*20+Orange*25 print(f"The total amount is {Amount}.")
9a7f2c1d48c3e97673dcfd99083b313f81351d60
sanketghanmare/Python-Practice
/Oop/accounts.py
1,975
3.765625
4
import datetime import pytz class Account: """ Simple account class with balance. Name starting with '_' are generally non-public. """ @staticmethod def _current_time(): utc_time = datetime.datetime.utcnow() return pytz.utc.localize(utc_time) def __init__(self, name, balance): self.name = name self.__balance = balance self._transaction_list = [(Account._current_time(), balance)] print(f"Account created for {self.name}") self.show_balance() def deposit(self, amount): if amount > 0: self.__balance += amount self.show_balance() self._transaction_list.append((Account._current_time(), amount)) def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount self._transaction_list.append((Account._current_time(), -amount)) else: print("The amount must be greater than zero and no more then your account balance.") self.show_balance() def show_balance(self): print(f"Balance is {self.__balance}") def show_transactions(self): for date, amount in self._transaction_list: if amount > 0: tran_type = 'deposited' else: tran_type = 'withdrawn' amount *= -1 print(f"{amount:6} {tran_type} on {date} local time was {date.astimezone()}") if __name__ == '__main__': # sanket = Account('Sanket', 0) # # sanket.show_balance() # # sanket.deposit(10000000) # sanket.withdraw(1000) # sanket.withdraw(1) # sanket.show_transactions() Jennifer = Account("Jennifer", 2343455) Jennifer.__balance = 134514551 Jennifer.deposit(1234) Jennifer.withdraw(234345) Jennifer.show_transactions() Jennifer.show_balance() Jennifer.show_balance() print(Jennifer.__dict__) print(Account.__doc__) help(Account)
233fc50076954e78b88bc8428768a353a8d6526a
Yamina2021/python_basics_yamina
/series.py
767
3.875
4
# Python3 implementation of the above approach # Function to print the # unique sub-string of length n def result(s, n) : # set to store the strings st = set(); for i in range(len(s)) : ans = ""; for j in range(i, len(s)) : ans += s[j]; # if the size of the string # is equal to 1 then insert if (len(ans) == n) : # inserting unique # sub-string of length L st.add(ans); break; # Printing the set of strings for it in st : print(it, end = " "); # Driver Code if __name__ == "__main__" : s = "49142"; n = 3; # Function calling result(s, n);
ca1ac51a67d0dad42a51253d7813f36b8b432036
ISANGDEV/Algorithm_Study
/18_Test_Graph_Theory/Jinuk/2_enterance.py
601
3.859375
4
def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b] = a else: parent[a] = b g = int(input()) p = int(input()) parent = [0] * (g+1) for i in range(g+1): parent[i] = i k = [] for _ in range(p): k.append(int(input())) result = 0 for i in k: r = find_parent(parent, i) if r != 0: result += 1 union_parent(parent, r, r-1) else: break print(result)
60225304f72c0aa657ca2b86c616ed2027800713
alicesilva/P1-Python-Problemas
/eh_triangulo.py
323
3.890625
4
# coding: utf-8 # Alice Fernandes Silva /UFCG, 2015.1, Programaçao 1 # Validação de triângulos a = int(raw_input()) b = int(raw_input()) c = int(raw_input()) if abs((a-b)) < a < b+c and abs((a-c)) < b < a+c and abs((a-b)) < c < a+b: perimetro = a + b + c print "triangulo valido. %d" %(perimetro) else: print "triangulo invalido."
7bd5cc0af57fa6b2ea86463320aaf4ebfa4b7251
diegog17/tarea1
/gameCountries.py
7,897
3.75
4
#!/usr/bin/python # -*- coding: utf_8 -*- # gameCountries.py: juego para adivinar paises import random def datosPais(pais): # Imprime las pistas para adivinar el pais en cuestion if (pais == "Argentina"): print "1) Messi, Agüero and Maradona were born in this country." print "2) The most popular tv show of this country is “Bailando por un sueño”." print "3) They are very famous for their tango." elif (pais == "Australia"): print "1) This country is an island and it is the only country with kangaroos." print "2) Surfers all around the world wants to go there because they have the best beaches to surf." print "3) The Olympics games in 2000 were held in this country." elif (pais == "Austria"): print "1) This country is located in central Europe" print "2) Amadeus Mozart, Sigmud Freud, Ludwig Van Beethoven were born there." print "3) The Capital city is Vienna" elif (pais == "Brazil"): print "1) This country is very famous for their “Carnaval”." print "2) This country is one of the two countries that speak Portuguese." print "3) They have won more world cups than anyone." elif (pais == "Canada"): print "1) The flag of this country has a leaf." print "2) The citizens of this country speak two languages, English and French." print "3) The weather in this country is too cold." elif (pais == "China"): print "1) It is the most populated country and one of the biggest in the world." print "2) Their language is very difficult to learn." print "3) Every tourist that goes to this country wants to visit The Great Wall." elif (pais == "Colombia"): print "1) This country is very famous for producing “Cafe”." print "2) The capital city of this country is Bogota." print "3) The colors of this country flag are yellow, red and blue." elif (pais == "Egypt"): print "1) This country has many deserts and the weather is really hot and dry." print "2) They are very famous for the pyramids and mommies." print "3) One of the most common animal is the camel." elif (pais == "England"): print "1) Their cities buses have two storeys." print "2) David Beckham was born in this country." print "3) This country has a queen and her name is Isabel." elif (pais == "France"): print "1) They are very famous for their perfumes." print "2) The Eiffel Tower is the most famous monument in this country." print "3) Many people say that the people of this country do not bathe a lot." elif (pais == "Germany"): print "1) This country is very famous for drinking lots of beer." print "2) They won four times the world cup." print "3) They defeated Argentina 4-0 in South Africa 2010 World cup." elif (pais == "Italy"): print "1) They are very famous for their “pasta” (spaghetti, ravioli, etc)" print "2) The shape of this country is very similar to a boot." print "3) Edinson Cavani(Uruguayan footballer) plays for a team of this country." elif (pais == "Jamaica"): print "1) This country is very well known for its reggae." print "2) Bob Marley was born there." print "3) The capital city is Kingston." elif (pais == "Japan"): print "1) This country is an island." print "2) The Playstation and Nintendo are originary from this country." print "3) Recently they had earthquakes that put many people in danger." elif (pais == "Mexico"): print "1) This country is very famous for their Tequila and spicy food." print "2) Marichi groups are very famous around the world." print "3) Uruguay defeated this country 1-0 in South Africa 2010 World Cup." elif (pais == "Netherlands"): print "1) They played against Uruguay in the World cup 2010." print "2) The capital city of this country is Amsterdam." print "3) Luis Suarez played for Ajax(Football team of this country)." elif (pais == "Russia"): print "1) This country is the biggest country in the world." print "2) The weather is really cold." print "3) The capital of this country is Moscow." elif (pais == "South Africa"): print "1) This country is one of the most powerful countries in Africa." print "2) The capital city of this country is Cape Town." print "3) The last World Cup was held in this country." elif (pais == "Spain"): print "1) They speak the same language that we do." print "2) We were once a colony of this country." print "3)”Las corridas de toros” are originally from this country." elif (pais == "Switzerland"): print "1) It is a very famous country because they have the best chocolate in the world." print "2) The capital of this country is Bern." print "3) Roger Ferderer (Tennis player) was born in this country." elif (pais == "United States of America"): print "1) This country is divided in fifty states." print "2) Michael Jordan, Madonna and Michael Jackson were born in this country." print "3) The statue of liberty is the most popular monument of this country." elif (pais == "Uruguay"): print "1) Carlos Gardel was born in this country." print "2) Football is the most popular sport in this country." print "3) The most popular drink in this country is “el mate”." def crearPregunta(n, lPais): #Crea las opciones al azar eligiendo una posicion para la correcta correct = random.randint(1,5) used = [] #Se asegura de no repetir paises en las opciones for i in range (1,6): if (i == correct): print i,")",lPais[n] used.append(n) else: op = random.randint(0,len(lPais)-1) while (op == n) or (used.count(op) != 0): op = random.randint(0,len(lPais)-1) used.append(op) print i,")",lPais[op] def countries(): #Inicializacion de la lista de paises que integran el juego paises = ["Argentina", "Australia", "Austria", "Brazil", "Canada", "China", "Colombia", "Egypt", "England", "France", "Germany", "Italy", "Jamaica", "Japan", "Mexico", "Netherlands", "Russia", "South Africa", "Spain", "Switzerland", "United States of America", "Uruguay"] salir = False print "--------------------------------------------------" print "|Welcome to Countries Trivia |" print "|Guess the country using the hints to make points|" print "|Good Luck |" print "--------------------------------------------------" answ = raw_input ("Are you ready? (write yes or no): ") if (answ.lower() == "no"): salir = True else: print "" while not salir: #Inicializacion de la lista que marca los paises sobre los #que ya se pregunto de manera de no repetir usado = [] for i in range(len(paises)): usado.append(False) #Variables a usar en el juego contador = len(paises) a = random.randint(0,len(paises)-1) puntaje = 0 #Comienzo del juego while (contador != 0): if (not usado[a]): usado[a] = True contador = contador - 1 print "HINTS:" datosPais(paises[a]) print "" print "OPTIONS:" crearPregunta(a, paises) print "" resp = raw_input("Write your answer: ") if (resp.lower() == paises[a].lower()): print "CORRECT! You won 3 points" puntaje = puntaje + 3 else: print "" print "Sorry but your answer is not correct" print "Last chance" resp = raw_input("Write your answer: ") if (resp.lower() == paises[a].lower()): print "CORRECT! You won 1 point" puntaje = puntaje + 1 else: print "" print "Sorry but your answer is not correct" print "The correct answer is", paises[a] if (contador != 0): print "You lost 1 point, better luck next one" else: print "You lost 1 point" puntaje = puntaje - 1 print "You now have", puntaje, "points" print "" a = random.randint(0,len(paises)-1) print "Final result:",puntaje,"points" again = raw_input("Do you want to play again? (write yes or no): ") if (again.lower() != "yes"): print "See you next time" salir = True else: print "Ok, let's go again" print"" if (__name__ == "__main__"): countries()
814382578dba6221b9e1bb4050a1c5d959179da8
karslio/PYCODERS
/Assignments-04-functions/2-exact_divisor.py
277
4
4
def exact_divisor(): number = int(input('number:')) # we want user input lists = [] for i in range(1, number + 1): if number % i == 0: lists.append(i) return f'exact divisors of a given number: {str(lists)[1:-1]}' print(exact_divisor())
13619ea228783811268558663e61caa188691e10
Yao-9/LeetCode150
/Python/44.py
656
3.625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): length = len(num) root = self.sortedArrayToBST_aux(num,length) return root def sortedArrayToBST_aux(self, num, length): if length <= 0: return None mid = (length - 1) / 2 node = TreeNode(num[mid]) node.left = self.sortedArrayToBST_aux(num[:mid], mid) node.right = self.sortedArrayToBST_aux(num[mid+1:], length / 2) return node a = Solution() res = a.sortedArrayToBST([1,3]) print res.val print res.right.val
af0f883c0b23d83f653309ebc7285c26ab5a198b
Andre-Williams22/SPD-1.4
/technical_interview_problems/most_frequent.py
828
4.25
4
# Most Frequently Occuring Item in Array #Example: list1 = [1, 3, 1, 2, 3, 1] # Output: => 1 def most_frequent(given_list): hashtable = {} # O(n) Space Complexity max_num = 0 # O(1) space => tracks the most occuring number max_count = 0 # O(1) space => tracks num of times number appears for i in given_list: #O(n) time if i in hashtable: # O(1) time hashtable[i] += 1 # O(1) time else: hashtable[i] = 1 # O(1) time if hashtable[i] > max_num: # O(1) time max_num = i # grabs key max_count = hashtable[i] # grabs value return max_num, max_count # for item in hashtable.values(): # if item > max_num: # max_num = item #return max_num array = [2, 5, 6, 3, 3, 5, 7, 5] print(most_frequent(array))
35922cf940eda9870aa1bc418d25679520929c2c
Swathign1995/python_course
/python_course/list_compre_with_conditions2.py
265
3.828125
4
friends=["Rolf","ruth","charlie","Jen"] guests=["Jose","Bob","Rolf","Charlie","michael"] friends_lower=set([f.lower() for f in friends]) present_friends=[ name.title() for name in guests if name.lower() in friends_lower ] print(present_friends)
52d5e3360dbb3c5a3b5d0478b0b66789cdc92bd2
Podakov4/pyCharm
/module_7/lesson_8.py
222
4.09375
4
# Задача 8. Факториал N = int(input('Введите число: ')) factorial = 1 for i in range(1, N + 1): factorial = factorial * i print('Факториал числа', N, 'равен', factorial)
44798963a2821bf20e8b665966155233345cc419
anbet/99-Prolog-Problems
/tcs_7_7.py
462
4.0625
4
def find(str1,n,ch): #print 'inside find' i=n while i<len(str1): if str1[i]==ch: return i i=i+1 return -1 str1= raw_input("Enter the string\n") str1= str(str1) #print str1 ch= raw_input("Enter character to be searched in string\n") #print ch n= raw_input("Enter the offset from where the search should begain\n") n=int(n) res= find(str1,n,ch) if res== -1: print "Character not found in string\n" else: print "Character found at index %d" %res
0ba95c83fe8fa48ab2337b4b95afc4aa8854eaa3
Vanditg/Leetcode
/Number_Of_Calls/EfficientSolution.py
1,068
3.6875
4
##================================== ## Leetcode ## Student: Vandit Jyotindra Gajjar ## Year: 2020 ## Problem: 933 ## Problem Name: Number of Recent Calls ##=================================== #Write a class RecentCounter to count recent requests. #It has only one method: ping(int t), where t represents some time in milliseconds. #Return the number of pings that have been made from 3000 milliseconds ago until now. #Any ping with time in [t - 3000, t] will count, including the current ping. #It is guaranteed that every call to ping uses a strictly larger value of t than before. # #Example 1: # #Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]] #Output: [null,1,2,3,3] import collections class Solution: def __init__(self): self.q = collections.deque() #Initialize the constructor def ping(self, t): self.q.append(t) #Append time in q while self.q[0] < t - 3000: #loop till we reach the condition self.q.popleft() #Pol left in q. return len(self.q) #Return length at the end.
6c47f00dbaf67a8ce437e3276e092e4d4d86f3aa
RafaelHuang87/Leet-Code-Practice
/449.py
1,213
3.6875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. """ l = [] def preOrder(root): if root: l.append(root.val) preOrder(root.left) preOrder(root.right) preOrder(root) return ' '.join(map(str, l)) def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. """ import collections vals = collections.deque([int(val) for val in data.split()]) def buildTree(vals, minVal, maxVal): while vals and minVal < vals[0] < maxVal: val = vals.popleft() root = TreeNode(val) root.left = buildTree(vals, minVal, val) root.right = buildTree(vals, val, maxVal) return root return buildTree(vals, float('-inf'), float('inf')) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
f23aa26e66c5c65c078e438809c043eed70ecfe1
victorvicpal/Udacity_python
/final_project/Data_base_creation.py
6,086
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 30 23:37:32 2016 @author: victor """ # --------------------------- # # Intro to CS Final Project # # Gaming Social Network # # --------------------------- # # # Background # ========== # You and your friend have decided to start a company that hosts a gaming # social network site. Your friend will handle the website creation (they know # what they are doing, having taken our web development class). However, it is # up to you to create a data structure that manages the game-network information # and to define several procedures that operate on the network. # # In a website, the data is stored in a database. In our case, however, all the # information comes in a big string of text. Each pair of sentences in the text # is formatted as follows: # # <user> is connected to <user1>, ..., <userM>.<user> likes to play <game1>, ..., <gameN>. # # For example: # # John is connected to Bryant, Debra, Walter.John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner. # # Note that each sentence will be separated from the next by only a period. There will # not be whitespace or new lines between sentences. # # Your friend records the information in that string based on user activity on # the website and gives it to you to manage. You can think of every pair of # sentences as defining a user's profile. # # Consider the data structures that we have used in class - lists, dictionaries, # and combinations of the two (e.g. lists of dictionaries). Pick one that # will allow you to manage the data above and implement the procedures below. # # You may assume that <user> is a unique identifier for a user. For example, there # can be at most one 'John' in the network. Furthermore, connections are not # symmetric - if 'Bob' is connected to 'Alice', it does not mean that 'Alice' is # connected to 'Bob'. # # Project Description # ==================== # Your task is to complete the procedures according to the specifications below # as well as to implement a Make-Your-Own procedure (MYOP). You are encouraged # to define any additional helper procedures that can assist you in accomplishing # a task. You are encouraged to test your code by using print statements and the # Test Run button. # ----------------------------------------------------------------------------- # Example string input. Use it to test your code. example_input="John is connected to Bryant, Debra, Walter.\ John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\ Bryant is connected to Olive, Ollie, Freda, Mercedes.\ Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\ Mercedes is connected to Walter, Robin, Bryant.\ Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\ Olive is connected to John, Ollie.\ Olive likes to play The Legend of Corgi, Starfleet Commander.\ Debra is connected to Walter, Levi, Jennie, Robin.\ Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\ Walter is connected to John, Levi, Bryant.\ Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\ Levi is connected to Ollie, John, Walter.\ Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\ Ollie is connected to Mercedes, Freda, Bryant.\ Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\ Jennie is connected to Levi, John, Freda, Robin.\ Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\ Robin is connected to Ollie.\ Robin likes to play Call of Arms, Dwarves and Swords.\ Freda is connected to Olive, John, Debra.\ Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures." # ----------------------------------------------------------------------------- # create_data_structure(string_input): # Parses a block of text (such as the one above) and stores relevant # information into a data structure. You are free to choose and design any # data structure you would like to use to manage the information. # # Arguments: # string_input: block of text containing the network information # # You may assume that for all the test cases we will use, you will be given the # connections and games liked for all users listed on the right-hand side of an # 'is connected to' statement. For example, we will not use the string # "A is connected to B.A likes to play X, Y, Z.C is connected to A.C likes to play X." # as a test case for create_data_structure because the string does not # list B's connections or liked games. # # The procedure should be able to handle an empty string (the string '') as input, in # which case it should return a network with no users. # # Return: # The newly created network data structure def create_data_structure(string_input): network={} if string_input=='': return network GAMES={} friends={} phrase=string_input.split('.') for element in phrase: if 'is connected' in element: new_list=element.split(' is connected to ') if len(new_list)>0: gamer=new_list[0] gamer_friends=new_list[1] friends[gamer]=gamer_friends.split(', ') else: gamer=new_list[0] friends[gamer]=new_list[1] if 'likes to play' in element: new_list2=element.split(' likes to play ') if len(new_list2)>0: games=new_list2[1] games=games.split(', ') GAMES[gamer]=games else: games=new_list2[1] GAMES[gamer]=games for key in friends.keys(): network[key] = {} network[key]['friends'] = friends[key] network[key]['games'] = GAMES[key] return network #net=create_data_structure(example_input) net2=create_data_structure('') net=create_data_structure(example_input) print(net2) print(net2.keys()) print(net.keys())
bbaaaa250690a948bee0caeae0791ef0f34c9639
xiaosean/leetcode_python
/Q705_Design-HashSet.py
1,149
3.546875
4
class Node: def __init__(self, key): self.key = key self.next = None class MyHashSet: def __init__(self): self.size = 1000 self.hash = [None]*self.size def gethash(self, key): return key%self.size def add(self, key: int) -> None: hash_key = self.gethash(key) node = self.hash[hash_key] cur_node = Node(key) cur_node.next = node self.hash[hash_key] = cur_node def remove(self, key: int) -> None: hash_key = self.gethash(key) node = self.hash[hash_key] last_node = None while node: if node.key == key: if last_node: last_node.next = node.next else: self.hash[hash_key] = node.next else: last_node = node node = node.next def contains(self, key: int) -> bool: hash_key = self.gethash(key) node = self.hash[hash_key] while node: if node.key == key: return True node = node.next return False
cc6104973d07a47a3d08f55c50eaff6bc191aca5
14Si28/python
/table.py
256
4.5625
5
''' Program to print the multiplication of a number till its square(Result) ''' n = input("Enter the number: ") n = int(n) for i in range(1,n+1): # Since for loop will break at n+1 and we are calculating till n, hence n+1 print(n, " * ", i, " = ", n*i)