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
ae93bc7c0b6aa789aea9f4e073f7d0b603ef4822
samanviekk/algorithms
/level_order_traversal.py
1,640
3.78125
4
import collections class TreeNode: def __init__(self, x): self. val = x self.left = None self.right = None def level_order_traversal(root): if root is None: return [] result = [] q = collections.deque([root]) while len(q) != 0: numnodes = len(q) temp = [] for _ in range(numnodes): node = q.popleft() temp.append(node.val) if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) result.append(temp) return result def level_order_recursive(root): if root is None: return [] result = [] def helper(q): if len(q) == 0: return temp = [] newq = [] for node in q: temp.append(node.val) if node.left is not None: newq.append(node.left) if node.right is not None: newq.append(node.right) result.append(temp[:]) helper(newq) helper([root]) return result def build_tree(input): def helper(input, i): if i >= len(input): return None if input[i] == 'null': return None node = TreeNode(input[i]) node.left = helper(input, 2 * i + 1) node.right = helper(input, 2 * i + 2) return node node = helper(input, 0) return node input = [3, 9, 20, 15, 17, 8, 'null'] root = build_tree(input) res = level_order_traversal(root) print(res) result = level_order_recursive(root) print("recursive:", result)
6917bb16b16e1a17e127ef08c577760fac45e3ee
hallfox/teampython
/lpthw/wookie/ex11.py
764
4.125
4
#raw_input takes input and returns strings print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weight?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) #test test - same as top #found online age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) #testing 2 print "On a scale of 1 to 10, how bored are you?" print "10 being REALLY bored" bored = raw_input() print "That's pretty bored" print "What's your favorite food?" food = raw_input() #study question 4, yes I see that - it put it there automatically
1c39e541a34434470b1e0713734df6056d6155af
BobIT37/Python3Programming
/venv/03-Methods and Functions/02-args and kwargs.py
1,057
4.03125
4
#args and kwargs def myfunc(a,b): return sum((a,b)) * .05 result = myfunc(40,60) print(result) def myfunc(a=0,b=0,c=0,d=0): return sum((a,b,c,d)) * .05 result2= myfunc(40,60,20) print(result2) # *args # When a function parameter starts with an asterisk it allows for an arbitrary number of arguments, # and the function takes them in as a tuple of values def myfunc(*args): return sum(args) * .05 result3 = myfunc(40,60,20) print(result3) def myfunc(*spam): return sum(spam)*.05 result4 = myfunc(40,60,20) print(result4) # **kwargs def myfunc(**kwargs): if 'fruit' in kwargs: print(f"my favorite fruit is {kwargs['fruit']}") else: print("I don't like fruit") myfunc(fruit='pineapple') myfunc() # *args and **kwargs def myfunc (*args, **kwargs): if 'fruit' and 'juice' in kwargs: print(f"i like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}") print(f"may I have some {kwargs['juice']} juice?") else: pass myfunc('eggs', 'spam', fruit='cherries', juice='orange')
a16c235b262e1c0abd685844c81209639e61f94f
spaderthomas/chinesemoon
/app.py
21,654
3.5625
4
# Features: # - combine units (temporarily) # To-do # - make all positions relative # - Clear unit when deleting last one # - space bar is broken? # - move display mode into this file, add a current display mode for switching without changing the mode youre in # Imports from tkinter import * from tkinter import filedialog from tkinter import simpledialog from tkinter import messagebox from tkinter import IntVar from math import floor try: import ttk py3 = 0 except ImportError: import tkinter.ttk as ttk py3 = 1 import main_support from controller import * # Autogenerated GUI code def vp_start_gui(): '''Starting point when module is the main routine.''' global val, w, root root = Tk() top = GUI(root) main_support.init(root, top) root.mainloop() w = None def create_GUI(root, *args, **kwargs): '''Starting point when module is imported by another program.''' global w, w_win, rt rt = root w = Toplevel (root) top = GUI (w) main_support.init(w, top, *args, **kwargs) return (w, top) def destroy_GUI(): global w w.destroy() w = None hardMode = False percentMode = False activeDisplayMode = 'character' # Marks which part of the active word should be displayed globalDisplayMode = 'character' # Which variant shows up first in general class GUI: # Flash card functions def showPinyin(self, word, event=None): if (word): self.vocabWordLabel.configure(text=word.pinyin) self.vocabWordLabel.configure(font=self.pinyinFont) def showDef(self, word, event=None): if (word): self.vocabWordLabel.configure(text=word.definition) self.vocabWordLabel.configure(font=self.englishFont) def showChar(self, word, event=None): if (word): self.vocabWordLabel.configure(text=word.character) self.vocabWordLabel.configure(font=self.pinyinFont) def onPressC(self, event): word = getActiveWord() self.showChar(word) def onPressD(self, event): word = getActiveWord() self.showDef(word) def onPressP(self, event): word = getActiveWord() self.showPinyin(word) def show(self, word, color, mode): self.vocabWordLabel.configure(foreground=color) if (mode == 'character'): self.showChar(word) elif (mode == 'pinyin'): self.showPinyin(word) elif (mode == 'definition'): self.showDef(word) return def cycleDisplay(self, event=None): global activeDisplayMode word = getActiveWord() if (activeDisplayMode == 'character'): activeDisplayMode = 'pinyin' self.showPinyin(word) elif (activeDisplayMode == 'pinyin'): activeDisplayMode = 'definition' self.showDef(word) elif (activeDisplayMode == 'definition'): activeDisplayMode = 'character' self.showChar(word) return 'break' def updateRatio(self, word): global percentMode if (percentMode): if (word.accessed == 0): ratioStr = "0%" else: ratio = float(word.correct) / float(word.accessed) * 100 ratioStr = str(floor(ratio)) ratioStr += "%" else: ratioStr = str(word.correct) + "/" + str(word.accessed) self.ratioLabel.configure(text=ratioStr) def nextWord(self, event=None): global globalDisplayMode countWordsTooEasy = 0 newWord = False wordColorHexStr = False while True: newWord = getRandomWord() # Change word color based on how correct it is if (newWord.accessed == 0): rateCorrect = 0 wordColorHexStr = '#000000' else: rateCorrect = float(newWord.correct) / newWord.accessed rateIncorrect = 1 - rateCorrect red = int(rateIncorrect * 200) #255 is too bright green = int(rateCorrect * 200) blue = int(0) wordColorHexStr = '#%02x%02x%02x' % (red, green, blue) # Reject words we get right too often if (hardMode.get()): if (rateCorrect > hardModeCutoff): countWordsTooEasy += 1 else: break else: break if (countWordsTooEasy > 1000): #the worst algorithm messagebox.showinfo("Get it girl!", "It looks like this unit is too easy for you -- we couldn't find a word with less than 2/3 correct rate!") root.mainloop() setActiveWord(newWord) self.show(newWord, wordColorHexStr, globalDisplayMode) self.updateRatio(newWord) ## Unit Menu def selectUnitOnRightClick(self, event): x = root.winfo_pointerx() - self.unitList.winfo_rootx() # Widget relative y = root.winfo_pointery() - self.unitList.winfo_rooty() posStr = "@" posStr = posStr + str(x) + "," + str(y) index = self.unitList.index(posStr) self.unitList.select_clear(0, END) self.unitList.select_set(index) self.unitList.activate(index) def showUnitMenu(self, event): try: self.unitMenu.tk_popup(event.x_root, event.y_root, 0) finally: self.unitMenu.grab_release() def changeUnitOnDoubleClick(self, event): makeUnitActive(self.unitList.get(ACTIVE)) self.nextWord() def promptNewUnit(self): unitName = simpledialog.askstring("New Unit!", "What's the name of the new unit?") root.withdraw() path = filedialog.askopenfilename() root.deiconify() # TKinter returns '' on cancel if path is not '': # Create unit and add it to dictionary newUnit = unitFromXLSX(path) addUnit(unitName, newUnit) # Add unit's name to our list self.unitList.insert(END, unitName) def deleteSelectedUnit(self): name = self.unitList.get(ACTIVE) delUnit(name) self.unitList.delete(ACTIVE) makeUnitActive() activeUnits = getActiveUnits() if (activeUnits): self.nextWord() else: self.vocabWordLabel.configure(font=self.englishFont) self.vocabWordLabel.configure(text="Add a unit!") def addSelectedUnitToSet(self): name = self.unitList.get(ACTIVE) addUnitToActive(name) ## Mode changing def activateDefMode(self, event=None): global activeDisplayMode, globalDisplayMode globalDisplayMode = 'definition' activeDisplayMode = 'definition' self.pinyinModeButton.configure(relief=RAISED) self.charModeButton.configure(relief=RAISED) self.defModeButton.configure(relief=SUNKEN) word = getActiveWord() self.showDef(word) def activatePinyinMode(self, event=None): global activeDisplayMode, globalDisplayMode globalDisplayMode = 'pinyin' activeDisplayMode = 'pinyin' self.defModeButton.configure(relief=RAISED) self.charModeButton.configure(relief=RAISED) self.pinyinModeButton.configure(relief=SUNKEN) word = getActiveWord() self.showPinyin(word) def activateCharMode(self, event=None): global activeDisplayMode, globalDisplayMode globalDisplayMode = 'character' activeDisplayMode = 'character' self.pinyinModeButton.configure(relief=RAISED) self.defModeButton.configure(relief=RAISED) self.charModeButton.configure(relief=SUNKEN) word = getActiveWord() self.showChar(word) ## Misc def correct(self, event): activeWord = getActiveWord() markCorrect(activeWord) self.nextWord() def incorrect(self, event): activeWord = getActiveWord() markIncorrect(activeWord) self.nextWord() def onClickResetButton(self): global activeDisplayMode resetActiveWordStats() activeWord = getActiveWord() self.updateRatio(activeWord) self.show(activeWord, '#000000', activeDisplayMode) def onClickRatioLabel(self, event): global percentMode percentMode = not percentMode activeWord = getActiveWord() self.updateRatio(activeWord) def viewUnitsInSet(self): activeUnits = getActiveUnits() str = "The units in your current practice set are:\n" for name in activeUnits.keys(): str += name + "\n" str = str[:-1] unitName = messagebox.showinfo("Whoa!", str) def serialize(self): global hardMode, percentMode state = {'hardMode' : hardMode.get(), 'percentMode' : percentMode} pickle.dump(state, open("gui.cm", "wb")) def deserialize(self): return pickle.load(open("gui.cm", "rb")) def onClose(self): self.serialize() serializeController() root.destroy() # Initialization def __init__(self, top=None): global hardMode, units, percentMode # Init all static things (positions, colors) handled by PAGE font10 = "-family Georgia -size 9 -weight normal -slant roman " \ "-underline 0 -overstrike 0" font9 = "-family Georgia -size 12 -weight normal -slant roman " \ "-underline 0 -overstrike 0" self.charFont = "-family Georgia -size 48 -weight normal -slant roman " \ "-underline 0 -overstrike 0" self.englishFont = "-family Georgia -size 24 -weight normal -slant roman " \ "-underline 0 -overstrike 0" self.pinyinFont = "-family Georgia -size 32 -weight normal -slant roman " \ "-underline 0 -overstrike 0" self.smallEnglishFont = "-family Georgia -size 12 -weight normal -slant roman " \ "-underline 0 -overstrike 0" _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#d9d9d9' # X11 color: 'gray85' top.geometry("901x450+511+97") top.title("月亮") top.configure(background="#d9d9d9") top.configure(highlightbackground="#d9d9d9") top.configure(highlightcolor="black") # Init all GUI elements self.unitList = Listbox(top) self.unitList.place(relx=0.01, rely=0.11, relheight=0.73, relwidth=0.33) self.unitList.configure(background="white") self.unitList.configure(disabledforeground="#a3a3a3") self.unitList.configure(font="TkFixedFont") self.unitList.configure(foreground="#000000") self.unitList.configure(highlightbackground="#d9d9d9") self.unitList.configure(highlightcolor="black") self.unitList.configure(selectbackground="#c4c4c4") self.unitList.configure(selectforeground="black") self.unitList.configure(width=294) self.unitMenu = Menu(self.unitList, tearoff=0) self.unitMenu.add_command(label="Delete", command=self.deleteSelectedUnit) self.unitMenu.add_command(label="Add to current practice set", command=self.addSelectedUnitToSet) self.unitSelect = Label(top) self.unitSelect.place(relx=0.11, rely=0.02, height=26, width=102) self.unitSelect.configure(activebackground="#f9f9f9") self.unitSelect.configure(activeforeground="black") self.unitSelect.configure(background="#d9d9d9") self.unitSelect.configure(disabledforeground="#a3a3a3") self.unitSelect.configure(font=font9) self.unitSelect.configure(foreground="#000000") self.unitSelect.configure(highlightbackground="#d9d9d9") self.unitSelect.configure(highlightcolor="black") self.unitSelect.configure(text='''Select Unit''') self.newUnit = Button(top) self.newUnit.place(relx=0.01, rely=0.87, height=43, width=296) self.newUnit.configure(activebackground="#d9d9d9") self.newUnit.configure(activeforeground="#000000") self.newUnit.configure(background="#d9d9d9") self.newUnit.configure(borderwidth="3") self.newUnit.configure(disabledforeground="#a3a3a3") self.newUnit.configure(font=font9) self.newUnit.configure(foreground="#000000") self.newUnit.configure(highlightbackground="#d9d9d9") self.newUnit.configure(highlightcolor="black") self.newUnit.configure(pady="0") self.newUnit.configure(text='''Add New Unit''') self.vocabWordLabel = Label(top) self.vocabWordLabel.place(relx=0.37, rely=0.13, height=286, width=432) #self.vocabWordLabel.place(relx=0.375, rely=0.11, relheight=.45, relwidth=.5) self.vocabWordLabel.configure(activebackground="#000080") self.vocabWordLabel.configure(activeforeground="white") self.vocabWordLabel.configure(activeforeground="#000000") self.vocabWordLabel.configure(background="#d9d9d9") self.vocabWordLabel.configure(disabledforeground="#a3a3a3") self.vocabWordLabel.configure(font=self.englishFont) self.vocabWordLabel.configure(foreground="#000000") self.vocabWordLabel.configure(highlightbackground="#d9d9d9") self.vocabWordLabel.configure(highlightcolor="black") self.vocabWordLabel.configure(wraplength=450) self.pinyinModeButton = Button(top) self.pinyinModeButton.place(relx=0.59, rely=0.87, height=43, width=155) self.pinyinModeButton.configure(activebackground="#d9d9d9") self.pinyinModeButton.configure(activeforeground="#000000") self.pinyinModeButton.configure(background="#d9d9d9") self.pinyinModeButton.configure(borderwidth="3") self.pinyinModeButton.configure(disabledforeground="#a3a3a3") self.pinyinModeButton.configure(font=font10) self.pinyinModeButton.configure(foreground="#000000") self.pinyinModeButton.configure(highlightbackground="#d9d9d9") self.pinyinModeButton.configure(highlightcolor="black") self.pinyinModeButton.configure(padx="0") self.pinyinModeButton.configure(pady="0") self.pinyinModeButton.configure(text='''Pinyin Mode!''') self.defModeButton = Button(top) self.defModeButton.place(relx=0.79, rely=0.87, height=43, width=175) self.defModeButton.configure(activebackground="#d9d9d9") self.defModeButton.configure(activeforeground="#000000") self.defModeButton.configure(background="#d9d9d9") self.defModeButton.configure(borderwidth="3") self.defModeButton.configure(disabledforeground="#a3a3a3") self.defModeButton.configure(font=font10) self.defModeButton.configure(foreground="#000000") self.defModeButton.configure(highlightbackground="#d9d9d9") self.defModeButton.configure(highlightcolor="black") self.defModeButton.configure(padx="0") self.defModeButton.configure(pady="0") self.defModeButton.configure(text='''Definition Mode!''') self.charModeButton = Button(top) self.charModeButton.place(relx=0.39, rely=0.87, height=43, width=155) self.charModeButton.configure(activebackground="#d9d9d9") self.charModeButton.configure(activeforeground="#000000") self.charModeButton.configure(background="#d9d9d9") self.charModeButton.configure(borderwidth="3") self.charModeButton.configure(disabledforeground="#a3a3a3") self.charModeButton.configure(font=font10) self.charModeButton.configure(foreground="#000000") self.charModeButton.configure(highlightbackground="#d9d9d9") self.charModeButton.configure(highlightcolor="black") self.charModeButton.configure(padx="0") self.charModeButton.configure(pady="0") self.charModeButton.configure(text='''Character Mode!''') hardMode = IntVar(root) hardMode.set(0) self.toggleHardButton = Checkbutton(top) self.toggleHardButton.place(relx=0.88, rely=0.02, relheight=0.06, relwidth=0.12) self.toggleHardButton.configure(activebackground="#d9d9d9") self.toggleHardButton.configure(activeforeground="#000000") self.toggleHardButton.configure(background="#d9d9d9") self.toggleHardButton.configure(disabledforeground="#a3a3a3") self.toggleHardButton.configure(font=font10) self.toggleHardButton.configure(foreground="#000000") self.toggleHardButton.configure(highlightbackground="#d9d9d9") self.toggleHardButton.configure(highlightcolor="black") self.toggleHardButton.configure(justify=LEFT) self.toggleHardButton.configure(text='''Hard Mode''') self.toggleHardButton.configure(variable=hardMode) self.resetButton = Button(top) self.resetButton.place(relx=0.88, rely=0.10, relheight=0.08, relwidth=0.11) self.resetButton.configure(activebackground="#d9d9d9") self.resetButton.configure(activeforeground="#000000") self.resetButton.configure(background="#d9d9d9") self.resetButton.configure(disabledforeground="#a3a3a3") self.resetButton.configure(foreground="#000000") self.resetButton.configure(highlightbackground="#d9d9d9") self.resetButton.configure(highlightcolor="black") self.resetButton.configure(pady="0") self.resetButton.configure(text='''Reset Word''') self.resetButton.configure(width=106) self.ratioLabel = Label(top) self.ratioLabel.place(relx=0.89, rely=0.22, height=26, width=82) self.ratioLabel.configure(background="#d9d9d9") self.ratioLabel.configure(disabledforeground="#a3a3a3") self.ratioLabel.configure(foreground="#000000") self.ratioLabel.configure(font=self.smallEnglishFont) top.option_add('*tearOff', False) # No popups of text in menu items self.menuBar = Menu(top) top.config(menu=self.menuBar) view = Menu(self.menuBar) self.menuBar.add_cascade(label="View", menu=view) view.add_command(label="View units in current set", command=self.viewUnitsInSet) # Init all programmatic things top.bind('n', self.nextWord) top.bind('p', self.onPressP) top.bind('d', self.onPressD) top.bind('c', self.onPressC) top.bind('<Return>', self.correct) top.bind('<Shift_R>', self.incorrect) top.bind('<space>', self.cycleDisplay) self.newUnit.configure(command=self.promptNewUnit) self.charModeButton.configure(command=self.activateCharMode) self.pinyinModeButton.configure(command=self.activatePinyinMode) self.defModeButton.configure(command=self.activateDefMode) self.unitList.bind('<Double-Button-1>', self.changeUnitOnDoubleClick) self.unitList.bind('<Button-3>', self.selectUnitOnRightClick) self.unitList.bind('<ButtonRelease-3>', self.showUnitMenu) self.resetButton.configure(command=self.onClickResetButton) self.ratioLabel.bind('<Button-1>', self.onClickRatioLabel) self.activateCharMode() # Default show characters first root.protocol('WM_DELETE_WINDOW', self.onClose) # Load in data. If we can't find it, display welcome message try: # Controller controllerState = deserializeController() loadUnits(controllerState['units']) makeUnitActive() activeWord = getActiveWord() if activeWord is not False: self.updateRatio(activeWord) # GUI guiState = self.deserialize() hardMode.set(guiState['hardMode']) percentMode = guiState['percentMode'] for name in controllerState['units']: self.unitList.insert(END, name) # Load up a fresh word from the first unit! self.nextWord() except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) messagebox.showinfo("!", "Welcome to chinesemoon! A handmade flash card program, just for you!. How to use:\n 1. Load a unit from an excel spreadsheet. Make sure you just have the characters in column 1, pinyin in column 2, and definition in column 3.\n2. Add the spreadsheet as a unit.\n\nGreat! Now you have a unit of vocabulary to study! Press <space> to toggle between character, definition, and pinyin. Press 'p', 'd', or 'c' to flip directly to pinyin, definition, or character. When studying, press enter to mark a word as correct and press right shift to mark it incorrect. If you want to study without affecting your score, use 'n' to go to the next word.\n\n Words will show up on a spectrum of green to red, indicating what percentage of the time you get them correct. Check hard mode to only display words you get wrong more than 1/3 of the time!") if __name__ == '__main__': vp_start_gui()
a76bb3bcafd39194bd6314988885e032f078c516
Yusful33/TicTacToeGame
/TicTacToeTake2.py
4,504
4.09375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 10:48:59 2019 @author: ycattaneo """ #Clears the board #print('\n'*100) #Creating a board def display_board(b): print('\n'*100) print(' | |') print(' ' + b[7] + ' | ' + b[8] + ' | ' + b[9]) print('-----------') print(' ' + b[4] + ' | ' + b[5] + ' | ' + b[6]) print(' | |') print('-----------') print(' | |') print(' ' + b[1] + ' | ' + b[2] + ' | ' + b[3]) #Testing out the above function #test_board = ['#','X','O','X','O','X','O','X','O','X'] #display_board(test_board) #Assigns a marker of X or O def player_input(): marker = '' while not (marker == 'X' or marker == 'O'): marker = input('Player 1: Do you want to be X or O?') if marker == 'X': return('X', 'O') else: return('O', 'X') #Testing above function #player_input() #Function to takes in the board list object (x,o) and #desired position and assigns it to the board def place_marker(b, l, position): b[position] = l #Testing function #place_marker(test_board, '$', 8) #display_board(test_board) #Function that takes in a board and a marker and then #checks to see if that mark has won def win_check(b,l): return((b[7] == l and b[8] == l and b[9] == l) or (b[4] == l and b[5] == l and b[6] == l) or (b[1] == l and b[2] == l and b[3] == l) or (b[7] == l and b[4] == l and b[1] == l) or (b[8] == l and b[5] == l and b[2] == l) or (b[9] == l and b[6] == l and b[3] == l) or (b[7] == l and b[5] == l and b[3] == l) or (b[9] == l and b[5] == l and b[1] == l)) #Testing #win_check(test_board, 'O') import random #Function that uses a random module to randomly decide #which player goes first def choose_first(): if random.randint(0, 1) == 0: return 'Player 2' else: return 'Player 1' #Checking if any spaces on the board are free def space_check(b,position): return(b[position] == ' ') #Checking if the board is full def full_board_check(b): for i in range(1,10): if space_check(b, i): return(False) return(True) #Asks for players ext position and then checks if that #position is free def player_choice(b): position = 0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(b,position): position = int(input('Choose your next position (1-9)')) return(position) #Asks if they want to play again def replay(): return(input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')) ####RUN Below Code to Play########### #Using functions above to play the game print('Welcome to Tic Tac Toe!') while True: #Reset the board theBoard = [' '] *10 player1_marker, player2_marker = player_input() turn = choose_first() print(turn + ' will go first.') play_game = input('Are you ready to play? Enter Yes or No. ') if play_game.lower()[0] == 'y': game_on = True else: game_on = False while game_on: if turn == 'Player 1': #Player1's turn display_board(theBoard) position = player_choice(theBoard) place_marker(theBoard, player1_marker, position) if win_check(theBoard, player1_marker): display_board(theBoard) print('Congratulations! You have won the game!') game_on = False else: if full_board_check(theBoard): display_board(theBoard) print('The game is a draw!') break else: turn = 'Player 2' else: #Player2's Turn display_board(theBoard) position = player_choice(theBoard) place_marker(theBoard, player2_marker, position) if win_check(theBoard, player2_marker): display_board(theBoard) print('Player 2 has won!') game_on = False else: if full_board_check(theBoard): display_board(theBoard) print('The game is a draw!') break else: turn = 'Player 1' if not replay(): break
301f8042fae2d6f3db204543af865da436088ca3
willbh1992/LPTHW
/ex11.py
1,477
4.09375
4
# Most of what software doe is the following # 1. Take some kind of input from a person # 2. Change it. # 3. Print out something to show how it changed print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) print ''' Four is the cosmic number Any integer can be reduced to or exapnded to it It is easiest to solve if you use numbers between 0 and 10 Did not write the code for it but it can compute any integer beyond that range ''' while True: print "Enter integer value between 0 and 10" number = int(raw_input()) if number == 1 or number == 2 or number == 6 or number == 10: print "%s becomes 3 becomes 5 becomes 4 and 4 is always 4" % number if number == 0 or number == 4 or number == 5 or number == 9: print "%s becomes 4 and 4 is always 4" % number if number == 3 or number == 7 or number == 8: print "%s becomes 5 become 4 and 4 is always 4" % number print "Have you figured it out?" print "Give up?" print ''' If you figured it out or gave up then type y for solution If you want to keep guessing type n: ''' response = raw_input() if response == 'y': print ''' Four is cosmic because if you count out the letters in an integer value and then move to the number counted out you will eventually reach four which is always four because it has four letters ''' break
4856451dfa52f1c85dc4116b9a55b192702fa54a
mosfeqanik/Python_Exercises
/arithmetic.py
181
3.796875
4
number1 = raw_input("please type an integer and press enter: ") number2 = raw_input("please type another integer and press enter: ") print(" number1 + number2", number1+number2)
e25c0183b1623bf02bf6eaf3c22b181912b1ec6c
sssandesh9918/Python-Basics-III
/Sorting and Searching/6.py
497
4.09375
4
#Binary Search def binarysearch(a,element): l=0 r=len(a)-1 while(l<=r): mid=int((l+r)/2) if a[mid]==element: return mid elif a[mid]<element: l=mid+1 else: return mid return -1 a=[1,5,6,7,13,19,26,33,48] element=int(input("Enter the element you want to search")) re=binarysearch(a,element) if re!= -1: print("Element is present at index", a.index(element)) else: print("Element is not present in array")
9f0f92226daf9256fde6000c2b6b837324df5453
misa9999/python
/courses/pythonBrasil/EstruturaDeDecisao/ex010.py
401
3.859375
4
# pede para inforar o turno de estudo, em seguida da uma saudação no turno esp # pergunta o turno de estudo M-matutino V-vespertino N-noturno horario = input('Turno de estudo: M-matutino/V-vespertino/N-noturno: ') if horario in 'mM': print('Bom dia!') elif horario in 'vV': print('Boa tarde!') elif horario in 'nN': print('Boa noite!') else: print('Valor inválido!')
4c341c964a04662b51bcbb3cd04ef7c40f1a60b6
cosmic-weber/lets_upgrade_assignments
/day6/day6_question1.py
1,229
3.796875
4
class BankAccount(): def __init__(self, owner_name, balance): self.owner_name = owner_name self.balance = balance self.money = 0 def deposite(self): print(self.owner_name + " You added Rs-/ ",self.balance) def Update_balace(self, amount): self.balance= self.balance + amount print(self.owner_name + " Your total balance is ", self.balance) def set_withdraw(self, money): self.money = money if int(self.money) > int(self.balance): print(self.owner_name + " You can't withdraw the money") else: b = int(self.balance) - int(self.money) print("you withdraw the amount of Rs-/", self.money) print("Remaining money in your balance is Rs-/",b) obc = BankAccount("Yaman",12000) obc.deposite() obc.Update_balace(8796) obc.set_withdraw(1234) romey = BankAccount("Hanna", 63527) romey.deposite() romey.Update_balace(5978) romey.Update_balace(9876) romey.set_withdraw(3467) julie = BankAccount("Julie", 987674) julie.deposite() julie.set_withdraw(3865829) leonard = BankAccount("sheldon", 150000000) leonard.deposite() leonard.set_withdraw(77969697)
d8d8e39f5705ff6dff350e393d263fce00f9579a
hanrick2000/DSAL
/ALGO_V2/DS_python/linked_list.py
1,922
4.25
4
# linked list: a chain of node object. # node: value + pointer(to the next node) # head pointer to the first node # tail pointer to the null class Node: def __init__(self, data, next=None): self.data = data self.next = next # join the node to get a linked list # linked list class with a single head pointer class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) if not self.head: self.head = new_node return current = self.head while current.next: current = current.next current.next = new_node def unshift(self, data): new_node = Node(data) if not self.head: self.head = new_node return data template_node = self.head self.head = new_node new_node.next = template_node return data def find(self, data): # find the first node by its data value if self.head == None: return None current_node = self.head while current_node: if current_node.data == data: return current_node current_node = current_node.next return None def size(self): if not self.head: return None length = 0 current_node = self.head while current_node.next: length += 1 current_node = current_node.next return length + 1 def print(self): print_node = self.head while print_node: print(print_node.data) print_node = print_node.next first_ll = LinkedList() # linked list object second_node = Node(4) first_ll.head = Node(3, second_node) first_ll.push(10) first_ll.unshift(88) # first_ll.print() first_ll.find(10).next = Node(67) first_ll.print() size = first_ll.size() print(size)
5069c8f89ba07ef50ca8f1274c8e33ab290be308
theshivambedi/Pythonprojetcs
/cointoss(10).py
126
3.5625
4
import random computerchoice = random.randint(0,1) if computerchoice == 1: print("Heads") else: print("Tails")
b5da18a3f1a74d2c33c94d04d6e0826058e5caa0
chefmohima/Katacode
/data_structures.py
7,054
4.5625
5
# Python data structures # Recipe1 : Unpacking sequences into variables # number and order should match when unpacking >>> data ['ACME', 50, 91.1, (2012, 12, 21)] >>> name, share, price, date = data >>> print('Name: {}, Share: {}, Price: {}, Date: {}'.format(name, share, price, date)) Name: ACME, Share: 50, Price: 91.1, Date: (2012, 12, 21) # If we want to split the date further: >>> name, share, price, (year, month, day) = data >>> print('Date: {}/{}/{}'.format(year, month, day)) Date: 2012/12/21 # Throwaway variable: when unpacking if there are certain values we dont need replace them with # _. Example if we dont want the date value from data replace with _ when unpacking >>> data ['ACME', 50, 91.1, (2012, 12, 21)] >>> name, share, price, _ = data >>> print(name, share, price) ACME 50 91.1 # Any iterable can be unpacked including strings # get the first and last characters from the string 'hello' >>> c1, _, _, _, c2 = 'hello' >>> print(c1, c2) h o # Recipe 2 : using * for unpacking # Unpack iterables of ARBITRARY lengths with * # Suppose we have this record of an employee with multiple contact numbers record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') # fetch all the contact numbers with * name, email, *phone_numbers = record print(phone_numbers) ['773-555-1212', '847-555-1212'] # * will eat up N number of variables into a list # using the * unpacking with split to fetch data # Suppose we have this line of data line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false' # Fetch the username, directory and shell name from the line >>> username, *middle_fields, dir, shell = line.split(':') >>> print(username, dir, shell) nobody /var/empty /usr/bin/false # throwaway multiple values with _* # In the data below fetch just the name and year >>> record = ('ACME', 50, 123.45, (12, 18, 2012)) name, *_, (*_, year) = record >>> name 'ACME' >>> year 2012 # Recipe 3: find N largest/ N smallest items in a sequence with heapq import heapq >>> nums = [100,10,30,90,40,60,1] >>> heapq.nlargest(2, nums) [100, 90] >>> heapq.nsmallest(2, nums) # using heapq nlargest/nsmallest with key >>> num = [-1,3,2,1,4,2,-3,-5,-10] >>> heapq.nlargest(2, num) [4, 3] # notice how the result changes when we use a key # In the below example, when we use key # we are using list of squares to compute the values >>> heapq.nlargest(2, num, key=lambda s:s**2) # Recipe 4: Map keys to multiple values in a dictionary # we can either use a normal dictionary and initialize every key value to an empty list # or use defaultdict(list) where key values will be list by default and do not need to be initialized # normal dicts >>> map1 = {} >>> map1['key1'] = [] # this initialization is required >>> map1['key1'].append('a') >>> map1['key1'].append('b') >>> map1 {'key1': ['a', 'b']} # dafultdict(list) >>> from collections import defaultdict >>> map2 = defaultdict(list) >>> map2['key1'].append('a') # no initialization needed >>> map2['key1'].append('b') >>> map2 defaultdict(<class 'list'>, {'key1': ['a', 'b']}) [-10, -5] # Recipe 5: ordering dictionary entries with OrderedDict # using an OrderedDict will preserve the order of insertion of items into the dictionary from collections import OrderedDict d = OrderedDict() d['foo'] = 1 d['bar'] = 2 d['spam'] = 3 d['grok'] = 4 # Outputs "foo 1", "bar 2", "spam 3", "grok 4" for key in d: print(key, d[key]) # Recipe 6: perform calculations on dict VALUES and do reverse lookup # usually we use dicts to look up using keys, however sometimes # we may need to do a reverse lookup or find values with ceratin key # to do this we can invert the dict with zip() function # this converts key: value pair to value:key pair # Normal function of zip is to pair up values one by one from N iterables >>> list(zip(['a', 'b', 'c'],[1,2,3],['x','y','z'])) [('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')] # invert key value pairs with zip >>> prices = { ... 'ACME': 45.23, ... 'AAPL': 612.78, ... 'IBM': 205.55, ... 'HPQ': 37.20, ... 'FB': 10.75 ... } >>> list(zip(prices.values(), prices.keys())) [(45.23, 'ACME'), (612.78, 'AAPL'), (205.55, 'IBM'), (37.2, 'HPQ'), (10.75, 'FB')] # find product with minimum price >>> min(zip(prices.values(), prices.keys())) (10.75, 'FB') # sort dictionary by value >>> sorted(zip(prices.values(), prices.keys())) [(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'), (612.78, 'AAPL')] # Computing on dict values without using zip # can use the key value to calculate min/max values in a dict >>> prices = { ... 'ACME': 45.23, ... 'AAPL': 612.78, ... 'IBM': 205.55, ... 'HPQ': 37.20, ... 'FB': 10.75 ... } >>> min(prices) # this computes the minimum value among the dict keys and not value 'AAPL' # to change this behavior use the key parameter min(prices, key = lamda k: prices[k]) 'FB' # this finds the key with minimum value # to find the correspnding value: prices[min(prices, key = lamda k: prices[k])] 10.75 # Recipe 7: find common elements in dictionaries >>> a = { ... 'x' : 1, ... 'y' : 2, ... 'z' : 3 ... } >>> >>> b = { ... 'w' : 10, ... 'x' : 11, ... 'y' : 2 ... } >>> a.keys() & b.keys() # find common keys {'x', 'y'} >>> a.keys() - b.keys(). # find keys in a that are not in b {'z'} >>> a.items() - b.items(). # find unique key values pairs from both dicts, the key 'y' has same value and hence removed {('x', 1), ('z', 3)} # Recipe 8: Remove duplicate values from a sequence but preserve order of sequence >>> a [1, 5, 2, 1, 9, 1, 5, 10] >>> set(a) {1, 2, 5, 9, 10} # notice that duplicates removed BUT order has changed # instead use this method to preserve the order of elements >>> s = set() >>> for item in a: ... if item not in s: ... print(item) ... s.add(item) ... 1 5 2 9 10 # Recipe 9: Most frequently occuring elements in a sequence from collections import Counter >>> words = [ ... 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', ... 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', ... 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', ... 'my', 'eyes', "you're", 'under' ... ] word_counts = Counter(words) print(word_counts) Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under':1}) # find word with max count >>> max(zip(word_counts.values(), word_counts.keys())) (8, 'eyes') # Recipe 10:mapping names to sequence elements, useful when position in a list/tuple has a specific value # example: suppose we have a list of coordinates each in the form of a tuple where 1st element # is longitude and second signifies latitude >>> from collections import namedtuple # namedtuple takes first argumnet as name of the namedtuple and names of the attributes stored >>> Coordinates = namedtuple('Coordinates', ['longitude', 'latitude']) >>> c1 = Coordinates(100,90) >>> c1.longitude 100 >>> c1.latitude 90 # Recip1 11:
772f9f3b8bf58a4ef7ce3531111d99df2a4b777e
AyanChawla/Codes
/Day Of the Programmer/Sol.py
925
3.84375
4
#!/bin/python3 import math import os import random import re import sys # Complete the dayOfProgrammer function below. def dayOfProgrammer(year): if(year>=1919): if((year%400==0) or (year%4==0 and not(year%100==0))): print("12.09.",year,sep="") else: print("13.09.",year,sep="") elif(year<=1917 and year>=1700): if (year%4==0): print("12.09.",year,sep="") else: print("13.09.",year,sep="") else: print("26.09.1918") if __name__ == '__main__': year = int(input().strip()) result = dayOfProgrammer(year) -------------------------------------------ALTERNATE if(year==1918) { return "26.09.1918"; } else if((year<1918 && year%4==0) ||(year>1918 &&(year%4==0 && year%100 !=0 || year%400==0))) { return "12.09." + year; } else { return "13.09." + year; }
a95e148f0430382fd47361fa2661aa717e279a7e
pananev/Training
/ML_Courses/dl_course_assignments/assignment3/model.py
3,345
3.625
4
import numpy as np from layers import ( FullyConnectedLayer, ReLULayer, ConvolutionalLayer, MaxPoolingLayer, Flattener, softmax_with_cross_entropy, l2_regularization, softmax ) class ConvNet: """ Implements a very simple conv net Input -> Conv[3x3] -> Relu -> Maxpool[4x4] -> Conv[3x3] -> Relu -> MaxPool[4x4] -> Flatten -> FC -> Softmax """ def __init__(self, input_shape, n_output_classes, conv1_channels, conv2_channels): """ Initializes the neural network Arguments: input_shape, tuple of 3 ints - image_width, image_height, n_channels Will be equal to (32, 32, 3) n_output_classes, int - number of classes to predict conv1_channels, int - number of filters in the 1st conv layer conv2_channels, int - number of filters in the 2nd conv layer """ # TODO Create necessary layers self.first_conv = ConvolutionalLayer(input_shape[-1], conv1_channels, 3, 1) self.first_relu = ReLULayer() self.first_maxpool = MaxPoolingLayer(4, 4) self.second_conv = ConvolutionalLayer(conv1_channels, conv2_channels, 3, 1) self.second_relu = ReLULayer() self.second_maxpool = MaxPoolingLayer(4, 4) self.flattener = Flattener() self.linear = FullyConnectedLayer(8, n_output_classes) self.layers = [self.first_conv,self.first_relu, self.first_maxpool, self.second_conv, self.second_relu, self.second_maxpool, self.flattener, self.linear] def compute_loss_and_gradients(self, X, y): """ Computes total loss and updates parameter gradients on a batch of training examples Arguments: X, np array (batch_size, height, width, input_features) - input data y, np array of int (batch_size) - classes """ # Before running forward and backward pass through the model, # clear parameter gradients aggregated from the previous pass for param in self.params(): self.params()[param].grad *= 0 # TODO Compute loss and fill param gradients # Don't worry about implementing L2 regularization, we will not # need it in this assignment inp = X.copy() for layer in self.layers: out = layer.forward(inp) inp = out from layers import cross_entropy_loss loss, out_grad = softmax_with_cross_entropy(out, y) for layer in reversed(self.layers): out_grad = layer.backward(out_grad) #print(f'Input shape: {layer.X.shape}, grad_shape: {out_grad.shape}') return loss def predict(self, X): # You can probably copy the code from previous assignment inp = X.copy() for layer in self.layers: inp = layer.forward(inp) probs = softmax(inp) pred = np.argmax(probs, axis=1) return pred def params(self): # TODO: Aggregate all the params from all the layers # which have parameters result = {'W1': self.first_conv.W, 'B1': self.first_conv.B, 'W2': self.second_conv.W, 'B2': self.second_conv.B, 'W3': self.linear.W, 'B3': self.linear.B} return result
7ddcd10eb2811586de0e92bfee443151d61dafa3
ianpepin/Tensorflow-Tutorial
/machineLearningAlgorithms-classification.py
3,118
3.625
4
import tensorflow as tf import pandas as pd CSV_COLUMN_NAMES = ["SepalLength", "SepalWidth", "PetalLength", "PetalWidth", "Species"] SPECIES = ["Setosa", "Versicolor", "Virginica"] trainPath = tf.keras.utils.get_file("iris_training.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv") testPath = tf.keras.utils.get_file("iris_test.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv") train = pd.read_csv(trainPath, names=CSV_COLUMN_NAMES, header=0) test = pd.read_csv(testPath, names=CSV_COLUMN_NAMES, header=0) # Here we use keras to grab our datasets and read them into a pandas dataframe # print(train.head()) # Pop the species column off and use it as our label trainY = train.pop("Species") testY = test.pop("Species") # print(train.head()) # The species column is now gone # print(train.shape) # We have 120 entries with 4 features # Input function def inputFn(features, labels, training=True, batchSize=256): # Convert the inputs to a Dataset dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle and repeat if you are in training mode if training: dataset = dataset.shuffle(1000).repeat() return dataset.batch(batchSize) # Feature columns: describe how to use the input myFeatureColumns = [] for key in train.keys(): # train.keys(): gives us all the columns myFeatureColumns.append(tf.feature_column.numeric_column(key=key)) print(myFeatureColumns) # Building the model # Build a DNN with 2 hidden layers with 30 and 10 hidden nodes each classifier = tf.estimator.DNNClassifier( feature_columns=myFeatureColumns, # Two hidden layers of 30 and 10 nodes respectively hidden_units=[30, 10], # The model must choose between 3 classes n_classes=3) # Training the model classifier.train(input_fn=lambda: inputFn(train, trainY, training=True), steps=10000) # We include a lambda to avoid creating an inner function previously (calls function that returns inputFn) evalResult = classifier.evaluate(input_fn=lambda: inputFn(test, testY, training=False)) print("\nTest set accuracy: {accuracy:0.3f}\n".format(**evalResult)) # Predictions def inputFunction(features, batch_size=256): # Convert the inputs to a Dataset without labels because we don't know the labels when making predictions. return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size) features = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'] predict = {} print("Please type numeric values as prompted.") for feature in features: valid = True while valid: val = input(feature + ": ") if not val.isdigit(): valid = False predict[feature] = [float(val)] predictions = classifier.predict(input_fn=lambda: inputFunction(predict)) for predDict in predictions: classId = predDict['class_ids'][0] probability = predDict['probabilities'][classId] print('Prediction is "{}" ({:.1f}%)'.format( SPECIES[classId], 100 * probability))
31e3c6875e1ceae10b1ff96c9ca1c5b34ecd0198
Jingyuan-L/code-practice
/tencent3.py
420
3.5
4
from collections import Counter nums = list(map(int, input().strip().split())) strings = [] for i in range(nums[0]): strings.append(input().strip()) # print(strings) counter = Counter(strings) common = counter.most_common(nums[1]) for i in range(nums[1]): print(common[i][0], common[i][1]) uncommon = sorted(counter.items(), key=lambda x: x[1]) for i in range(nums[1]): print(uncommon[i][0], uncommon[i][1])
740b44fed84fc8530fe2fceb1e659bd4d843a230
diput102/learnpy
/py100/py_ex4.py
481
3.609375
4
def compday(): Y=int(input('year')) M=int(input('Month')) D=int(input('day')) days1=[31,28,31,30,31,30,31,31,30,31,30,31] days2=[31,29,31,30,31,30,31,31,30,31,30,31] # i=0 # days=0 # count=0 if ((Y%400==0)|(Y%4==0)&(Y%100!=0)): print('润') for i in range(0,M-1): days+=days1[i] else: print('平') for i in range(0,M-1): days+=days2[i] count=days+D return count
657d7bf9b626e9ff584175b9769562bad870c267
Taddist/CodeForce
/705A.py
345
3.625
4
n=int(input()) ih="I hate " th="I hate that I love" t=" it" s="" if(n==1): print(ih+t) if(n==2): print(th+t) if(n>=3): if(n%2==0): n=n//2 while(n>0): s=s+th n=n-1 if(n>0): s=s+" that " print(s+t) else : n=n-1 n=n//2 while(n>0): s=s+th n=n-1 if(n>=0): s=s+" that " print(s+ih+"it")
885ce6d26de250aaca3fae5069493c1d0639651a
ryanpethigal/IntroProgramming-Labs
/pi.py
105
3.84375
4
import math terms = int(input("enter number of terms to sum: ")) for i in range (,terms,2): print(i)
8e72550841d7ac33e52ffc9e99be61af2cfdf6e9
AsherThomasBabu/AlgoExpert
/Arrays/Array-Of-Products/naive.py
748
4.1875
4
# Write a function that takes in a non-empty array of integers and returns an array of the same length, where each element in the output array is equal to the product of every other number in the input array. # In other words, the value at output[1] is equal to the product of every number in the Input array other than input[1] # Note that you're expected to solve this problem without using division. # Sample Input # array = [5, 1, 4, 2] # Sample Output # [8, 40, 10, 20] def arrayOfProducts(array): result = [] for i in range(len(array) ): tempProduct = 1 for j in range(len(array)): if i != j: tempProduct *= array[j] result.append(tempProduct) return result
4971f3a592af0001bf5b40df0c351ce639de529c
venosu/python
/calculator.py
303
3.96875
4
def calculate(a, b, c): if a == '+': return b + c elif a == '-': return b - c elif a == '*' or a == 'x': return b * c elif a == ':' or a == '/': return b / c number1 = 69 number2 = 69 action = '*' print(calculate(action, number1, number2))
249c082b1cd17c7e3ec646a61d58ff0af0285dc6
Konstantin-Bogdanoski/VI
/Lab03_Informirano prebaruvanje/Подвижни_Препреки.py
4,908
3.625
4
CoveceRedica = input() CoveceKolona = input() KukaRedica = input() KukaKolona = input() from Python_informirano_prebaruvanje import Problem from Python_informirano_prebaruvanje import astar_search from Python_informirano_prebaruvanje import recursive_best_first_search coordinates = {0:(CoveceRedica,CoveceKolona),1:(KukaRedica,KukaKolona)} def updateDigi(P): X, Y ,Nasoka = P if ((Y == 0 and Nasoka == -1) or (X == 4 and Nasoka == 1)\ and (Y==4 and Nasoka==-1) or (X==10 and Nasoka==1)): Nasoka = Nasoka * (-1) Ynew = Y + Nasoka Xnew = X + Nasoka Pnew = Xnew ,Ynew , Nasoka return Pnew def updateVert(P): X, Y, Nasoka = P if(X==5 and Nasoka==-1) or (X==9 and Nasoka==1): Nasoka = Nasoka * (-1) Xnew = X + Nasoka Pnew = Xnew , Y , Nasoka return Pnew def updateHori(P): X ,Y, Nasoka = P if(Y==0 and Nasoka==-1) or (Y==4 and Nasoka==1): Nasoka = Nasoka * (-1) Ynew = Y + Nasoka Pnew = X , Ynew , Nasoka return Pnew def mhd(n ,m): CoveceRedica ,CoveceKolona = coordinates[n] KukaRedica ,KukaKolona = coordinates[m] return abs(int(CoveceRedica) - int(KukaRedica))+abs(int(CoveceKolona) - int(KukaKolona)) class Istrazhuvach(Problem): def __init__(self,initial ,goal): self.initial = initial self.goal = goal def goal_test(self, state): g = self.goal return (state[0] == g[0] and state[1] == g[1]) def h(self ,node): return mhd(0,1) def successor(self, state): successors = dict() X=state[0] Y=state[1] P1 = (state[2],state[3],state[4]) P2 = (state[5],state[6],state[7]) P3 = (state[8],state[9],state[10]) #desno if ((X < 5 and Y < 5) or (X > 4 and Y < 10)): Xnew = X Ynew = Y+1 P1new = updateHori(P1) P2new = updateDigi(P2) P3new = updateVert(P3) if (Xnew !=P1new[0] or Ynew !=P1new[1] or Ynew!=P1new[1]+1\ or (Xnew != P2new[0] or Xnew != P2new[0] - 1 or Ynew != P2new[1] or Ynew != P2new[1] + 1)\ or (Ynew != P3new[1] or (Xnew != P3new[0] or Xnew != P3new[0]+1))): Statenew = (Xnew, Ynew, P1new[0], P1new[1], P1new[2], P2new[0], P2new[1], P2new[2], P3new[0], P3new[1], P3new[2]) successors["Desno"] = Statenew #levo if Y>0: Xnew = X Ynew = Y-1 P1new = updateHori(P1) P2new = updateDigi(P2) P3new = updateVert(P3) if (Xnew !=P1new[0] and Ynew !=P1new[1] or Ynew!=P1new[1]+1\ or (Xnew != P2new[0] or Xnew != P2new[0] - 1 or Ynew != P2new[1] or Ynew != P2new[1] + 1)\ or (Ynew != P3new[1] or Xnew != P3new[0] or Xnew != P3new[0]+1)): Statenew = (Xnew, Ynew, P1new[0], P1new[1], P1new[2], P2new[0], P2new[1], P2new[2], P3new[0], P3new[1], P3new[2]) successors["Levo"] = Statenew # gore if (X > 5 and Y > 5) or (X > 0 and Y < 6): Xnew = X-1 Ynew = Y P1new = updateHori(P1) P2new = updateDigi(P2) P3new = updateVert(P3) if (Xnew !=P1new[0] or Ynew !=P1new[1] or Ynew!=P1new[1]+1\ or (Xnew != P2new[0] or Xnew != P2new[0] - 1 or Ynew != P2new[1] or Ynew != P2new[1] + 1)\ or (Ynew != P3new[1] or (Xnew != P3new[0] or Xnew != P3new[0]+1))): Statenew = (Xnew, Ynew, P1new[0], P1new[1], P1new[2], P2new[0], P2new[1], P2new[2], P3new[0], P3new[1], P3new[2]) successors["Gore"] = Statenew #dole if (X<10): Xnew = X+1 Ynew = Y P1new = updateHori(P1) P2new = updateDigi(P2) P3new = updateVert(P3) if (Xnew !=P1new[0] or (Ynew !=P1new[1] or Ynew!=P1new[1]+1)\ or (Xnew != P2new[0] or Xnew != P2new[0] - 1 or Ynew != P2new[1] or Ynew != P2new[1] + 1)\ or (Ynew != P3new[1] or Xnew != P3new[0] or Xnew != P3new[0]+1)): Statenew = (Xnew, Ynew, P1new[0], P1new[1], P1new[2], P2new[0], P2new[1], P2new[2], P3new[0], P3new[1], P3new[2]) successors["Dolu"] = Statenew return successors def result(self , state , action): possible = self.successor(state) return possible[action] def actions(self, state): return self.successor(state).keys() K = [int(KukaRedica),int(KukaKolona)] IstrazhuvachInstance = Istrazhuvach((int(CoveceRedica),int(CoveceKolona),2,2,-1,2,8,-1,8,8,-1),K) answer = astar_search(IstrazhuvachInstance) print(answer.solution())
b22f13fb5b6907f37bf3da84e87b974d77f3cde9
sunsun101/DSA
/insertion_sort.py
1,038
4.09375
4
# declaring empty list list = [] take_input = True # taking input for the list while take_input: try: element = int(input("Please enter a number for the list :")) list.append(element) except ValueError: print("Please provide a valid number") condition = False while not condition: yes_no = input("Do you want to provide another value?(y/n)") if yes_no == 'y': take_input = True condition = True elif yes_no == 'n': take_input = False condition = True else: print("Incorrect input! Please enter (y/n)") print("List you provided is :", list) for j in range (1, len(list)): # determine the key key = list[j] # set i to find preceeding element i = j - 1 while i >= 0 and list[i] > key: # replace the suceeding element by preceeding if it is greater than key list[i + 1] = list[i] i = i - 1 list[i + 1] = key print("List Sorted in ascending order is :", list)
d24bee8481661a5d55983b14eab7a76c940a8393
AmbyMbayi/CODE_py
/DataStructure/Question4.py
273
3.75
4
"""write a python program to get all values from an enum class Expected output [92,23,42,539,34,53] """ from enum import IntEnum class City(IntEnum): Kisumu = 45 Nairobi = 67 Alego = 56 Usenge =4 city_code_list = list(map(int, City)) print(city_code_list)
0dc4742a017f4f4a5f7551927e311fb1ad64e3af
mdamyanova/SoftUni-CSharp-Web-Development
/00.Open Courses/Python/ExamPreparation/CharsInString.py
468
3.84375
4
input_str = input() dict_chars = {} if input_str is None or input_str is '': print("INVALID INPUT") else: for char in input_str: if char in dict_chars: dict_chars[char] += 1 else: dict_chars[char] = 0 counter_max = 0 most_common_char = '' for key, value in dict_chars.items(): if value > counter_max: counter_max = value most_common_char = key print(most_common_char)
2e5bfe41f92e6f9f8572ccdfe190fc57fca9981e
kneyzberg/python-oo-practice
/wordfinder.py
1,496
3.84375
4
from random import choice class WordFinder: """Word Finder: finds random words from a dictionary. >>> wordfinder = SpecialWordFinder("./test.txt") 4 words read >>> lst = ["kale", "parsnips", "apples", "mango"] >>> wordfinder.random() in lst True """ def __init__(self, path): """Creates word finder with list of words from path""" self.path = path self.word_list = self.create_word_list() print(f"{len(self.word_list)} words read") def create_word_list(self): """Creates list of words from file at path""" word_list = [] try: with open(self.path) as file: for line in file: if line.endswith("\n"): word_list.append(line[:-1]) else: word_list.append(line) return word_list except OSError: print("Invalid file path") def random(self): """Returns a random word in list of words""" return choice(self.word_list) class SpecialWordFinder(WordFinder): def __init__(self, path): """Creates word finder that filters out empty spaces and #'s""" super().__init__(path) def create_word_list(self): """Filters empty spaces and #'s out of word list""" word_list = super().create_word_list() return [word for word in word_list if not word.startswith("#") and not word == ""]
afb849c33fd86658ae19945fd4190e7a0ac5ddcc
kouroshkarimi/LeNet-MNIST-Classification
/LeNet_predict.py
2,041
3.515625
4
# IMPORT PACKAGES import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import mnist import cv2 from tensorflow.keras import backend as K import numpy as np import tensorflow.keras.utils as util # PREPARING DATA print("[INFO] Downloading mnist dataset.") (train_images, train_labels), (test_images, test_labels) = mnist.load_data() if K.image_data_format() == "channels_first": train_images = train_images.reshape(train_images.shape[0], 1, 28, 28) test_images = test_images.reshape(test_images.shape[0], 1, 28, 28) else: train_images = train_images.reshape(train_images.shape[0], 28, 28, 1) test_images = test_images.reshape(test_images.shape[0], 28, 28, 1) train_images = train_images /255.0 test_images = test_images / 255.0 train_labels = util.to_categorical(train_labels, 10) test_labels = util.to_categorical(test_labels, 10) # LOAD MODEL SAVED AFTER TRAIN model = keras.models.load_model("LeMnist_model.h5") # A LOOP TO SHOW IMAGES AND OUR MODEL PREDICTION FOR THAT IMAGE for i in np.random.choice(np.arange(0, len(test_labels)), size=(10,)): # classify the digit probs = model.predict(test_images[np.newaxis, i]) prediction = probs.argmax(axis=1) # extract the image from the test_images if using "channels_first" # ordering if K.image_data_format() == "channels_first": image = (test_images[i][0] * 255).astype("uint8") # otherwise we are using "channels_last" ordering else: image = (test_images[i] * 255).astype("uint8") # merge the channels into one image image = cv2.merge([image] * 3) # resize the image from a 28 x 28 image to a 96 x 96 image so we # can better see it image = cv2.resize(image, (96 * 2, 96 * 2), interpolation=cv2.INTER_LINEAR) # show the image and prediction cv2.putText(image, str(prediction[0]), (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) print("[INFO] Predicted: {}, Actual: {}".format(prediction[0], np.argmax(test_labels[i]))) cv2.imshow("Digit", image) cv2.waitKey(0)
7f80db20f8bab60cb7726ce14365def14a151d5a
kutayakgn/Python_Poll_Analyzer
/CSE3063F20P2_GRP2_Iteration1/ReadFile.py
5,168
3.59375
4
# Read answer keys, student list and report files from Student import * from Question import * from xlrd import open_workbook from AnswerKey import * from Poll import * import csv class ReadFile: def __init__(self): self.students = [] self.allPolls = [] # Read answer key file def readAnswerKey(self, fileName): with open(fileName, 'r', encoding='utf-8') as file: keys = [] questions = [] reader = csv.reader(file) poll_name = "" is_first_line = True for row in reader: # Set the name of the poll if is_first_line: poll_name = row[0] is_first_line = False else: # Get question text and create Question questionKey = Question("".join(row[0].splitlines())) # for question with correct answers question = Question(row[0]) # to add the question to the poll without any answers given questions.append(question) # Create an answer key for the poll answer_key = AnswerKey(poll_name, questionKey, row[1: len(row)]) answer_key.trace() # Keep the answer keys keys.append(answer_key) if len(questions) != 0: if len(self.allPolls) == 0: poll = Poll(poll_name, keys, questions) poll.trace() self.allPolls.append(poll) elif self.allPolls[0].pollName != answer_key.poll_name: poll = Poll(poll_name, keys, questions) poll.trace() self.allPolls.append(poll) # Read student list def readStudentFile(self, fileName): wb = open_workbook(fileName) for sheet in wb.sheets(): number_of_rows = sheet.nrows number_of_columns = sheet.ncols for row in range(1, number_of_rows): values = [] for col in range(1, number_of_columns): value = sheet.cell(row, col).value if value != '': values.append(value) if values and type(values[0]) == float: # Create student if len(values) == 5: student = Student(values[1], values[2], values[3], values[4]) else: # if the description is empty student = Student(values[1], values[2], values[3], '') student.trace() # Keep the students self.students.append(student) return self.students # Read the report file def readReportFile(self, fileName,usedPolls): number = 0 with open(fileName, 'r', encoding='utf-8') as file: reader = csv.reader(file) poll1 = Poll("poll1", [], []) for row in reader: questions = [] for i in range(4, len(row) - 1): if i % 2 == 0: # Create a question and add the answer question = Question("".join(row[i].splitlines())) question.setAnswer(row[i + 1]) questions.append(question) poll1.questions.append(question) # find which student, and which poll then create that poll and add the student's polls for student in self.students: if student.checkStudent(row[1]): for poll in self.allPolls: if poll.checkPoll(questions): if poll.answerKeys[0].used==False: temp_poll=Poll(poll.pollName,poll.answerKeys,poll.questions) usedPolls.append(temp_poll) count=0 for poll in usedPolls: if poll.pollName==usedPolls[len(usedPolls) - 1].pollName: count=count+1 if poll.answerKeys[0].used == False: if count > 1: usedPolls[len(usedPolls)-1].pollName=usedPolls[len(usedPolls)-1].pollName+"-"+str(count) poll.answerKeys[0].used=True number = number + 1 temp = Poll(temp_poll.pollName,temp_poll.answerKeys,temp_poll.questions) temp.questions = poll1.questions temp.setDate(row[3]) student.addPoll(temp) poll1.questions = [] for poll in self.allPolls: poll.answerKeys[0].used=False
0df6221df1aa5b145a40866f3d7ac14081f81d89
milton9220/Python-basic-to-advance-tutorial-source-code
/twelveth.py
208
4.0625
4
#n=int(input("how many times you want to print:")) #i=1 #while i<=n: #print("Hellow World!") #i=i+1 n=int(input("enter number:")) sum=0 i=1 while i<=n: sum=sum+i i=i+1 print(sum)
368dd056a50e84c52b6128dd5e199b6b1c100599
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/aron/lesson08/test_circle.py
1,038
3.875
4
import unittest from .circle import * class MyTestCase(unittest.TestCase): def test_radius(self): c = Circle(4) self.assertEqual( c.radius, 4) def test_diameter(self): c = Circle(4) self.assertEqual(c.diameter, 8) c.diameter = 2 self.assertEqual(c.diameter, 2) self.assertEqual( c.radius, 1) def test_area(self): c = Circle(2) self.assertEqual(c.area, 12.566370) with self.assertRaises(AttributeError): c.area = 42 def test_from_diameter(self): c = Circle.from_diameter(8) self.assertEqual(c.diameter, 8) self.assertEqual(c.radius, 4) def test_print(self): c = Circle(4) self.assertEqual(str(c), "Circle with radius: 4") self.assertEqual(repr(c), "Circle(4)") print(c.__repr__()) def test_add(self): c1 = Circle(2) c2 = Circle(4) c3 = c1 + c2 self.assertEqual(c3.radius, 6) if __name__ == '__main__': unittest.main()
fafd7a28679e7bcc741c68ff2c10a171d4395cb7
ciecmoxia/moxiatest
/Month1/TCP_Server_outerloop.py
1,828
3.578125
4
# 网络的概念,五层:应用层(应用)、传输层(tcp、udp端口)、网络层(ip)、数据链路层(ethernet mac地址)、物理层(0和1) # tcp 的整个流程类似打电话的一个过程: import socket # 服务端: # a. 建立链接,买手机 tcp_server=socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 基于文件类型的套接字家族,名字:AF_UNIX,基于网络类型的套接字家族,名字:AF_INET ; SOCK_STREAM:TCP协议,Sock_DGRAM:UDP协议 tcp_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # b. 绑定电话卡 tcp_server.bind(("ip", 端口)) tcp_server.bind(('127.0.0.1',8000)) # c. 待机 tcp_server.listen(最大链接数) back_log=5 buffer_size=1024 tcp_server.listen(back_log) while True: # 链接循环,外层循环,保证服务端永久执行 # d. 接听电话 print('很高兴为大家服务!') conn,addr=tcp_server.accept()# 三次握手 没有数据,只是连接,合并了两次握手 #在此之前阻塞,等待信息 while True: # 通信循环,内层循环 try: # e. 接收消息 data=conn.recv(buffer_size) if not data: break # 客户端强制中断,linux会一直返回空给服务端,用if not data: break解决 # 客户端强制中断,windows会抛异常给服务端,用try\except解决 if data.decode('utf-8')=='exit': conn.send(data) break print('客户端说:',data.decode('utf-8'))# .encode('utf-8')改为.decode('utf-8') # f. 发消息 msg=input('>>: ').strip() if not msg: continue conn.send(msg.encode('utf-8')) except Exception as e: print('出现异常,异常信息为:',e) break # g. 挂电话,循环里接电话,一一对应 conn.close()# 四次挥手 考虑到有数据是否传完 # h. 关闭服务端手机关机 tcp_server.close()
f85ad26e411a7c927766de8cdf9fade761dd6ed9
Reshma262/Pythontutorials
/Regex1.py
298
4.125
4
#Check if a string contains only defined characters using Regex import re def check(str, pattern): if re.search(pattern, str): print("Valid String") else: print("Invalid String") pattern = re.compile('^[1234]+$') check('2134', pattern) check('349', pattern)
4eabf5ad76a3e493e12053c1944962a034fd74c1
swarnaprony/python_crash_course
/exercise_10/exercise_10_3.py
779
3.875
4
#exercise_10_3 #guest user_name = input('Write your name here: ') user_name_file = 'guest.txt' with open(user_name_file, 'a') as user_name_object: user_name_object.write(f"{user_name}\n") #exercise_10_4 #guest_book user_name_entry = "Enter your name: " user_name_entry += "if ypu finished with adding name write 'quit' to get out: " guest_user = '' while guest_user != 'quit': guest_user_list = 'guest_user_name_list.txt' with open(guest_user_list, 'a') as guest_user_object_all: if guest_user != 'quit': guest_user = input(user_name_entry) guest_user_object_all.write(f"{guest_user}\n") guest_user_object_all.write(f"Thanks for visiting us {guest_user}. \n") else: print('List is ready')
5b67f97b62c318177c18b11e16b2d7195c9e129f
benjamin22-314/codewars
/number-format.py
297
3.75
4
# https://www.codewars.com/kata/number-format def number_format(n): return format(n, ',') # tests print(number_format(-10)) print(number_format(100000) == "100,000") print(number_format(5678545) == "5,678,545") print(number_format(-420902) == "-420,902") print(number_format(-3) == "-3")
b54eb74e1d90a1b5f005f516963916b4eaf949de
Patrick-Heffernan/Mass-Emailing-Tool
/Autoemail.py
635
3.5625
4
import openpyxl, ezgmail wb = openpyxl.load_workbook('Email Addresses.xlsx') sheet = wb['Sheet1'] emails = {} #Make the excel data into a dictionary for i in range(1,sheet.max_row-1): name = sheet.cell(i, 1).value email_address = sheet.cell(i,2).value emails[name] = email_address subject = "Testing!" #Insert subject to your email for k, v in emails.items(): #Loop through the dictionary data and send email to each address with the corresponding name sendTo = v content = "Hello, " + str(k) + ". This is a test" #Insert the content of your email ezgmail.send(sendTo, subject, content)
14faac596d6e8f4abe545956af721337432c8e38
ahmadradmehr/Assorted-Python-Problems
/LongestSubstringWithoutRepeatingCharacters.py
1,030
3.953125
4
""" Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class LengthOfLongestSubstring(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ dic = {} l = r = max_length = 0 while r < len(s) and l <= len(s)-max_length: if s[r] in dic and dic[s[r]] == 1: dic[s[l]] -= 1 l += 1 else: dic[s[r]] = 1 max_length = max(max_length, r - l + 1) r += 1 return max_length
ed25b1e8f5be95cea13165622a8e9cae0f074704
andreaton/kids-code
/Silvia/.idea/hi.py
781
4.03125
4
import math #print("Hello, world!") #name=input("What's your name? ") #print("your name is "+name) area=TriangoloArea(76,4) print (str(area)) area=TriangoloArea(89,5) print (str(area)) perimetro=TriangoloPer(57,14,29) print (str(perimetro)) #base=input("Give me the base of a triangle ") #height=input("Give me the height of a triangle ") #area=float(base)*float(height)/2 #print(str(area)+" is the area of the triangle.") #list=[3,5.667,9,10,1] #print(list) #sum=sum(list) #print(sum) #truncate=math.trunc(sum) #print(truncate) #a=math.pow(2, 3) #b=4**3 #print(a) #print(b) #x=4 #y=9 #z=100 #print(math.sqrt(x)) #print(math.sqrt(y)) #print(math.sqrt(z)) #myfile=open("c:\\temp\\silvia.txt",'w') #myfile.write("This is Silvia's file"+str(x)+str(y)+str(z))
2534b8c987dce17f3007ddf87504e80baaef8d4e
JohannesBuchner/pystrict3
/tests/data23/recipe-579042.py
1,034
4.375
4
""" dunderdoc.py A Python function to print the .__doc__ attribute (i.e. the docstring) of each item in a list of names given as the argument. The function is called dunderdoc because it is an informal convention in the Python community to call attributes such as __name__, that begin and end with a double underscore, dunder-name, and so on. Author: Vasudev Ram - http://www.dancingbison.com Copyright 2015 Vasudev Ram """ def dunderdoc(names): for name in names: print('-' * 72) print(name + '.__doc__:') print(eval(name).__doc__) print('-' * 72) # Call dunderdoc() on some basic objects: a = 1 # an integer b = 'abc' # a string c = False # a boolean d = () # a tuple e = [] # a list f = {} # a dict g = set() # a set dunderdoc(('a', 'b', 'c', 'd', 'e', 'f', 'g')) # Call dunderdoc() on some user-defined objects: class Foo(object): """ A class that implements Foo instances. """ def bar(args): """ A function that implements bar functionality. """ dunderdoc(['Foo', 'bar'])
389498db31a2e1907ccf0ec38995cfd26dc5ae20
taurusyuan/python
/03_function/hm_06_函数的返回值.py
287
3.59375
4
def sum_2_num(num1, num2): sum = num1 + num2 return sum # 注意:return 就表示返回,与return缩进相同格数的下方的代码不会被执行到! result = sum_2_num(50,20) # 使用变量来接受函数执行的返回结果 print("计算结果:%d" % result)
ebe5578369ad2ddd67a53ba297a97ee8d2fb9558
GunjanMA/LSB-Steganographic-Algorithm
/steganography.py
989
3.921875
4
import sys import image_merge as image import hide_text as text def main(): if(len(sys.argv) > 2): steg(sys.argv[1], sys.argv[2]) else: desteg(sys.argv[1]) def steg(cover_path, hidden_path): ''' Function to hide data (either an image or text) within another image INPUT: string, path to the cover image; string, path to the hidden data OUTPUT: a new image with the hidden data encoded in the least significant bits ''' if hidden_path[-4:] == '.txt': text.encrypt(cover_path, hidden_path) else: image.merge(cover_path, hidden_path) def desteg(image_path): ''' Function to decode hidden data in an image INPUT: string, path to the coded image OUTPUT: If hidden data is an image, the hidden image is saved. If hidden data is text, the text is saved. ''' try: text.decrypt(image_path) except: image.unmerge(image_path) if __name__ == "__main__": main()
c609060f9520c0490c6bb7fcd1e4dcb59548906f
peeyush1999/p3
/Python Tutorial Sheet/Recursion tutorial sheet/recursion_13.py
388
3.578125
4
def revArray(mylist,start,end): if(end<start): return mylist temp = mylist[start] mylist[start] = mylist[end] mylist[end] = temp return revArray(mylist,start+1,end-1) num = int(input()) inputs = input().split(' ') for i in range(num): inputs[i] = int(inputs[i]) print(revArray(inputs,0,len(inputs)-1))
67bdc887c59bdf2d8be5ea18f52b6f70dc0e50fd
iampkuhz/OnlineJudge_cpp
/leetcode/python/passedProblems/144-binary-tree-preorder-traversal.py
1,111
4.25
4
#!/usr/bin/env python # encoding: utf-8 """ Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # iter,看答案,2次过,第一次对齐错误 class Solution(object): def preorderTraversal(self, root): ans, nds = [], [root] while len(nds) > 0: nd = nds.pop() while nd: if nd.right != None: nds.append(nd.right) ans.append(nd.val) nd = nd.left return ans # 一次过,简单,dfs class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ re = [] def dfs(node): if node == None: return re.append(node.val) dfs(node.left) dfs(node.right) dfs(root) return re
f9b4f7565a7511d9d2d27419501b7ebf7fc69013
d-lan2/PythonExampleProject
/src/modules/module.py
512
3.71875
4
"""An example python module""" from typing import List import requests #Dynamic typing def total(x,y): """Returns the sum of xs""" return x + y #Static typing (really just type hints) see https://docs.python.org/3/library/typing.html def listTotal(xs: List[float]) -> float: result: float = 0.0 for x in xs: result += x return result def getResponseCode(): r = requests.get("https://www.google.com") return r.status_code def getRequest(url): return requests.get(url)
d67928afcf6545b4c6b4f0577329f1c250588407
IrenaeusChan/DNA-Sequence-Analysis
/s_complex.py
4,740
3.859375
4
""" String Complexiy Calculations 3 Methods: Standard Bit Compression Ratio Shannon's Entropy Evolutionairy Method (Randomly Generating String) by Irenaeus Chan """ import sys import string import random import zlib import csv import bisect from math import log def weightedChoice(choices): """ Raymond Hettinger - http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice """ values, weights = zip(*choices) total = 0 cum_weights = [] for w in weights: total += w cum_weights.append(total) x = random.random()*total i = bisect.bisect(cum_weights, x) return values[i] def bitCompress(s): """ Compares the ratio of the compressed string to its original bit size by Irenaeus Chan """ if (len(s) == 0): return 0; else: return float(len(zlib.compress(s)))/len(s); #Standard Compression def entropyInBits(S): """ Compute entropy of a string, on a per-character basis. by Eddie Ma """ if (len(S) == 0): return 0; D = len(S) #Denominator N = {} #Numerators Dictionary, of (Key, Value) for s in S: if s not in N: N[s] = 0 #If the Char is "new". Create a New Spot for it N[s] += 1 #Adds 1 to the Character Count p = lambda(s): 1.*N[s]/D """Creates a function P(x) = 1.*N[x]/D 1.* converts the entire value into a float. Same as N[s]/float(D) This is the probability of the character appearing in the String""" return -sum([p(s)*log(p(s), 2) for s in N]) #Find the Entropy Summation for every character seen in the String def evolution(s): """ Creates a skeleton string and attempts to randomly build the string using Weighted Averages. Tries to build the string Character by Character (Faster) by Irenaeus Chan """ if (len(s) == 0): return 0 s = s.upper(); """ Creating the Weighted Averages to use for Random Selection """ N = {} #Numerators Dictionary, of (Key, Value) for char in s: if char not in N: N[char] = 0 #If the Char is "new". Create a New Spot for it N[char] += 1 skeleton = list(''.join('0') for i in xrange(len(s))); #Creates the skeleton e.g. GATTACA = 000000 complexity_count = 0; used = []; for i in xrange(len(skeleton)): del used[:] c = ''.join([weightedChoice(dict.items(N))]); #Randomly chooses a character from the dictionary used.append(c); while True: """ Keeps randomly changing each character until the character matches the original string Once the character finally matches the original string character, moves on to the next character Only ends once it iterates over every single character in the Skeleton String """ complexity_count += 1; if (c == s[i]): skeleton[i] = c; break; c = ''.join([weightedChoice(dict.items(N))]); while (c in used): #Ensures no repeats c = ''.join([weightedChoice(dict.items(N))]); used.append(c); complexity_count = 1.*complexity_count/len(s) return complexity_count; #Return how many iterations it took to create the word def readFile(file_name): seq = [] with open(file_name, "r") as stream: for i, line in enumerate(csv.reader(stream, delimiter=",")): seq.append(line) return seq if __name__ == "__main__": if len(sys.argv) < 2: print "ERROR: Please provide a file:" print "\tTaxon, Process ID, Sample ID, DNA Sequence" print "\tDeliminted by Commas" sys.exit(1) tags = readFile(sys.argv[1]); with open("output.txt", "w") as output: for i, line in enumerate(tags): #print tags[i][0] + " " + tags[i][1] + " " + tags[i][2] #print bitCompress(tags[i][3]), entropyInBits(tags[i][3]), evolution(tags[i][3]) value = str(bitCompress(tags[i][3])) + " " + str(entropyInBits(tags[i][3])) + " " + str(evolution(tags[i][3])) + "\n" print tags[i][0] + " " + tags[i][1] + " " + tags[i][2] + " " + value output.write(tags[i][0] + " " + tags[i][1] + " " + tags[i][2] + " " + value)
614d996694c53ed79255931dc0a8ae20282f2265
JackPMX/leetcode-practice
/algorithm/1047. 删除字符串中的所有相邻重复项/case2.py
338
3.78125
4
class Solution: def removeDuplicates(self, S: str) -> str: hStack = list() for char in S: if(hStack and hStack[-1] == char): hStack.pop() else: hStack.append(char) return "".join(hStack) s = Solution() sstr = "abccbdef" print(s.removeDuplicates(sstr))
7be1c15f35c7097c85375b3fe530504bc9e3eecf
RookieWangXF/py-basic
/basic/list.py
414
4.03125
4
# list 可变的有序集合 classmates = ['Tom','Mike','Bob'] print(classmates) print(len(classmates)) print(classmates[0]) print(classmates[2]) print(classmates[-1]) classmates.append('Adam') print(classmates) classmates.insert(1, 'Jack') print(classmates) classmates.pop(1) print(classmates) # tuple 不可变的无序集合 t = (1, 2, 3, 4, 5) print(t) t = ('a', 'b', ['A', 'B']) t[2][0]='c' print(t[0][0])
592469e599587b3de0a292d3ee09dbda0064346e
Raghavkhandelwal7/help-me-
/swappingfile.py
409
3.65625
4
def swapfileData(): filename1=input("Enter the file name: ") filename2=input("Enter the file name to be swapped: ") with open(filename1,'r') as a: data_a = a.read with open(filename2,'r') as b: data_b = b.read with open(filename1,'w') as a: data_b = a.write(filename2) with open(filename2,'w') as b: data_a = b.write(filename1) swapfileData()
c1f675174216904835fdad2b24df9870a5516f46
Zachary-Jackson/Secret-Messages
/ciphers/cipher.py
1,256
4.0625
4
import os import string class Cipher: """This is a base template class for a cipher""" @classmethod def clear(cls): """This method clears the screen for easier reading and use""" os.system('cls' if os.name == 'nt' else 'clear') def encryption(self, *args, **kwargs): raise NotImplementedError() def decryption(self, *args, **kwargs): raise NotImplementedError() def get_user_message(self): """ Gets the user's encryption/decryption message Ensures that no punctuation or digits are in the message :return: a message string """ digits_and_punctuation = string.digits + string.punctuation while True: message = input('Please enter a message to encrypt\n\n') # check if a digit or number is in message invalid_characters = False for char in digits_and_punctuation: if char in message: invalid_characters = True break if not invalid_characters: return message # Prepare the user for another message self.clear() print('Digits and Punctuation (234 (*&) are not allowed')
87ac289924683d12e5d5ebbf0f9c87edaed32afc
itsanjan/advent-of-code
/2018/day1/base.py
497
3.6875
4
with open('input.txt') as inputfile: changes = list(map(int, inputfile.readlines())) print(changes) #---P1 current_frequency=0 for change in changes: current_frequency += change print(current_frequency) #----P2 change=0 observed=set() current_frequency=0 while True: for change in changes: current_frequency +=int(change) if current_frequency in observed: print(current_frequency) quit() observed.add(current_frequency)
b91dca32a7b2c091da236384300b109efc0acdf3
Terrub/RLA
/src/app/world.py
1,653
3.625
4
# coding=utf-8 """ The world object """ from math import pi, sin class Tile: """ The World tile class """ def __init__(self, p_type, p_id): """ Constructor """ self.type = p_type self.id = p_id class World: """ The world class """ def __init__(self, randomiser, width, height): """ Constructor """ self.height = width self.width = height self.randomiser = randomiser self.tiles = {} @staticmethod def _create_tile(randomiser, key, h, y): """ Creates a tile for given key, height and y position. """ tile_type = World._calculate_tile_type(randomiser, h, y) tile = Tile(p_type=tile_type, p_id=key) return tile @staticmethod def _calculate_tile_type(randomiser, h, y): """ Returns the tile type based on local algorithm and given params. """ p = randomiser.random() tile_type = 'grass' if p < sin(y / h * pi) else 'stone' return tile_type def get_tile_key_from(self, x, y, z): """ Returns the tile key for given coordinates. """ h = self.height w = self.width return (z * h * w) + (y * w) + x def get_tile_at(self, key, y): """ Returns tile info for given coordinates. """ tiles = self.tiles if key not in tiles: height = self.height randomiser = self.randomiser tiles[key] = World._create_tile(randomiser, key, height, y) tile = tiles[key] return tile
0fd470377430f7f1b951a348fdcb9d04685b4a70
ColdGrub1384/Pyto
/Pyto/Samples/SciKit-Image/plot_random_shapes.py
2,049
3.921875
4
""" ============= Random Shapes ============= Example of generating random shapes with particular properties. """ import matplotlib.pyplot as plt from skimage.draw import random_shapes # Let's start simple and generate a 128x128 image # with a single grayscale rectangle. result = random_shapes((128, 128), max_shapes=1, shape='rectangle', multichannel=False) # We get back a tuple consisting of (1) the image with the generated shapes # and (2) a list of label tuples with the kind of shape (e.g. circle, # rectangle) and ((r0, r1), (c0, c1)) coordinates. image, labels = result print('Image shape: {}\nLabels: {}'.format(image.shape, labels)) # We can visualize the images. fig, axes = plt.subplots(nrows=2, ncols=3) ax = axes.ravel() ax[0].imshow(image, cmap='gray') ax[0].set_title('Grayscale shape') # The generated images can be much more complex. For example, let's try many # shapes of any color. If we want the colors to be particularly light, we can # set the `intensity_range` to an upper subrange of (0,255). image1, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((100, 255),)) # Moar :) image2, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((200, 255),)) image3, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((50, 255),)) image4, _ = random_shapes((128, 128), max_shapes=10, intensity_range=((0, 255),)) for i, image in enumerate([image1, image2, image3, image4], 1): ax[i].imshow(image) ax[i].set_title('Colored shapes, #{}'.format(i-1)) # These shapes are well suited to test segmentation algorithms. Often, we # want shapes to overlap to test the algorithm. This is also possible: image, _ = random_shapes((128, 128), min_shapes=5, max_shapes=10, min_size=20, allow_overlap=True) ax[5].imshow(image) ax[5].set_title('Overlapping shapes') for a in ax: a.set_xticklabels([]) a.set_yticklabels([]) plt.show()
74f92c768d6ec3e7766a73af03201626575650d3
navroopbath/coding-exercises
/Mergesort.py
2,036
4.25
4
import unittest class Mergesort: ''' Given an array of ints arr as input, return arr in ascending sorted order. ''' @staticmethod def mergesort(arr): if (arr != None): return Mergesort.recursive_mergesort(arr) else: return None ''' Starts the mergesort in a recursive manner. ''' @staticmethod def recursive_mergesort(arr): if len(arr) == 0: # an empty array is already 'sorted' so return it return [] if len(arr) == 1: # an array with one element is sorted so return it return arr mid = len(arr)/2 # recursively sort both the left and right halves of the array left_merge = Mergesort.recursive_mergesort(arr[0:mid]) right_merge = Mergesort.recursive_mergesort(arr[mid:len(arr)]) sorted_arr = [] # grab the first element from left_merge, right_merge, compare them, # and insert the smaller element into sorted_arr, and pop the smaller element while len(left_merge) > 0 and len(right_merge) > 0: left_item = left_merge[0] right_item = right_merge[0] if left_item <= right_item: sorted_arr.append(left_item) left_merge.pop(0) else: sorted_arr.append(right_item) right_merge.pop(0) if len(left_merge) > 0: sorted_arr += left_merge if len(right_merge) > 0: sorted_arr += right_merge return sorted_arr class TestMergeSortMethods(unittest.TestCase): def test_edge_case_empty_array(self): test_arr = [] self.assertEqual(Mergesort.mergesort(test_arr), []) def test_edge_case_null_array(self): self.assertEqual(Mergesort.mergesort(None), None) def test_length_ten_array(self): test_arr = [5, 1, 4, 3, 10, 17, 18, 6, 20, 9] self.assertEqual(Mergesort.mergesort(test_arr), [1, 3, 4, 5, 6, 9, 10, 17, 18, 20]) if __name__ == '__main__': unittest.main()
4bdd9f24cd67cca3c2d6c9d2a3ad09248e38a96a
sirjanaghimire/ProjectWork_Infotek
/python_practice/8_OOPS_python/Z12_inharitance.py
959
3.875
4
class phone: def __init__(self, brand,model_name,price): self.brand = brand self.model_name = model_name self.price = price def full_name(self): return f"{self.brand} {self.model_name}" def make_a_call(self,number): return f"calling {number}....." class smartphone(phone): def __init__(self,brand, model_name, price, ram, internal_memory,rear_camera): phone.__init__(self,brand, model_name, price) # super().__init__(brand,model_name,price) self.ram = ram self.internal_memory = internal_memory self.rear_camera = rear_camera p1=phone('nokia','1100',10000) p2=smartphone('oneplus','5',30000,8,'6 GB','20 MP') print(p1.full_name()) print(p2.full_name()) # class phone: # def __init__(self,name): # self.name = name # def m1(self): # print("i am here") # class smartphone(phone): # p1=phone('sirjana') # p1.m1()
da82412c887586880363bc465d52c77c6cf0f8f3
emilianoNM/Tecnicas3-2
/Repo23.py
256
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Area del Circulo def areaCirculo(): print "..:Area del Circulo:.." tmp = int(raw_input(">Dame el radio del circulo: ")) print "> El area del circulo es: ", (3.1416) * tmp * tmp areaCirculo()
6938c72561cc4160ef178889d818a70c472f5279
sj43/Code-Storage
/DailyCodingProblem/FlightItineraryProblem.py
513
3.78125
4
def get_itinerary(flights, flight_plan): if not flights: return flight_plan last_stop = flight_plan[-1] for i, (coming_from, going_to) in enumerate(flights): flight_minus_current = flights[:i] + flights[i+1:] flight_plan.append(going_to) if coming_from == last_stop: return get_itinerary(flight_minus_current, flight_plan) flight_plan.pop() return None print(get_itinerary([('HNL','AKL'),('YUL','ORD'),('ORD','SFO'),('SFO','HNL')],['YUL']))
4c5822a04d7b04e09d5a28a233a089344a89e369
RonnyCaicedoV/Exposicion
/basicoo.py
4,906
3.796875
4
from ast import Num class Basico: def numerosN(n1): n1= int(input("Escriba numero de n: ")) print("Los numeros de 1 a n son: ") for x in range(1,n1+1): print(x, end=" ") def numerosNsuma(n): n= int(input("Escriba el valor de n: ")) suma= n * (n + 1)/2 print(suma) def multiplo(numero,multip): numero= int(input("Digite el primer numero: ")) multip= int(input("Digite el segundo numero: ")) if numero % multip == 0: print("El numero {} si es multiplo de {} ".format(numero,multip)) else: print("El numero {} no es multiplo de {} ".format(numero,multip)) def DivisoresNumero(numero): conta_divisores= 0 numero= int(input("Digite su numero: ")) for i in range(1, numero + 1): if numero % i == 0: conta_divisores +=1 return conta_divisores def primo(numero): numero = int(input("Digite el numero: ")) esPrimo = True for c in range (2,numero): if numero%c==0: esPrimo= False break if esPrimo: print("El numero {} es primo".format(numero)) else: print("El numero {} no es primo".format(numero)) def perfecto(numero): suma = 0 numero = int(input("Digite un numero: ")) print("El numero es perfecto?: ") for d in range(1, numero): if numero % d == 0: suma += d return suma == numero class Intermedio (Basico): def numerosN(n): for x in range(1,n+1): return x def factorial(numero): numero = int(input("Digite un numero: ")) factorial=1 if numero != 0: for a in range(1,numero+1): factorial= factorial*a print("Factorial: ", factorial) def fibonacci(n): limite = int(input("Escriba su limite: ")) a = 1 b = 0 for s in range(0, limite): b = b+a a = b-a print(a, end=" ") def primosGemelos(num1,num2): comprobar= True while comprobar: num1 = int(input("Ingrese el primer numero: ")) num2 = int(input("Ingrese el segundo numero: ")) a=0 if num1 > 0 and num2 > 0 and num1 != num2: comprobar = False if num1 > num2: num1 ^= num2 num2 ^= num1 num1 ^= num2 for i in range (num1, num2+1): creciente = 2 esPrimo = True while esPrimo and creciente < i: if i % creciente == 0: esPrimo = False else: creciente +=1 if esPrimo and not a: a = i elif esPrimo and a: b = i if b-a ==2: print(a, "y",b, "Son primos gemelos") a = i else: if num1 == num2: print ("Los numeros son iguales. Intente de nuevo..") else: print ("Los numeros no son correctos, intente de nuevo...") def amigos (num1, num2): num1 = int(input("Ingrese el primer numero: ")) num2 = int(input("Ingrese el segundo numero: ")) vec_1=[] vec_2= [] sum_1= 0 sum_2= 0 for i in range (1,num1): if num1 % i == 0: vec_1.append(i) for i in range(1,num2): if num2 % i == 0: vec_2.append(i) for k in vec_1: sum_1= sum_1 + k for k in vec_2: sum_2= sum_2 + k if sum_1 == num2 and sum_2 == sum_1: print("Los numeros son amigos") else: print("Los numeros no son amigos") """ Nnum = Basico() print(Nnum.numerosN()) """ """ sumN= Basico() sumN.numerosNsuma() """ """ multi= Basico() multi.multiplo() """ """ divi = Basico() print(divi.DivisoresNumero()) """ """ prim= Basico() prim.primo()""" """ Fact = Intermedio() Fact.factorial() """ """ perfec= Basico() perfec.perfecto() """ """ fibo= Intermedio() fibo.fibonacci() """ """ priGem= Intermedio() priGem.primosGemelos(()) """ """ ami= Intermedio() ami.amigos(()) """
91e19b53296c8e5b1cc0eb16983b08516715fda8
FullStackToro/Bank_Account
/main.py
1,022
3.796875
4
if __name__ == '__main__': class bankAccount: def __init__(self, interes): self.interes = interes self.saldo=0 def deposito(self, monto): self.saldo += monto return self def retiro(self, monto): if self.saldo >= monto: self.saldo -= monto elif monto>self.saldo: print('Fondos insuficientes: cobrar una tarifa de $5') self.saldo -= 5 return self def accountInfo(self): print('*'*45, '\n Interés:', self.interes, '%' '\n Saldo: $', self.saldo, '\n', '*'*44,) return self def tasa_interes(self): self.saldo = self.saldo+self.saldo*self.interes/100 return self c1=bankAccount(2) c2=bankAccount(1.5) c1.deposito(2000).deposito(4000).deposito(5000).retiro(1000).tasa_interes().accountInfo() c2.deposito(12000).deposito(34000).retiro(5000).retiro(1000).tasa_interes().accountInfo()
ffdd499623b49422c8f34b068734a3c72af349e8
dodmaneaditya/python_code
/python_basics/scalar_type_and_values.py
1,274
3.609375
4
''' Author : Aditya Hegde Description : Demo on Scalar Types : integer, float, string & Boolean Date: ''' print("\n ----------- Demo on Integer Type ------------------ \n") a = 10 b = 0b10 #binary c = 0o10 #octal d = 0x10 #hexa decimal e = int(10.5) #decimal to int f = int(-3.5) g = int("105") # from string to int print("Integer Value: \n", a, "\n", b, "\n", c, "\n", d, "\n", e, "\n", f, "\n", g) print("\n ----------- Demo on Floating Type ------------------ \n") f1= 20.5 f2 = 3e4 f3 = 1.564e-20 f4 = float(10) f5 = float("1.564") f6 = float("nan") f7 = float("inf") f8 = float("-inf") f9 = 1.5 + 1 print("\n Floating Values: \n", f1, "\n", f2, "\n", f3, "\n", f4, "\n", f5, "\n",f6, "\n", f7, "\n", f8, "\n",f9) print("\n----Demo on None-------\n") n1 = None # Assigns a null value print("n1 is:") print(n1 is None) print("\n-----------------Demo on Bool----------------\n") # bool() function returns either TRUE or FALSE value b1 = bool(0) b2 = bool(41) b3 = bool(-19) b4 = bool(0.0) b5 = bool(0.3) b6 = bool([]) b7 = bool([1,2,3]) b8 = bool("") b9 = bool("aditya") print("\n Boolean Values are: \n", True, "\n", False,"\n", b1, "\n",b2, "\n", b3,"\n", b4, "\n", b5, "\n", b6, "\n", b7, "\n", b8, "\n" , b9)
0d3a5ee621d662558770852b8981f1f3dd20b16d
lensabillion/CS487
/RangeSumOfBST.py
670
3.59375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rangeSumBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: int """ def sum(node): if not node: return 0 if node.val < L: return sum(node.right) if node.val > R: return sum(node.left) return node.val + sum(node.left)+ sum(node.right) return sum(root)
3d6e2e5a3822b8012a0e87db42c50bd2b950b554
HwangYoungHa/ComputerNetwork
/chatbot/practice2.py
329
3.515625
4
import requests # request를 통해 api에 요청 params = {'param1': 'value1', 'param2': 'value'} response = requests.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,JPY,EUR', params=params) # 요청한 data를 slicing s = str(response.text)[7:15] usd = float(s) # 출력 print("USD :", usd)
bc25110ad1ebde0cc1bfa88d68c7d970913ef2aa
marth00165/pythonBasics
/lesson5.py
1,163
4.34375
4
from math import * # You can import functions from libraries this enables the math library print("You can print numbers") print(2) # You Can Print numbers print("") print("Numbers can be whole or decimal numbers") print(3.14) # You Can Print Whole or Decimal numbers print("") print("You can print strings along with numbers", 7) print("") print("You can also do basic math", 3+7) # You can add, subtract, multiply, divide anything you want print("") print("You can adjust the order of operations", 3*4+5) print("By using parenthesis", 3*(4+5)) print("") print("You can use Mod operations", 10 % 3) print("") num_1 = 7 print("You can store numbers as variables", num_1) print("") print("You can convert numbers into strings: #" + str(num_1) + " is Brandon Roy's Jersey Number") print("") print("You can use different Math Functions on numbers") num_2 = -5 print("This prints the absolute value: " + str(abs(num_2)) + "\n") # notice how I'm able to use the str() method before the abs() method! print("This is a power function:", pow(3, 2)) print("") print("There are many math functions you can find them at: https://docs.python.org/3/library/math.html ")
5c18e189034c7627712973a66b9f64ef1ddb1d8e
hamidswer/recursive-factorial
/recursive-factorial.py
181
3.828125
4
def recursive_factorial(n): if (n==1): factorial = 1 else: factorial = n * recursive_factorial(n-1) return factorial print(recursive_factorial(4)) # 24
25d8686edf010b02b7a68b6942ec4bf92c08895e
gwyrwch/math-methods-labs
/OutputMethods.py
990
3.765625
4
class OutputMethods: @staticmethod def print_matrix(matrix): for line in matrix: print([round(el, 3) for el in line]) print() @staticmethod def print_system(matrix): for line in matrix: print('[', end='') for el in line[:-1]: print("{:6.3f}".format(el), end=' ') print(']', '|', [round(line[-1], 3)]) print() @staticmethod def get_answer(matrix_x): out = [] for line in matrix_x: out += [line[-1]] print('answer: ', [round(el, 3) for el in out]) @staticmethod def print_extended_matrix(matrix): for line in matrix: print('[', end='') for el in line[:len(line) // 2]: print("{:6.3f}".format(el), end=' ') print('|', end=' ') for el in line[len(line) // 2:]: print("{:6.3f}".format(el), end=' ') print(']') print()
99929ee87ac4f4c0e409134de31992298471c23a
Artembbk/fmsh
/Python/xo_game.py
2,103
3.78125
4
from graph import * FIELD_S = 300 SQUARE_S = 100 X_FIELD = 100 Y_FIELD = 100 move = 0 squares = [[0]*3 for i in range(3)] def square(x, y, a): return rectangle(x, y, x+a, y+a) def cross(x, y, a): line(x, y, x+a, y+a) line(x+a, y, x, y+a) def init(): penColor("black") for i in range(3): for j in range(3): squares[i][j] = square(X_FIELD + SQUARE_S*j, Y_FIELD + SQUARE_S*i, SQUARE_S) penSize(3) def hit(x, y, obj): x1, y1, x2, y2 = coords(obj) return (x1 <= x <= x2) and (y1 <= y <= y2) def check(): A = [[0]*3 for i in range(8)] for i in range(3): A[6][i] = squares[i][i] A[7][i] = squares[i][2-i] for j in range(3): A[i][j] = squares[i][j] A[j+3][i] = squares[i][j] for L in A: if L[0] == L[1] == L[2]: return True def finish_game(w): if w == 1: label("Победили крестики!", 100, 60) elif w == 0: label("Победили нолики!", 100, 60) else: label("Ничья!", 100, 60) for i in range(3): for j in range(3): if type(squares[i][j]) == int: squares[i][j] = "W" def mouseClick(event): global move for i in range(3): for j in range(3): if type(squares[i][j]) == int: if hit(event.x, event.y, squares[i][j]): move += 1 x1, y1, x2, y2 = coords(squares[i][j]) if move % 2 == 1: penColor("red") cross(x1 + SQUARE_S//10, y1 + SQUARE_S//10, (SQUARE_S*8)//10) squares[i][j] = "X" else: penColor("blue") circle(x1 + SQUARE_S//2, y1 + SQUARE_S//2, SQUARE_S//2 - SQUARE_S//10) squares[i][j] = "O" if check() and move % 2 == 1: finish_game(1) elif check() and move % 2 == 0: finish_game(0) elif move == 9: finish_game(2) init() onMouseClick(mouseClick) run()
9b8e0f984188488c447eeb2da69408c199eeb469
mrtomrichy/PiMote
/examples/PiFace/pifaceexample.py
1,213
3.90625
4
''' An example application to toggle the LED's on a PiFace Written by Tom Richardson 2013 To run, type 'python pifaceexample.py' It will run on the Pi's local IP on port 8090 ''' import pifacedigitalio as p from pimote import * # Initialize PiFace p.init() pfd = p.PiFaceDigital() class MyPhone(Phone): # Override to get messages sent from phone def buttonPressed(self, id, message, phoneId): global pfd global buttons j = 0 # Loop through buttons for j in range(0, 8): if buttons[j].getId() == id: # Change the LED self.changeLed(pfd, j, buttons[j]) #Used to turn an LED on or off depending on input def changeLed(self, pfd, led, b): if b.getValue(): pfd.leds[led].turn_on() else: pfd.leds[led].turn_off() # Create the phone object thisphone = MyPhone() thisphone.setTitle("PiFace Control") # A list to hold all the buttons (saves 8 variables) buttons = [] i=0 # Create all buttons (one for each LED) and add to phone for i in range(0, 8): b = ToggleButton("Toggle LED " + str(i), False) buttons.append(b) thisphone.add(b) # Create the server myserver = PhoneServer() # Add the phone myserver.addPhone(thisphone) # Start server myserver.startServer("0.0.0.0", 8090)
5e6acc130314653495c28934f20cfef9ffa1a778
Crush-on-IT/algorithm-study
/src/Shortest Path/1753_최단경로/백준_1753_최단경로_Screwlim.py
1,082
3.515625
4
import heapq import sys INF = int(1e9) V, E = map(int, sys.stdin.readline().split()) start_node = int(sys.stdin.readline()) graph = [[]for i in range(V+1)] distance = [INF] *(V+1) for _ in range(E): s_node, d_node, weight = map(int, sys.stdin.readline().split()) graph[s_node].append((d_node, weight)) def dijkstra(start): global graph, distance q = [] heapq.heappush(q, (0, start)) distance[start] = 0 while q: print(q) dist, now = heapq.heappop(q) if distance[now] < dist: #현재 저장된 최단거리 vs 이전에 저장된 최단거리 print("hey!", end=" ") print(distance[now], dist) continue for i in graph[now]: #각 인접한 node의 거리 확인 cost = dist + i[1] if cost < distance[i[0]]: distance[i[0]] = cost print(cost, i[0]) heapq.heappush(q, (cost, i[0])) dijkstra(start_node) for i in range(1, V+1): if distance[i] == INF: print("INF") else: print(distance[i])
63870e0b5dad088ed29995cd03df35a5cc739a1e
codio-content/Coding_with_Python-Loops
/content/2-loops/utility.py
486
4.0625
4
counter = 1 # This is a 'counter' variable. total = 0 # This is out utility variable 'totla' while counter <= 10: # If the condition is true, it enters the loop total = total + counter # We add the current value of 'counter' to 'total' counter = counter + 1 # Here we add 1 to the counter. # This is known as 'incrementing' the counter. print(total) # And finally, we output 'total'
ac4cffbbfa06716170b17efd00f2645797dd616d
v1ktos/Python_RTU_08_20
/Diena_1_4_thonny/while.py
800
4.03125
4
# print("Hello") # print("Hello") i = 0 while i < 5: print("Hello No.", i) i += 1 print("Always happens once loop is finished") print("i is now", i) i = 10 while i > 0: print("Going down the floor:", i) # i could do more stuff i -= 2 print("Whew we are done with this i:", i) i = 20 while True: print("i is",i) if i > 28: break i += 2 while True: res = input("Enter number or q to quit ") if res == "q": print("No more calculations today") break elif res == "a": # TODO check if if the input is text print("I can't cube a letter a") continue # means we are not going to try to convert "a" to float num = float(res) print(f"My calculator says cube of {num} is {num**3}") print("All done whew!")
9f0c6c844d916d2658e2aa87dd76fd57d4fa1e45
shabbirkhan0015/python_programs
/inheritance2.py
844
3.828125
4
class shirt: def __init__(self,color,brand): self.color=color self.brand=brand print("color:",self.color) print('brand:',self.brand) class formalwear(shirt): def __init__(self,color,brand,slimfit,dottedOrNot): shirt.__init__(self,color,brand) self.slimfit=slimfit self.dottedOrNot=dottedOrNot class causalwear(shirt): def __init__(self,color,brand,sleeve,multicolor): shirt.__init__(self,color,brand) self.sleeve=sleeve self.multicolor=multicolor class partywear(shirt): def __init__(self,color,brand,shining,collar): shirt.__init__(self,color,brand) self.shining=shining self.collar=collar print("shining or not:",self.shining) print('collar type:',self.collar) p1=partywear("RED","louis phillipe","YES","round")
e1a2b90eeb05362462bb241a9a82606a8a3cda7c
Arthur-Lucifer/Python
/类与对象.py
1,196
3.828125
4
# class Circle: # radius = 0 # def __init__(self,radius): # self.radius = radius # def CircleArea(self): # return self.radius**2*3.1415926 # def CirclePerimeter(self): # return 2*3.1415926*self.radius # for i in range (1,11): # c = Circle(i) # print("半径为",i,"的圆,",end='') # print('面积:',format(c.CircleArea(),'.2f'),end='') # print('周长:',format(c.CirclePerimeter(),'.2f')) class Account: ID = 0 balance = 0 rate = 0 def __init__(self,ID,balance,rate): self.ID = ID self.balance = balance self.rate = rate def Save(self,money): self.balance += money def Draw(self,money): self.balance -= money if self.balance < 0: return False return True def Print(self): print("账号:",self.ID,end=' ') print("余额:",self.balance,end=' ') print("年利率:",self.rate,end=' ') print("月利率:",self.rate/12,end=' ') print("月息:",self.rate/12*self.balance) account = Account(998866,2000,0.045) account.Print() account.Save(150) account.Print() account.Draw(1500) account.Print()
32190a10b7cced742ca31321e584c0eeef7f2d05
ross-hugo/project_euler
/7_prime_number/sol.py
507
3.765625
4
#!/usr/bin/python import sys def num_primes(n): primes = [2] i = 3 while True: if len(primes) >= 10001: break add_prime = True for prime in primes: if i % prime == 0: add_prime = False if add_prime: primes.append(i) i += 2 return primes[10000] def main(): num = 10001 if len(sys.argv) != 1: num = int(sys.argv[1]) print(num_primes(num)) if __name__ == "__main__": main()
330e35273dd4b3919ba4f7095414b127fa14ea0e
mohammadfebrir/learningPython
/calculate.py
124
3.609375
4
age1=10 age2=2 age3=age1+age2 age4=age1/age2 age5=age1*age2 print("age3 =",age3) print("age4 =",age4) print("age5 =",age5)
93a8b072dae0b2c0c81cce7e14f13c67b59ebeef
crive150/pythonProjects
/LearningPython/subStringCounter.py
354
4.25
4
#Counts amount of times a specific substring is found within larger string, in this case susbtring : 'bob' s = 'azcbobobegghakl' counter = 0 answer = 0 stringHolder ='' for counter in range(len(s)): stringHolder = s[counter:counter+3] if stringHolder =='bob': answer +=1 print ('Number of times bob occurs is: '+ str(answer))
c08e2c41b90a30338d54c48fd0c86ea69519e772
roshstar1999/Daily-Leetcode
/First_Bad_Version.py
683
3.609375
4
#isBadVersion () API function predifined that returns whether an entered product no. is defect one or not(True or False) #We are to find the first bad version in the list class Solution: def firstBadVersion(self, n): #used binary search algorithm left=1 right=n while left!=right: mid=int((left+right)/2) if isBadVersion(mid): right=mid-1 if not isBadVersion(right): return mid else: left=mid+1 if isBadVersion(left): return left return right
b5a2c8087a0519f313bb8a12af07c759bfa0d6a8
linrakesh/python
/pandas/math_operation_series.py
252
3.78125
4
# mathematical operation on pandas series import pandas as pd s= pd.Series(range(10)) s1 = pd.Series(range(20,30)) print(s) print(s1) s2 = s+s1 print("s2 = s+s1") print(s2) s2 = s+50 print("s2= s+50") print(s2) s2 = s*s1 print("s2= s*s1") print(s2)
5fa9898c41992f84a99435fbf9dbeb4ee0cecd92
kevvrites/leetcode_python
/Add_Binary.py
1,672
3.859375
4
# Author: Kevin Liu # Problems available at https://leetcode.com/ # Start Date: 08/19/2021 # Start Time: 09:28 AM ET # Complete Date: 08/19/2021 # Complete Time: 09:52 AM ET # Note: Problem may or may not be completed in one sitting. # Add Binary # https://leetcode.com/problems/add-binary/ # Given two binary strings a and b, return their sum as a binary string. # Example Cases # Example 1: # Input: a = "11", b = "1" # Output: "100" # Example 2: # Input: a = "1010", b = "1011" # Output: "10101" # Constraints # 1 <= a.length, b.length <= 104 # a and b consist only of '0' or '1' characters. # Each string does not contain leading zeros except for the zero itself. # ------------------------------------------------------------------------------------------------------------------------------------ # Thought process: # 1. The optimal way probably involves some sort of "staying in binary" without converting to decimal. # 2. Long method: convert the inputs to decimal, add together, then convert back to binary. def to_decimal(s): length = len(s) dec = 0 for i in range(length): if s[i] == '1': dec += 2 ** (length - 1 - i) return dec def to_binary(num): return "{0:b}".format(int(num)) def add_binary(a,b): dec_a = to_decimal(a) dec_b = to_decimal(b) ans = dec_a + dec_b return to_binary(ans) # Submission Result: # Runtime: 0036 ms (top 56.48%) # Memory Usage: 14.4 MB (top 76.33%) # One line solution: use built-in formatting tools. def add_binary(a,b): return "{0:b}".format(int(a, 2) + int(b, 2)) # Submission Result: # Runtime: 0028 ms (top 08.77%) # Memory Usage: 14.1 MB (top 06.30%)
9f8da68d182fb6a7a10aaad29943aa7d402830bb
epson121/principles_of_computing
/ttt.py
3,213
3.640625
4
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # Change as desired NTRIALS = 10 # Number of trials to run MCMATCH = 1.0 # Score for squares played by the machine player MCOTHER = 1.0 # Score for squares played by the other player SCORES = [] # Add your functions here. def mc_trial(board, player): """ Docs """ while board.check_win() == None: empty = board.get_empty_squares() rand_sq = empty[random.randrange(len(empty))] board.move(rand_sq[0], rand_sq[1], player) player = provided.switch_player(player) def mc_update_scores(scores, board, player): """ Docs """ if board.check_win() == provided.DRAW: return winner = board.check_win() for row in range(board.get_dim()): for col in range(board.get_dim()): square = board.square(row, col) if square == winner: scores[row][col] += MCMATCH if winner == player else MCOTHER elif square == provided.EMPTY: continue else: scores[row][col] -= MCMATCH if winner == player else MCOTHER def get_best_move(board, scores): """ Docs """ res = {} empties = board.get_empty_squares() print empties print scores idx = 0 jdx = 0 for elem in empties: #for col in range(len(empties)): res[elem] = scores[idx][jdx] if jdx + 1 == 3: jdx = 0 idx += 1 else: jdx += 1 print "ITEMS: " + str(res.items()) result = [key for key,val in res.items() if val == max(res.values())] print "RESULT: " + str(result) return random.choice(result) def mc_move(board, player, trials): """ Docs """ global SCORES #This function takes a current board, which #player the machine player is, and the number #of trials to run. The function should use the #Monte Carlo simulation described above to return #a move for the machine player in the form of a #(row, column) tuple. Be sure to use the other #functions you have written! #Start with the current board. #Repeat for the desired number of trials: first_sc = [0 for i in range(board.get_dim())] SCORES = [first_sc for i in range(board.get_dim())] trial_board = board.clone() while trials >= 0: #Play an entire game by just randomly choosing a move for each player. mc_trial(trial_board, player) #Score the resulting board. mc_update_scores(SCORES, trial_board, player) trials -= 1 #print SCORES bemti = get_best_move(board, SCORES) #print "BEST MOVE: " + str(bm) return bemti #Add the scores to a running total across all trials. #To select a move, randomly choose one of the empty squares on the board that has the maximum score. # Test game with the console or the GUI. # Uncomment whichever you prefer. # Both should be commented out when you submit for # testing to save time. #provided.play_game(mc_move, NTRIALS, False) #poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)
b699082e618e829fd3ec270e38e540139d8c3722
ayush-mehta/Competitive_Programming
/Circular Array Rotation.py
341
3.578125
4
# https://www.hackerrank.com/challenges/circular-array-rotation/problem def circularArrayRotation(a, k, queries): out = list() if k > len(a): k = k % len(a) a = a[-k:] + a[:-k] for query in queries: out.append(a[query]) return out a = [1, 2, 3] k = 4 q = [0, 1, 2] print(circularArrayRotation(a, k, q))
27da6cf39a47457799b2d111349e423f69a96fb8
ogsf/Python-Exercises
/Python Exercises/src/Ch5_Ex1.py
249
4
4
''' Created on May 17, 2013 @author: Kevin Write a function called 'do_plus' that accepts two parameters /n and adds them together with the '+' operation. ''' def do_plus(a,b): print type(a) return a+b print do_plus(2,3)
d15794dd0aa436fcc8256e8e953b2478da6b1d61
pvargos17/pat_vargos_python_core
/week_02/mini_projects/lyrics.py
777
3.953125
4
''' -------------------------------------------------------- PROGRAMMED SONG LYRICS -------------------------------------------------------- Programmatically create your own song lyrics with multiple verses, interlaced with a repeating chorus. - use one block of text as verse input (hint: linebreaks can be helpful!) - use a for loop for creating the full lyrics ''' # I cheated, i cant come up with lyrics Stole this from the beatles. lyrics = """ When I find myself in times of trouble, Mother Mary comes to me And in my hour of darkness she is standing right in front of me""" chorus = "Speaking words of wisdom, let it be" verse = lyrics.split("\n\n") # split the lyrics on two newlines for v in verse: print(v) print((chorus + "\n") * 2)
06ad186bb2bbe72edb8ae904781eaa3e09aeae8c
ankitbarak/algoexpert
/Hard/maxPathSum.py
863
4.09375
4
# Write a function that takes in a Binary Tree and returns its max path sum # A path is a collection of connected nodes in a tree where no node is connected to more than two # other nodes; a path sum is the sum of the values of the nodes in a particular path def maxPathSum(tree): _, maxSum = findMaxSum(tree) return maxSum def findMaxSum(tree): if tree is None: return(0, float("-inf")) leftMaxSumAsBranch, leftMaxPathSum = findMaxSum(tree.left) rightMaxSumAsBranch, rightMaxPathSum = findMaxSum(tree.right) maxChildSumAsBranch = max(leftMaxSumAsBranch, rightMaxSumAsBranch) value = tree.value maxSumAsBranch = max(maxChildSumAsBranch + value, value) maxSumAsRootNode = max(leftMaxSumAsBranch + value + rightMaxSumAsBranch, maxSumAsBranch) maxPathSum = max(leftMaxPathSum, rightMaxPathSum, maxSumAsRootNode) return(maxSumAsBranch, maxPathSum)
7cad67850c1b3f7439f26d8ebf8fa88eda594409
agiannoul/ArAn
/plotask1.py
233
3.59375
4
import matplotlib.pyplot as plt import numpy as np def f(x): return np.exp(pow(np.sin(x),3))+pow(x,6)-2*pow(x,4)-pow(x,3)-1 t1 = np.arange(-2, 2, 0.02) plt.plot(t1, f(t1) , 'b') plt.grid() plt.ylabel("f(x)") plt.show()
6f880cf19fefa55490c7401a6ba9640e0bb3e537
Swarnava-Sadhukhan/Python-Tkinter-Projects
/Dictionary/dic.py
489
3.671875
4
from tkinter import * from PyDictionary import PyDictionary import json root=Tk() root.geometry('250x200') #search the meaning def find_meaning(): word=e1.get() dic=PyDictionary() l1.config(text=str(dic.meaning(word))) e1=Entry(root,font=('times 15',15,'bold')) e1.grid(row=2,column=2) btn=Button(root,text='Find meaning',command=find_meaning) btn.grid(row=4,column=2) l1=Label(root,text="",font='times 10') l1.grid(row=6,column=2) root.mainloop()
f4958ec98c241d7f6b7dda36d5db13a6d560d5ae
mel-haya/42-AI-Bootcamp
/M01/ex02/vector.py
4,147
3.796875
4
class Vector: def __init__(self,values): if isinstance(values,list): self.values = values elif isinstance(values,int): i = 0 self.values = [] while i < values: self.values.append(i) i+=1 elif isinstance(values,tuple) and len(values) == 2: self.values = list(range(values[0],values[1])) else: raise ValueError("Invalid Vector value") self.size = len(self.values) def __add__(self,other): ret = Vector(self.size) i = 0 if isinstance(other, (int, float)): while i < self.size: ret.values[i] = self.values[i] + other i+=1 return ret elif isinstance(other, Vector): if self.size != other.size: raise ValueError("the two vectors have diffrent dimentions") while i < self.size: ret.values[i] = self.values[i] + other.values[i] i+=1 else: raise ValueError("invalid addition") return ret def __radd__(self,other): ret = Vector(self.size) i = 0 if not isinstance(other, (int, float)): raise ValueError("invalid addition") while i < self.size: ret.values[i] = self.values[i] + other i+=1 return ret def __sub__(self,other): ret = Vector(self.size) i = 0 if isinstance(other, (int, float)): while i < self.size: ret.values[i] = self.values[i] - other i+=1 return ret elif isinstance(other, Vector): if self.size != other.size: raise ValueError("the two vectors have diffrent dimentions") while i < self.size: ret.values[i] = self.values[i] - other.values[i] i+=1 else: raise ValueError("invalid subtraction") return ret def __rsub__(self,other): ret = Vector(self.size) i = 0 if not isinstance(other, (int, float)): raise ValueError("invalid subtraction") while i < self.size: ret.values[i] = - self.values[i] + other i+=1 return ret def __mul__(self,other): ret = 0 i = 0 if isinstance(other, (int, float)): while i < self.size: ret += self.values[i] * other i+=1 return ret elif isinstance(other, Vector): if self.size != other.size: raise ValueError("the two vectors have diffrent dimentions") while i < self.size: ret += self.values[i] * other.values[i] i+=1 else: raise ValueError("invalid dot product") return ret def __rmul__(self,other): ret = 0 i = 0 if not isinstance(other, (int, float)): raise ValueError("invalid dot product") while i < self.size: ret += self.values[i] * other i+=1 return ret def __truediv__(self, other): ret = 0 i = 0 if other == 0: raise ValueError("div on zero") if isinstance(other, (int, float)): while i < self.size: ret += self.values[i] / other i+=1 return ret else: raise ValueError("invalid division") def __rtruediv__(self, other): ret = 0 i = 0 if 0 in self.values: raise ValueError("div on zero") if isinstance(other, (int, float)): while i < self.size: ret += other / self.values[i] i+=1 return ret else: raise ValueError("invalid division") def __str__(self): return "this " + str(self.size) + "D vector values are " + str(self.values) def __repr__(self): ret = "Vector(" + str(self.size) + "," + str(self.values) + ")" return ret
b100a24731332ab6be087d7728bfb419f38bfe72
verabrayan/ADA
/ADA tarea3/templates/gas.py
940
3.515625
4
from sys import stdin """Nombre: Brayan David Vera Leyton fecha: 8/marzo/2019 codigo: 8918691 Recursos: #Codigo mic tomado de la pagina del profesor Camilo Rocha, como se discutio en clase https://bitbucket.org/snippets/hquilo/b6n5e """ def mic(L,H,a): ans,low,n,ok,N = list(),L,0,True,len(a) while ok and low<H and n!=N: ok = a[n][0]<=low best,n = n,n+1 while ok and n!=N and a[n][0]<=low: if a[n][1]>a[best][1]: best = n n += 1 ans.append(best) low = a[best][1] ok = ok and low>=H if ok==False: ans = list() return ans def main(): inp=stdin line=stdin.readline() while line!='0 0\n': road,gas = [ int(x) for x in line.split() ] a=[] for j in range(gas): tmp=inp.readline().strip() location,rad=[int(x) for x in tmp.split()] a.append([location-rad,location+rad]) a.sort() ans=mic(0,road,a) if len(ans)!=0: print(gas-len(ans)) else: print(-1) line=stdin.readline() main()
f5eeba7c946e9edbe29760d6b612c53d3261c4b7
kmu-cs-swp2-2018/class-01-kyun2024
/homework/10-2/guess.py
746
3.671875
4
class Guess: def __init__(self, word): self.word = word self.guessedChars = set() self.numTries = 0 self.filledWord = "_" * len(word) def display(self): print("Current: " + self.filledWord) print("Tries: " + str(self.numTries)) pass def guess(self, character): self.guessedChars.add(character) if not character in self.word: self.numTries+=1 else: wl = list(self.filledWord); for i in range(len(self.word)): if self.word[i] == character: wl[i] = character self.filledWord = ''.join(wl) if not self.word.find('_'): return True return False
3fce2aaca6025f248d9869d37c9ae60b0fb9e44b
zuhara/Lycaeum-Mentoring
/test_exercise.py
1,807
3.53125
4
import exercise import random def test_digits(): a = exercise.digits(3467) e = 4.0 assert a == e def test_words(): a = exercise.words("Hello World") e = 2 assert a == e def test_Mtable(): a = exercise.Mtable(3) e = [3,6,9,12,15,18,21,24,27,30] assert a == e def test_Mtable2(): a = exercise.Mtable2(3,5) e = [3,6,9,12,15,] assert a == e def test_bigger(): x = random.random() y = random.random() a = exercise.bigger(x,y) e = max(x,y) assert a == e def test_biggest_in_list(): for count in range(10,50): n = [random.random() for _ in range(count)] a = exercise.biggest_in_list(n) e = max(n) assert a == e def test_fizzbizz(): a = exercise.fizzbizz(20) e = [1, 2, 'fizz', 4, 'bizz', 'fizz', 7, 8, 'fizz', 'bizz', 11, 'fizz', 13, 14, 'fizzbizz', 16, 17, 'fizz', 19, 'bizz'] assert a == e def test_fizzbizz1(): a = exercise.fizzbizz(-5) e = 0 assert a == e def test_panagram(): a = exercise.panagram("The quick brown fox jumps over the lazy dog") e = True assert a == e def test_pangram1(): a = exercise.panagram("The quick brown fox jumped over the lazy dog") e = False assert a == e def test_pangram2(): a = exercise.panagram("The Quick brown Fox jumps over the lazy dog") e = True assert a == e def test_feq(): a = exercise.freq("Hello World") e = {' ': 1, 'o': 2, 'e': 1, 'H': 1, 'l': 3, 'r': 1, 'd': 1, 'W': 1} assert a == e def test_evaluate(): a = exercise.evaluate("32+5*") e = 25 assert a == e def test_evaluate1(): a = exercise.evaluate("82/3-") e = 1 assert a == e import pytest def test_evaluate2(): with pytest.raises(ZeroDivisionError): exercise.evaluate("80/")
0e0a0b5d5a7ce37d158cbc3c1a3121a41b119679
wills201/Challenge-Probs
/increment.py
205
3.859375
4
listofnums = [5,2,3,2] new_list = [] # def increment(nums): # for num in nums: # return num # increment(listofnums) listofnums = str(listofnums) for i in listofnums: print(listofnums)
f1eb61bc3952f6136b6c39c70178ef3aed768f6e
JoeySuttonPreece/IntroProgramming_Group2
/Week3/Python/3.py
325
3.8125
4
def getNum(): while (True): try: print("Guess the magic number. It's somewhere between 1 and 10!!!") num = int(input()) break except ValueError: pass return num while (True): if (getNum() == 5): break print("Congrats on guessing the 5!!!")
ce8ff6d6f3d7cd0e74afee7b273b0b5136e83953
fengsy868/HangmanSolver
/tree_generator.py
3,520
4.09375
4
#this programme generate a set of decision trees for Hangman according to all the English words # I have used Python tree class implemented by Joowani https://github.com/joowani/binarytree import pickle from binarytree import tree, bst, convert, heap, Node, pprint print 'Start reading the dictionary file...' with open('words.txt') as f: allWords = f.read().splitlines() print 'There are '+str(len(allWords))+' words in the file' maxlen = 0 for word in allWords: if len(word) > maxlen: maxlen = len(word) print 'The longest word has '+str(maxlen)+' letters' treelist=[];wordlengthlist=[]; height_tree = 18 for n in xrange(maxlen): #Create a list of binary search trees and a list of lists of different length words treelist.append(heap(height=height_tree, max=True)) wordlengthlist.append([]) for word in allWords: wordlengthlist[len(word)-1].append(word) print 'There are '+str(len(wordlengthlist[8]))+' Word with 9 letters' #This function aims at find the (rank)th frequent letter in a word's list def find_most_frequent_letter(wordlist,rank): count=[0] for n in xrange(26): count.append(0) for word in wordlist: #find most frequent letter in 6 length word for letter in list(word): if letter.isalpha(): #to avoid the char <<'>> count[ord(letter) - 97] += 1 new = count[:] #copy the rank list for i in xrange(rank-1): new.remove(max(new)) #delete the most biggest number in new list return chr(count.index(max(new))+97) #return the (rank)th frequent letter in wordlist # These twofunction used to delete word do/dont contains certain letter from the wordlist def generate_new_list_with_letter_correct(letter, wordlist): temp_list= [] for word in wordlist: if letter in word: temp_list.append(word.replace(letter,'')) wordlist[:] = [] for word in temp_list: wordlist.append(word) def generate_new_list_with_letter_wrong(letter, wordlist): temp_list = [] for word in wordlist: if letter in word: temp_list.append(word) for word in temp_list: wordlist.remove(word) # main iteration function to fill the tree def fill_the_tree(node,wordlist,deepth,height): if deepth == height+1: return deepth-1 local_wordlist1 = wordlist[:] #this for wrong guess local_wordlist2 = wordlist[:] #this for correct guess #get the value for left node, wrong guess generate_new_list_with_letter_wrong(node.value, local_wordlist1) node.left.value = find_most_frequent_letter(local_wordlist1, 1) #left node contains the next most frequent letter if guess is wrong deepth = fill_the_tree(node.left, local_wordlist1, deepth+1, height) #get the value for right node, correct guess generate_new_list_with_letter_correct(node.value, local_wordlist2) node.right.value = find_most_frequent_letter(local_wordlist2, 1) deepth = fill_the_tree(node.right, local_wordlist2, deepth+1, height) return deepth-1 #list of 31 most common letter for different length first_guess = ['a','a','a','a','s','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i'] find_most_frequent_letter(wordlengthlist[12],1) # Fill the 31 binary trees for different length for i in xrange(31): print 'Building the tree for word length ',i treelist[i].value = first_guess[i] wordlist = wordlengthlist[i] fill_the_tree(treelist[i], wordlist, 1, height_tree) final_list = [] for tree in treelist: final_list.append(convert(tree)) resultfile = open('result.txt', 'w') pickle.dump(final_list, resultfile)
f79bd7c5549a4af3cc983c4e0d92753f7fbfeb2b
haodongxi/leetCode
/22.py
937
3.84375
4
from typing import List def generateParenthesis(n: int) -> List[str]: if n == 0: return [] if n == 1: return ["()"] dict = {} for item in generateParenthesis(n-1): for i in range(len(item)+1): j = i+1 tempS = insertStr(item,"(",i) while j<=len(item)+1: tempS = insertStr(tempS,")",j) if isValid(tempS): dict[str(tempS)] = 1 j = j+1 return list(dict.keys()) def insertStr(s,target,index): str_list = list(s) str_list.insert(index, target) a_b = ''.join(str_list) return a_b def isValid(s: str) -> bool: if len(s) == 0: return True if len(s)%2 != 0: return False if "()" in s : s = s.replace("()","") return isValid(s) else : return False if __name__ == "__main__": print(generateParenthesis(3))
3feee02c30bf5d4fd7b9310cddf2ef52b219d865
JS01230/Document_Parser3
/part3.py
3,349
3.59375
4
#Document Parser v3: Final Version #This version of parser gives the user the ability to determine keywords she/he would like #the parser to use when sifting through the meta-data. Here we append sys.argv with those words. #This parser also splits the program into functions to simplify the process. import sys import os import re sys.argv.append(raw_input("Welcome to Document Tagger Part 3! Today we will be \ntaking keywords chosen by you and using the parser to search \nthrough the metadata of Project Gutenberg texts to find your words. \nEnter the first word: ")) sys.argv.append(raw_input("Great! Now let's try a second word: ")) sys.argv.append(raw_input("A third word: ")) sys.argv.append(raw_input("Okay! This is the final word: ")) print sys.argv title_ptn = re.compile(r'(?:title:\s*)(?P<title>((\S*( )?)+)' + r'((\n(\ )+)(\S*(\ )?)*)*)', re.IGNORECASE) author_ptn = re.compile(r'(author:)(?P<author>.*)', re.IGNORECASE) translator_ptn = re.compile(r'(translator:)(?P<translator>.*)', re.IGNORECASE) illustrator_ptn = re.compile(r'(illustrator:)(?P<illustrator>.*)', re.IGNORECASE) meta_search_dict = dict(author=author_ptn, title=title_ptn, translator=translator_ptn, illustrator=illustrator_ptn, ) def meta_search(meta_search_dict, text): """Returns results of search for metadata from text""" results = {} for k in meta_search_dict: result = re.search(meta_search_dict[k], text) if result: results[k] = result.group(k) else: results[k] = None return results def file_opener(fl_path): """Given a full path to a file, opens that file and returns its contents""" with open(fl_path, 'r') as f: return f.read() def file_path_maker(directory, fl_name): return os.path.join(directory, fl_name) def kw_pattern_maker(kws): """Returns dictionary of keyword regular expression patterns""" result = {kw: re.compile(r'\b' + kw + r'\b') for kw in kws} return result def kw_counter(pattern, text): """Returns the number of matches for a keyword in a given text""" matches = re.findall(pattern, text) return len(matches) def doc_tag_reporter(directory, kws): """ This will iterate through the text documents in Project Gutenberg and reveal the data we ask of it """ for fl in os.listdir(directory): if fl.endswith('.txt'): fl_path = file_path_maker(directory, fl) text = file_opener(fl_path) meta_searches = meta_search(meta_search_dict, text) kw_searches = kw_pattern_maker(kws) print "Here's the info for {}:".format(fl) for k in meta_searches: print "{0}: {1}".format(k.capitalize(), meta_searches[k]) print "\n****KEYWORD REPORT****\n\n" for kw in kw_searches: print "\"{0}\": {1}".format(kw, kw_counter(kw_searches[kw], text)) print '\n\n' print "***" * 25 def main(): directory = "C:\Python27\projects\document_tagger\part3" kws = [i for i in sys.argv[1:]] doc_tag_reporter(directory, kws) if __name__ == '__main__': main() raw_input("\n\nPress any key to exit...")
943db3b5effafd8fc2c9d8bcfb220d59b0a0deab
ahmedfadhil/PyTip
/DepthFirstSearch.py
808
3.921875
4
from collections import defaultdict # This class represents a directed graph using # adjacency list representation class Graph: # Graph constructor def __init__(self): self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): visited[v] = True print(v) for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # DFS function def DFS(self, v): # Mark all vertices as not visited visited = [False] * (len(self.graph)) # Call the recursive helper self.DFSUtil(v, visited) gr = Graph() gr.addEdge(0, 1) gr.addEdge(0, 2) gr.addEdge(1, 2) gr.addEdge(2, 3) gr.addEdge(3, 3) gr.DFS(0)
f2beb4026244232bb5d261791ec823be69830215
MubashirullahD/cracking-the-coding-interview
/chapter0/perm.py
580
4.125
4
""" Example: Design an algorithm to print all permutations of a string. For simplicity, assume all characters are unique. abcd abdc acbd acdb adbc adcb """ def fac(iteration): if iteration <= 1: return 1 else: return iteration * fac(iteration-1) def perm(remainder, parsed): if not remainder: print(parsed) return for letter in remainder: newRemainder = "".join(l for l in remainder if l != letter) perm(newRemainder, parsed+letter) if __name__ == "__main__": string = "abcd" perm(string, "")
65818debf30ece5aaea46dd9d09d68e317fa1c6e
saurabh-kumar88/DataStructure
/Tree/tree2.py
4,201
3.9375
4
from collections import deque class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def depth(self): left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return max(left_depth, right_depth) + 1 class BinaryTree(object): def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_search(tree.root, "") elif traversal_type == "inorder": return self.inorder_search(tree.root, "") elif traversal_type=="postorder": return self.postorder_print(tree.root, "") else: print("This Traversal type : `{}` is not supported ".format(traversal_type) ) return False def preorder_search(self, start, traversal): """Root --> Left->right->left.left->left.right""" if start: traversal += (str(start.value) + "-") traversal = self.preorder_search(start.left, traversal) traversal = self.preorder_search(start.right, traversal) return traversal def inorder_search(self, start, traversal_type ): """Search left sub tree nodes first : Left --> Root --> Right""" traversal = "" if start: traversal = self.preorder_search(start.left, traversal) traversal += (str(start.value) + "-") traversal = self.preorder_search(start.right, traversal) return traversal def postorder_print(self, start, traversal): """Left->Right->Root""" if start: traversal = self.postorder_print(start.left, traversal) traversal = self.postorder_print(start.right, traversal) traversal += (str(start.value) + "-") return traversal # preorder search def traverse(self, start): traversal = "" if start: traversal += str(start.value) traversal = self.traverse(start.left.value) traversal = self.traverse(start.right.value) return traversal class Solution(object): def isCousins(self, root, x: int, y: int) -> bool: if self.get_level(root, x ) == self.get_level(root, y ): if self.parent_search(root, x) != self.parent_search(root, y): return True return False def get_level(self, root, node_value): Q = [] level = 1 Q.append(root) Q.append(None) while(len(Q)): temp = Q[0] Q.pop(0) if( temp == None ): if len(Q) == 0: return None if (Q[0] != None): Q.append(None) level += 1 else: if( temp.value == node_value ): return level if (temp.left): Q.append(temp.left) if (temp.right): Q.append(temp.right) return 0 def parent_search(self, root, child_node): if not root: return None if root.left and root.left.value == child_node: return root if root.right and root.right.value == child_node: return root return self.parent_search(root.left, child_node) or self.parent_search(root.right, child_node) # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 if __name__ == "__main__": # initialize tree tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) # tree.root.right.left = Node(6) # tree.root.right.right = Node(7) print( tree.print_tree("preorder") ) # print( tree.print_tree("inorder") ) # print( tree.print_tree("postorder") ) # obj = Solution() # result = obj.isCousins( tree.root, 4, 7 ) # print(result)
1b8f333f840a3fee154c1433301d5fe4ad2f0610
Friendktt/My-work
/lol.py
241
3.734375
4
"""kuy""" def main(): """kuy""" num = str(input()) num1 = num.split(" ") print(num1[0][-1]+num1[1][-1]+num1[2][-1]+num1[3][-1]+num1[4][-1]+num1[5][-1]\ +num1[6][-1]+num1[7][-1]+num1[8][-1]+num1[9][-1]) main()
a1bd7edb044a69a52667cee2bb04b017b893a721
Raymond-Lind/SFM
/SFM.py
5,596
4.125
4
# Simulated File System Stored in Memory # Created by Raymond Lind # Main Class class Files: def __init__(self, father, name): self.father = father self.name = name self.directory = [] # Directory list self.file = [] # File list # Configure Home Directory & Path Management home = Files(father=None, name='home') current = home # Colors for customization yellow = '\033[93m' red = '\033[91m' blue = '\u001b[34m' green = '\033[92m' reset = '\033[0m' # Name input to give user specialized experience entry = input('Please give me your name before entering the File System: ') print(blue + '\nHey {}, welcome to the File System!'.format(entry) + reset + '\nType' + green + ' help' + reset + ' for more information.\n') path = blue + entry + '@FileSystem:' + reset # Function to create a file def touch(name): global current current.file.append({name: ''}) #Function to create a directory def mkdir(name): global current directory = Files(father=current, name=name) current.directory.append(directory) # Function to change into new directory def cd(name): global current, path if name == '..': if current.father is not None: path = path[:(len(path) - len(current.name)) - 1] current = current.father else: for i in current.directory: if i.name == name: current = i path = path + '/' + name return return print(red + 'Directory does not exist' + reset) # Function to list files and directories def ls(): global current for i in current.file: for key, value in i.items(): print(key, value) for i in current.directory: print(green + i.name + reset) # Main loop simulating a file system with commands if __name__ == '__main__': while True: print(path, end=red + ' --> ' + reset) command = input().split(' ') # Creates touch command capability in loop if command[0] == 'touch': try: for files in current.file: for key in files: if command[1] == key: print(green + "Timestamp for " + reset + red + command[1] + reset + green + " has been updated." + reset) current.file.remove(files) touch(command[1]) except: # Error handling in touch requests print(red + '--------------\nError in usage\n-------------- ' + reset + '\nTry: ' + red + 'touch' + reset + ' FileName\n') # Creates mkdir command capability in loop elif command[0] == 'mkdir': try: for dirs in current.directory: if command[1] == dirs.name: print(red + "This directory name already exists. Try a different name." + reset) current.directory.remove(dirs) mkdir(command[1]) except: # Error handling in mkdir requests print(red + '--------------\nError in usage\n-------------- ' + reset + '\nTry: ' + red + 'mkdir' + reset + ' DirectoryName\n') # Creates cd command capability in loop elif command[0] == 'cd': try: cd(command[1]) except: # Error handling in cd requests print(red + '--------------\nError in usage\n-------------- ' + reset + '\nTry: ' + red + 'cd' + reset + ' DirectoryName\n') # Creates ls command capability in loop elif command[0] == 'ls': ls() # Creates help command capability in loop elif command[0] == 'help': print('---------------\n' + red + 'COMMAND OPTIONS' + reset + '\n---------------') print(red + 'mkdir' + reset + ' ~ Create Directory\n' + red + 'touch' + reset + ' ~ Create Empty File\n' + red + 'ls' + reset + ' ~ List Directories & Files in Current Directory\n' + red + 'cd' + reset + ' ~ Open Directory\n' + red + 'exit' + reset + ' ~ Exit File System\n' + red + 'usage' + reset + ' ~ Shows how to use commands\n') # Creates usage command capability in loop elif command[0] == 'usage': print('-------------\n' + red + 'COMMAND USAGE' + reset + '\n-------------') print(red + 'usage' + reset + ' = ' + red + 'usage\nls' + reset + ' = ' + red + 'ls\n' + red + 'mkdir' + reset + ' = ' + red + 'mkdir' + reset + ' NEW_DIRECTORY_NAME\n' + red + 'touch' + reset + ' = ' + red + 'touch' + reset + ' NEW_FILE_NAME\n' + red + 'cd' + reset + ' = ' + red + 'cd' + reset + ' DIRECTORY_NAME\n' + red + 'exit' + reset + ' = ' + red + 'exit\n' + reset) # Creates exit command capability in loop elif command[0] == 'exit': positive = input(yellow + 'Are you sure you want to exit?\nyes|no: ' + reset) if positive == 'yes': # Exits file system exit() elif positive == 'no': # Returns you to loop print(yellow + 'Okay, going back to File System... \n' + reset) else: # Returns to loop if no answer defined print(red + '\nyes or no not specified, returning you to File System... \n' + reset) else: # Displays this if command does not exist print(red + '----------------------') print('{} is not a command'.format(command[0])) print('----------------------' + reset) # END
140be5baddbfc03cd26d917a51bb872000390714
Punkrockechidna/PythonCourse
/python_basics/data_types/sets_exercise.py
723
4.46875
4
# Scroll to bottom to see solution # You are working for the school Principal. We have a database of school students: school = {'Bobby', 'Tammy', 'Jammy', 'Sally', 'Danny'} # during class, the teachers take attendance and compile it into a list. attendance_list = ['Jammy', 'Bobby', 'Danny', 'Sally'] # using what you learned about sets, create a piece of code that the school principal can use to immediately find out # who# missed class so they can call the parents. (Imagine if the list had 1000s of students. The principal can use # the lists # generated by the teachers + the school database to use python and make his/her job easier): # Find the students that miss class! print(school.difference(attendance_list))
e0944ec702bffd17fd2d18643614b1db4e889c23
treywaevin/Tkinter-Calculator
/main.py
4,160
3.859375
4
# Code made by @treywaevin on github from tkinter import * # Create window win = Tk() win.title('Calculator') win.geometry('525x675') win.resizable(False,False) # Instances expression = "" neg = False # Button Inputs def inputNum(digit): global expression global neg if digit is 'C': print('test') expression = "" equation.config(text="0") elif digit is "sign": if not neg: expression += "-" # adds neg symbol to beginning of num neg = True equation.config(text=expression) else: try: if equation[(len(expression)-1):] == '-': expression = expression[0:(len(expression)-1)] equation.config(text=expression) except TypeError: print('error') elif digit is '%': decimal = float(expression) / 100 expression = str(decimal) equation.config(text=expression) else: print('else') expression += str(digit) equation.config(text=expression) # Evaluate Equation def evalEq(): global expression # displays error when answer cannot be computed try: solution = eval(expression) expression = str(solution) equation.config(text = expression) except ZeroDivisionError: equation.config(text="error") # Layout labels and buttons equation = Label(win, background='grey', foreground='white',text='0', anchor='e', height=6, font=("Courier,90")) equation.grid(row=0, column=0, sticky='nsew', columnspan=4) btnClear = Button(win, background='light grey', text='C', command = lambda: inputNum('C')).grid(row=1, column=0, ipadx=53, ipady=45) btnSign = Button(win, background='light grey', text='+/-', command = lambda: inputNum('sign')).grid(row=1, column=1, ipadx=53, ipady=45) btnPcnt = Button(win, background='light grey', text='%', command = lambda:inputNum('%')).grid(row=1, column=2, ipadx=59, ipady=45) btnPlus = Button(win, background='orange', text='+', command = lambda: inputNum('+')).grid(row=1, column=3, ipadx=53, ipady=45) btn1 = Button(win, background='light grey', text='1', command= lambda: inputNum(1)).grid(row=2, column=0, ipadx=54, ipady=45) btn2 = Button(win, background='light grey', text='2', command = lambda: inputNum(2)).grid(row=2, column=1, ipadx=59, ipady=45) btn3 = Button(win, background='light grey', text='3', command = lambda: inputNum(3)).grid(row=2, column=2, ipadx=60, ipady=45) btnSub = Button(win, background='orange', text='-', command = lambda: inputNum('-')).grid(row=2, column=3, ipadx=55, ipady=45) btn4 = Button(win, background='light grey', text='4', command = lambda: inputNum(4)).grid(row=3, column=0, ipadx=54, ipady=45) btn5 = Button(win, background='light grey', text='5', command = lambda: inputNum(5)).grid(row=3, column=1, ipadx=59, ipady=45) btn6 = Button(win, background='light grey', text='6', command = lambda: inputNum(6)).grid(row=3, column=2, ipadx=59, ipady=45) btnMul = Button(win, background='orange', text='x', command = lambda: inputNum('*')).grid(row=3, column=3, ipadx=55, ipady=45) btn7 = Button(win, background='light grey', text='7', command = lambda: inputNum(7)).grid(row=4, column=0, ipadx=54, ipady=45) btn8 = Button(win, background='light grey', text='8', command = lambda: inputNum(8)).grid(row=4, column=1, ipadx=59, ipady=45) btn9 = Button(win, background='light grey', text='9', command = lambda: inputNum(9)).grid(row=4, column=2, ipadx=59, ipady=45) btnDiv = Button(win, background='orange', text='/', command = lambda: inputNum('/')).grid(row=4, column=3, ipadx=55, ipady=45) btn0 = Button(win, background='light grey', text='0', command = lambda: inputNum(0)).grid(row=5, column=0, ipadx=54, ipady=45, columnspan=2, sticky='nsew') btnDec = Button(win, background='light grey', text='.', command = lambda: inputNum('.')).grid(row=5, column=2, ipadx=59, ipady=45) btnEval = Button(win, background='orange', text='=', command = evalEq).grid(row=5, column=3, ipadx=55, ipady=45) win.mainloop()