blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
713f27ced7d6e57dc790dc700c996d0046584b74
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/opt-lab-lcr-v2.py
2,739
3.59375
4
''' Lab: LCR Simulator https://github.com/PdxCodeGuild/2019-10-28-fullstack-night/blob/master/1%20Python/labs/optional-LCR.md ''' import random #this is the function for each player turn: def player_roll(player_name, chips, player_L, player_R): die_sides = ["L", "C", "R", "*", "*", "*"] player_roll = [] if chips[player_name] < 3: for die in range(chips[player_name]): player_roll.append(random.choice(die_sides)) else: for roll in range(3): player_roll.append(random.choice(die_sides)) print(f"{player_name} rolled {player_roll}.") for die in player_roll: if die in ['L', 'C', 'R']: chips[player_name] -= 1 if die == 'L': chips[player_L] += 1 print(f"{player_name} passed a chip to {player_L}.") elif die == 'C': chips['Center'] += 1 print(f"{player_name} passed a chip to Center.") elif die == 'R': chips[player_R] += 1 print(f"{player_name} passed a chip to {player_R}.") print(f"The chip count is:\n{chips}") return chips #break function: def break_out(chips, player1, player2, player3): if chips[player1] + chips['Center'] == 9 or chips[player1] + chips['Center'] == 9 or chips[player3] + chips['Center'] == 9: return True # #turn counter function: ##FUNCTION DIDN'T WORK # def turn_counter(turns): # print(f"Turn {turns}:") # turns += 1 # return turns #we get the player names: player1 = input("Enter Player One's name: ") player2 = input("Enter Player Two's name: ") player3 = input("Enter Player Three's name: ") #we establish the starting chip count: chips = { player1: 3, player2: 3, player3: 3, 'Center': 0, } turns= 0 #this loop runs the whole game while True: #player 1 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player1, chips, player2, player3) if break_out(chips, player1, player2, player3) == True: break #player 2 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player2, chips, player3, player1) if break_out(chips, player1, player2, player3) == True: break #player 3 turn: # turn_counter(turns) turns += 1 print(f"\nTurn {turns}:") player_roll(player3, chips, player1, player2) if break_out(chips, player1, player2, player3) == True: break print() for player in chips: if chips[player] > 0: print(f"{player} won with {chips[player]} chip(s) left. {player} takes the pot. Congrats") break print(f"\nAfter {turns} turns, here is the final chip count:\n{chips}")
ae03c569f2eb80951263f0556482c783d009e549
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/optional-labs/tic-tac-toe/tic_tac_toev2.py
2,803
3.890625
4
''' Tic-Tac-Toe ''' # import numpy class Player: def __init__(self, name, token): self.name = name self.token = token class Game: def __init__(self): board = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', } # for row in range(3): # row_list = [] # for column in range(3): # column = ' ' # row_list.append(column) # board.append(row_list) self.board = board def __repr__(self): board = self.board return board[1] + '|' + board[2] + '|' + board[3] + '\n' + board[4] + '|' + board[5] + '|' + board[6] + '\n' + board[7] + '|' + board[8] + '|' + board[9] def move(self, player): while True: move = int(input("Which move? (1-9): ")) if self.board[move] in '123456789': self.board[move] = player.token break else: print("You can't do that") continue # x = int(input(f"{player.name} x: ")) # y = int(input(f"{player.name} y: ")) # if self.board[y - 1][x - 1] == ' ': # self.board[y - 1][x - 1] = player.token # break # else: # print("You can't do that") # continue print(self) Game.calc_winner(self) if Game.is_full(self) == True: print("Board full. Game Over") quit() # return __r def calc_winner(self): X_O = ['X', 'O'] for token in X_O: for row in self.board: if set(row) == {token}: print(f"{token} wins!") quit() for i in range(3): column = [] for row in self.board: column.append(row[i]) if set(column) == {token}: print(f"{token} wins!") quit() diagonal_1 = self.board[0][0], self.board[1][1], self.board[2][2] diagonal_2 = self.board[0][2], self.board[1][1], self.board[2][0] if set(diagonal_1) == {token} or set(diagonal_2) == {token}: print(f"{token} wins!") quit() def is_full(self): long_board = [] for row in self.board: for column in row: long_board.append(column) return ' ' not in long_board player1_name = 'Pete' player2_name = 'Matt' test = Game() player1 = Player(player1_name, 'X') player2 = Player(player2_name, 'O') print(test) while True: test.move(player1) test.move(player2)
2928ceeee16232bba71cac568fab3e3c19ee15bf
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab20.py
649
3.640625
4
def get_second_digit(num): if num < 10: return None return num % 10 def validate_credit_card(cc_str): if len(cc_str) != 16: return False cc = [] for i in range(len(cc_str)): cc.append(int(cc_str[i])) check_digit = cc.pop(-1) cc.reverse() for i in range(0, len(cc), 2): cc[i] *= 2 total = 0 for i in range(len(cc)): if cc[i] > 9: cc[i] -= 9 total += cc[i] second_digit = get_second_digit(total) return second_digit == check_digit credit_card_str = '4556737586899855' print(validate_credit_card(credit_card_str))
eb0bf7381ff1ea3d9f11dec46d6e2ff775d65c7e
pjz987/2019-10-28-fullstack-night
/Assignments/dustin/lab23.py
586
3.515625
4
''' By: Dustin DeShane Filename: lab23.py ''' songs = [] with open("songlist.csv", 'r') as song_list: rows = song_list.read().split('\n') headers = rows.pop(0).split(',') #set first row as headers/keys #print(headers) for row in rows: row = row.split(',') #iterate through rows and split them into component parts # Normal way # song = {} # for i in range(len(headers)): # song[headers[i]] = row[i] # Fancy python way song = dict(zip(headers, row)) songs.append(song) print(songs)
abacfce7f2c434836cfdcbbe6f763df0dce691fe
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab09.py
177
4
4
import decimal #user input d_ft = int(input("Input distance in feet: ")) #conversion d_meters = d_ft/0.3048 #equals print("The distance in meters is %i meters." % d_meters)
c41cf49d568bee4f2e2caaf24483b0e032b247eb
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab11_v1.py
146
3.640625
4
operation = input("What operation would you like to do?") num_1 = int(input("Enter first number.")) num_2 = int(input("Enter second number."))
8ed3fb8ef261e016ce96a2af1f955eab2003e599
pjz987/2019-10-28-fullstack-night
/Assignments/jake/Python_Assignments/lab20-credit_card_check.py
1,172
3.6875
4
def validator(n): validatelist=[] for i in n: validatelist.append(int(i)) for i in range(0,len(n),2): validatelist[i] = validatelist[i]*2 if validatelist[i] >= 10: validatelist[i] = validatelist[i]//10 + validatelist[i]%10 if sum(validatelist)%10 == 0: print('This a valid credit card') else: print('This is not valid credit card') def cardnumber(): result='' while True: try: result = input('Please enter the 16 digit credit card number : ') if not (len(result) == 16) or not type(int(result) == int) : raise Exception except Exception: print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.') continue else: break return result def goagain(): return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y' def main(): while True: result = cardnumber() validator(result) if not goagain(): break if __name__ == '__main__': main()
2d304bd9b8bcae2dc320a8a252ca066983467326
pjz987/2019-10-28-fullstack-night
/Assignments/pete/python/lab23-contact-list/lab23-contact-list-v3.py
3,638
3.828125
4
''' Lab 23: Contact List Version3 When REPL loop finishes, write the updated contact info to the CSV file to be saved. I highly recommend saving a backup contacts.csv because you likely won't write it correctly the first time. ''' with open('cities_list.csv', 'r') as cities: #establish the rows rows = cities.read().split('\n') #find the header headers = rows[0] #split the headers into its own list header_list = headers.split(',') cities_list = [] #for each line other than the header for city in rows[1:]: #get a list for each row row_list = city.split(',') city_dict = {} #for each item in the row list for i in range(len(row_list)): city_dict[header_list[i]] = row_list[i] cities_list.append(city_dict) print(f"cities_list:\n{cities_list}") ####START VERSION 2 while True: #create a record new_city_yn = input("Add new city to list (Y/N)? ").lower() while True: if new_city_yn == 'n': break else: user_city = input("Enter City: ") user_country = input("Enter Country: ") user_landmark = input("Enter Landmark: ") user_food = input("Enter Food: ") user_list = [user_city, user_country, user_landmark, user_food] user_dict = {} for i in range(len(user_list)): user_dict[header_list[i]] = user_list[i] cities_list.append(user_dict) print(f"Updated list:\n{cities_list}") break #retrieve a record retrieve_city_yn = input("Retrieve City info (Y/N)? ").lower() while True: if retrieve_city_yn == 'n': break else: user_retrieve = input("Enter City for info retrieval: ") for city_dict in cities_list: if city_dict['City'] == user_retrieve: break print(f"City info:\n{city_dict}") break #update a record update_yn = input("Update a city's info (Y/N)? ").lower() while True: if update_yn == 'n': break else: user_update_city = input("Which City would you like to update? ") user_update_attribute = input("Which attribute would you like to update? ") user_update_new_attribute = input("And what would you like to change it to? ") for city_dict in cities_list: if city_dict['City'] == user_update_city: break city_dict[user_update_attribute] = user_update_new_attribute print(f"Updated List:\n{cities_list}") break #delete a record remove_city_yn = input("Would you like to remove a City from the list (Y/N)? ").lower() while True: if remove_city_yn == 'n': break else: user_remove_city = input("Which city would you like to delete from the list? ") for city_dict in cities_list: if city_dict['City'] == user_remove_city: break cities_list.remove(city_dict) print(f"Updated List:\n{cities_list}") break again_yn = input("Would you like to change anything else (Y/N)? ").lower() if again_yn == 'n': break save_changes = input("Save Changes (Y/N)? ").lower() if save_changes == 'y': out_data = headers for row in cities_list: out_data += '\n' for header in header_list: out_data += row[header] + ',' out_data = out_data[:-1] # print(out_data) with open('cities_list.csv', 'w') as cities: cities.write(out_data)
61902e6f6ac8f23acb98798c79228bab0c09d829
pjz987/2019-10-28-fullstack-night
/Assignments/duncan/python/lab03_grading.py
1,030
4.0625
4
''' A = range(90, 100) B = range(80, 89) C = range(70, 79) D = range(60, 69) F = range(0, 59) ''' import random print("Welcome to the Grading Program!") user_grade = int(input("What is your numerical score?")) # set up +/- if user_grade % 10 in range(1,6): sign = "-" elif user_grade % 10 in range(6,11): sign = "+" # 90 <= grade <= 100: # if user_grade in range(min, max) if user_grade in range(90, 101): print(f"You received the grade A{sign}") elif 80 <= user_grade <= 89: print(f"You received the grade: B{sign}") elif user_grade in range(70, 80): print(f"You received the grade: C{sign}") elif user_grade in range(60, 70): print(f"You received the grade: D{sign}") else: print(f"You received the grade: F{sign}") rival = random.randint(1,100) print(f"Your rival's score is {rival}.") if rival > user_grade: print("Your rival is better than you.") elif rival < user_grade: print("You are better than your rival") else: print("You have tied with your rival. That's the worst.")
b3a7d72bede78555fe345a47f43661641b90e65d
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab12_v1.py
265
3.984375
4
import random target = random.randint(1,10) guess = '' while True: guess = input('guess the number! ') guess = int(guess) if guess == target: print('that\'s correct!') break else: print('that\'s incorrect!')
188fa1987331719b38bedc7fc2ecfa785328c1fd
harshidkoladara/Python_Projects
/PoliceComplainSystem/Template Files/mainconnection.py
466
3.625
4
import sqlite3 from sqlite3 import Error def sql_connection(): try: con = sqlite3.connect('mydatabase.db') return con except Error: print(Error) def sql_table(con): cursorObj = con.cursor() #cursorObj.execute('insert into data VALUES(1,0," "))') cursorObj.execute("select num from data where id=1") rows = cursorObj.fetchall() for row in rows: return row[0] con.commit()
1d9b46c9cf7ecff4ea5e4ea41dc18f269dcf1ff6
soupierbucket/Lets-Build
/Calculator_Using_Python/Calc_Using_Python.py
4,608
4.125
4
#Import section from tkinter import * #Funtion definations def click(num): """ To display the number num: input onclick parameter """ value = entry.get() entry.delete(0, END) entry.insert(0, str(value) + str(num)) return def clear(): """ To clear the screen """ entry.delete(0, END) return def add(): """ To perform addition """ global num1 num1 = "0" num1 = entry.get() + "+" entry.delete(0, END) return def subtract(): """ To perform Substraction """ global num1 num1 = "0" num1 = entry.get() + "-" entry.delete(0, END) return def divide(): """ To perform float division """ global num1 num1 = "0" num1 = entry.get() + "/" entry.delete(0, END) return def multiply(): """ To perform Multiplication """ global num1 num1 = "0" num1 = entry.get() + "*" entry.delete(0, END) return def mod(): """ To Find the remainder """ global num1 num1 = "0" num1 = entry.get() + "%" entry.delete(0, END) return def compute(): """ Logic to perform the said function """ try: num2 = entry.get() num3 = str(num1)+str(num2) e = eval(num3) entry.delete(0, END) entry.insert(0,e) except: entry.delete(0, END) entry.insert(0,"ERROR") root = Tk() #Initialises a blank window root.title("Calculator") entry = Entry(root, width = 45, borderwidth = 4) entry.grid(row = 0, column = 1, columnspan = 4, padx =8, pady=10) #Buttons definations #Number buttons button1 = Button(root, text = "1", padx = 40, pady = 20, command = lambda : click(1), fg = "Black") button2 = Button(root, text = "2", padx = 40, pady = 20, command = lambda : click(2), fg = "Black") button3 = Button(root, text = "3", padx = 40, pady = 20, command = lambda : click(3), fg = "Black") button4 = Button(root, text = "4", padx = 40, pady = 20, command = lambda : click(4), fg = "Black") button5 = Button(root, text = "5", padx = 40, pady = 20, command = lambda : click(5), fg = "Black") button6 = Button(root, text = "6", padx = 40, pady = 20, command = lambda : click(6), fg = "Black") button7 = Button(root, text = "7", padx = 40, pady = 20, command = lambda : click(7), fg = "Black") button8 = Button(root, text = "8", padx = 40, pady = 20, command = lambda : click(8), fg = "Black") button9 = Button(root, text = "9", padx = 40, pady = 20, command = lambda : click(9), fg = "Black") button0 = Button(root, text = "0", padx = 40, pady = 20, command = lambda : click(0), fg = "Black") button = Button(root, text = ".", padx = 42, pady = 20, command = lambda : click(".")) #Clear button buttonClear = Button(root, text = "AC", padx = 36, pady = 20, command = clear) #Function buttons buttonAdd = Button(root, text = "+", padx = 25, pady = 13, command = lambda : add()) buttonSub = Button(root, text = "-", padx = 25, pady = 13, command = lambda : subtract()) buttonDiv = Button(root, text = "/", padx = 25, pady = 13, command = lambda : divide()) buttonMul = Button(root, text = "*", padx = 25, pady = 13, command = lambda : multiply()) buttonMod = Button(root, text = "%", padx = 25, pady = 13, command = lambda : mod()) buttonEqual = Button(root, text = "CALCULATE", padx = 117, pady = 20, command = compute) #To place buttons in grid button1.grid(row = 3, column = 0,padx =5, pady=3) button2.grid(row = 3, column = 1) button3.grid(row = 3, column = 2) button4.grid(row = 2, column = 0) button5.grid(row = 2, column = 1) button6.grid(row = 2, column = 2) button7.grid(row = 1, column = 0) button8.grid(row = 1, column = 1) button9.grid(row = 1, column = 2) button0.grid(row = 4, column = 1) button.grid(row = 4, column = 0) buttonClear.grid(row = 4, column = 2, pady=3) buttonAdd.grid(row = 1, column = 4) buttonSub.grid(row = 2, column = 4) buttonDiv.grid(row = 3, column = 4) buttonMul.grid(row = 4, column = 4) buttonMod.grid(row = 5, column = 4) buttonEqual.grid(row = 5, column = 0, columnspan=3, pady=5) #To add some colors to the buttons! buttonAdd.config(bg = "#AAAAAA", fg = "WHITE") buttonSub.config(bg = "#AAAAAA", fg = "WHITE") buttonDiv.config(bg = "#AAAAAA", fg = "WHITE") buttonMul.config(bg = "#AAAAAA", fg = "WHITE") buttonMod.config(bg = "#AAAAAA", fg = "WHITE") buttonEqual.config(bg = "#BDBDBD", fg = "WHITE") root.mainloop() #Finally lets render
3a495c4e7a920cda01b5805f0eaebc9f3fc455ae
n20002/Task
/0813.py
2,637
3.734375
4
import sys from itertools import count from random import randint def checkfn(left, right, guess): if left < right and guess == 'h': return True if left == right and (guess == 'h' or guess == 'l'): return True if left > right and guess == 'l': return False def create_title(title): separator = '*' * 14 return '\n'.join([ separator, f'* {title} *', separator ]) message = 'High or Low ?(h/l)' print(create_title('High & Low')) for i in count(): left = randint(1,13) right = randint(1,13) print(' [問題表示]') print('***** *****') print('* * * *') print('* {0} * * *'.format(left)) print('* * * *') print('***** *****') guess = input(message) if checkfn(left, right, guess) == True and guess == 'h': print('→Highを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Win!') if checkfn(left, right, guess) == True and guess == 'l': print('→Lowを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Win!') if checkfn(left, right, guess) == False and guess == 'h': print('→Highを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Lose...') print('---ゲーム終了---') sys.exit() if checkfn(left, right, guess) == False and guess == 'l': print('→lowを選択しました。') print(' [結果発表]') print('***** *****') print('* * * *') print('* {0} * * {1} *'.format(left, right)) print('* * * *') print('***** *****') print('You Lose...') print('---ゲーム終了---') sys.exit()
e128273e27389122b8d02b180980fa8562c940fb
jostaylor/Word_Search_Generator
/WordSearch.py
7,628
4.125
4
import random import sys # TODO What can I add? # Make the program more user-friendly: # Maybe if we get an infiniteError, allow the user to alter the words or the size of the grid and retry # Add a file writer for the key to the word search # Make it easier for the user to input without having to type them in all over again if something goes wrong # TODO NOTE: Max length for an rtf file (and all other file types I think) is 28 class colors: # Allows me to use colors in the terminal HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # All letters into one string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" elements = [] # Empty List # Asks for size of grid length = int(input("Length of grid:")) height = int(input("Height of grid:")) # Adds <height> lists to elements count1 = 0 while count1 < height: elements.append([]) count1 += 1 # Adds random letters to fill a length x height grid for i in range(height): count2 = 0 while count2 < length: elements[i].append(letters[random.randint(0, 25)]) count2 += 1 # Prints grid for i in range(height): print(elements[i]) # Asks for words to put in word search print("Input the words you want in the word search:\nType \'done\' when you are finished") # Puts words into a list called words words = [] repeat = True while repeat is True: inpt = input() if inpt.lower() == 'done': repeat = False elif inpt.lower() == 'undo': # Allows user to undo the word the recently inputted print("Removed %s" % words[len(words) - 1]) words.remove(words[(len(words) - 1)]) # Checks if word will fit inside grid elif len(inpt) > height and len(inpt) > length: print("Word too large.") else: words.append(inpt.upper()) # Prints set of words print(words) alreadyUsed = [] # Empty list # Dictionary holding all the slot directions with with xy coord changes allDirections = {'directionx0': 0, 'directionx1': 1, 'directionx2': 1, 'directionx3': 1, 'directionx4': 0, 'directionx5': -1, 'directionx6': -1, 'directionx7': -1, 'directiony0': -1, 'directiony1': -1, 'directiony2': 0, 'directiony3': 1, 'directiony4': 1, 'directiony5': 1, 'directiony6': 0, 'directiony7': -1} ''' DIRECTION KEY: 0 = North 1 = NorthEast 2 = East 3 = SouthEast 4 = South 5 = SouthWest 6 = West 7 = NorthWest Y Value is flipped! ''' def canWordBeInserted(word, direction, x, y): # Checks if word can be inserted result = True i = 0 for letter in range(0, len(word)): # Checks if the whole word will fit in the grid if isSpotAvailable([x + (i * (allDirections['directionx%d' % direction])), y + (i * (allDirections['directiony%d' % direction]))], word[i]) is False: result = False i += 1 return result def insertLetter(letter, x, y): # Inserts letter into the grid elements[y][x] = letter # Inserts letter alreadyUsed.append([x, y]) alreadyUsed.append(letter) def isSpotAvailable(location, letter): # Checks if 'location'(given as [x, y]) is available for 'letter' result = True for i in range(len(alreadyUsed)): # Loops through alreadyUsed if i % 2 == 0: # If the spot being looked at is a coord pair if alreadyUsed[i][0] == location[0] and \ alreadyUsed[i][1] == location[1] and alreadyUsed[i + 1] != letter: result = False if location[0] >= length or location[0] < 0: # Checks if x-value of location is within the grid result = False if location[1] >= height or location[1] < 0: # Checks if y-value of location is within the grid result = False return result def printKey(): # Finds and prints grid with letters of words standing out for i in range(height): # Iterates through y values string = '' # Empty string for j in range(len(elements[i])): # Iterates through x values doThis = True for k in range(len(alreadyUsed)): # Iterates through alreadyUsed if k % 2 == 0: # Only checks coord pair in alreadyUsed if [j, i] == alreadyUsed[k]: # If that spot is being taken up by part of a word string += (colors.OKBLUE + '%s ' + colors.ENDC) % (elements[i][j]) # Prints letter with color doThis = False # Makes sure it doesn't print again normally (non-colored) break if doThis is True: string += '%s ' % elements[i][j] print(string) def printGrid(): # Prints grid for i in range(height): string = '' for j in range(len(elements[i])): string += '%s ' % elements[i][j] print(string) # Inserts word into grid for word in words: infiniteError = 0 retry = True while retry is True: # Loops until a the word has found a spot where it will fit retry = False infiniteError += 1 if infiniteError >= 15000: # Is this number alright? sys.exit("Process expired. Perhaps there were too many words in too small of a space..") # Chooses random values for x, y, and direction y = random.randint(0, height - 1) x = random.randint(0, length - 1) direction = random.randint(0, 7) if canWordBeInserted(word, direction, x, y) is False: retry = True else: i = 0 for letter in range(0, len(word)): # Inserts word into grid insertLetter(word[letter], x + (i * (allDirections['directionx%d' % direction])), y + (i * (allDirections['directiony%d' % direction]))) i += 1 printGrid() print(words) print("Press ENTER when you would like to the key") input() printKey() response = input("Would you like to save this word search?") if response.lower() == 'yes': title = input("What would you like to call this word search?") path = '' house = input("Are you at your (moms) house or your (dads) house?") if house.lower() == 'dads': path = 'C:\\Users\\jtlov_000\\Desktop\\Everything\\Coding and Programming\\PythonWordSearches' else: path = 'C:\\Users\\Josh\\Desktop\\Everything\\Coding and Programming\\PythonWordSearches' askfiletype = int(input("Do you want a 1)docx file \t2)txt file \t3)rtf file")) filetype = '' while True: if askfiletype == 1: filetype = '.docx' break elif askfiletype == 2: filetype = ".txt" break elif askfiletype == 3: filetype == ".rtf" break else: print("Please re-enter") file1 = open(path + '//' + title + filetype, 'w') # Creates a file of name with title file1.write(title + '\n\n') # Prints grid for i in range(height): string = '' for j in range(len(elements[i])): string += '%s ' % elements[i][j] file1.write(string + '\n') # Prints words file1.write("\n\n") for word in words: file1.write(word + '\t') file1.close() print("Goodbye") sys.exit()
e3131b62735d783016b26f1b6f25ca8754cb2458
IamGianluca/algorithms
/ml/sampling/metropolis.py
2,929
3.625
4
import numpy as np class MetropolisHastings(object): """Implementation of the Metropolis-Hastings algorithm to efficiently sample from a desired probability distributioni for which direct sampling is difficult. """ def __init__(self, target, data, iterations=1000): """Instantiate a *MetropolisHastings* object. Args: target (scipy.stats.Distribution): The target distribution. This distribution should proportionally approximate the desired distribution. NOTE: Any object implementing a *logpdf* method would do the job. data (numpy.array): N-dimensional array containing the observed data. NOTE: Will be soon deprecated. iterations (int): The number of iterations the algorithm needs to run. Attributes: shape (tuple): The dimensions of the *data* array. traces (list): The points sampled through the Markov chain sampling algorithm. """ self.target = target self.data = data # NOTE: will be deprecated in future release self.iterations = iterations self.shape = data.shape self.traces = list() def optimise(self): """Sample from target distribution. Returns: list: A sample of points from the target distribution. """ current_position = self._random_initialisation() for iteration in range(self.iterations): proposal = self._suggest_move(current_position=current_position) if self._evaluate_proposal(current_position, proposal): current_position = proposal self.traces.extend([current_position]) return self.traces def _random_initialisation(self): """Find random point to start Markov chain. """ # TODO: make sure point is within function domain return np.random.rand(self.shape[0]) def _suggest_move(self, current_position): """Suggest new point. Args: current_position (numpy.array): Current position. Returns: numpy.array: New candidate point. """ # TODO: use current_position as mean of randn, to improve efficiency jump = np.random.randn(self.shape[0]) return np.sum((current_position, jump), axis=0) def _evaluate_proposal(self, current, proposal): """Evaluate proposed move. Args: current (numpy.array): Current position. proposal (numpy.array): Proposed move. Returns: bool: Whether the proposed move is accepted. """ acceptance_probability = min( np.exp(self.target.logpdf(x=proposal) - \ self.target.logpdf(x=current)), 1 ) return np.random.uniform() < acceptance_probability
f008d73d640609771b8f2aaa149449a10f7706ee
aniroxxsc/Hackerrank-ProblemSolving-Python
/SuperReducedString
632
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the superReducedString function below. def superReducedString(s): for i in range(0,len(s)-1): if s[i]==s[i+1]: s1=s[0:i] if (i+2)<=len(s): s2=s[i+2:] else: s2="" s=s1+s2 s=superReducedString(s) break if(s==""): s="Empty String" return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = superReducedString(s) fptr.write(result + '\n') fptr.close()
fe82e7566405f33f301201bd5cce475c0147d805
mohasinac/Learn-LeetCode-Interview
/Strings/Count and Say.py
1,812
4.0625
4
""" he count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Explanation: This is the base case. Example 2: Input: 4 Output: "1211" Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". """ class Solution: def countAndSay(self, terms: int) -> str: """ 1 has only 1 2 will 11 as (previous had only single 1) 3 will have 21 as (previous had 2 continous 1 ) 4 will have 1211 as prvious has a single 2 and single 1 5 will have 111221 as previous has single 1 single 2 and then double 1 6 will have 312211 as previous has thrice 1 twice 2 and then double 1 """ ans="1" for i in range(1,terms): n=ans last=n[0] count=0 ans="" for c in n: if c==last: count+=1 else: ans+=str(count)+str(last) count=1 last=c if count: ans+=str(count)+str(last) return ans
81ff46e99809f962f6642b33aa03dd274ac7a16e
mohasinac/Learn-LeetCode-Interview
/Strings/Implement strStr().py
963
4.28125
4
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). """ class Solution: def strStr(self, haystack: str, needle: str) -> int: n = len(needle) h = len(haystack) if n<1 or needle==haystack: return 0 if h<1: return -1 for i, c in enumerate(haystack): if c==needle[0] and (i+n)<=h and all([haystack[i+j]==needle[j] for j in range(1,n)]): return i return -1
7e558fb4d31490ea5317a9b131c8e022e0504f20
msam04/Assignment2.2
/Python_Module2_2.py
236
3.890625
4
# coding: utf-8 # In[19]: for i in range (1, 6): str = "*" for j in range (1, i): str = str + "*" print(str) length = len(str) for j in range (1, len(str) + 1): print(str[:length]) length -= 1
885a56023c3b3877e0d2bccf0db93f3c65351b95
i2mint/stream2py
/stream2py/simply.py
4,464
3.5625
4
""" Helper Function to construct a SourceReader and StreamBuffer in one Example of usage: :: from stream2py.simply import mk_stream_buffer counter = iter(range(10)) with mk_stream_buffer( read_stream=lambda open_inst: next(counter), open_stream=lambda: print('open'), close_stream=lambda open_inst: print('close'), auto_drop=False, maxlen=2, ) as count_stream_buffer: count_reader = count_stream_buffer.mk_reader() print(f'start reading {count_reader.source_reader_info}') for i in count_reader: # do stuff with read data print(i) if count_stream_buffer.auto_drop is False: count_stream_buffer.drop() print('done reading') """ import contextlib from typing import Callable, Any, Optional from stream2py import SourceReader, StreamBuffer from stream2py.utility.typing_hints import ComparableType, OpenInstance @contextlib.contextmanager def mk_stream_buffer( read_stream: Callable[[OpenInstance], Optional[Any]], open_stream: Callable[[], OpenInstance] = None, close_stream: Callable[[OpenInstance], None] = None, info: Callable[[OpenInstance], dict] = None, key: Callable[[Any], ComparableType] = None, maxlen: Optional[int] = 100, sleep_time_on_read_none_seconds: float = None, auto_drop: bool = True, enumerate_data: bool = True, ): """Helper Function to construct a SourceReader and StreamBuffer in one :: from time import sleep from stream2py import mk_stream_buffer # download txt from: https://www.gutenberg.org/cache/epub/1524/pg1524.txt FILE = 'hamlet.txt' with mk_stream_buffer( read_stream=lambda open_inst: next(open_inst, None), open_stream=lambda: open(FILE, 'rt'), close_stream=lambda open_inst: open_inst.close(), key=lambda read_data: read_data[0], maxlen=None, ) as stream_buffer: buffer_reader = stream_buffer.mk_reader() sleep(1) # do stuff with buffer_reader print(buffer_reader.range(start=40, stop=50)) :param read_stream: takes open instance and returns the next read item :param open_stream: open stream and return an open instance such as a file descriptor :param close_stream: take open instance and close the instance :param info: dict help in describing the instance :param key: sort key for read items :param maxlen: max read items to keep in buffer window :param sleep_time_on_read_none_seconds: time to wait if data is not ready to be read :param auto_drop: False is useful when data can be read independent of time and will quickly overflow the buffer maxlen before data is consumed. StreamBuffer.drop() must be called to continue reading after buffer has filled up. Default True. :param enumerate_data: wrap read data in an enumerated tuple. Default True. :return: """ class SimplifiedSourceReader(SourceReader): open_instance: OpenInstance = None open_time = 0 sleep_time_on_read_none_s = sleep_time_on_read_none_seconds read_idx = 0 def open(self): self.read_idx = 0 if open_stream is not None: self.open_instance = open_stream() self.open_time = self.get_timestamp() def read(self): read_data = read_stream(self.open_instance) if enumerate_data: read_data = (self.read_idx, read_data) self.read_idx += 1 return read_data def close(self): if close_stream is not None: close_stream(self.open_instance) @property def info(self): if info is not None: return info(self.open_instance) return { 'open_time': self.open_time, 'open_instance': str(self.open_instance), } def key(self, data: Any): if key is not None: return key(data) return data stream_buffer = StreamBuffer( source_reader=SimplifiedSourceReader(), maxlen=maxlen, sleep_time_on_read_none_s=sleep_time_on_read_none_seconds, auto_drop=auto_drop, ) try: stream_buffer.start() yield stream_buffer finally: stream_buffer.stop()
78ae22f42201983039a2b6aba20195284063b3e4
andrei10t/AdventOfCode
/AdventOfCode2020/day3.py
968
3.546875
4
def readFile(filename) -> list: with open(filename, "r") as f: return [line[:-1] for line in f.readlines()] def readtest() -> list: input = list() with open("test.txt", "r") as f: for line in f.readlines(): input.append(line) return input def part1(file): counter = check(3, 1, file) return counter def check(x, y, input): counter = 0 xs = 0 ys = 0 mod = len(input[0]) while ys < len(input) - 1: xs = (xs + x) % mod ys += y print(xs) print(ys) if input[ys][xs] == "#": counter += 1 print("c" + str(counter)) return counter def part2(input): result = ( check(1, 1, input) * check(3, 1, input) * check(5, 1, input) * check(7, 1, input) * check(1, 2, input) ) return result if __name__ == "__main__": # print(part1(readFile("in.txt"))) print(part2(readFile("in.txt")))
997f0d32c5609f5e9dac7fb94b933f4e28d64809
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO
/exercicio11.py
410
4.15625
4
# 11. Altere o programa anterior para mostrar no final a soma dos números. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 num1 = int(input("Digite o primeiro número inteiro: ")) num2 = int(input("Digite o segundo número inteiro: ")) for i in range (num1 + 1, num2): print(i) for i in range (num2 + 1, num1): print(i) soma = num1 + num2 print("A soma dos dois números inteiros é: ", i + i)
2d0c69eabcd187406a0e982cbc343c88d88a26cb
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO
/exercicio14.py
601
3.96875
4
# 14. Faça um programa que peça 10 números inteiros, calcule e mostre a # quantidade de números pares e a quantidade de números impares. # Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01 import math numero = [[], []] valor = 10 for c in range(1, 11): valor = int(input(f"Digite o {c}º valor: ")) if valor % 2 ==0: numero[0].append(valor) else: numero[1].append(valor) numero[0].sort() numero[1].sort() print(f"Os valores digitados são: {numero}") print(f"Os valores pares digitados são: {numero[0]}") print(f"Os valores ímpares digitados são: {numero[1]}")
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c
Divyendra-pro/Calculator
/Calculator.py
761
4.25
4
#Calculator program in python #User input for the first number num1 = float(input("Enter the first number: ")) #User input for the operator op=input("Choose operator: ") #User input for the second number num2 = float(input("Enter the second number:" )) #Difine the operator (How t will it show the results) if op == '+': print("You choosed for Addition ") print(num1+num2) elif op == '-': print("You choosed for subtraction ") print(num1-num2) elif op == '*': print("You choosed for multiplication ") print(num1*num2) elif op == '/': print("Your choosed for division ") print(num1/num2) else: print("Enter a valid operator") print("Some valid operators: " "+ " "- " "* " "/ ")
1f8f158a5528bff42b1eb0876794211096386475
gruenwalds/geekbrains
/Gruenwald_4_4.py
396
3.921875
4
digits = [int(element) for element in input("Введите числа: ").split()] even_number = 0 sum_numbers = 0 for counter in digits: if counter % 2 == 0: even_number = even_number + counter for nums in range(1, len(digits), 2): sum_numbers = sum_numbers + digits[nums] sum_numbers = sum_numbers + even_number print("Сумма чисел равна: ", sum_numbers)
006703a80291ab29120be71a5a713a213d8d45bc
DeFeNdog/LeetCode
/arrays_and_strings/first-unique-character-in-a-string.py
667
4.0625
4
''' ## First Unique Character in a String Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. ''' from collections import Counter hash class Solution: def firstUniqChar(self, s): count = Counter(s) for idx, ch in enumerate(s): if count[ch] == 1: return idx return -1 if __name__ == '__main__': s = Solution() print(s.firstUniqChar("leetcode")) print(s.firstUniqChar("loveleetcode"))
b7ce6e275957e54ae4a4fd8e70f44a422396cbae
DeFeNdog/LeetCode
/linked_lists/add-two-numbers.py
2,323
3.90625
4
''' ## Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. Solution: Doubly-linked list Time complexity: O(max(m,n)). Assume that mmm and nnn represents the length of l1 and l2 respectively, the algorithm above iterates at most max⁡(m,n) times. Space complexity : O(max⁡(m,n)). The length of the new list is at most max⁡(m,n)+1. ''' class ListNode: def __init__(self, val): self.val = val self.next = None self.previous = None self.head = None self.tail = None return def add_list_item(self, item): if not isinstance(item, ListNode): item = ListNode(item) if self.head is None: self.head = item else: self.tail.next = item self.tail = item return def traverse_list(self): if self.head is None: return else: n = self.head while n is not None: print(n.val, " ") n = n.next class Solution: def addTwoNumbers(self, l1=None, l2=None): dummyHead = ListNode(0) p, q = l1, l2 curr = dummyHead carry = 0 while p or q: x = p.val if p else 0 y = q.val if q else 0 sum = carry + x + y carry = sum / 10 curr.next = ListNode(sum % 10) curr = curr.next if p: p = p.next if q: q = q.next if carry > 0: curr.next = ListNode(carry) return dummyHead.next if __name__ == '__main__': s = Solution() ll1 = ListNode(0) ll1.add_list_item(3) ll1.add_list_item(4) ll1.add_list_item(2) # ll1.traverse_list() ll2 = ListNode(0) ll2.add_list_item(4) ll2.add_list_item(6) ll2.add_list_item(5) # ll2.traverse_list() print(s.addTwoNumbers(ll1, ll2))
8a3f462060774d17383f404bf97467015cd94489
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex053_detector_de_palindromo.py
1,157
4.15625
4
# Class Challenge 13 # Ler uma frase e verificar se é um Palindromo # Palindromo: Frase que quando lida de frente para traz e de traz para frente # Serão a mesma coisa # Ex.: Apos a sopa; a sacada da casa; a torre da derrota; o lobo ama o bolo; # Anotaram a data da maratona. # Desconsiderar os espaços e acentos. Programa tira os espaços print('Descobrindo se a frase é um Palindromo.') frase = str(input('Digite uma frase: ')).strip().upper() array = frase.split() junto = ''.join(array) n = len(junto) s = 0 for a in range(1, n+1): if junto[a-1] != junto[n-a]: s += 1 if s == 0: print('A frase é um Palindromo.') else: print('A frase não é um Palindromo') # Exemplo do professor print('\nExemplo do professor: ') palavras = frase.split() inverso = '' for letra in range(len(junto)-1, -1, -1): inverso += junto[letra] print('O inverso de {} é {}.'.format(junto, inverso)) if inverso == junto: print('Temos um Palindromo') else: print('Não temos um Palindromo') # 3ª Alternativa como o Python inverso2 = junto[::-1] # Frase junto, do começo ao fim, porém de traz para frente # Por isso o -1 print(inverso2)
51fba057f0a7253f1ad30a5c0d6c38171b888e77
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex082_dividindo_valores_em_varias_listas.py
1,188
4.03125
4
# Class Challenge 17 # Ler vaios números # Ter duas listas extras, só com pares e ímpares # Mostrar as 3 listas # Dica: Primeiro le os valores, depois monta as outras duas listas big = list() par = list() impar = list() while True: big.append(int(input('Enter a number: '))) resp = ' ' while resp not in 'YN': resp = str(input('Do you want to continue? [Y/N] ')).strip().upper()[0] if resp == 'N': break print('='*50) print(f'All numbers entered have been: {big}') for a in big: if a % 2 == 0: if a not in par: par.append(a) if a % 2 == 1: if a not in impar: impar.append(a) print(f'All the even numbers that appear are: {par}') print(f'All the odd numbers that appear are: {impar}') # Teacher example: print('\nTeacher exaple:') num = [] p = [] i = [] while True: num.append(int(input('Enter a number: '))) resp = str(input('Do you wanna continue? [S/N]')) if resp in 'Nn': break for v in num: if v % 2 == 0: p.append(v) else: i.append(v) print('-=' * 30) print(f'The full list is: {num}') print(f'The even list is: {p}') print(f'The odd list is: {i}')
9d82ae750f0a2f3d2531e9832d9e32ae142a67ea
NathanaelV/CeV-Python
/Aulas Mundo 1/aula09_manipulando_texto.py
4,673
4.34375
4
# Challenge 022 - 027 # Python armazena os carcteres de uma string, as letras de uma frase, separadamente # Python conta os espaços e a contagem começa com 0 # Para exibir um caracter específico só especificar entre [] # Fatiamento frase = 'Curso em Vídeo Python' print('\nFATIAMENTO!\n') print('frase[9]:', frase[9]) print('frase[13]:', frase[13]) print('frase[9:13]:', frase[9:13]) # Do 9 ao 13, sem incluir o 13 # Caso eu queira incluir até o final da frase se inclui um número a mais do que # foi contado. Se a contagem acabar em 20 coloco [9:21] assim aparece tudo print('frase[9:21:2]:', frase[9:21:2]) # Vai do 9 ao 21 pulando de 2 em 2 print('frase[:5]:', frase[:5]) # Começa no 0 e vai até o 4, pois exclui o 5 print('frase[15:]:', frase[15:]) # Começa no 15 e vai até o último print('frase[9::3]:', frase[9::3]) # Começa no 9 e vai até o final pulando de 3 em 3 # Analise print('\nANALISE!\n') # fução length print('Sentence Length. len(frase): ', len(frase)) # Quantos carcteres tem na palavra, incluindo so espaços # Caso use com uma lista, mostrará quantos componentes tem o Array o = frase.count('o') # Conta quantas vezes o letra 'o' minusculo aparece na frase # Python diferencia maiúsculo de minúsculo print('Quantas vezes a letra o aparece na frase: ', format(o)) print('Quantas veses a letra o aparece até o carcater 13:', end=' ') print(frase.count('o', 0, 13)) # Quantas vezes a letra 'o' aparece na frase # Até o caracter 13, sem contar o 13, contagem com fatiamento print('Apartir de que carcter aparece o trecho deo:', end=' ') print(frase.find('deo')) # Indica onde começa os caracteres procurados, 'deo' print('Encontrar a palavra Android: ', end='') print(frase.find('Android')) # Se pedir para localizar uma palavra que não existe # na String, será retornado um valor: -1 print('A palavra Curso está na frase?: ', 'Curso' in frase) # para saber se a palavra Curso existe na frase # Responde True or False print('Prucurar vídeo, v minúsculo: ', frase.find('vídeo')) print('Usando comando lower: ', frase.lower().find('vídeo')) #Transformação print('\nTRANSFORMAÇÃO!\n') print('frase.replace(Python,android): ', frase.replace('Python', 'Android')) # Troca a primeira palavra pela segunda. # Não precisa ter o mesmo tamanho. o Python adapta # Não é possível atribuir outroa valor a String. O adroid só aparece no lugar # de Python na impressão, mas na memoria ainda é Python # Para conseguir mudar é necessário usar outro comando frase = frase.replace('Python', 'Android') print('O Valor da Str frase foi alterada: {}'.format(frase)) frase.upper() # Coloca todas as letras em maiúscula frase.lower() # Transforma tudo em minúsculo frase.capitalize() # Joga tudo para minusculo e depois só coloca a primeira letra maiúscula frase.title() # Transforma todas as letras depois dos espaços em Maiúsculo # Funções para remover os espaços no começo da frase # Acontece da pessoa dar alguns espaços antes de começar a digitar frase2 = ' Aprenda Python ' frase2.strip() # Remove os espaços antes da primeira letra e os que vem depois # Da ultima letra frase2.rstrip() # Só Remove os espaços do lado direito Right, por causa do r frase2.lstrip() # Só Remove os espços do lado esquerdo left, por causa do l # Divisão print('\nDIVISÃO E JUNSÃO\n') print('Comando frase.split(): \n', frase.split()) # Cria uma divisão onde existir espaços. Criando uma nova lista separada = frase.split() print(separada[0]) # Mostra o primeiro intem da lista print(separada[0][2]) # No primeiro intem da lista, vai mostrar a 3ª letra print(len(separada)) # Mostra a quantidade de elementos na lista print('Join: ') print('-'.join(frase)) # Junta as palvras divididas usado o que tiver entre ''. # Nesse caso teria - entre as palavras, pois fiz '-'.join(frase) # Para escrever um texto grande usa-se: print("""Texto muito Grande com Enter""") # O texto é impresso incluindo os Enter print('\nTexto ' # Desse jeito o python pula linhas aqui 'pequeno com aspas ' # Mas na hora de colocar na tela 'simples e enter') # Sai tudo em uma só linha # Combinação de funções: print('Quntos O maiúsculos tem na frase: ') print(frase.count('O')) print('E agora? Usando função upper():') print(frase.upper().count('O')) # Espaço também conta como carcter frase3 = ' Curso em Video Python ' # Não aparece os espaços na impressão print('Frase com espaços: {}.\nQuantidade: {}'.format(frase, len(frase3))) print('Com corte de espaços: {}'.format(len(frase3.strip())))
4d7ae2dfa428ee674fdd151230a36c39c09e7055
NathanaelV/CeV-Python
/Aulas Mundo 3/aula19_dicionarios.py
2,623
4.21875
4
# Challenge 90 - 95 # dados = dict() # dados = {'nome':'Pedro', 'idade':25} nome é o identificador e Pedro é o valor # idade é o identificador e 25 é a idade. # Para criar um novo elemento # dados['sexo'] = 'M'. Ele cria o elemento sexo e adiciona ao dicionario # Para apagar # del dados['idade'] # print(dados.values()) Ele retornará - 'Pedro', 25, 'M' # print(dados.keys()) It will return - 'nome', 'idade', 'sexo' # print(dados.items()) it will return all things - 'name', 'Pedro' ... # Esses conceitos são bons para laços, for, while filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'} for k, v in filme.items(): print(f'O {k} é {v}') print() person = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 40} print(f'{person["nome"]} is {person["idade"]} years old.') # Não posso usar person[0] ele não reconhece print(f'Using person.keys(): {person.keys()}') print(f'Using person.values(): {person.values()}') print(f'Using person.items(): {person.items()}') # Using for: print('\nUsing for:') print('\nUsing For k in person.key: or For k in person:') for k in person.keys(): # = to use person print(k) print('\nUsing k in person.values():') for k in person.values(): print(k) print('\nUsing k, v in person.items():') for k, v in person.items(): print(f'V = {v}; K = {k}') del person['sexo'] print("\nAfter using del person['sexo']") for k, v in person.items(): print(f'V = {v}; K = {k}') # Alterando e adicionando elementos: print('\nChanging the name and adding weight.') person['peso'] = 98.5 person['nome'] = 'Leandro' for k, v in person.items(): print(f'V = {v}; K = {k}') # Criando um dicionário dentro de uma lista: Brazil = list() estado1 = {'UF': 'Rio Janeiro', 'sigla': 'RJ'} estado2 = {'UF': 'São Paulo', 'sigla': 'SP'} Brazil.append(estado1) Brazil.append(estado2) print(f'Brazil: {Brazil}') print(f'Estado 2: {estado2}') print(f'Brazil[0]: {Brazil[0]}') print(f"Brazil[0]['uf']: {Brazil[0]['UF']}") print(f"Brazil[1]['sigla']: {Brazil[1]['sigla']}") # Introsuzindo Valores: print('\nIntroduzindo Valores: ') brasil = list() estado = dict() for a in range(0, 3): estado['uf'] = str(input('UF: ')) estado['sigla'] = str(input('Sigla: ')) brasil.append(estado.copy()) # Caso use o [:] dará erro. for e in brasil: print(e['sigla'], ' = ', e['uf']) # Mostra os identificadores e os valores print('\nItems: ') for e in brasil: for k, v in e.items(): print(f'O compo {k} tem o valor {v}') # Mostra os valore dentro da lista print('\nValues:') for e in brasil: for v in e.values(): print(v, end=' - ') print()
c8ac81bcd8433c0749e3afc2330ff91a325b5180
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex068_jogo_do_par_ou_impar.py
1,810
3.921875
4
# Class Challenge 15 # Make a game to play 'par ou impar' (even or odd). The game will only stop if the player loses. # Show how many times the player has won. from random import randint c = 0 print('Lets play Par ou Impar') while True: comp = randint(1, 4) np = int(input('Enter a number: ')) rp = str(input('type a guess [P/I]: ')).strip().upper()[0] while rp not in 'PpIi': rp = str(input('Enter a valid guess [P/I]: ')).strip().upper()[0] print(f'You played {np} and computer played {comp}') s = np + comp if s % 2 == 0: r = 'P' else: r = 'I' if rp == r: print('~~' * 20) print('CONGRATULATIONS! You Win.') print('Lets play again...') print('~~' * 20) c += 1 else: print('~~' * 20) print('The Computer win') print(f'You won {c} matches in a row') print('Try again.') print('~~' * 20) break # Teacher Example: print('\nTeacher example: ') v = 0 while True: jogador = int(input('Digite um valor: ')) computador = randint(1, 4) total = jogador + computador tipo = '' while tipo not in 'PI': tipo = str(input('Par ou Ímpar? [P/I] ')).strip().upper()[0] print(f'Você jogou {jogador} e o computador {computador}. Total de {total}', end='') print('DEU PAR' if total % 2 == 0 else 'DEU ÍMPAR') if tipo == 'P': if total % 2 == 0: print('Você VENCEU!') v += 1 else: print('Você PERDEU!') break elif tipo == 'I': if total % 2 == 1: print('Você VENCEU!') v += 1 else: print('Você PERDEU!') break print('Vamos Jogar Novamente...') print(f'GAME OVER. Você venceu {v} vez(es).')
1426a37e040bc9a849200f43c5cc612fee91e36e
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex040_aquele_classico_da_media.py
1,058
3.875
4
# Class Challenge 12 # Calcular a média e exibir uma mensagem: # Abaixo de 5.0 reprovado, entre 5 e 6.9 recuperação e acima de 7 aprovado cores = {'limpo': '\033[m', 'negrito': '\033[1m', 'vermelho': '\033[1;31m', 'amarelo': '\033[1;33m', 'verde': '\033[1;32m'} n1 = float(input('Insira a 1ª nota do aluno: ')) n2 = float(input('Insira a 2ª nota do aluno: ')) m = n1 * 0.5 + n2 * 0.5 if m < 5: print('Voce foi {0}REPROVADO!{1} Sua média foi {2}{3:.1f}{1}' .format(cores['vermelho'], cores['limpo'], cores['negrito'], m)) elif 5 <= m < 6.9: print('Você está de {0}RECUPERAÇÃO!{1} Sua média foi {2}{3:.1f}{1}' .format(cores['amarelo'], cores['limpo'], cores['negrito'], m)) else: print('{0}PARABÉNS{1} você foi {2}APROVADO!{1} Sua média foi {0}{3:.1f}{1}' .format(cores['negrito'], cores['limpo'], cores['verde'], m)) # Exemplo do professor: print('Com a nota {:.1f} e a nota {:.1f} sua média foi {:.1f}.'.format(n1, n2, m)) # Teste lógico segue da mesma maneira
c6bd3a2159ebf010f5a9e17f9e1b1c8a968f88f2
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex005_antecessor_e_sucessor.py
386
4.03125
4
# Class challenge 007 # Mostrar o antecessor e o sucessor de um numero inteiro n = int(input('\nDigite Um numero inteiro: ')) a = n - 1 s = n + 1 print('O antecessor do numero {} é {}.'.format(n, a), end=' ') print('E o sucessor é {}'.format(s)) # Exemplo do professor n = int(input('Digite um número: ')) print('O antecessor de {} é {} e o sucessor é {}.'.format(n, n-1, n+1))
1bc7549e958d98847832cc25cf3ce84a242bb458
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex027_primeiro_e_ultimo_nome_de_uma_pessoa.py
421
3.9375
4
# Class Challenge 09 # Ler o nome completo de uma pessoa e mostar o primeiro e o último nome = str(input('Digite o seu nome completo: ')).strip() a = nome.split() print('O primeiro nome é {} e o último é {}'.format(a[0], a[0])) # Exemplo do Professor print('\nExemplo do Professor\n') print('Olá, muito prazer.') print('Seu primeiro nome é: {}'.format(a[0])) print('Seu útimo nome é: {}'.format(a[len(a)-1]))
8ca33acd165cec49c7c84b75394da1cf6b7d1f0d
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex090_dicionario_em_python.py
930
3.84375
4
# Class Challenge 19 # Read name and media of several students # Show whether the student has failed or passed student = dict() na = str(input('Enter the student name: ')) m = float(input('Enter the student media: ')) student['name'] = na student['media'] = m if m >= 7: student['Situation'] = 'Aprovado' elif 5 <= m < 7: student['Situation'] = 'Recuperação' else: student['Situation'] = 'Reprovado' print('-=' * 30) for v, i in student.items(): print(f' - {v.capitalize()} es equal a {i}') # Teacher Example: print('\nTeacher Example:') aluno = dict() aluno['Nome'] = str(input('NOme: ')) aluno['media'] = float(input(f'Media do {aluno["nome"]}')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) for k, v in student.items(): print(f' - {k} é igual {v}')
1e8dc17f6182d9c87f9c60a56e49021c5c4c7114
NathanaelV/CeV-Python
/Modulos Curso em Video/ex107_exercitando_modulos_em_python.py
499
3.828125
4
# Class Challenge 22 # Criar um módulo chamado moeda.py # Ter as funções aumentar() %; diminuir() %; dobrar() e metade() # Fazer um programa(esse) que importa e usa esses módulos # from ex107 import moeda from ex107 import moeda num = float(input('Enter a value: ')) print(f'Double of {num} is {moeda.dobrar(num)}') print(f'A half of {num} is {moeda.metade(num)}') print(f'{num} with 15% increase is {moeda.aumentar(num, 15)}') print(f'{num} with 30% reduction is {moeda.diminuir(num, 30)}')
ee8ebbe66eaae522f183e71a96c5b6bf218b34ad
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex031_custo_da_viagem.py
538
3.84375
4
# Class Challenge 10 # Calcular o preço da passagem de ônibus # R$ 0,50 para viagens até 200 km # R$ 0,45 para viages acima de 200 km d = int(input('Qual a distância da sua viagem? ')) if d <= 200: p = d * 0.5 else: p = d * 0.45 print('O preço da sua passagem é R$ {:.2f}'.format(p)) # Exemplo do professor print('\nExemplo do professor!') print('você está prestes a começar uma viagem de {} km'.format(d)) preço = d * 0.50 if d <= 200 else d * 0.45 print('E o preço da sua passagem será {:.2f}'.format(preço))
d76dc80b873a755892779f45844e57ce177ac511
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex088_palpites_para_a_mega_sena.py
1,652
4.0625
4
# Class Challenge 18 # Ask the user how many guesses he wants. # Draw 6 numbers for each guess in a list. # In a interval between 1 and 60. Numbers can't be repeated # Show numbers in ascending order. # To use sleep(1) from random import randint from time import sleep luck = list() mega = list() print('=' * 30) print(f'{"MEGA SENNA!":^30}') print('=' * 30) guess = int(input('How many guesses would you like? ')) for a in range(0, guess): while True: num = randint(1, 60) if num not in luck: luck.append(num) if len(luck) == 6: break luck.sort() mega.append(luck[:]) luck.clear() print(f'\n=-=-=-=-= Drawing {guess} Games =-=-=-=-=') sleep(0.5) for n, m in enumerate(mega): print(f'Game {n+1:<2}: [ ', end='') for a in range(0, 6): if a < 5: print(f'{m[a]:>2}', end=' - ') else: print(f'{m[a]:>2} ]') sleep(0.5) print(f'{" < GOOD LUCK! > ":=^35}') # Teacher Example: print('\nTeacher Example: ') lista = list() jogos = list() print('-' * 30) print(f'{"JOGA NA MEGA SENA":^30}') print('-' * 30) quant = int(input('Quantos jogos você quer que eu sorteie? ')) tot = 1 while tot <= quant: cont = 0 while True: num = randint(1, 60) if num not in lista: lista.append(num) cont += 1 if cont >= 6: break lista.sort() jogos.append(lista[:]) lista.clear() tot += 1 print('-=' * 3, f' SORTEANDO {quant} JOGOS ', '-=' * 3) for i, l in enumerate(jogos): print(f'Jogo {i+1}: {l}') sleep(0.5) print('-=' * 5, f'{"< BOA SORTE >":^20}', '-=' * 5)
8ea4a1eae9758fac4e17895d3a290b4b5b7e56bf
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex024_verificando_as_primeiras_letras_de_um_texto.py
839
4.0625
4
# Class Challenge 09 # Ler o nome da Cidade e ver se começa com a palavra 'Santo' cidade = input('Digite o nome da sua cidade: ') minusculo = cidade.lower().strip().split() # primeira = minu.strip() # p = primeira.split() print('Essa cidade tem a palavra santo?: {}'.format('santo ' in minusculo)) print('Santo é a primeira palavra?: {}'.format('santo ' in minusculo[0])) # Se escrever kjalSANTO ele avisa como True # print('Posição sem espaços: {}'.format(minu.find('santo'))) print('A palavra Santo aparece na posição: {}'.format(cidade.lower().find('santo'))) # Exemplo do Professor print('\nExemplo do Professor:') cid = str(cidade).strip() # Sempre que for ler uma String, usar o strip() para tirar os espaços indesejados print(cid[:5].lower() == 'santo') # Irá ler só até a 5ª lentra e comparar se é igual a santo
8e28da8e0eb769a6a9735bb6edf36567011b2a0a
NathanaelV/CeV-Python
/Aulas Mundo 3/aula20_funçoes_parte1.py
1,450
4.1875
4
# Challenge 96 - 100 # Bom para ser usado quando um comando é muito repetido. def lin(): print('-' * 30) def título(msg): # No lugar de msg, posso colocar qualquer coia. print('-' * 30) print(msg) print('-' * 30) print(len(msg)) título('Im Learning Python') print('Good Bye') lin() def soma(a, b): print(F'A = {a} e B = {b}') s = a + b print(f'A soma A + B = {s}') print('\nSomando dois Valores') soma(4, 6) soma(b=5, a=8) # Posso inverter a ordem, contanto que deixe explicito quem é quem # Emapacotamento def cont(*num): # Vai pegar os parametros e desempacotar, não importq quantos print(num) # Vai mostrar uma tupla, entre parenteses. # Posso fazer tudo que faria com uma tupla def contfor(*num): for v in num: print(f'{v}', end=', ') print('Fim') def contar(*num): tam = len(num) print(f'Recebi os valores {num} e ao todo são {tam} números') print('\nContando o número de itens') contfor(1, 2, 3, 5, 3, 2) cont(1, 7, 3) contar(3) def dobra(lst): # Por ser uma lista, não preciso usar o * pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 print('\nDobrando valores') value = [5, 3, 6, 3, 8, 9, 0] print(value) dobra(value) print(value) def somamelhor(*num): s = 0 for n in num: s += n print(f'A soma de {num} é igual a {s}.') print('\nSoma varios valores') somamelhor(3, 5, 1, 3) somamelhor(3, 5)
560596b12e9cda1ebdadfb4ab2b5c945ad0265d1
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex103_ficha_do_jogador.py
1,173
4.21875
4
# Class Challenge 21 # Montar a função ficha(): # Que recebe parametros opcionais: NOME de um jogador e quantos GOLS # O programa deve mostrar os dados, mesmo que um dos valores não tenha sido informado corretamente # jogador <desconhecido> fez 0 gols # Adicionar as docstrings da função def ficha(name='<unknown>', goals=0): """ -> Function to read a player name and scored :param name: (Optional) If user don't enter a name, the program will print '<unknown>' :param goals: (Optional) If user don't enter number of goals, the program will print 0 :return: No return """ print(f'Player {name} scored {goals} goals.') n = input('Whats player name: ') g = input('How many goals player scored: ') if n == '' and g == '': ficha() elif n == '': ficha(goals=g) elif g == '': ficha(n) else: ficha(n, g) # Teacher example: def fichap(nome='<desconhecido>', gol=0): print(f'O jogador {nome} fez {gol} gol(s).') # Principal Program n = str(input('Nome do Jogador: ')) g = str(input('Número de gol(s): ')) if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == '': ficha(goals=g) else: ficha(n, g)
f1f9c6ff93b2e33c013618b98735aa2c128f980f
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex051_progressao_aritimetica.py
300
3.859375
4
# Class Challenge 13 # Ler o primeiro termo e a razão da P.A. e mostrar os 10 primeiros números print('{:=^40}'.format(' 10 TERMOS DE UMA PA ')) t = int(input('Digite o 1º termo: ')) r = int(input('Digete a razão da PA: ')) for a in range(t, t + 10*r, r): print(a, end=', ') print('\nFim!')
143b16bde692bfc1ace62443b270d9dd50d8185c
NathanaelV/CeV-Python
/Exercicios Mundo 1/ex003b.py
357
4.09375
4
# Class Challenge 006 # Para números Inteiros a = int(input('Digite um número: ')) b = int(input('Digete outro número: ')) c = a + b print('A soma entre {} e {} é: {}'.format(a, b, c)) #Para números Reais d = float(input('Digite um número: ')) e = float(input('Digite outro número: ')) f = d + e print('A soma entre {} e {} é: {}'.format(d, e, f))
c0f6d267dcdcd1a2dc364976bb815a9e7a524cb9
arjngpta/miscellaneous
/experiment.py
239
3.5625
4
import os i = 0 n = [1,2,3] file_list = os.listdir(os.getcwd()) for file_name in file_list: i = i + 1 if i in n: print "i is in n" else: print "i is not in n" print i print n
090e9e030c462324d39a04eab7f05a2e44e2c8a9
Scuba-Chris/game_of_greed
/game_of_greed.py
3,808
3.53125
4
import random from collections import Counter import re class Game: def __init__(self, _print=print, _input=input): self._print = print self._input = input # self._roll_dice = roll_dice self._round_num = 10 self._score = 0 self.rolled = [] self.keepers = [] def calculate_score(self, dice): roll_counter = Counter(dice) while True: score_count = 0 if len(roll_counter) > 0: if len(roll_counter) == 6: return 1500 elif len(roll_counter) == 3 and roll_counter.most_common()[2][1] == 2: return 1500 for key, value in roll_counter.items(): if roll_counter[5] == 4 and roll_counter[1] == 2: score_count += 2000 elif key == 1 and value == 6: score_count += 4000 elif key == 1 and value == 5: score_count += 3000 elif key == 1 and value == 4: score_count += 2000 elif key == 1 and value == 3: score_count += 1000 elif key >= 2 and value == 3: score_count += (key)*100 elif key >= 2 and value == 4: score_count += (key)*200 elif key >= 2 and value == 5: score_count += (key)*300 elif key >= 2 and value == 6: score_count += (key)*400 elif key == 1 and value <= 2: score_count += (value)*100 elif key == 5 and value < 3: score_count += (value)*50 roll_counter.popitem() else: break return score_count return 0 def roll_dice(self, num_dice): return [random.randint(1,6) for i in range(num_dice)] def dice_handling(self, num_dice=6): selected_dice = () self.rolled = self.roll_dice(num_dice) # selected_dice = tuple(int(char) for char in self.keepers) self._print(selected_dice) # def validate_roll(): # roll_counter = Counter(roll) # keepers_counter = Counter(keepers) # return len(keepers_counter - roll_counter) def dice_inputs(self, message): while True: try: user_input = self._input(message) user_input = [int(num) for num in user_input] for num in user_input: if 1 > num or num > 6: raise ValueError('please enter 1 -6') # regex_obj = re.compile(r'[1-6]{1-6}') # match_obj = regex_obj.match(user_input) except ValueError: self._print('Please only enter numbers') continue else: return user_input def play(self): self._print('welcome to game of greed!') start_awnser = self._input('are you ready to play? - ') if start_awnser == 'y': self.dice_handling() self._print(self.rolled) held_dice_returned_str = (self.dice_inputs('what numbers would you like to keep? - ')) # held_dice = re.findall(r'[1-6]{1,6}', str) self.keepers.append(held_dice_returned_str) else: self._print('ok. maybe another time') if __name__ == "__main__": game = Game() game.play() game.dice_handling() # try: # game.calculate_score(dice) # print(game.roll_dice(6)) # except: # print('well then')
5d86ca4b127b79be2a7edc2a93e45dfc0502ccd7
JiJibrto/lab_rab_12
/individual2.py
1,358
4.34375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # Реализовать класс-оболочку Number для числового типа float. Реализовать методы # сложения и деления. Создать производный класс Real, в котором реализовать метод # возведения в произвольную степень, и метод для вычисления логарифма числа. import math class Number: def __init__(self, num): self.a = float(num) def sum(self, b): return self.a + b def deg(self, b): return self.a / b class Real (Number): def expo(self, b): return self.a ** b def log(self, b): return math.log(self.a, b) if __name__ == '__main__': print("Инициализация обьекта класса Number") a = Number(input("Enter a> ")) print(f"Сумма чисел: {a.sum(float(input('Enter b> ')))}") print(f"Деление чисел: {a.deg(float(input('Enter b> ')))}") print("Инициализация обьекта класса Real") b = Real(input("Enter a> ")) print(f"Нахождение логарифма: {b.log(int(input('Enter b> ')))}") print(f"Возведение в степень: {b.expo(int(input('Enter b> ')))}")
c1ab809f56fb6edf4827b1978bdb32bc9b7bb532
nickolasbmm/lista2ces22
/ex11.py
550
3.78125
4
#Function with argument list def square_sequence(*arglist): print("Squared sequence: ",end="") for x in arglist: print("{} ".format(x**2),end="") print("") print("Example function with argument list") print("Initial sequence: 1 2 3 4 5") square_sequence(1,2,3,4,5) #Functio with argument dictionary def person_function(**argdict): for key in argdict: print(key," works as: ",argdict[key]) print("Example function with argument dictionary") person_function(Anne = "Student", John = "Professor", Ralph = "Shopkeeper")
b765209f2c2fc302496ec89993d73d87e2d80d56
rbngtm1/Python
/data_structure_algorithm/array/Plus_0ne.py
464
3.90625
4
given_array = [1, 2, 3, 4, 5] # length = len(given_array)-1 #print(length) # for i in range(0, len(given_array)): # #print(i) # if i==length: # given_array[i]=given_array[i]+1 # else: # given_array[i]=given_array[i] # print(given_array) ############################################ mylastindex=(given_array[-1]+1) print(mylastindex) remaining_array=(given_array[:-1]) remaining_array.append(mylastindex) print(remaining_array)
0036738f5c4ebd10ed148ed836ff304ead8b66f0
rbngtm1/Python
/data_structure_algorithm/array/contains_duplicate.py
374
3.96875
4
array = [1,2,3,4] my_array = [] # for i in array: # if i not in my_array: # my_array.append(i) # if array == my_array: # print('false') # else: # print('true') def myfunc(): for i in range(len(array)): if array[i] in my_array: return True else: my_array.append(array[i]) return False a=myfunc() print(a)
c80bffe95bc94308989cec03948a4a91239d13aa
rbngtm1/Python
/data_structure_algorithm/array/remove_duplicate_string.py
398
4.25
4
# Remove duplicates from a string # For example: Input: string = 'banana' # Output: 'ban' ########################## given_string = 'banana apple' my_list = list() for letters in given_string: if letters not in my_list: my_list.append(letters) print(my_list) print (''.join(my_list)) ## possile solution exist using set data structure but ## set structure is disorder
ee2da66a029f7bc9afad26c6025573e21bea8ae9
gyeongchan-yun/useful-python
/threading_event_queue.py
679
3.515625
4
import threading from queue import Queue evt_q = Queue() def func(): number = int(threading.currentThread().getName().split(":")[1]) if (number < 2): evt = threading.Event() evt_q.put(evt) evt.wait() for i in range(10): print ("[%d] %d" % (number, i)) if (number > 2): for _ in range(evt_q.qsize()): evt = evt_q.get() evt.set() if __name__ == '__main__': threads = [threading.Thread(target=func, name="name:%i" % i) for i in range(0, 4)] for thread in threads: thread.start() for thread in threads: thread.join() print ("exit")
1984969edc15b4e08db867aae9241e40ad8ff8ec
AbdAyyad/opensouq
/opensouqback/stringsapp/hamming_distance.py
546
3.671875
4
class hamming_distance: def __init__(self, first_string, second_string): self.first_string = first_string self.second_string = second_string self.initlize_disance() def initlize_disance(self): self.distance = 0 for i in range(len(self.first_string)): if self.first_string[i] != self.second_string[i]: self.distance +=1 def __str__(self): return 'strings: {} {}\nhamming distance: {}'.format(self.first_string, self.second_string, self.distance)
30e54e336c427637344711d8f9646d2b1fd6d43e
wendyzou02/python-test
/demolib.py
147
3.953125
4
def sum_even(start_num, end_num): sum = 0 for x in range( start_num, end_num+1 ): if x%2==0: sum += x return sum
bee174e6985d80c2a2cceb86590b5db9dbc00af6
ingridcoda/knapsack-problem
/src/model.py
575
3.578125
4
class Item: def __init__(self, size, value): self.size = size self.value = value def __str__(self): return f"{self.__dict__}" def __repr__(self): return self.__str__() class Knapsack: def __init__(self, size=0, items=None): self.size = size self.items = [] if items: self.items = items def __str__(self): return f"{self.__dict__}" def __repr__(self): return self.__str__() def get_total_value(self): return sum([item.value for item in self.items])
d2b48f3f46963d6b8a07c766acd0475e6adb4487
jbloom04/python-test
/functions.py
193
3.546875
4
batteries=[1,3,7,5] def light(batt1,batt2): # if batt1 % 2 == 0 and batt2 % 2 == 0: if batt1 in batteries and batt2 in batteries: return True else: return False
342c9e28fead18d6fc82c40892f6743b1926564a
sofieditmer/cds-visual
/assignments/assignment3_EdgeDetection/edge_detection.py
4,205
3.578125
4
#!/usr/bin/env python """ Load image, draw ROI on the image, crop the image to only contain ROI, apply canny edge detection, draw contous around detected letters, save output. Parameters: image_path: str <path-to-image-dir> ROI_coordinates: int x1 y1 x2 y2 output_path: str <filename-to-save-results> Usage: edge_detection.py --image_path <path-to-image> --ROI_coordinates x1 y1 x2 y2 --output_path <filename-to-save-results> Example: $ python edge_detection.py --image_path data/img/jefferson_memorial.jpeg --ROI_coordinates 1400 880 2900 2800 --output_path output/ Output: image_with_ROI.jpg image_cropped.jpg image_letters.jpg """ # Import dependencies import os import sys sys.path.append(os.path.join("..")) import cv2 import numpy as np import argparse # Define a function that automatically finds the upper and lower thresholds to be used when performing canny edge detection. def auto_canny(image, sigma=0.33): # Compute the median of the single channel pixel intensities v = np.median(image) # Apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(image, lower, upper) # Return the edged image return edged # Define main function def main(): # Initialise ArgumentParser class ap = argparse.ArgumentParser() # Argument 1: the path to the image ap.add_argument("-i", "--image_path", required = True, help = "Path to image") # Argument 2: the coordinates of the ROI ap.add_argument("-r", "--ROI_coordinates", required = True, help = "Coordinates of ROI in the image", nargs='+') # Argument 3: the path to the output directory ap.add_argument("-o", "--output_path", required = True, help = "Path to output directory") # Parse arguments args = vars(ap.parse_args()) # Output path output_path = args["output_path"] # Create output directory if it doesn't exist already if not os.path.exists("output_path"): os.mkdir("output_path") # Image path image_path = args["image_path"] # Read image image = cv2.imread(image_path) # Extract filename from image path to give image a unique name image_name, _ = os.path.splitext(os.path.basename(image_path)) ## DRAW ROI AND CROP IMAGE ## # Define ROI coordinates ROI_coordinates = args["ROI_coordinates"] # Define top left point of ROI top_left = (int(ROI_coordinates[0]), int(ROI_coordinates[1])) # Define bottom right point of ROI bottom_right = (int(ROI_coordinates[2]), int(ROI_coordinates[3])) # Draw green ROI rectangle on image ROI_image = cv2.rectangle(image.copy(), top_left, bottom_right, (0, 255, 0), (2)) # Save image with ROI cv2.imwrite(os.path.join(output_path, f"{image_name}_with_ROI.jpg"), ROI_image) # Crop image to only include ROI image_cropped = image[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]] # Save the cropped image cv2.imwrite(os.path.join(output_path, f"{image_name}_cropped.jpg"), image_cropped) ## CANNY EDGE DETECTION ## # Convert the croppe image to greyscale grey_cropped_image = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2GRAY) # Perform Gaussian blurring blurred_image = cv2.GaussianBlur(grey_cropped_image, (3,3), 0) # I use a 3x3 kernel # Perform canny edge detection with the auto_canny function canny = auto_canny(blurred_image) ## FIND AND DRAW CONTOURS ## # Find contours (contours, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw green contours on the cropped image image_letters = cv2.drawContours(image_cropped.copy(), contours, -1, (0,255,0), 2) # Save cropped image with contours cv2.imwrite(os.path.join(output_path, f"{image_name}_letters.jpg"), image_letters) # Message to user print(f"\nThe output images are now saved in {output_path}.\n") # Define behaviour when called from command line if __name__=="__main__": main()
bed107a24a36afeb2176c3200aec2c525a24a55a
Silicon-beep/UNT_coursework
/info_4501/home_assignments/fraction_class/main.py
1,432
4.21875
4
from fractions import * print() ####################### print('--- setup -----------------') try: print(f'attempting fraction 17/0 ...') Fraction(17, 0) except: print() pass f1, f2 = Fraction(1, 2), Fraction(6, 1) print(f'fraction 1 : f1 = {f1}') print(f'fraction 2 : f2 = {f2}') ###################### print('--- math -------------------') # addition print(f'{f1} + {f2} = {f1 + f2}') # subtraction print(f'{f1} - {f2} = {f1 - f2}') # multiplication print(f'{f1} * {f2} = {f1 * f2}') # division print(f'{f1} / {f2} = {f1 / f2}') # floor division print(f'{f2} // {f1} = {f2 // f1}') # modulo print(f'{Fraction(7,1)} % {Fraction(2,1)} = {Fraction(7,1) % Fraction(2,1)}') # exponentiation # only works with a whole number as fraction 2 print(f'{f1} ** {f2} = {f1 ** f2}') # print(f'{Fraction(2,1)} ** {Fraction(5,4)} = {Fraction(2,1) ** Fraction(5,4)}') # print(2**(5/4), (Fraction(2, 1) ** Fraction(5, 4)).float) ##################### print('--- simplifying ------------') print(f'{f1} = {f1.simplify()}') print(f'{f2} = {f2.simplify()}') print(f'18/602 = {Fraction(18,602).simplify()}') print(f'72/144 = {Fraction(72,144).simplify()}') print(f'0/13 = {Fraction(0,10).simplify()}') #################### print('--- other things -----------') print(f'convert to float ... {f1} = {f1.float}, {f2} = {f2.float}') print(f'inverting a fraction ... {f1} inverts to {f1.invert()}') #################### print()
04dbc79957d16af67ab89c8aa72796517db8b5a6
madboy/adventofcode
/2015/days/twelve.py
734
3.78125
4
#!/usr/bin/env python import fileinput import json def count(numbers, ignore): if type(numbers) == dict: if ignore and "red" in numbers.values(): return 0 else: return count(numbers.values(), ignore) elif type(numbers) == list: inner_sum = 0 for e in numbers: inner_sum += count(e, ignore) return inner_sum elif type(numbers) == int: return numbers return 0 def bookkeeping(ignore): total = 0 for i in j: total += count(i, ignore) return total s = "" for line in fileinput.input(): s += line.strip() j = json.loads(s) print("first attempt:", bookkeeping(False)) print("second attempt:", bookkeeping(True))
c1f76fc8405ea15ec3d9112ff8efc51c5801fcb5
Nduwal3/Python-Basics-III
/academy-cli/academy/student.py
2,517
3.703125
4
import csv class Student: def __init__(self): # this.mode = mode # this.data = data pass def file_read_write(self, mode, data=None): with open ('files/students.csv', mode) as student_data: result=[] if mode == 'r': students = csv.DictReader(student_data) if students is not None: for row in students: result.append(row) else: # Create a writer object from csv module students = csv.writer(student_data) # Add contents of list as last row in the csv file students.writerow(data) return result def get_all_students(self, mode): students_list = self.file_read_write(mode) val = next(iter(students_list)) print(list(val.keys())) for item in students_list: print(list(item.values())) def get_Student_info(self, name, mode): students_list = self.file_read_write(mode) for item in students_list: if name in item.values(): print(item) else: print("no record found") break def update_student_detail(self, id, mode): students_list = self.file_read_write(mode) print("update_student_detail") print(mode) def create_new_student(self, student_data, mode): print(student_data) students_list = self.file_read_write(mode, data = student_data) print(self.__get_records_count(students_list)) print("update_student_detail") print(mode) pass def delete_student(self, name, mode): updated_list =[] students_list = self.file_read_write(mode) for student in students_list: if student.get('student_name') != name: updated_list.append(student) self.__update_file(updated_list) def __update_file(self, updatedlist): print(updatedlist) val = next(iter(updatedlist)) header = list(val.keys()) print(header) with open('files/students.csv',"w") as f: Writer=csv.DictWriter(f, fieldnames=header) Writer.writeheader() for row in updatedlist: Writer.writerow(row) print("File has been updated") def __get_records_count(self, student_list): return student_list[-1:]
7413ffdb53524a72e59fae9138e1b143a9a2e046
quanghona/Caro2
/board.py
3,919
3.515625
4
import os import curses import random class CaroBoard(object): """A class handle everything realted to the caro board""" def __init__(self, width, height): self.width = width self.height = height self.board = [[' ' for x in range(self.width)] for y in range(self.height)] self._turnCount = 0 def ConfigBoard(self): pass def UpdateBoard(self, Pos_X, Pos_Y, Marker): if self.board[Pos_X][Pos_Y] == ' ': self.board[Pos_X][Pos_Y] = Marker self._turnCount += 1 return True else: return False def CheckBoard(self, Pos_X, Pos_Y, PlayerMarker): CheckProcess = 'UpperLeft' Combo = 1 CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y # Checking if the current player has won the game # this is written for python 2 so it doesn't support nonlocal keyword while CheckProcess != 'Complete': if CheckProcess == 'UpperLeft': if CurrentCheckPosX - 1 >= 0 and CurrentCheckPosY - 1 >= 0 and \ self.board[max(0, CurrentCheckPosX - 1)][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Up' elif CheckProcess == 'Up': if CurrentCheckPosY - 1 >= 0 and \ self.board[CurrentCheckPosX][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'UpperRight' elif CheckProcess == 'UpperRight': if CurrentCheckPosX + 1 < self.width and CurrentCheckPosY - 1 >= 0 \ and self.board[min(self.width-1, CurrentCheckPosX + 1)][max(0, CurrentCheckPosY - 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 CurrentCheckPosY -= 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Right' elif CheckProcess == 'Right': if CurrentCheckPosX + 1 < self.width and \ self.board[min(self.width-1, CurrentCheckPosX + 1)][CurrentCheckPosY] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'DownRight' elif CheckProcess == 'DownRight': if CurrentCheckPosX + 1 < self.width and \ CurrentCheckPosY + 1 < self.height and \ self.board[min(self.width-1, CurrentCheckPosX + 1)][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX += 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Down' elif CheckProcess == 'Down': if CurrentCheckPosY + 1 < self.height and \ self.board[CurrentCheckPosX][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'DownLeft' elif CheckProcess == 'DownLeft': if CurrentCheckPosX - 1 >= 0 and \ CurrentCheckPosY + 1 < self.height and \ self.board[max(0, CurrentCheckPosX - 1)][min(self.height-1, CurrentCheckPosY + 1)] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 CurrentCheckPosY += 1 else: CurrentCheckPosX, CurrentCheckPosY = Pos_X, Pos_Y Combo = 1 CheckProcess = 'Left' elif CheckProcess == 'Left': if CurrentCheckPosX - 1 >= 0 and \ self.board[max(0, CurrentCheckPosX - 1)][CurrentCheckPosY] == PlayerMarker: Combo += 1 CurrentCheckPosX -= 1 else: CheckProcess = 'Complete' if Combo >= 5: return True return False def CheckMarkPos(self, Pos_X, Pos_Y): return self.board[Pos_X][Pos_Y] == ' ' def CheckFull(self): return self._turnCount == (self.width * self.height) def GetParameters(self): return {'Width':self.width, 'Height':self.height}
23aeff17e64ba6acfdcf8c85ae0dab9ae2ebf676
divanescu/python_stuff
/coursera/webd/func_assn42.py
926
3.765625
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * global url url = raw_input('Enter - ') position = int(raw_input('Position: ')) def retrieve_url(url): #url = raw_input('Enter - ') #position = int(raw_input("Position: ")) html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # Retrieve all of the anchor tags tags = soup('a') list_of_urls = list() for tag in tags: urls = tag.get('href', None) #print urls strings = str(urls) list_of_urls.append(strings.split()) #print 'url on position ',position,":", list_of_urls[position - 1] new_url = list_of_urls[position-1] print 'Retrieving:', new_url url = new_url return new_url for i in range(3): retrieve_url(url)
3474489ac3abf4439f4af04a6f2a69a743e168d6
divanescu/python_stuff
/coursera/PR4E/assn46.py
348
4.15625
4
input = raw_input("Enter Hours: ") hours = float(input) input = raw_input("Enter Rate: ") rate = float(input) def computepay(): extra_hours = hours - 40 extra_rate = rate * 1.5 pay = (40 * rate) + (extra_hours * extra_rate) return pay if hours <= 40: pay = hours * rate print pay elif hours > 40: print computepay()
a15be41097001cf7f26c42b7dbb076e8ed2bf45c
divanescu/python_stuff
/coursera/PR4E/assn33.py
347
3.84375
4
input = raw_input("Enter Score:") try: score = float(input) except: print "Please use 0.0 - 1.0 range !" exit() if (score < 0 or score > 1): print "Please use 0.0 - 1.0 range !" elif score >= 0.9: print "A" elif score >= 0.8: print "B" elif score >= 0.7: print "C" elif score >= 0.6: print "D" else: print "F"
17d4df0314c967d5cb2192b274b40cf8c3abd248
Eladfundo/task_1_18
/Code/nnet/wbg.py
1,412
3.625
4
import torch def weight_initialiser(N_prev_layer,N_current_layer,device='cpu'): """ Initializes the weight in the constructor class as a tensor. The value of the weight will be w=1/sqr_root(N_prev_layer) Where U(a,b)= Args: N_prev_layer: Number of element in the previous layer. N_current_layer:Number of elmemets in current Layer. Returns: weight: Tensor of value of weight. """ weight_val = 1.0/(N_prev_layer**0.5) print(weight_val) tensor = torch.ones((N_current_layer,N_prev_layer),requires_grad=True) weight=tensor.new_full((N_current_layer, N_prev_layer), weight_val) weight=weight.to(device) return weight def bias_initialiser(N_current_layer,device='cpu'): """ Initializes the bias as a tensor. The value of the bias will be b=0 Args: N_current_layer:Number of elmemets in current Layer. Returns: bias: Tensor of filled with 0. """ bias=torch.zeros((N_current_layer,1),requires_grad=True) bias=bias.to(device) return bias def batch_size_calc(inputs): """ parm:Takes in the input tensor returns:batch size(Integer) """ inputs_size_arr=list(inputs.size()) batch_size=inputs_size_arr[0] return batch_size
a6dd4e5cf972068af342c8e08e10b4c7355188e6
DivyaRavichandr/infytq-FP
/strong .py
562
4.21875
4
def factorial(number): i=1 f=1 while(i<=number and number!=0): f=f*i i=i+1 return f def find_strong_numbers(num_list): list1=[] for num in num_list: sum1=0 temp=num while(num): number=num%10 f=factorial(number) sum1=sum1+f num=num//10 if(sum1==temp and temp!=0): list1.append(temp) return list1 num_list=[145,375,100,2,10] strong_num_list=find_strong_numbers(num_list) print(strong_num_list)
fa798298cb31dce23c22393e07eaa94e0bb0a655
DivyaRavichandr/infytq-FP
/ticketcost.py
511
3.765625
4
def calculate_total_ticket_cost(no_of_adults, no_of_children): total_ticket_cost=0 ticket_amount=0 Rate_per_adult=37550 Rate_per_child=37550/3 ticket_amount=(no_of_adults*Rate_per_adult)+(no_of_children*Rate_per_child) service_tax=0.07*ticket_amount total_cost=ticket_amount+service_tax total_ticket_cost=total_cost-(0.1*total_cost) return total_ticket_cost total_ticket_cost=calculate_total_ticket_cost(2,3) print("Total Ticket Cost:",total_ticket_cost)
c60d478bce2ff6881160fa2045b2d10860d2730f
DivyaRavichandr/infytq-FP
/sumofdigits.py
131
3.765625
4
def sumofnum(n): sum=0 while(n!=0): sum=sum+int(n%10) n=int(n/10) return sum n=int(input("")) print(sumofnum(n))
4f7fdbff2edfa799c9db9ff345873be308face22
anfauglit/recursion
/prntstr.py
1,834
3.875
4
import random def print_str(n): # decompose the integer n and prints its digits one by one if n < 0: print('-',end='') print_str(-n) else: if n > 9: print_str(int(n / 10)) print(n % 10, end='') def digitsum(n): # calculate the sum of all its digits if n < 0: return digitsum(-n) else: if n > 0: return digitsum(int(n / 10)) + (n % 10) return 0 def digital_root(n): # digital root of an integer calculated recursivly as the sum of # all its digits and stops when the sum becomes a signle digit integer print(n) if int(n / 10) == 0: return n return digital_root(digitsum(n)) def ithdigit(n, i): # returns digit at the i'th position in the integer n # positions are counted from the right if i == 0: return n % 10 return ithdigit(int(n/10), i-1) def l_ithdigit(n, i): # returns digit at the i'th position in the integer n # positions are counted from the left n_len = len(str(n)) return ithdigit(n,n_len - i - 1) def print_str_iter(n): for i in range(len(str(n))): print(l_ithdigit(n,i), end='') def print_str_1(n): # print empty string if n equals zero if n > 0: print_str_1(int(n / 10)) print(n % 10, end='') def print_tab(n): print(n * ' ', end='') def do_nothing(d): return def simple_statement(d): print_tab(d) print('this is a python statement') def if_statement(d): print_tab(d) print('if (condition):') make_block(d+1) def for_statement(d): print_tab(d) print('for x in y:') make_block(d+1) def make_statement(d): n = random.randint(0,2) opts = [simple_statement, if_statement, for_statement] opts[n](d) def make_block(d): # generating random syntactically correct python-like programs if d > 10: simple_statement(d) else: n = random.randint(0,1) make_statement(d) opts = [do_nothing, make_block] opts[n](d) make_block(0)
d9f949f598d68412fa4035e6fe8b613d006b4dc3
AlfredKai/KaiCodingNotes
/LeetCode/Easy/Power of Three.py
392
3.703125
4
class Solution: def isPowerOfThree(self, n: int) -> bool: if n == 1: return True powOf3 = 3 while powOf3 <= n: if powOf3 == n: return True powOf3 *= 3 return False a = Solution() print(a.isPowerOfThree(27)) print(a.isPowerOfThree(0)) print(a.isPowerOfThree(9)) print(a.isPowerOfThree(45))
67b9abf27cf5751ad6b1085fe81235d4b5880d64
AlfredKai/KaiCodingNotes
/LeetCode/Medium/328. Odd Even Linked List.py
1,258
3.828125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return None if not head.next: return head oddHead = ListNode() oddTail = ListNode() evenHead = ListNode() evenTail = ListNode() odd = True pointHead = ListNode() pointHead.next = head while pointHead.next: if odd: if not oddHead.next: oddHead.next = pointHead.next oddTail.next = pointHead.next pointHead.next = pointHead.next.next oddTail = oddTail.next oddTail.next = None odd = False else: if not evenHead.next: evenHead.next = pointHead.next evenTail.next = pointHead.next pointHead.next = pointHead.next.next evenTail = evenTail.next evenTail.next = None odd = True oddTail.next = evenHead.next return oddHead.next
d31c7945dae63c6f6aff2d57588108bcbc3e492e
AlfredKai/KaiCodingNotes
/LeetCode/Hard/1044. Longest Duplicate Substring.py
1,255
3.625
4
from collections import Counter class Solution: def longestDupSubstring(self, S: str) -> str: def check_size(size): hash = set() hash.add(S[:size]) for i in range(1, len(S) - size + 1): temp = S[i:i+size] if temp in hash: return S[i:i+size] else: hash.add(temp) return '' n = len(S) i = 0 j = n - 1 while i <= j: mid = (i+j)//2 if len(check_size(mid)) > 0: i = mid if i + 1 == j: r = check_size(j) if len(r) > 0: return r else: return check_size(i) else: j = mid if i + 1 == j: r = check_size(mid-1) if len(r) > 0: return r else: return check_size(mid-2) if i == j: return check_size(mid-1) a = Solution() print(a.longestDupSubstring('abcd')) print(a.longestDupSubstring('banana'))
14dfc412b8f990b71480104de064457d69f91493
AlfredKai/KaiCodingNotes
/LeetCode/Medium/Construct Binary Tree from Preorder and Inorder Traversal.py
1,146
3.8125
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if len(preorder) == 0: return None def x(root, innerPre, innerIn): if len(innerPre) == 0: return None if len(innerPre) == 1: return TreeNode(innerPre[0]) rootInorder = innerIn.index(root.val) preLeft = innerPre[1:rootInorder+1] preRight = innerPre[rootInorder+1:] inLeft = innerIn[0:rootInorder] inRight = innerIn[rootInorder+1:] if len(preLeft) > 0: root.left = x(TreeNode(preLeft[0]), preLeft, inLeft) if len(preRight) > 0: root.right = x(TreeNode(preRight[0]), preRight, inRight) return root return x(TreeNode(preorder[0]), preorder, inorder) a = Solution() a.buildTree([3,9,20,15,7], [9,3,15,20,7])
2ecc33dd88220ed4fe133c1260a92bb34a872e5d
AlfredKai/KaiCodingNotes
/LeetCode/Contests/185/1418. Display Table of Food Orders in a Restaurant.py
1,306
3.921875
4
from typing import List class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: # ["David","3","Ceviche"] foods = set() tableNum = set() tableDish = {} for order in orders: tableN = int(order[1]) if (tableN, order[2]) not in tableDish: tableDish[(tableN, order[2])] = 1 else: tableDish[(tableN, order[2])] += 1 if order[2] not in foods: foods.add(order[2]) if tableN not in tableNum: tableNum.add(tableN) heads = ['Table'] foods = sorted(foods) for f in foods: heads.append(f) result = [heads] for t in sorted(tableNum): row = [] row.append(str(t)) for f in foods: if (t,f) in tableDish: row.append(str(tableDish[(t, f)])) else: row.append('0') result.append(row) return result # study python sorted() a = Solution() a.displayTable([["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]])
72db36b3000749d043e69702b38ef7c345cc99ef
mathtenote01/python
/triple_step.py
334
3.765625
4
def pattern_of_triple_step(N: int): if N < 0: return 0 elif N == 0: return 1 else: return ( pattern_of_triple_step(N - 1) + pattern_of_triple_step(N - 2) + pattern_of_triple_step(N - 3) ) if __name__ == "__main__": print(pattern_of_triple_step(1))
ccc3586c6e51d05a034f6f02781b0e307ae3a93e
Mariliacaps/teste-python
/CAP05/EXERCICIO05-13.py
747
3.75
4
divida=float(input("Valor da dívida: ")) taxa=float(input("Taxa de juros mensal (Ex.: 3 para 3%):")) pagamento=float(input("Valor a ser pago mensal: ")) mes=1 if (divida*(taxa/100)>= pagamento): print("O juros são superiores ao pagamento mensal.") else: saldo = divida juros_pago=0 while saldo>pagamento: juros=saldo*taxa/100 saldo=saldo+juros-pagamento juros_pago=juros_pago+juros print ("Saldo da dívida do mês %d é de R$%6.2f."%(mes,saldo)) mes=mes+1 print("Para pagar a divida de R$%8.2f, a %5.2f %% de juros,"%(divida,taxa)) print("Você precisa de %d meses, pagando R$%8.2f de juros."%(mes-1, juros_pago)) print("No ultimo mês, você teria um saldo de R$%8.2f a pagar." %(saldo))
763f30a67c364954d0b3539145857295a684329f
Mariliacaps/teste-python
/CAP03/EXERCICIO3-7.py
264
3.890625
4
#programa que peça 2 numeros inteiros e imprima a soma dos 2 numeros na tela numero01=int(input("Digite o primeiro numero: ")) numero02=int(input("Digite o segundo numero: ")) resultado=numero01+numero02 print(f"o resultado da soma dos numeros é: {resultado} ")
5703e7ab721d71cb537c3eb659ea65352c81d4d1
Mariliacaps/teste-python
/CAP04/programa4-3.py
281
4.09375
4
salario=float(input("Digite o salario para o calculo do imposto: ")) base=salario imposto=0 if base>3000: imposto=imposto+((base-3000)*0.35) base=3000 if base>1000: imposto=imposto+((base-1000)*0.20) print(f"salario: R${salario:6.2f} imposto a pagar: R${imposto:6.2f}")
be1ae90fe39e8bfdc0b0bc64ab50ba9c62650c8e
tobetobe/python_start
/hello.py
504
4
4
# for index, item in enumerate(['a', 'b', 'c']): # print(index, item) def printHello(): """ say Hello to the console Just print a "hello """ print("hello") # printHello() # list = ['bca', 'abc', 'ccc'] # sorted(list) # print(list) # list = [v*2 for v in range(1, 10)] # print(list) list = ['aa', 'b', 'c'] for v in list: print(v.title()) # a = [1] # if a: # print(a) # b = a # print(b) # b.append(2) # print(a, b) # b = [] # print(bool(b)) # if b: # print(b)
580a0daea555236dcc97ca069180fc26d3cb1093
yangtuothink/Python_AI_note
/other_add/sock(key=) demo.py
372
4
4
""" sort() 函数内含有 key 可以指定相关的函数来作为排序依据 比如这里指定每一项的索引为1 的元素作为排序依据 默认是以第一个作为排序依据 """ def func(i): return i[1] a = [(2, 2), (3, 4), (4, 1), (1, 3)] a.sort(key=func) # [(4, 1), (2, 2), (1, 3), (3, 4)] # a.sort() # [(1, 3), (2, 2), (3, 4), (4, 1)] print(a)
87f3692eb4df2e6e113a4c71f00a09712d29b89c
MrWater/XPyTest
/Python/GUI/test_listbox.py
1,019
3.546875
4
import tkinter root = tkinter.Tk() # selectmode: single multiple browse(移动鼠标进行选中,而不是单击选中) EXTENDED支持shift和ctrl listbox = tkinter.Listbox(root, selectmode=tkinter.MULTIPLE) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) listbox = tkinter.Listbox(root, selectmode=tkinter.BROWSE) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) listbox = tkinter.Listbox(root, selectmode=tkinter.EXTENDED) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) # selection_set 两个参数索引表示范围,一个则选中一个 # selection_clear 取消选中 # curselection() 当前选中项,而不是索引 # selection_includes(index) 判断某个索引是否被选中 # listvariable 绑定变量 # listbox不支持command设置毁掉函数,必须使用bind来指定 print(listbox.size()) print(listbox.get(3)) print(listbox.get(3,9)) listbox.bind('<Double-Button-1>', lambda event: print(listbox.curselection())) root.mainloop()
1d1a37c8933d54fe5f697a5718b13d09233dda7c
MrWater/XPyTest
/cv/test.py
121
3.546875
4
#-*-coding:utf8-*- import numpy as np arr = np.random.random((2, 2, 2, 3)) print(arr) np.random.shuffle(arr) print(arr)
1e629e6a649ca028d7eef107d2e51f98a96c0f46
D4N-W4TS0N/Python-Lockdown
/while_loops.py
75
3.671875
4
i = 1 while i <= 10: print(i * "this is a while loop") i = i + 1
4d4c2670577d87081d1404c1414ecda037d8f769
psk264/rock-paper-scissors
/game.py
3,680
4.15625
4
# game.py # Rock-Paper-Scissors program executed from command line #import modules to use additional third party packages import random import os import dotenv #Input command variation, using print and input # print("Enter your name: ") # player_name = input() #Above statements can be reduced to single line of code #Option 1: # print("Fetching player name from command line") # player_name = input("Enter your name: ") #Option 2: Fetching player name from command line using command: PLAYER_NAME="Guest" if env is missing (package needed: os) # PLAYER_NAME = os.getenv("PLAYER_NAME") # player_name = PLAYER_NAME # print("Fetching player name from command line using command \'PLAYER_NAME=\"Guest\" python game.py\'") #Option 3:Fetching player name from environment variable (package needed: dotenv) dotenv.load_dotenv() player_name = os.getenv("PLAYER_NAME") print("Fetching player name from env file") #User Choice: if(player_name and player_name.strip()): print("Welcome, ", player_name, "! Get ready to play Rock-Paper-Scissors.") else: print("OOPS! player name is empty. No problem, we got your back!") player_name = input("Please enter the player name: ") user_choice = input("Please choose one of 'rock', 'paper', 'scissors': ") print(player_name+"'s choice:", user_choice) #Computer Choice: # one way to write the choice statement is to enter the list in the argument # computer_choice = random.choice(["rock","paper","scissors"]) #another way to write choice statement using list valid_options = ["rock","paper","scissors"] computer_choice = random.choice(valid_options) # print("Computer's choice:", computer_choice) #******************************************************************** #Game Logic Approach 1 #This can be improved by removing duplicate checks and improved readability #******************************************************************** # if(user_choice in valid_options): # if(user_choice == computer_choice): # print("Its a tie!") # elif(user_choice == "rock"): # if(computer_choice == "scissors"): # print(player_name, "won!") # elif(computer_choice == "paper"): # print("Oh, the computer won. It's ok.") # elif(user_choice == "paper"): # if(computer_choice == "rock"): # print(player_name, "won!") # elif(computer_choice == "scissors"): # print("Oh, the computer won. It's ok.") # elif(user_choice == "scissors"): # if(computer_choice == "paper"): # print(player_name, "won!") # elif(computer_choice == "rock"): # print("Oh, the computer won. It's ok.") # print("Thanks for playing. Please play again!") #******************************************************************** #Game Logic Approach 2 #******************************************************************** if(user_choice in valid_options): print("Computer's choice:", computer_choice) if(user_choice == computer_choice): print("Its a tie!") elif(user_choice == "rock" and computer_choice == "scissors") or (user_choice == "paper" and computer_choice == "rock") or (user_choice == "scissors" and computer_choice == "paper"): print(f"{player_name} won! {user_choice} beats {computer_choice}") else: print(f"Oh, the computer won! {computer_choice} beats {user_choice}") print("It's ok") print("Thanks for playing. Please play again!") else: print("Oops, invalid input. Accepted values: 'rock', 'paper', 'scissors'. You entered '" + user_choice + "'") print("THIS IS THE END OF OUR GAME. PLEASE TRY AGAIN.") exit()
ecbd94b636438891fa11ed64943fa66eef961d00
ezeutno/All_Comp_Math_Assignment
/Exam Simulation/Data.py
2,014
3.84375
4
from sympy import * import numpy as np import math as m import matplotlib.pyplot as plt #Latihan Exam BiMay #Number 1 def fact(num): res = 1 for i in range(1,num+1): res *= i return res def Maclaurin(x,n): res = 0 if type(n) is np.ndarray: data = [] for a in np.nditer(n): for k in range(a): res += ((-1)**k/fact(2*k+1))*(x**(2*k+1)) data.append(res) res = 0 return np.array(data) else: for k in range(n): res += ((-1)**k/fact(2*k+1))*(x**(2*k+1)) return res print("Number 1") maclaurinRes = Maclaurin(np.pi/3,100) exactValueSIN = 0.5*m.sqrt(3) print("SIN 60 : ",maclaurinRes,"|",exactValueSIN) print("Margin of Error : ", (abs(exactValueSIN - maclaurinRes)/exactValueSIN)*100,"%") #Number 2 print("Number 2") n = np.array([5,10,20,50,100]) multiMacRes = abs(np.ones(5)*exactValueSIN - Maclaurin(np.pi/3,n)) plt.plot(n,multiMacRes,label = "ERROR") plt.legend() plt.show() #Number 3 print("Number 3") x = symbols('x') expression = sin(x)/(1+x**2) resInter = integrate(expression,(x,0,pi/2)).evalf() print("Result : ",resInter) #Number 4 print("Number 4") f = lambda x: np.sin(x)/(1+x**2) def simpIntegrat(n, fx=f, a=0, b=np.pi/2): if type(n) is np.ndarray: data = [] for h in np.nditer(n): x = np.linspace(a,b,h+1) w = np.ones(h+1) w[1:-1:2] = 4 w[2:-2:2] = 2 data.append(sum(w*fx(x))*abs(x[0]-x[1])/3) return np.array(data) else: x = np.linspace(a,b,n+1) w = np.ones(n+1) w[1:-1:2] = 4 w[2:-2:2] = 2 return sum(w*fx(x))*abs(x[0]-x[1])/3 n = np.array([2,5,10,50,100,200,1000,10000,20000,30000,35000]) res = simpIntegrat(n) print("n".ljust(5),"estimassion".ljust(23),"error%") print("="*50) for i in range(len(n)): print(repr(n[i]).ljust(5),repr(res[i]).ljust(23),(abs(res[i]-resInter)/resInter)*100) print("="*50)
caded9115b67830a704ea736272a43d4923b7a90
Jeduroid/intermediate-python-course
/dice_roller.py
537
3.953125
4
import random def main(): dice_rolls = int(input('\nHow many dice you want to roll : ')) dice_size = int(input('\nHow many sides a dice have : ')) dice_sum = 0 for i in range(0,dice_rolls): roll = random.randint(1,dice_size) dice_sum += roll if roll == 1: print(f'You rolled a {roll} ! Critical Failure !') elif roll ==dice_size: print(f'You rolled a {roll} ! Criticial Success !') else: print(f'You rolled a {roll}') print(f'Dice sum = {dice_sum}') if __name__== "__main__": main()
f0b385abec60ac9edaa7d68ea9cceb83c52062e1
ktheylin/ProgrammingForEveryone
/Python-GettingStarted/assg4-6.py
278
3.828125
4
def computepay(hrs, rate): if hrs <= 40: gross_pay = hrs * rate else: gross_pay = 40 * rate + ( (hrs - 40) * (rate * 1.5) ) return(gross_pay) hrs = float(raw_input("Enter Hours: ")) rate = float(raw_input("Enter Rate per Hour: ")) print computepay(hrs,rate)
3abb8b828e114b048fd19d232e858e0f204f2901
ktheylin/ProgrammingForEveryone
/Python-WebAccessData/week4-followLinks.py
733
3.5
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * tag_index = 17 loop = 7 count = 0 #url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html' url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Asiya.html' # Continue to read the next URL until loop counter has been met while count < loop: html = urllib.urlopen(url).read() soup = BeautifulSoup(html) tags = soup('a') # Get the index number of the tag tag = tags[tag_index] # print tag url = tag.get('href', None) print 'Retrieving:', url count = count + 1
36f889bbd9010c826012a2e0b12600aba9ab9ee3
Leo-Simpson/c-lasso
/classo/stability_selection.py
5,674
3.59375
4
import numpy as np import numpy.random as rd from .compact_func import Classo, pathlasso """ Here is the function that does stability selection. It returns the distribution as an d-array. There is three different stability selection methods implemented here : 'first' ; 'max' ; 'lam' - 'first' will compute the whole path until q parameters pop. It will then look at those paremeters, and repeat it for each subset of sample. It this case it will also return distr_path wich is an n_lam x d - array . It is usefull to have it is one want to plot it. - 'max' will do the same but it will stop at a certain lamin that is set at 1e-2 * lambdamax here, then will look at the q parameters for which the max_lam (|beta_i(lam)|) is the highest. - 'lam' will, for each subset of sample, compute the classo solution at a fixed lambda. That it will look at the q highest value of |beta_i(lam)|. """ def stability( matrix, StabSelmethod="first", numerical_method="Path-Alg", Nlam=100, lamin=1e-2, lam=0.1, q=10, B=50, percent_nS=0.5, formulation="R1", seed=1, rho=1.345, rho_classification=-1.0, true_lam=False, e=1.0, w=None, intercept=False, ): rd.seed(seed) n, d = len(matrix[2]), len(matrix[0][0]) if intercept: d += 1 nS = int(percent_nS * n) distribution = np.zeros(d) lambdas = np.linspace(1.0, lamin, Nlam) if StabSelmethod == "first": distr_path = np.zeros((Nlam, d)) distribution = np.zeros(d) for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) # compute the path until n_active = q. BETA = np.array( pathlasso( submatrix, lambdas=lambdas, n_active=q + 1, lamin=0, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, w=w, intercept=intercept, )[0] ) distr_path = distr_path + (abs(BETA) >= 1e-5) pop = biggest_indexes(BETA[-1], q) distribution[pop] += 1.0 # to do : output, instead of lambdas, the average aciv """ distr_path(lambda)_i = 1/B number of time where i is (among the q-first & activated before lambda) """ # distribution = distr_path[-1] return (distribution * 1.0 / B, distr_path * 1.0 / B, lambdas) elif StabSelmethod == "lam": for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) regress = Classo( submatrix, lam, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, true_lam=true_lam, w=w, intercept=intercept, ) if type(regress) == tuple: beta = regress[0] else: beta = regress qbiggest = biggest_indexes(abs(beta), q) for i in qbiggest: distribution[i] += 1 elif StabSelmethod == "max": for i in range(B): subset = build_subset(n, nS) submatrix = build_submatrix(matrix, subset) # compute the path until n_active = q, and only take the last Beta BETA = pathlasso( submatrix, n_active=0, lambdas=lambdas, typ=formulation, meth=numerical_method, rho=rho, rho_classification=rho_classification, e=e * percent_nS, w=w, intercept=intercept, )[0] betamax = np.amax(abs(np.array(BETA)), axis=0) qmax = biggest_indexes(betamax, q) for i in qmax: distribution[i] += 1 return distribution * 1.0 / B """ Auxilaries functions that are used in the main function which is stability """ # returns the list of the q highest componants of an array, using the fact that it is probably sparse. def biggest_indexes(array, q): array = abs(array) qbiggest = [] nonnul = np.nonzero(array)[0] reduc_array = array[nonnul] for i1 in range(q): if not np.any(nonnul): break reduc_index = np.argmax(reduc_array) index = nonnul[reduc_index] if reduc_array[reduc_index] == 0.0: break reduc_array[reduc_index] = 0.0 qbiggest.append(index) return qbiggest # for a certain threshold, it returns the features that should be selected def selected_param(distribution, threshold, threshold_label): selected, to_label = [False] * len(distribution), [False] * len(distribution) for i in range(len(distribution)): if distribution[i] > threshold: selected[i] = True if distribution[i] > threshold_label: to_label[i] = True return (np.array(selected), np.array(to_label)) # submatrices associated to this subset def build_submatrix(matrix, subset): (A, C, y) = matrix subA, suby = A[subset], y[subset] return (subA, C, suby) # random subset of [1,n] of size nS def build_subset(n, nS): return rd.permutation(n)[:nS]
bb18f87d4e9fe1d0489fe3f833200955d9d80e80
ysabhi1993/Python-Practice
/Queue_imp.py
1,305
3.953125
4
class Node: def __init__(self, data): self.data = data self.nextnode = None class Queue: def __init__(self): self.head = None self.size = 0 def IsEmpty(self): return self.head == None def enqueue(self, data): currentnode = None newnode = Node(data) if self.head is not None: currentnode = self.head else: self.head = newnode currentnode = self.head while currentnode.nextnode is not None: currentnode = currentnode.nextnode currentnode.nextnode = newnode newnode.nextnode = None def dequeue(self): currentnode = self.head self.head = currentnode.nextnode return currentnode.data def peek(self): return self.head.data def print_queue(self): currentnode = self.head while currentnode is not None: print(currentnode.data) currentnode = currentnode.nextnode def size_queue(self): self.size = 0 currentnode = self.head while currentnode is not None: self.size += 1 currentnode = currentnode.nextnode return self.size
c4c527c574ca40c828dacc7da03a6216a946f53c
ysabhi1993/Python-Practice
/useful_functions.py
7,609
3.984375
4
#Checks if a number is even or odd def checkOE(): num = int(input("Enter a number:")) if num%2 == 1: print('The number you entered is odd') elif num%4 == 0: print('The number you entered is divisible by 4') else: print('The number is even') #prints out a string that says if a number is divisible by another def check_div(num,check): if num%check == 0: print('The number is divisible by {}' .format(check)) else: print('The number is not divisible by {}'.format(check)) #prints out a list of all integers < a user specified input def under_ten(a): b = int(input("Enter a number:")) c = [i for i in a if i < b] print(c) #prints out a list of all the factors def factors(a): b = [] for i in range(1,a+1): if (a%i) == 0: b.append(i) print(b) #compares and prints the common objects in a list to a new list without repetation def common_list(a,b): c = [] for i in a: if i in b: if i not in c: c.append(i) print(c) def common_list1(a,b): return (a&b) #read a string and verify if its a palindrome def palindrome(a): b = list(a) #it is not necessary to convert the string into a list, but if we need to change in-place, it will help. b.reverse() c = list(a) if c == b: print('its a palindrome') else: print('not a palindrome') def palindrome_trivial(a): #b = list(a) count = 0 for i in range(int(len(a)/2)+1): if a[i] == a[ len(a) -i - 1]: count +=1 else: count+=0 if count >= int(len(a)/2): print('its a palindrome') else: print('not a palindrome') #make a new list of all even numbers from a given list in one line def even_list(a): b=[i for i in a if i%2 == 0] return b #guess a random number def guess_num(): import random str_input = '' count = 0 while str_input is not 'exit': b = random.randint(1,9) count += 1 i_input = input("enter a number:") if i_input == 'exit': str_input = 'exit' elif int(i_input) == b: print('correct') elif int(i_input) > b: print(b) print('too high') else: print(b) print('too low') print("number of attempts:{}".format(count - 1)) #prime or not def primality(a): c = [] for i in range(1, a+1): if a%i == 0: c.append(i) if c == [1,a]: print('the number is prime') else: print('the number is not prime. These are its factors: {}'.format(c)) #fibonacci series def fibonacci_seq(n): a = [0,1] for i in range(1,n+1): a.append( a[i] + a[i-1]) print(a) #list remove duplicates def rem_dup_list(a): a = list(a) b = [] for i in a: if i not in b: b.append(i) return b def rem_dup_set(a): a = list(a) b = list(set(a)) return b #reverse word order def rev_word(): a = input("enter a string:") b = a.split(" ") c = [] for i in range(len(b)): c.append(b[len(b) - i - 1]) b.reverse() print(" ".join(b)) return c #find the median of sorted arrays def findMedianSortedArrays(nums1, nums2): nums3 = nums1 + nums2 nums3.sort() if len(nums3) == 0: return 0 elif len(nums3) == 1: return nums3[0] elif len(nums3) % 2 == 1: return nums3[int(len(nums3)/2)] else: a = float((nums3[int(len(nums3)/2) -1] + nums3[int(len(nums3)/2)])) return a/2 #sum of two numbers in an array equals target def twoSum(nums, target): a = [] if len(nums) <= 1: return False else: for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: a.append(i) a.append(j) return a def twoSum1(nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i+1] else: buff_dict[target - nums[i]] = i+1 #finding hamming distance def hammingDistance(x, y): count = 0 z = x^y z = list(bin(z)[2:]) for i in z: if i == '1': count += 1 return count #find the sum of all digits def addDigits(num): #d = [int(i) for i in list(str(num))] #num = sum(d) while num>9: d = [int(i) for i in list(str(num))] num = sum(d) addDigits(num) else: return num def findContentChildren(g, s): count = 0 a = [] s = list(set(s)) print(s) for i in s: if i in g: count += 1 g.remove(i) a.append(i) print(count) g.sort() for i in a: s.remove(i) for i in s: for j in g: if i > j: count += 1 g.remove(j) break #Ransom Note def canConstruct(ransomNote, magazine): return not collections.Counter(ransomNote) - collections.Counter(magazine) def canConstruct(ransomNote, magazine): count = 0 ransomNote = list(ransomNote) magazine = list(magazine) if ransomNote == [] and magazine == []: return True else: for i in ransomNote: if i in magazine: magazine.remove(i) count += 1 if count == len(ransomNote): return True else: return False #intersection of two arrays def intersection(nums1, nums2): return list(set(nums1)&set(nums2)) #sum if squares of n integers def sum_of_squares(n): count = 0 for i in range(n+1): count += i**2 return count #check if integer repeats def int_rep(a): import collections b = list(dict(collections.Counter(a)).values()) if 2 in b: print('repetitions yes') else: print('no repetitions') #p-norm def norm(v,p=2): a = [i**p for i in v] b = sum(a)**(1/p) print(b) #int to binary def converti_b(a): c = 0 while a>0: b = a%2 a = int(a/2) c += 1 return c def firstUniqChar(s): count = [0]*len(s) for i in range(len(s)): for j in range(len(s)): if s[i] == s[j]: count[i] += 1 print(count) if s == '': return -1 else: if 1 in count: for i in range(len(count)): if count[i] == 1: return i break else: return -1 #find integer value of excel column def titleToNumber(s): count = 0 a = len(s) for i in range(a): count+= (26**(a-i-1))*(ord(s[i])-64) return count
47358be77fec8fc5229dfb73736cb8a92f74e406
nan0314/RRTstar
/RRTstar.py
12,203
3.640625
4
import pygame import random as r import pylineclip as lc ############################################ ## Constants ############################################ # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0,0,255) YELLOW = (255,255,0) PURPLE = (128,0,128) # This sets the wdith of the screen WIDTH = 800 WINDOW_SIZE = [WIDTH, WIDTH] # RRT Constants NODE_RADIUS = 4 # The radius of a node as it is drawn on the pygame screen RRT_RADIUS = 20 # The radius used to place new nodes SEARCH_RADIUS = 30 # The radius searched when considering reconnecting nodes END_RADIUS = 20 # The allowable distance from the end node needed to end the algorithm NODES = 20 # The number of new nodes created in a single step of the algorithm ############################################ ## Classes ############################################ class obstacle(): ''' This class represents an obstacle in the grid ans stores the positional data associated with a given obstacle ''' def __init__(self,x1,y1,x2,y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 class node(): ''' This class represents an RRT node and stores the necessary information associated with that node. ''' def __init__(self,x,y): # Positional Data self.x = x self.y = y # Node cost (distance of path to this point) self.cost = 0 # Start/end or path self.start = False self.end = False self.path = None ############################################ ## Functions ############################################ def between(sample,b1,b2): ''' This function takes a sample integer and checks to see if that integer is between to outher boundary integers b1 and b2 ''' if b1 <= sample and sample <= b2: return True elif b2 <= sample and sample <= b1: return True else: return False def euclidean(x1,y1,x2,y2): ''' This function calculates the Euclidean distance between two points. Note that the arguments are the individual x and y values of the two points, not two pairs of points. ''' ans = ((x1-x2)**2 + (y1-y2)**2)**.5 return ans def updatePOS(closest,pos): ''' This function is part of the RRT* algorithm that is used to set the location of a new node. To do this, a random point is generated anywhere on the map and the node closest to that is found. This function takes those two as inputs and calculates a new position by taking the nearest node and moving a constant distance (RRT_RADIUS) in the direction of the random point closest - nearest node to random point pos - random point coordinates [x,y] ''' # Vector from closest to pos vector = [pos[0]-closest.x,pos[1]-closest.y] # Adjust vector to RRT radius length magnitude = (vector[0]**2 + vector[1]**2)**.5 normed_vector = [x / magnitude * RRT_RADIUS for x in vector] # Calculate the position of the new node new_pos = [int(closest.x+normed_vector[0]),int(closest.y+normed_vector[1])] return new_pos def drawBoard(obstacles, nodes): # Set the screen background screen.fill(WHITE) # Draw obstacles for i in obstacles: w = i.x2-i.x1 h = i.y2-i.y1 rectangle = pygame.rect.Rect(i.x1,i.y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) # Draw nodes if nodes != []: for i in nodes: if i.start or i.end: continue pygame.draw.circle(screen,RED,(i.x,i.y),NODE_RADIUS) # Draws node pygame.draw.line(screen,RED,(i.x,i.y),(i.path.x,i.path.y)) # Draws links between nodes pygame.draw.circle(screen,BLUE,(start.x,start.y),NODE_RADIUS) # Draws start node pygame.draw.circle(screen,YELLOW,(end.x,end.y),END_RADIUS) # Draws end circle around end node. pygame.draw.circle(screen,PURPLE,(end.x,end.y),NODE_RADIUS) # Draws end node def endGame(end_node): ''' This function is called at the end of the RRT* algorithm when a path to the end node has been found. It takes the end_node and redraws the complete path using purple instead of the standard red. ''' # Draw the path in purple starting from the end node current = end_node while current.path is not None: pygame.draw.circle(screen,PURPLE,(current.x,current.y),NODE_RADIUS) # Draw nodes in the path pygame.draw.line(screen,PURPLE,(current.x,current.y),(current.path.x,current.path.y)) # Draw links between nodes current = current.path # Move back to the prior node in the path. # Update the screen pygame.display.flip() ############################################ ## Visualization ############################################ # Initialize pygame pygame.init() # Set the size of the screen screen = pygame.display.set_mode(WINDOW_SIZE) # Set the screen background screen.fill(WHITE) # Set title of screen pygame.display.set_caption("RRT* Pathfinding Algorithm") # Used to manage how fast the screen updates clock = pygame.time.Clock() # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Shape variables x1 = x2 = y1 = y2 = 0 # RRT variables obstacles = [] # List to hold the obstacle objects nodes = [] # List to hold the node objects placed = False # Has the user finished placing objects? Started = False # Has the user started the algorithm? start = None # start node end = None # end node found = False # Has a path been found from start to stop drawing = False # Is user currently drawing an obstacle (used to show obstacles as user is drawing with click-drag) ############################################ ## Main Loop ############################################ done = False while not done: # Board setup for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # If user presses the spacebar, switch from placing obstacles to placing start and end or the algorithm starts. if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if placed: Started = True else: placed = True # Skip setup commands if algorithm has started if Started: continue # Create obstacle # User clicks and the position is svaed elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and not placed: x1, y1 = event.pos drawing = True # Draw obstacle as user is dragging cursor on screen elif event.type == pygame.MOUSEMOTION and drawing == True: x2, y2 = event.pos w = x2-x1 h = y2-y1 drawBoard(obstacles,nodes) rectangle = pygame.rect.Rect(x1,y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) # Draw and save obstacle when user releases mouse elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and not placed: x2, y2 = event.pos w = x2-x1 h = y2-y1 rectangle = pygame.rect.Rect(x1,y1,w,h) pygame.draw.rect(screen, BLACK, rectangle) obstacles.append(obstacle(x1,y1,x2,y2)) drawing = False # Create start node elif pygame.mouse.get_pressed()[0] and placed and start is None: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() start = node(pos[0],pos[1]) start.start = True nodes.append(start) pygame.draw.circle(screen,BLUE,(start.x,start.y),NODE_RADIUS) # Create end node elif pygame.mouse.get_pressed()[2] and placed and end is None: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() end = node(pos[0],pos[1]) end.end = True pygame.draw.circle(screen,YELLOW,(end.x,end.y),END_RADIUS) pygame.draw.circle(screen,PURPLE,(end.x,end.y),NODE_RADIUS) # RRT* Algorithm if Started: # Set up algorithm invalid = False # True if node placement is invalid num = 0 # Number of valid nodes succesfully placed # Add NODES amount of nodes while num<=NODES: # Generate random position pos = [r.randint(0,WIDTH-1),r.randint(0,WIDTH-1)] # Find the closest node to that position closest = start for i in nodes: distance = euclidean(i.x,i.y,pos[0],pos[1]) if euclidean(closest.x,closest.y,pos[0],pos[1]) > euclidean(i.x,i.y,pos[0],pos[1]): closest = i if distance == 0: invalid = True # If the node is on top of another node, try again if invalid: invalid = False continue # Update the position to be RRT_RADIUS away from the closest node in the direction of the original position pos = updatePOS(closest,pos) # Check to see if the node is in an obstacle and if so try again for i in obstacles: if between(pos[0],i.x1,i.x2) and between(pos[1],i.y1,i.y2): invalid = True break if invalid: invalid = False continue # Find the cheapest node in RRT_RADIUS cheapest = closest for i in nodes: if euclidean(i.x,i.y,pos[0],pos[1]) <= SEARCH_RADIUS and i.cost < cheapest.cost: cheapest = i # If line between cheapest and new node intersects obstacle, try again for i in obstacles: xlist = [i.x1,i.x2] ylist = [i.y1,i.y2] x3,y3,x4,y4 = lc.cohensutherland(min(xlist), max(ylist), max(xlist), min(ylist), cheapest.x, cheapest.y, pos[0], pos[1]) if x3 is not None or y3 is not None or x4 is not None or y4 is not None: invalid = True break if invalid: invalid = False continue # If completely successful, create new node connected to cheapest near node newNode = node(pos[0],pos[1]) newNode.cost = cheapest.cost + euclidean(newNode.x,newNode.y,cheapest.x,cheapest.y) newNode.path = cheapest # Stores the node that the newNode is linked to # Record and store the new node nodes.append(newNode) num+=1 # Rewire nearby nodes if cheaper to do so for i in nodes: tempCost = newNode.cost + euclidean(newNode.x,newNode.y,i.x,i.y) if tempCost < i.cost and euclidean(newNode.x,newNode.y,i.x,i.y)< SEARCH_RADIUS: i.path = newNode i.cost = tempCost # Check if end has been found if euclidean(newNode.x,newNode.y,end.x,end.y) <= END_RADIUS: end.path = newNode found = True # Draw new nodes to board drawBoard(obstacles,nodes) # End node has been found if found: # Draw the path to the end node endGame(end) go = False # Allow the user to continue algorithm to add more nodes and optimize path while not go: for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: go = True if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop go = True pygame.display.flip() # End the pygame instance pygame.quit()
4f32d0b2293ff8535a870cd9730528ecf4874190
comedxd/Artificial_Intelligence
/2_DoublyLinkedList.py
1,266
4.21875
4
class LinkedListNode: def __init__(self,value,prevnode=None,nextnode=None): self.prevnode=prevnode self.value=value self.nextnode=nextnode def TraverseListForward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.nextnode is None): print("None") break current_node = current_node.nextnode def TraverseListBackward(self): current_node = self while True: print(current_node.value, "-", end=" ") if (current_node.prevnode is None): print("None") break current_node = current_node.prevnode # driver code if __name__=="__main__": node1=LinkedListNode("Hello ") node2=LinkedListNode("Dear ") node3=LinkedListNode(" AI ") node4=LinkedListNode("Student") head=node1 tail=node4 # forward linking node1.nextnode=node2 node2.nextnode=node3 node3.nextnode=node4 # backward linking node4.prevnode=node3 node3.prevnode=node2 node2.prevnode=node1 head.TraverseListForward() tail.TraverseListBackward()
85f7053fa27c235f58c6042f625a691c47f622c0
comedxd/Artificial_Intelligence
/0-13-Nested_Function_NON_Local_variables.py
297
3.578125
4
# Defining the nested function only def print_msg(msg): def printer(): print(msg) #nested function is accessing the non-local variable 'msg' printer() print("i am outer function") printer() # calling the nested function # driver code print_msg("this is message")
b45abb8df2533c41170f40dcbd293c6c58ab29fc
comedxd/Artificial_Intelligence
/0-5-dataprotection.py
403
3.890625
4
class Square: def __init__(self): self._height = 2 self._width = 2 def set_side(self,new_side): self._height = new_side # variables having name starting with _ are called protected variables self._width = new_side # protected variable can be accessed outside class square = Square() square._height = 3 # not a square anymore print(square._height,square._width)
76348acf643b1cd9764e1184949478b3b888b014
jdipendra/asssignments
/multiplication table 1-.py
491
4.15625
4
import sys looping ='y' while(looping =='y' or looping == 'Y'): number = int(input("\neneter number whose multiplication table you want to print\n")) for i in range(1,11): print(number, "x", i, "=", number*i) else: looping = input("\nDo you want to print another table?\npress Y/y for yes and press any key to exit program.\n") if looping =='y' or looping == 'Y': looping = looping else: sys.exit("program exiting.......")
e6e94d3d50a56f104d1ad9993d78f8c44394b753
jdipendra/asssignments
/check square or not.py
1,203
4.25
4
first_side = input("Enter the first side of the quadrilateral:\n") second_side = input("Enter the second side of the quadrilateral:\n") third_side = input("Enter the third side of the quadrilateral:\n") forth_side = input("Enter the forth side of the quadrilateral:\n") if float(first_side) != float(second_side) and float(first_side) != float(third_side) and float(first_side) != float(forth_side): print("The Geometric figure is an irregular shaped Quadrilateral.") elif float(first_side) == float(third_side) and float(second_side) == float(forth_side) and float(first_side) != float(second_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a rectangle.") else: print("The Geometric figure is a parallelogram.") elif float(first_side) == float(second_side) == float(third_side) == float(forth_side): digonal1 = input("Enter first digonal:\n") digonal2 = input("Enter second digonal:\n") if float(digonal1) == float(digonal2): print("The Geometric figure is a square.") else: print("The Geometric figure is a rhombus.")
a7b9b32d1a9e5ee6c7cf1a3b1556a5140a0c98d9
jdipendra/asssignments
/mine calculator.py
4,012
4.46875
4
import sys menu = True def calculator(): print("You can do the following mathematical operations with BRILLIANT-CALCLATOR APP") print("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Square Root\n6.Square\n7.Exponential\n8.nth Root") choice = int(input("Enter Your choice")) condition = 'Y' while condition == 'Y': if choice == 1: print("You choose an Addition.\nNow enter the entries which you want to add together:") elif choice == 2: print("You choose a Subtraction.\nNow enter the entries which you want to subtract:") elif choice == 3: print("You choose a Multiplication.\nNow enter the entries which your want to multiply together:") elif choice == 4: decision = 1 while decision == 1: divident = input("enter Divident:\n\t") divisor = input("Enter Divisor:\n\t") result = int(divident) / int(divisor) reminder = int(divident) % int(divisor) print("\nResult of the division operation:\n\tquotent :", int(result), "\n\treminder :", reminder) print("Do you want to divide another number?\n") decision = input("What you want to do?\n\t1.Menu\n\t2.Division\n\t3.Exit program\n") if decision == 1: calculator() elif decision == 2: decision = decision elif decision == 3: decision = 0 sys.exit("---------Program Exiting after division operation!!!---------") elif choice == 5: print("You choose to calculate the Square Root.\nEnter the number whose Square Root you want to calculate:") number = input("enter the number whose square root is to be calculated:\n") result = print("nth root:", float(number) ** (1 / float(2))) elif choice == 6: print("You choose to calculate Square of a number.\nEnter a number whose Square you want to calculate:") number = input("enter the number whose nth root is to be calculated:\n") result = print("nth root:", float(number) ** (float(2))) elif choice == 7: print("You choose to calculate exponential value.\nEnter base and exponent:") base = (input("Enter base")) exponent = (input("Enter exponent of base")) result = print("The base ", base, "and exponent", exponent, "returned the value", float(base) ** float(exponent)) elif choice == 8: print("You choose to calculate nth root of the number.\nEnter the nht value of root and a number:") elif choice == 9: print( "You choose to calculate average value of the number.\nEnter numbers whose average you want to calculate:") list = [] i = 0 n = int(input("Enter number of elements whose Average you want to calculate:")) while (i < n): print("enter another item of the list") element = float(input()) list.append(element) i += 1 print(list) sum = 0 for item in range(0, len(list)): sum = sum + list[item] print("The average of the numbers is:", sum / n) sys.exit("Program Exiting") elif choice == 10: print("You choose to calculate nth root of the number:") number = input("enter the number whose nth root is to be calculated:\n") nth_root = input("enter the nth root value") result = print("nth root:", float(number) ** (1 / float(nth_root))) else: print("Invalid input!!!") condition = 'f' sys.exit("\nThank you for using BRILLIANT-CALCULATOR APP\nprogram exiting.....") calculator()
a45c34fe97086442b252db0c6f9fd373d5cb6100
potroshit/Data_science_basic_1
/home_work_1/home_work_1_Avdeev.py
644
3.859375
4
# задание 1 arr = [1, 2, 3, 4, 5, 6, 7, 8] for i in arr: if i % 2 == 0: a1 = i a2 = [i] * i print(a1, a2) # задание 2 x = int(input()) y = int(input()) if -1 <= x <= 1 and -1 <= y <= 1: print("принадлежит") else: print("нет") # задание 3 A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] B = [] for i in A: if i % 2 == 0: B.append(i) print(B) # задание 4 name = input() print(f'Привет, {name}!') # задание 5 num = int(input()) print(f"The next number for the number {num} is {num + 1}. The previous number for the number {num} is {num - 1}.")
bacbbfa0ee5a53bbf8d572568d0555d2696e0514
potroshit/Data_science_basic_1
/home_work_1/Клачев_Максим_10И2.py
760
3.609375
4
#a = input('Ввести имя: ') #a = list(a) #a = a[1:-1] #b = input('Ввести класс: ') #a.append(b) #c = input('Ввести фамилию: ') #a+=c #print(a) #1 j = [1, 2, 3, 4, 5, 6, 7] u = [[i]*i for i in j if i % 2 == 0] print(j[i], u) #2 x = int(input()) y = int(input()) if -1<= x <= 1 and -1 <= y <= 1: print('Принадлежит') else: print('Не принадлежит') #3 a = input() a.split() a = list(a) b = [] for i in a: if i%2==0: b.append(i) print(b) #4 n = input() print('Привет', n, '!') #5 a k= int(input()) print('The next number for the number', str(k), 'is', str(k+1)+'.', 'The previous number for the number', str(k), 'is', str(k-1)+'.')