blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
5207495ad7699318b8650d2f61272995fceecbc4
aruncancode/wshsprojects
/002_AddingMachine/adding_machine.py
3,062
4.03125
4
from tkinter import * def add(): # retrieves the value from the input box and assigns it to a variable number1 = float(inpNumber1.get()) number2 = float(inpNumber2.get()) result = number1 + number2 # assigns the result variable to the text variable lblResult.config(text=result) def subtraction(): # retrieves the value from the input box and assigns it to a variable number1 = float(inpNumber1.get()) number2 = float(inpNumber2.get()) result = number1 - number2 # assigns the result variable to the text variable lblResult.config(text=result) def multiplication(): number1 = float(inpNumber1.get()) number2 = float(inpNumber2.get()) result = number1 * number2 lblResult.config(text=result) def division(): number1 = float(inpNumber1.get()) number2 = float(inpNumber2.get()) try: result = number1/number2 lblResult.config(text=result) except: ZeroDivisionError lblResult.config(text="ZeroDivisionError") def clear(): inpNumber1.delete(0, END) inpNumber2.delete(0, END) lblResult.config(text='') # Design the Graphical User Interface (GUI) # Build the form Form = Tk() # This creates a GUI and assigns it a name Form.title("GUI Adding Machine") Form.configure(bg="darkgrey") # Sets the dimensions of the form, Length X Width, the X and Y coordinates Form.geometry("350x500+1000+300") # Create our form controls (the widgets/objects on the form, buttons, labels, inoutboxes, images, etc) # input boxes # set the name and style inpNumber1 = Entry(Form, font=("default", 14)) inpNumber2 = Entry(Form, font=("default", 14)) # set its location and dimensions inpNumber1.place(x=100, y=100, width=150, height=30) inpNumber2.place(x=100, y=150, width=150, height=30) # labels lblResult = Label(Form, font=("default", 14), bg='cyan') lblResult.place(x=100, y=200, width=150, height=30) # buttons # set name, style and assign a function to the command property btnAdd = Button(Form, text="Add", fg="black", bg="white", command=add) btnAddition = Button(Form, text="Addition", fg="black", bg="white", command=add) btnAddition.place(x=35, y=275, width=275, height=30) # set its location and dimensions btnSubtract = Button(Form, text="Subtract", fg="black", bg="white", command=subtraction) btnSubtract.place(x=35, y=300, width=275, height=25) # set its location and dimensions btnMultiplication = Button(Form, text="Multiplication", fg="black", bg="white", command=multiplication) btnMultiplication.place(x=35, y=325, width=275, height=25) # set its location and dimensions btnDivision = Button(Form, text="Division", fg="black", bg="white", command=division) btnDivision.place(x=35, y=350, width=275, height=25) # set its location and dimensions btnClear = Button(Form, text="Clear", fg="black", bg="white", command=clear) btnClear.place(x=35, y=375, width=275, height=25) # set its location and dimensions # run the code Form.mainloop()
c1f32f2060251d7e5b4349eafb98023bcaece3a0
suryaaathhi/python
/vowel.py
245
3.96875
4
#enter the variable variable=(input()) l=variable.isalpha() if(l==True): if( variable=="a" or variable=="e" or variable=="i" or variable=="o" or variable=="u"): print("Vowel") else: print("Consonant") else: print("invalid")
b848f777182c2bce5c0a87a38b14608b39cc45fb
satishjasthi/CodeWar-Kata-s
/FindTheOddInt.py
606
4.09375
4
#Details:Given an array, find the int that appears an odd number of times. #There will always be only one integer that appears an odd number of times. #my first attempt code :) def find_it(l): return([number for number in l if (l.count(number)%2 != 0)][0]) #a = find_it([1,1,5,3,3,6,5,3,6,6,6]);print(a) #other amazing solutions: import operator def find_it(xs): return reduce(operator.xor, xs) from collections import Counter def find_it(l): return [k for k, v in Counter(l).items() if v % 2 != 0][0] def find_it(seq): for i in seq: if seq.count(i)%2!=0: return i
eb667a28193f5c61ffc489d15285584d0a34ae13
D10D3/Battleship
/battleship.py
10,098
3.90625
4
import os import random os.system('cls') """ Single Player BattleShip Game Info: Boards have 100 cells in 10 rows numbered A0 through J9 (chose to use 0-9 instead of traditional 1-10 to simplify code) Cells will have 3 states: "-" = empty or unknown "O" = filled "X" = bombed "@" = known hit players have 7 ships in their fleet: Aircraft Carrier (5 cells) Battleship (4 cells) Cruiser (3 cells) Submarine (3 cells) Destroyer (2 cells) """ def initialize_board(board): board = {} for c in range(65,75): for i in range(10): board[chr(c) + str(i)] = '-' return board def error(): #if I screwed up print "D10D3, your code sucks again" quit() def display_board(board): #displays selected board neatly print " 0 1 2 3 4 5 6 7 8 9" print " ____________________" for c in range(65,75): char = chr(c) pstr = char + " |" for i in range(10): pstr += " " + board[char + str(i)] pstr += "|" print pstr print " ----------------------" def shipname(ship): #convert ships cell to ship name shiplist = [ "Aircraft Carrier (5 cells)", "BattleShip (4 cells)", "Cruiser (3 cells)", "Submarine (3 cells)", "Destroyer (2 cells)"] shipname = "" shipname = shiplist[ship-1] return shipname def player_setup(board): #Player places his ships for i in range (1,6): while True: os.system('cls') intro_banner() ships = [5,4,3,3,2] #cell size of each of the ships ship_length = ships[i-1] display_board(board) print "-= PLAYER BOARD SETUP =-" print "" print " For each selection, first choose the top left ship position," print " then choose to fill to the right or down" print " Where would you like to place %s" % shipname(i) choice = choose_cell() #player chooses coordinate while True: direction = raw_input (' Fill in ship across or down? (A or D)> ') direction.lower() if direction == 'a': break elif direction == 'd': break else: print " Please enter A or D" selection = generate_selection(choice,ship_length,direction) test = test_selection(selection,board) if test: board = write_ship(selection,board) break else: print "" print " That ship won't fit there, choose another spot" raw_input (' <Press a Enter to select again>') return board def AI_setup(board): #AI places ships for i in range (1,6): while True: ships = [5,4,3,3,2] #cell size of each of the ships ship_length = ships[i-1] choice = choose_cell_AI() #Computer chooses coordinate dir_pos = ["a","d"] #possible orientations: Across or Down direction = random.choice(dir_pos) selection = generate_selection(choice,ship_length,direction) test = test_selection(selection,board) if test: board = write_ship(selection,board) print "Generating game boards..." break else: print "Generating game boards..." return board def choose_cell(): #Asks player for cell choice, returns value while True: row = raw_input (' What Row? (A-J)> ') row = row.upper() letters = "ABCDEFGHIJ" if row in letters: break else: print " Please type a letter from A to J" raw_input (' <Press a Enter to select again>') while True: column = raw_input(' What Column? (0-9)> ') #column = int(column) numbers = '0,1,2,3,4,5,6,7,8,9' if column in numbers: break else: print " Please type a number from 1 to 10" raw_input (' <Press a Enter to select again>') choice = "" choice = choice + row + column return choice def choose_cell_AI(): #Generates random cell choice, returns value letters = "ABCDEFGHIJ" numbers = "0123456789" row = random.choice(letters) column = random.choice(numbers) choice = "" choice = choice + row + column return choice def generate_selection(choice,ship_length,direction): #Generates list of selected cells to place ship selection = [choice] if direction == 'a': #across stuff for i in range(1,ship_length): addrow = choice[0] addnum = choice[1] addnum = int(addnum) addnum += i addnum = str(addnum) addselect = "" addselect = addselect + addrow + addnum selection.append(addselect) else: #down stuff for i in range(1,ship_length): addrow = ord(choice[0]) #translates the letter into and ascii number addrow += (i) #iterates it by 1 addrow = chr(addrow) #translates it back into a letter! addnum = choice[1] addselect = "" addselect = addselect + addrow + addnum selection.append(addselect) return selection def test_selection(selection,board): #checks if all cells for selected ship placement are allowed test = False badcell = False for i in range(0,len(selection)): #creates loop based on length of selection if selection[i] in board: if board[selection[i]] == "-": fnord = "fnord" else: badcell = True else: badcell = True if badcell: test = False else: test = True return test def test_shot(selection,board): #checks if shot is valid test = False badcell = False for i in range(0,len(selection)): #creates loop based on length of selection if selection[i] in board: if board[selection[i]] == "-": fnord = "fnord" elif board[selection[i]] == "O": fnord = "fnord" elif board[selection[i]] == "X": badcell = True elif board[selection[i]] == "@": badcell = True else: badcell = True else: badcell = True if badcell: test = False else: test = True return test def write_ship(selection,board): #writes the (now checked) ship selection to the board # writecell = 0 for i in range(0,len(selection)): #creates loop based on length of selection board[selection[i]] = "O" return board def intro_banner(): #fancy graphics print""" ______ ___ _____ _____ _ _____ _____ _ _ ___________ | ___ \/ _ \_ _|_ _| | | ___/ ___| | | |_ _| ___ \\ | |_/ / /_\ \| | | | | | | |__ \ `--.| |_| | | | | |_/ / | ___ \ _ || | | | | | | __| `--. \ _ | | | | __/ | |_/ / | | || | | | | |____| |___/\__/ / | | |_| |_| | \____/\_| |_/\_/ \_/ \_____/\____/\____/\_| |_/\___/\_| Ver 0.9 by D10D3 """ def did_anyone_win(p_board,c_board): #uses a letter loop and a number loop to check #every cell of both boards for intact ship cells #if none found on a board, the opponent is the winner o_count_player = 0 o_count_computer = 0 for i in range(0,10):#letter loop letter_index = "ABCDEFGHIJ" letter = letter_index[i] letter = str(letter) for j in range(0,10):#number loop number_index = range(0,10) number = number_index[j] number = str(number) checkcell = letter + number if p_board[checkcell] == "O": o_count_player += 1 # else: # fnord = "fnord" if c_board[checkcell] == "O": o_count_computer += 1 # else: # fnord = "fnord" if o_count_player == 0: winner = "computer" elif o_count_computer == 0: winner = "player" else: winner = None return winner def win_lose(winner): #declare winner, ask if play again print "" if winner == "player": print " You Win!" else: print " You Lose" print "" while True: again = raw_input (' Play Again? Y or N> ') again.lower if again == "y" or again == "Y": break elif again == "n" or again == "N": print "Thanks for playing!" quit() else: print " Enter Y or N" def man_or_ran(player_board): #choose manual or random player board setup while True: #choose manual or random player ship placement print "" print ' Would you like to place your ships manually or randomly?' setup = raw_input(' <M>anual or <R>andom? > ') setup.lower() if setup == 'm': player_board = player_setup(player_board) break elif setup == 'r': player_board = AI_setup(player_board) break else: print " Please enter M or R" return player_board #***INITIALIZE AND SETUP*** os.system('cls') intro_banner() player_board = {} computer_board = {} hit_board = {} player_board = initialize_board(player_board) computer_board = initialize_board(computer_board) hit_board = initialize_board(hit_board) player_board = man_or_ran(player_board) computer_board = AI_setup(computer_board) #***BEGIN GAME LOOP*** while True: while True: #did anyone win? if so play again? winner = did_anyone_win(player_board,computer_board) if winner: win_lose(winner) os.system('cls') intro_banner() player_board = {} computer_board = {} hit_board = {} player_board = initialize_board(player_board) computer_board = initialize_board(computer_board) hit_board = initialize_board(hit_board) player_board = man_or_ran(player_board) computer_board = AI_setup(computer_board) break else: fnord = "fnord" break os.system('cls') intro_banner() print " -= PLAYER SHIPS =-" print "" display_board(player_board) print "" print " -= Enemy =-" display_board(hit_board) #Show the player where they have shot(and hit) so far #display_board(computer_board) #cheat mode for debugging print "" #Player Attack while True: print " Choose A Cell to Attack!" target = choose_cell() #player chooses coordinate shooting = [target] test = test_shot(shooting,computer_board) print "" if test: if computer_board[target] == "-": computer_board[target] = "X" hit_board[target] = "X" print " You didn't hit anything." break else: computer_board[target] = "@" print "You hit an enemy ship!" hit_board[target] = "@" break else: print "" print " That is not a valid target!" raw_input (' <Press a Enter to select again>') #Computer Attack while True: target = choose_cell_AI() #AI chooses coordinate shooting = [target] test = test_shot(shooting,player_board) if test: if player_board[target] == "-": player_board[target] = "X" print " Computer attacks %s and misses" % target raw_input (' <Press a Enter to continue>') break else: player_board[target] = "@" print " Computer attacks %s and hits!" % target raw_input (' <Press a Enter to continue>') break else: fnord = "fnord"
cc86f40a36fb6e74dae178fa6e1fd7324c17703e
Matt-Zimmer/week-3-lab-Matt-Zimmer
/week-03-lab-Matt-Zimmer.py
2,807
3.875
4
###################################### # IT 2750 - Spring 2021 - Week 3 Lab # # Password Cracking # # Author: Matt Zimmer # # Student: S00646766 # ###################################### ############################################ #### SCROLL DOWN ######################### #### DON'T EDIT CODE IN THIS SECTION ##### ############################################ # Import the zipfile module import zipfile # Open a zip file with a given password def openZip(file, password=''): # Create a new zip file object and open # the zip file zip = zipfile.ZipFile(file) # Attempt to extract all contents of the zip file # to the current directory. Return True if success # and False if failure try: if password == '': zip.extractall() else: zip.extractall(pwd=bytes(password, 'utf-8')) return True except Exception as e: return False ############################################ #### START FROM HERE ##################### ############################################ # Step 1: Create a list variable and initialize it with the # first 10 of the top 25 most used passwords in 2019, per the following link: # https://en.wikipedia.org/wiki/List_of_the_most_common_passwords # USE THE FIRST TABLE, "According to SplashData" passwords = ['123456', '123456789', 'qwerty', 'password', '1234567', '12345678', '12345', 'iloveyou', '111111', '123123'] # Step 2: Ask the user for the filename of the zip file that # we will attempt to crack (just the filename, not the full # path... make sure the actual zip file is in the same # directory as the python script and that the current working # directory in the command prompt is that same directory) fileName = (input("What zip file do you want to use? ")) # Step 3: Create a loop that iterates through each password # in the list. You can use a while loop or for loop for passwordType in passwords: print("Attempting Password... " + passwordType) # Step 4: For each iteration of the loop, attempt to crack # the zipfile password by calling the openZip function and # passing the filename and the password to try. The openZip # function returns True if it was successful and False if it # was not. An example of calling the function is # result = openZip(filename, password) filename = True result = openZip(filename, passwordType) # Step 5: For each iteraton of the loop, let the user know # what the result of the crack attempt was (True = success, # False = failure) and what password was tried for passwordType in passwords: if passwordType != "": print('...failed') else: print('...Success!!!')
eafef01f598c0b42b79646000b0e6355d56ded43
keelymeyers/SI206-Project1
/206project1.py
5,635
3.96875
4
import os import csv import filecmp ## Referenced code from SI 106 textbook 'Programs, Information, and People' by Paul Resnick to complete this project def getData(file): #Input: file name #Ouput: return a list of dictionary objects where #the keys will come from the first row in the data. #Note: The column headings will not change from the #test cases below, but the the data itself will #change (contents and size) in the different test #cases. #Your code here: data_file = open(file, "r") new_file = csv.reader(data_file) final = [] for row in new_file: d = {} d['First'] = row[0] d['Last'] = row[1] d['Email'] = row[2] d['Class'] = row[3] d['DOB'] = row[4] final.append(d) #print (final[1:]) return final[1:] #Sort based on key/column def mySort(data,col): #Input: list of dictionaries #Output: Return a string of the form firstName lastName #Your code here: x = sorted(data, key = lambda x: x[col]) return str(x[0]['First'])+ " " + str(x[0]['Last']) #Create a histogram def classSizes(data): # Input: list of dictionaries # Output: Return a list of tuples ordered by # ClassName and Class size, e.g # [('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)] #Your code here: #data = [{'first:keely, last: meyers, class: junior, dob: 5/18/97'}] dd = dict() for s in data: if s['Class'] == 'Freshman': if 'Freshman' not in dd: dd['Freshman'] = 1 else: dd['Freshman'] += 1 elif s['Class'] == 'Sophomore': if 'Sophomore' not in dd: dd['Sophomore'] = 1 else: dd['Sophomore'] += 1 elif s['Class'] == 'Junior': if 'Junior' not in dd: dd['Junior'] = 1 else: dd['Junior'] += 1 elif s['Class'] == 'Senior': if 'Senior' not in dd: dd['Senior'] = 1 else: dd['Senior'] += 1 class_count = list(dd.items()) new_class_count = sorted(class_count, key = lambda x: x[1], reverse = True) return new_class_count # Find the most common day of the year to be born def findDay(a): # Input: list of dictionaries # Output: Return the day of month (1-31) that is the # most often seen in the DOB #Your code here: bday_dict = {} for names in a: n_bday = names['DOB'].strip() new_bday = n_bday[:-5] #print (new_bday) if new_bday[1] == '/': day = new_bday[2:] elif new_bday[2] == '/': day = new_bday[3:] bday_dict[names['First']] = day #print (bday_dict) day_counts = {} for birthday in bday_dict: if bday_dict[birthday] in day_counts: day_counts[bday_dict[birthday]] += 1 else: day_counts[bday_dict[birthday]] = 1 #print(day_counts) sorted_birthdays = sorted(day_counts.items(), key = lambda x: x[1], reverse = True) return int(sorted_birthdays[0][0]) # Find the average age (rounded) of the Students def findAge(a): # Input: list of dictionaries # Output: Return the day of month (1-31) that is the # most often seen in the DOB #Your code here: ages = [] count = 0 for item in a: year = item['DOB'][-4:] age = (2017 - int(year)) ages.append(age) count += 1 avg_age = round(sum(ages)/count) #print (avg_age) return avg_age #Similar to mySort, but instead of returning single #Student, all of the sorted data is saved to a csv file. def mySortPrint(a,col,fileName): #Input: list of dictionaries, key to sort by and output file name #Output: None #Your code here: outfile = open(fileName, "w") x = sorted(a, key = lambda x: x[col]) #print (x) #note: x is sorted correctly. for s in x: outfile.write("{},{},{}\n".format(s['First'], s['Last'], s['Email'])) outfile.close() ################################################################ ## DO NOT MODIFY ANY CODE BELOW THIS ################################################################ ## We have provided simple test() function used in main() to print what each function returns vs. what it's supposed to return. def test(got, expected, pts): score = 0; if got == expected: score = pts print(" OK ",end=" ") else: print (" XX ", end=" ") print("Got: ",got, "Expected: ",expected) return score # Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not. def main(): total = 0 print("Read in Test data and store as a list of dictionaries") data = getData('P1DataA.csv') data2 = getData('P1DataB.csv') total += test(type(data),type([]),40) print() print("First student sorted by First name:") total += test(mySort(data,'First'),'Abbot Le',15) total += test(mySort(data2,'First'),'Adam Rocha',15) print("First student sorted by Last name:") total += test(mySort(data,'Last'),'Elijah Adams',15) total += test(mySort(data2,'Last'),'Elijah Adams',15) print("First student sorted by Email:") total += test(mySort(data,'Email'),'Hope Craft',15) total += test(mySort(data2,'Email'),'Orli Humphrey',15) print("\nEach grade ordered by size:") total += test(classSizes(data),[('Junior', 28), ('Senior', 27), ('Freshman', 23), ('Sophomore', 22)],10) total += test(classSizes(data2),[('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)],10) print("\nThe most common day of the year to be born is:") total += test(findDay(data),13,10) total += test(findDay(data2),26,10) print("\nThe average age is:") total += test(findAge(data),39,10) total += test(findAge(data2),41,10) print("\nSuccessful sort and print to file:") mySortPrint(data,'Last','results.csv') if os.path.exists('results.csv'): total += test(filecmp.cmp('outfile.csv', 'results.csv'),True,10) print("Your final score is: ",total) # Standard boilerplate to call the main() function that tests all your code. if __name__ == '__main__': main()
2d69346d0d83057fd18eb28f51e9135b16f1a87f
juelianzhiren/python_demo
/alice.py
236
3.640625
4
filename="alice.txt"; try: with open(filename) as f_obj: contents = f_obj.read(); except FileNotFoundError: msg = "Sorry, the file " + filename + " doesn't exist"; print(msg); title = "Alice in Wonderland"; print(title.split());
9d2496045c0476bf19d4b3ce8f65894093f5083d
ynadji/scrape
/scrape-basic
638
3.65625
4
#!/usr/bin/env python # # Basic webscraper. Given a URL and anchor text, find # print all HREF links to the found anchor tags. # # Usage: scrape-basic http://www.usenix.org/events/sec10/tech/ "Full paper" # # returns: # # http://www.usenix.org/events/sec10/tech/full_papers/Sehr.pdf # ... # http://www.usenix.org/events/sec10/tech/full_papers/Gupta.pdf # # Pipe into "wget -i -" to download the files one-by-one. # from scrape import * import slib import sys,os if len(sys.argv) != 3: print "usage: scrape-basic URL A-TEXT" sys.exit(1) main_region = s.go(sys.argv[1]) slib.basic(main_region, 'a', 'href', content=sys.argv[2])
e775866737d6da83a8311e5eaa45df7dcee199ea
vigneshrajmohan/CharterBot
/CharterBot.py
3,356
3.765625
4
# PyChat 2K17 import random import time def start(): pass def end(): pass def confirm(question): while True: answer = input(question + " (y/n)") answer = answer.lower() if answer in ["y" , "yes", "yup"]: return True elif answer in ["n", "no", "nope"]: return False def has_keyword(statement, keywords): for word in keywords: if word in statement: return True return False def get_random_response(): responses = ["I understand", "Mhm", "Well... could you please elaborate?", "I'm sorry, this is out of my field, please press 3 to be connected with another one of our representative." ] return random.choice(responses) def get_random_name(): responses = ["Vinny", "Danny", "Mark", "Finn", "Noah", "Will", "Desmond", "Bill", "Ajit"] return random.choice(responses) def get_response(statement): statement = statement.lower() service_words = ["phone", "internet", "vision"] problem_words = [" not ", "broken", "hate", "isn't"] competitor_words = ["at&t", "verizon", "comcast", "dish"] if statement == "1": response = "We provide the nation's fastest internet, highest quality phone service, and the best selection of channels. Press 3 to get connected to a representative" elif statement == "2": response = "We're sorry that you are having problems with our products. Please press '3' to be connected with one of our representatives" elif statement == "3": response = "Hello my name is " + get_random_name() + ". How may I be of service to you?" elif has_keyword(statement, service_words): response = "Our products are of optimum quality. Please visit out website charter.com or spectrum.com for more information." elif has_keyword(statement, problem_words): response = "So sorry to hear that, have you tried turning it off and back on?" elif has_keyword(statement, competitor_words): response = "Stay with us and we'll add $100 in credit to your account for loyalty." else: response = get_random_response() return response def play(): talking = True print("""+-+-+-+-+-+-+-+ |C|H|A|R|T|E|R| +-+-+-+-+-+-+-+""") print("Hello! Welcome to Charter customer service. ") print("We are always happy to help you with your Charter services or products.") print("Please wait for some time while we get you connected") time.sleep(1) print("*elevator music*") time.sleep(10) print("Thank you for waiting") print("Please press 1 for more information on our services.") print("Please press 2 if you have a problem with one of our services.") print("Please press 3 to be connected to a representative.") while talking: statement = input(">> ") if statement == "Goodbye": talking = False else: response = get_response(statement) print(response) print("Goodbye. It was nice talking to you.") start() playing = True while playing: play() playing = confirm("Would you like to chat again?") end()
4819a44f44262619c27320ce0fab50351f5039d6
urmomlol980034/GCALC-V.2
/square.py
419
3.796875
4
from os import system, name from time import sleep from math import sqrt def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') def square(): sleep(1) clear() print('You have chosen: Square Root') f = eval(input('What number do you want to be square rooted?\n> ')) equ = sqrt(f) print('Your answer is:',equ) input('|:PRESS ENTER WHEN DONE:|') sleep(1) clear()
0d9f1324ec8c52ff6f2639439d705e11f65a35be
prah23/Stocker
/ML/scraping/losers/daily_top_losers.py
943
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 29 23:52:33 2020 @author: pranjal27bhardwaj """ # This function will give the worst performing stocks of the day import requests from bs4 import BeautifulSoup import pandas as pd import matplotlib.pyplot as plt def daily_losers(): dfs = pd.read_html('https://money.rediff.com/losers/bse/daily',header=0) for df in dfs[:-1]: print(df) df1 = df[['Company', '% Change']] print(df1) df1.to_csv('daily_top_losers.csv', index=False) daily_losers() def plot_daily_losers(): plt.style.use('fivethirtyeight') data_daily_losers = pd.read_csv('daily_top_losers.csv') data_daily_losers_final = data_daily_losers[:16] x4 = data_daily_losers_final.plot.bar(x = 'Company', y = '% Change', title = 'Daily Top Losers', color='Black') plt.savefig('daily_top_losers.png', bbox_inches='tight') plt.show(x4) plot_daily_losers()
d6aa861af8b2d53326a1dc779682273bb09ac52c
rlgustavo/DarkWord
/Dark-world/Dark_World_S1.py
26,383
3.546875
4
""" Grupo 4 Indice: 1. Definição de cores 2. Abertura do display, considerando altura e largura 3. Iniciado a função Clock 4. Carregando para a memória as músicas presentes./ definido a função para o som das teclas 5. Carregando imagens para memória/redimensionando B1, referente a imagens, de setas e B3, referente a imagem da tela inicial. 6. Definida a função para a esfera rodar como sprite 7. Contém os textos de todo o jogo, assim como as funções que rodam esses textos. 8. Contem as chaves, em texto, que serão colocadas nas fases. 9. Lê valores das setas, Q e enter, retornando se estão ou não pressionados. 10. Contém as fases do jogos de 0 a 10, essas utilizam-se de outros elementos encontrados nos índices 7,8 e 14.4. Contendo também, na fase 10, uma varíavel que altera 16.1 11. Teclas de fase compreende, exclusivamente, a fase 3. 12. Tela inicial encontra-se dentro do loop de game, e aparece quando iniciar estiver em True. Também encontra-se a opção de instruções aqui. 13. 'O jogo' desenha e passa os sprites da Orbita (6.), também fornecendo qual fase deve ser rodada. 14. A lista de eventos é definida a cada passagem, sendo apagada no começo desse setor. Duas listas são formados: Eventos e Respostas. 15. Movimentação usa as informações de 9. Para definir a direção e quanto a esfera se moverá. 16. Regras impede a esfera de passar da tela e muda o limite dos sprites, fazendo a imagem mudar. 17. Utiliza-se da função relógio para reduzir a velocidade e atualiza o display. """ import pygame import random pygame.init() #________________1.Cores________________ branco = (255,255,255) vermelho = (255,0,0) preto = (0,0,0) cinza_escuro = (50,50,50) #________________2.Set de display________________ dimensao_tela = [720,480] tela = pygame.display.set_mode(dimensao_tela) pygame.display.set_caption("Dark dimension") posição_x = dimensao_tela[0]/2 posição_y = dimensao_tela[1]/2 #________________3.Set Clock________________ relogio = pygame.time.Clock() #________________4.Set Musicas________________ soundtrack = pygame.mixer.Sound('musicas/smash_hit_ost_zen_mode.mp3') soundtrack.set_volume(0.1) inicial = pygame.mixer.Sound('musicas/inicio.mp3') inicial.set_volume(0.2) teclas = pygame.mixer.Sound('musicas/Click.mp3') teclas.set_volume(0.2) def som_teclas(): soundtrack.stop() teclas.play(1) soundtrack.play(-1) #________________5.Set imagens________________ # esferas_1 = pygame.image.load('Esferas_180_1.png') esferas_2 = pygame.image.load('Esferas_180_2.png') esferas_3 = pygame.image.load('Esferas_180_3.png') esferas_4 = pygame.image.load('Esferas_180_4.png') esferas_5 = pygame.image.load('Esferas_180_5.png') esferas_6 = pygame.image.load('Esferas_180_6.png') esferas_7 = pygame.image.load('Esferas_180_7.png') esferas_8 = pygame.image.load('Esferas_180_8.png') esferas_9 = pygame.image.load('Esferas_180_9.png') esferas_10 = pygame.image.load('Esferas_180_10.png') esferas_11 = pygame.image.load('Esferas_180_11.png') esferas_12 = pygame.image.load('Esferas_180_12.png') esferas_13 = pygame.image.load('Esferas_180_13.png') esferas_14 = pygame.image.load('Esferas_180_14.png') esferas_15 = pygame.image.load('Esferas_180_15.png') brilhar_0 = pygame.image.load('Transform/Esferas_Shine_0.png') brilhar_1 = pygame.image.load('Transform/Esferas_Shine_1.png') brilhar_2 = pygame.image.load('Transform/Esferas_Shine_2.png') brilhar_3 = pygame.image.load('Transform/Esferas_Shine_3.png') brilhar_4 = pygame.image.load('Transform/Esferas_Shine_4.png') brilhar_5 = pygame.image.load('Transform/Esferas_Shine_5.png') brilhar_6 = pygame.image.load('Transform/Esferas_Shine_6.png') brilhar_7 = pygame.image.load('Transform/Esferas_Shine_7.png') brilhar_8 = pygame.image.load('Transform/Esferas_Shine_8.png') brilhar_9 = pygame.image.load('Transform/Esferas_Shine_9.png') brilhar_10 = pygame.image.load('Transform/Esferas_Shine_10.png') brilhar_11 = pygame.image.load('Transform/Esferas_Shine_11.png') brilhar_12 = pygame.image.load('Transform/Esferas_Shine_12.png') biblioteca_1 = pygame.image.load('Navigation_keys(1).png') biblioteca_1 = pygame.transform.scale(biblioteca_1, [120, 100]) biblioteca_2 = pygame.image.load('Coruja(1).png') biblioteca_3 = pygame.image.load('universe.jpg') biblioteca_3 = pygame.transform.scale(biblioteca_3, [200, 200]) lista_esfera = [esferas_1,esferas_2,esferas_3,esferas_4, esferas_5,esferas_6,esferas_7,esferas_8, esferas_9,esferas_10,esferas_11,esferas_12, esferas_13,esferas_14,esferas_15, brilhar_0,brilhar_1,brilhar_2,brilhar_3, brilhar_4,brilhar_5,brilhar_6,brilhar_7, brilhar_8,brilhar_9,brilhar_10,brilhar_11, brilhar_12] quantidade_sprite = len(lista_esfera) # 5.1-> Centro de imagens B1 e B3 centro1 = [] centro3 = [] for i in biblioteca_3.get_rect(): centro3.append(i) for i in biblioteca_1.get_rect(): centro1.append(i) #________________6.Formas________________ tamanho = 10 def orbitas(): global largura global altura largura = 259 altura = 259 tela.blit(lista_esfera[sprite],(posição_x-(largura/2),posição_y-(altura/2))) #________________7.Textos________________ mensagem = ["Olá... tente... espaço","sinto que está perdido", "Mas já sabe se mover...","Isso é bom...", "se for mais fácil...","segure Q","Agora podemos seguir", "Talvez...","eu consiga facilitar...","Melhor?", "Acredito que sim...","Agora ouça...","Aqui... não é seguro", "Não sei como veio parar aqui","Mas tem de achar a chave!", "encontre a chave...","Fim da fase", "Fase 2: Repita", "Muito bem...","a primeira porta foi aberta", "está indo bem...","mas não deve parar","Outra chave está perdida", "encontre-a","Fim da fase", "Fase 3: Una","Cada passo é um passo...", "As vezes", "o começo será arduo", "mas veja...", "podia ser pior","imagine se tivesse mais de uma?", "Opa, acho que falei demais hihi","Fim da fase", "Fase 4: Tente","Nunca duvidei!","ta...quando apertou o primeiro", "até duvidei", "mas sabia que conseguiria!","...sei que estamos chegando", "quase posso sentir","uma pitada do fim...", "Mas... temos um problema","Eles sabem que estamos aqui", "A chave... ela se move!","Boa sorte...", "Fim da fase", "Fase 5: Escolha","Há muitas coisas curiosas aqui","Notou?", "Veja... Não é apenas preto", "Você é a luz desse lugar!","Que poético...","Ou pelo menos seria", "Se não estivesse preso aqui","Por isso...","Sem chave dessa vez", "Me responda de forma simples","Você quer sair daqui?","Sim ou Não", "Ok... vamos recomeçar","Então vamos continuar!", "Fase 6: Reconheça","O quê?","Ah, isso de chave e tudo mais", "É... elas nunca foram necessárias","Sabe... eu tentei", "Realmente tentei tornar isso mais fácil", "Mas eu prevejo que continuará", "Retomando ao começo","Sendo tão simples achar a saída", "Apenas me diga","O que é isso?","Fim da fase", "Fase 7: Ouça","A coruja... ela é uma base muito boa", "para o que quero explicar", "Uma ave observadora","tratada como a sabedoria", "é sempre isso que buscamos","Mas não importe o quão corra atrás", "nunca alcaçará...","Por isso, aceitamos nossos erros", "E mesmo que não saiba responder a próxima","não se preocupe", "Apenas tente novamente","veja... sequer notou os números", "que passou por toda essa fase...","elas são sua saída", "diga-me","Quais foram?","Viu... não foi tão ruim", "Agora calma... leia tudo e responda", "Some o primeio com o ultimo","eleve a", "soma do segundo com o penultimo","E então me diga", "Qual a chave da sabedoria?", "Não era bem isso o que eu esperava...","Fim da fase", "Fase 8: Perdoe","Okay... desculpa","Foi intensional a pergunta passada", "Eu não quero que fique irritado","ou algo do tipo","Apenas...", "Queria que ficasse um pouco mais","Estamos perto do fim", "E... também não quero","que seu esforço seja em vão", "Aquela conta que lhe pedi...","só... me diga o resultado", "Fim da fase", "Fase 9: Não esqueça","É isso...","Este é o fim", "O ultimo dos desafios", "Assim que terminar, poderá ir","Não quero que seja difícil", "Só que... represente seu tempo aqui","Por isso...", "Lembra das letras que pegou?","Faltou uma", "Ela esteve em algum lugar","Mas não sei onde","Porém...", "Não precisa voltar","Ela completa uma palavra", "E só dela que preciso","Qual é... a palavra?", "Obrigado..." "Seu tempo foi precioso","E mesmo assim","Insisto em perguntar", "Você quer ficar?","Sim ou Não?","Eu gosto de você, vamos de novo", "Okay... já não há limites... Ande, vá","Fim"] tamanho_mensagem = len(mensagem)-1 mensagem1 = 0 def Informações_texto(): global cor global tamanho_fonte global posição_txt_y cor = cinza_escuro tamanho_fonte = 30 posição_txt_y = dimensao_tela[1] - 70 def txt(): font = pygame.font.SysFont('lucidacalligraphy',tamanho_fonte) texto = font.render(mensagem[mensagem1],10,cor) centro = [] for i in texto.get_rect(): centro.append(i) posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2) tela.blit(texto,[posição_txt_x,posição_txt_y]) # 7.1 -> Textos tela inicial def outros_texto(): # -> Título font = pygame.font.SysFont("CASTELLAR", 45) nome_jogo = font.render("Dark World", 45, (75,0,130)) tela.blit(nome_jogo, [200, (dimensao_tela[1] / 2 - 20)]) # -> Texto "Começar" Centralizado font = pygame.font.SysFont("lucidacalligraphy", 25) começar = font.render("Começar", 45, cor1) centro = [] for i in começar.get_rect(): centro.append(i) posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2) tela.blit(começar, [posição_txt_x, (dimensao_tela[1] / 2)+50]) # -> Texto "Instruções" centralizados font = pygame.font.SysFont("lucidacalligraphy", 25) começar = font.render("Instruções", 45, cor2) centro = [] for i in começar.get_rect(): centro.append(i) posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2) tela.blit(começar, [posição_txt_x, (dimensao_tela[1] / 2)+90]) # 7.2 -> Textos de Instruções def txt_instruções(): font = pygame.font.SysFont("lucidacalligraphy", 15) esc_ins = font.render(" |Esc para voltar ao menu", 45, (255,255,255)) tela.blit(esc_ins, [dimensao_tela[0]-290, (dimensao_tela[1]-120)]) font = pygame.font.SysFont("lucidacalligraphy", 15) nome_jogo = font.render(" |Segure q para melhor ver", 45, (255,255,255)) tela.blit(nome_jogo, [dimensao_tela[0]-290, (dimensao_tela[1] -80)]) font = pygame.font.SysFont("lucidacalligraphy", 15) nome_jogo = font.render(" |Use letras e números para fases", 45, (255,255,255)) tela.blit(nome_jogo, [dimensao_tela[0]-290, (dimensao_tela[1]-40)]) #________________8.Chaves________________ chaves = ["Pressione: H","U","M","A","N","2","7","8","3","1","5"] posição_chave_x = dimensao_tela[0] - 200 posição_chave_y = 50 tamanho_chave = 20 fase = 0 def keys(): font_chave = pygame.font.SysFont('lucidacalligraphy',tamanho_chave) chave = font_chave.render(chaves[chave_fase],10,preto) tela.blit(chave,[posição_chave_x,posição_chave_y]) #________________9.Comandos________________ def left_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: return True return False def right_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT]: return True return False def up_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_UP]: return True return False def down_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_DOWN]: return True return False def q_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_q]: return True return False def enter_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_KP_ENTER]: return True return False #________________10.Fases________________ def phase_1(): global mensagem1 global cor global tamanho_fonte global posição_txt_y global fase global chave_fase if mensagem1 <= 8: cor = preto tamanho_fonte = 55 posição_txt_y = dimensao_tela[1]/2 - 170 if "espaço" in eventos: if mensagem1 < 15: mensagem1 += 1 if mensagem1 >= 17: mensagem1 = 0 if mensagem1 == 15: chave_fase = 0 keys() if "h" in eventos: mensagem1 = 16 fase = 1 txt() def phase_2(): global mensagem1 global posição_chave_x global posição_chave_y global fase global chave_fase if "espaço" in eventos: if mensagem1 < 23: mensagem1 += 1 if mensagem1 == 23: posição_chave_x = 50 posição_chave_y = dimensao_tela[1] -120 chave_fase = 1 keys() if "u" in eventos: mensagem1 = 24 fase = 2 txt() def phase_3(): global mensagem1 global posição_chave_x global posição_chave_y global fase global chave_fase if "espaço" in eventos: if mensagem1 < 32: mensagem1 += 1 if mensagem1 == 32: posição_chave_x = 15 posição_chave_y = dimensao_tela[1] -30 chave_fase = 2 keys() posição_chave_x = dimensao_tela[0] -200 posição_chave_y = dimensao_tela[1]/2 chave_fase = 3 keys() if "ma" in eventos: mensagem1 = 33 fase = 3 txt() def phase_4(): global mensagem1 global posição_chave_x global posição_chave_y global fase global chave_fase if "espaço" in eventos: if mensagem1 < 45: mensagem1 += 1 if mensagem1 == 45: posição_chave_x = random.randint(30,dimensao_tela[0])-10 posição_chave_y = random.randint(30,dimensao_tela[1])-20 chave_fase = 4 keys() if "n" in eventos: mensagem1 = 46 fase = 4 txt() def phase_5(): global mensagem1 global respostas global fase if len(respostas)>3: respostas.clear() if "espaço" in eventos: if mensagem1 < 59: mensagem1 += 1 if ["S","I","M"] == respostas: mensagem1 = 61 fase = 5 respostas.clear() if ["N","A","O"] == respostas: mensagem1 = 60 fase = 0 respostas.clear() print(respostas) txt() tempo_aparição = 0 def phase_6(): global mensagem1 global respostas global fase global tempo_aparição if len(respostas)>6: respostas.clear() if "espaço" in eventos: if mensagem1 < 72: mensagem1 += 1 if mensagem1 == 72: tempo_aparição += 1 if tempo_aparição < 10: tela.blit(biblioteca_2,[dimensao_tela[0]-150, dimensao_tela[1]-150]) elif tempo_aparição == 30: tempo_aparição = 0 if ["C","O","R","U","J","A"] == respostas: mensagem1 = 73 fase = 6 respostas.clear() print (respostas) txt() primeira_parte = False def phase_7(): global mensagem1 global posição_chave_x global posição_chave_y global respostas global fase global chave_fase global primeira_parte if "espaço" in eventos: if mensagem1 < 90: mensagem1 += 1 elif primeira_parte: if mensagem1 < 97: mensagem1 += 1 if mensagem1 == 75: posição_chave_x = 50 posição_chave_y = dimensao_tela[1] -120 chave_fase = 5 keys() elif mensagem1 == 79: posição_chave_x = dimensao_tela[0] -100 posição_chave_y = 120 chave_fase = 6 keys() elif mensagem1 == 82: posição_chave_x = dimensao_tela[0] -300 posição_chave_y = dimensao_tela[1] -120 chave_fase = 7 keys() elif mensagem1 == 85: posição_chave_x = dimensao_tela[0]/2 posição_chave_y = -40 chave_fase = 8 keys() elif mensagem1 == 87: posição_chave_x = 50 posição_chave_y = dimensao_tela[1] -120 chave_fase = 9 keys() elif mensagem1 == 90: posição_chave_x = dimensao_tela[0]/2 posição_chave_y = dimensao_tela[1]/2 chave_fase = 10 keys() if ["2","7","8","3","1","5"] == respostas: primeira_parte = True mensagem1 = 91 respostas.clear() if ["C","O","R","U","J","A"] == respostas: fase = 7 mensagem1 = 99 respostas.clear() if len(respostas)>6: fase = 0 mensagem1 = 98 respostas.clear() print(respostas) txt() def phase_8(): global mensagem1 global respostas global fase if len(respostas)>7: respostas.clear() if "espaço" in eventos: if mensagem1 < 111: mensagem1 += 1 if ["5","7","6","4","8","0","1"] == respostas: mensagem1 = 112 fase = 8 respostas.clear() print (respostas) txt() def phase_9(): global mensagem1 global respostas global fase if len(respostas)>7: respostas.clear() if "espaço" in eventos: if mensagem1 < 129: mensagem1 += 1 if ["H","U","M","A","N","O"] == respostas: mensagem1 = 130 fase = 9 respostas.clear() print (respostas) txt() limite = True def phase_10(): global mensagem1 global fase global limite global posição_txt_y if "espaço" in eventos: if mensagem1 < 134: mensagem1 += 1 if ["S","I","M"] == respostas: mensagem1 = 135 fase = 0 respostas.clear() if ["N","A","O"] == respostas: mensagem1 = 136 limite = False respostas.clear() if posição_x-(largura/2) >= dimensao_tela[0]+200: posição_txt_y = dimensao_tela[1]/2 mensagem1 = 137 if posição_x-(largura/2) <= 0-200: posição_txt_y = dimensao_tela[1]/2 mensagem1 = 137 if posição_y-(altura/2) <= 0-200: posição_txt_y = dimensao_tela[1]/2 mensagem1 = 137 if posição_y-(altura/2) >= dimensao_tela[1]+200: posição_txt_y = dimensao_tela[1]/2 mensagem1 = 137 print(respostas) txt() #________________11.Teclas de fases________________ "tecla fase 3" def m_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_m]: return True return False def a_is_down(): keys = pygame.key.get_pressed() if keys[pygame.K_a]: return True return False "__________________________________Game__________________________________" # -> Pré informações de game sair = True sprite = 0 eventos = [] respostas = [] velocidade_de_mov = 15 vermelho_em = "começar" iniciar = True instruções = False cor1 = vermelho cor2 = branco inicial.play(-1) musica = 1 # -> Loop de Game while sair: tela.fill(preto) #________________12.tela inicial game________________ if "esc" in eventos: instruções = False iniciar = True if iniciar: tela.blit(biblioteca_3,[(dimensao_tela[0]/2)-centro3[2]/2,20]) outros_texto() if up_is_down(): vermelho_em = "começar" cor1 = vermelho cor2 = branco if down_is_down(): vermelho_em = "instruções" cor1 = branco cor2 = vermelho if vermelho_em == "começar" and "enter" in eventos: iniciar = False inicial.stop() if vermelho_em == "instruções" and "enter" in eventos: instruções = True if instruções: tela.blit(biblioteca_1,[(140)-centro1[2]/2,370]) txt_instruções() #________________13.O jogo________________ else: orbitas() sprite += 1 soundtrack.play(-1) Informações_texto() if fase == 0: phase_1() elif fase == 1: phase_2() elif fase == 2: phase_3() elif fase == 3: phase_4() elif fase == 4: phase_5() elif fase == 5: phase_6() elif fase == 6: phase_7() elif fase == 7: phase_8() elif fase == 8: phase_9() elif fase == 9: phase_10() #________________14.Eventos________________ #14.1-> Sair if "sair" in eventos: sair = False eventos.clear() #limpeza de eventos for event in pygame.event.get(): if event.type == pygame.QUIT: eventos.append("sair") #14.2-> Teclas de alterar texto if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: eventos.append("espaço") #14.3-> Teclas do início if event.key == pygame.K_RETURN: eventos.append("enter") if event.key == pygame.K_ESCAPE: eventos.append("esc") #14.4-> Teclas Chaves if event.key == pygame.K_h: eventos.append("h") som_teclas() if event.key == pygame.K_u: eventos.append("u") som_teclas() if m_is_down(): if event.key == pygame.K_a: eventos.append("ma") som_teclas() if a_is_down(): if event.key == pygame.K_m: eventos.append("ma") som_teclas() if event.key == pygame.K_n: eventos.append("n") som_teclas() #14.4-> Teclas de Respostas if event.key == pygame.K_s: respostas.append("S") som_teclas() if event.key == pygame.K_i: respostas.append("I") som_teclas() if event.key == pygame.K_m: respostas.append("M") som_teclas() if event.key == pygame.K_n: respostas.append("N") som_teclas() if event.key == pygame.K_a: respostas.append("A") som_teclas() if event.key == pygame.K_o: respostas.append("O") som_teclas() if event.key == pygame.K_c: respostas.append("C") som_teclas() if event.key == pygame.K_r: respostas.append("R") som_teclas() if event.key == pygame.K_u: respostas.append("U") som_teclas() if event.key == pygame.K_j: respostas.append("J") som_teclas() if event.key == pygame.K_0: respostas.append("0") som_teclas() if event.key == pygame.K_1: respostas.append("1") som_teclas() if event.key == pygame.K_2: respostas.append("2") som_teclas() if event.key == pygame.K_3: respostas.append("3") som_teclas() if event.key == pygame.K_4: respostas.append("4") som_teclas() if event.key == pygame.K_5: respostas.append("5") som_teclas() if event.key == pygame.K_6: respostas.append("6") som_teclas() if event.key == pygame.K_7: respostas.append("7") som_teclas() if event.key == pygame.K_8: respostas.append("8") som_teclas() if event.key == pygame.K_9: respostas.append("9") som_teclas() if event.key == pygame.K_h: respostas.append("H") som_teclas() #________________15.Movimentação________________ if left_is_down(): posição_x += -velocidade_de_mov if right_is_down(): posição_x += velocidade_de_mov if up_is_down(): posição_y += -velocidade_de_mov if down_is_down(): posição_y += velocidade_de_mov #________________16.Regras________________ # 16.1-> Não ultrapasse o limite da tela if limite: if posição_x + tamanho >= dimensao_tela[0]: posição_x += -velocidade_de_mov if posição_x <= 0: posição_x += velocidade_de_mov if posição_y + tamanho >= dimensao_tela[1]: posição_y += -velocidade_de_mov if posição_y <= 0: posição_y += velocidade_de_mov # 16.2-> Se pressionar Q sua forma muda if q_is_down(): if sprite == quantidade_sprite: sprite = quantidade_sprite -4 else: if sprite > quantidade_sprite - 13: sprite +=-2 elif sprite == quantidade_sprite - 13: sprite = 0 #________________17.Atual. Dysplay________________ relogio.tick(10) pygame.display.update() pygame.quit() quit()
ef8e05fe07b951ec8d95b0c64491616b227eb0a2
bmanandhar/python-playground
/b.py
233
3.734375
4
n = 100 for i in range(100): i = i + 2 print(i) arr = [1,2,3,4,5] for i in range(len(arr)): for j in range(5): print('i is :-', i) print('j is: ', j) x = [7,2,4,1,5] for i in range(len(x) - 1): for
e0241ab69dbb1a40c43e0db5fdcd2f0cc545100b
BOURGUITSamuel/NmapScanner_Project
/Scanner.py
2,154
3.71875
4
# coding: utf-8 import sys import nmap import re import time # Using the nmap port scanner. scanner = nmap.PortScanner() # Regular Expression Pattern to recognise IPv4 addresses. ip_add_pattern = re.compile("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$") # Display the program banner. print("-------------------") print("Nmap python scanner") print("-------------------") # Ask user to input the ip address he want to scan. while True: ip_addr = input("Please enter the IP address you want to scan: ") if ip_add_pattern.search(ip_addr): print(f"{ip_addr} is a valid ip address") type(ip_addr) break else: print("Invalid IP address !") continue # Ask user which scan he want to do while True: resp = input("""\nPlease enter the type of scan you want to run: 1)SYN ACK Scan 2)UDP Scan 3)Comprehensive Scan \n""") print(f"You have selected option {resp}") if resp == '1': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, '1-1024', '-v -sS') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['tcp'].keys()) time.sleep(10) break elif resp == '2': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, '1-1024', '-v -sU') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['udp'].keys()) time.sleep(10) break elif resp == '3': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, '1-1024', '-v -sS -sV -sC -A -O') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['tcp'].keys()) time.sleep(10) break elif resp >= '4': print("Please enter a valid option. Enter 1-3") continue
21791a22f0b353d69cf2f6ce03dff7a488cb2bbc
lazorfuzz/gameofde_rest
/ciphers/benchmark.py
1,410
3.53125
4
from Dictionaries import LanguageTrie, trie_search, dictionarylookup import time class Color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def test(sentence, lang, iterations): '''Tests a dictionary lookup on a sentence using a trie search v.s. a line-by-line lookup.''' print(Color.BLUE + 'Testing sentence: %r' % sentence + Color.END) print('%sWord count:%s %d' % (Color.CYAN, Color.END, len(sentence.split()))) print('%sTesting trie_search: %s %d iterations' % (Color.YELLOW, Color.END, iterations)) start = time.time() for i in range(iterations): trie_search(sentence, lang) stop = time.time() print(Color.GREEN + ' Time elapsed:' + Color.END, stop - start, 'seconds') print('%sTesting dictionarylookup: %s %d iterations' % (Color.YELLOW, Color.END, iterations)) start = time.time() for i in range(iterations): word_arr = sentence.split() for w in word_arr: dictionarylookup('en', w) stop = time.time() print(Color.GREEN + ' Time elapsed:' + Color.END, stop - start, 'seconds'); print ('-' * 50) if __name__ == '__main__': test('the quick brown fox jumps over the lazy red dog.', 'en', 100) test('the quick brown fox jumps over the lazy red dog. ' * 5, 'en', 100)
159d935411dd314c544af263dc1edf7e5d9f8238
ztoolson/Intro-to-Algorithms-and-Data-Structures
/LinkedList.py
4,457
4.3125
4
class List: """ Implementation of a Singely Linked List. """ def __init__(self): """ (List) -> NoneType Initialize the head and tail of the list """ self.head = None self.tail = None def __str__(self): """ (List) -> str """ result = '' node_counter = 0 node = self.head while node != None: result = 'Node ' + str(node_counter) + ': ' + str(node.data) + '\n' node = node.next node_counter += 1 return result def is_empty(self): """ (List) -> bool Checks to see if the head of the list is a reference to none. """ return self.head == None def insert(self, node, data=None): """ (List, ListNode, Object) -> NoneType Creates and inserts a new node AFTER an existing node, updating the tail when inserted at the end. """ new_node = ListNode(data, node.next) node.next = new_node if self.tail == node: self.tail = new_node def insert_end(self, data): """ (List, Object) -> NoneType Insert the node at the end of the List. """ # Check if the list is empty if self.tail == None: new_node = ListNode(data, None) self.head = self.tail = new_node # The new node is both head and tail else: self.insert(self.tail, data) def insert_beginning(self, data): """ (List, Object) -> NoneType Insert Node at the beginning of the List. """ new_node = ListNode(data, self.head) self.head = new_node def add(self, data): """ (List, Object) -> NoneType Simplier name than insert_beginning. """ self.insert_beginning(data) def remove_after(self, node): """ (List, ListNode) -> NoneType Remove the node after the specified node. """ node.next = node.next.next if node.next == None: self.tail = node def remove_beginning(self): """ (List) -> NoneType Remove the first node in the List. """ self.head = self.head.next if self.head == None: self.tail = None def length(self): """ (List) -> int Return the number of items in the list. """ current = self.head count = 0 while current != None: count = count + 1 current = current.get_next() return count def find_first(self, data): """ (List, Object) -> ListNode Finds the first occurance of the specified data in the list and returns the node. If data is not in the list, will return None. """ find_first_func(lambda x: x == data) def find_first_func(self, func): """ (List, Function) -> Node User supplies a predicate (function returning a boolean) and returns the first node for which it returns True. >>> node = list.find_first_func(lambda x: 2*x + 7 == 19) """ node = list.head while node != None: if func(node.data): return node node = node.next class ListNode: """ The basic building block for a linked list data structure. """ def __init__(self, new_data, new_next = None): """ (Node, Object, ListNode) -> NoneType Initialize the Node with the data. Assumes the Node doesn't point to any Node to start. Nodes should only point to another ListNone, or to None if there isn't one. """ self.data = new_data self.next = new_next def get_data(self): """ (ListNode) -> Object Return the data in the Node. """ return self.data def get_next(self): """ (ListNode) -> ListNode Return the Node which the current node points to. This is the next node in the list. """ return self.next def set_data(self, new_data): """ (ListNode, Object) -> NoneType Set the data inside the Node """ self.data = new_data def set_next(self, new_next): """ (ListNode, Object) -> NoneType Set a Node for which the current Node will now point to. """ self.next = new_next
17911c3e3c9f130caeeddf9dc571068a25d7bf4b
ArnaudParan/stage_scientifique
/gestion_doonees/operations_vect.py
1,890
3.5625
4
#!/usr/bin/python3.4 #-*-coding:utf-8-* from donnees import * import math as Math ## # @brief crée la moyenne d'un tableau # @param tab le tableau qu'on moyenne # @return la moyenne def moy (tab) : taille_tab = len (tab) moyenne = 0. for elem in tab : moyenne += float(elem) / float(taille_tab) return moyenne def moy_par_point(vals_point_simplex) : for point in range(len (vals_point_simplex)) : vals_point_simplex[point] = moy(vals_point_simplex[point]) ## # @brief multiplie un vecteur par un scalaire # @param vect le vecteur # @param scal le scalaire # @return le produit def mult (scal, vect) : produit = [] for i in range (len (vect)) : produit.append (vect[i] * scal) return produit def somme (vect1, vect2) : somme = vect1 for cpt in range (len(somme)) : somme[cpt] += vect2[cpt] return somme ## # @brief additionne trois vecteurs # @param x1 le premier vecteur # @param x2 le deuxième vecteur # @param x3 le troisième vecteur # @return la somme #TODO retirer la désinformation def add (vect1 ,vect2 ,vect3) : somme = [] #envoie une evectception si les vecteurs n'ont pas la meme taille if len (vect1) != len (vect2) or len (vect2) != len (vect3) or len (vect3) != len (vect1) : raise "trois vecteurs de taille différente additionnés" for i in range (len (vect1)) : somme.append (vect1[i] + vect2[i] + vect3[i]) return somme ## # @brief la norme infinie d'un vecteur # @param x le vecteur # @return la norme def norminf (x) : sup = max (x) inf = min (x) return max ([abs (sup), abs (inf)]) def sommeScalVect(l,x): somme=[] for i in range(len(x)): somme.append(x[i]+l) return somme def variance(serieStat) : moyenne = moy(serieStat) distanceTot = 0. for valExp in serieStat : distanceTot += (valExp - moyenne)**2 variance = Math.sqrt(distanceTot/len(serieStat)) return variance
177f4d54814f1f899d2ea119454b0d692dfff382
AphelionGroup/Examples
/SampleBots/WeatherBot/getWeather.py
2,199
3.578125
4
import argparse from flask import Flask from flask_restful import Resource, Api, reqparse import json import urllib2 class getWeather(Resource): def forecast(self, city): answer = None # calls the weather API and loads the response res = urllib2.urlopen(weather_today + city) data = json.load(res) # gets the temperature information temp = data['main']['temp'] # converts the returned temperature in Celsius c = temp - 273.15 # and converts the returned temperature in fahrenheit f = 1.8 * (temp - 273) + 32 # compose the answer we want to return to the user answer = str( data['weather'][0]['description']).capitalize() + '. Current temperature is %.2fC' % c + '/%.2fF' % f return answer # This recieves requests that use the POST method. def post(self): # Uses the request parser to extract what we want from the JSON. args = parser.parse_args() variables = args['memoryVariables'] city = variables[0]['value'] # calls the getForecast function response = self.forecast(city) # Captures the first variable and it's currentValue. return {"text": response}, 200 if __name__ == "__main__": PARSER = argparse.ArgumentParser(description='Weather bot launcher') PARSER.add_argument('apikey', help='openweathermap API key', type=str, default='') PARSER.add_argument('--port', help='port to serve on', type=int, default=5000) BUILD_ARGS = PARSER.parse_args() # endpoint to a weather API weather_today = 'http://api.openweathermap.org/data/2.5/weather?appid={}&q='.format(BUILD_ARGS.apikey) app = Flask(__name__) api = Api(app) api.add_resource(getWeather, '/getWeather') # Use RequestParser to pull out the intentName, memoryVariables and chatResult. parser = reqparse.RequestParser() parser.add_argument('intentName') parser.add_argument('memoryVariables', type=dict, action='append') parser.add_argument('chatResult', type=dict) app.run(host='0.0.0.0', debug=True, port=BUILD_ARGS.port)
b13aa117b4f2bd0f0a04ce3b04ff9950c239a7f6
wenjie711/Leetcode
/python/021_merge_2_sorted_lists.py
909
3.953125
4
#!/usr/bin/env python #coding: utf-8 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def mergeTwoLists(self, l1, l2): l = ListNode(0) p = l while l1 and l2: if(l1.val < l2.val): p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l1: p.next = l1 if l2: p.next = l2 return l.next s = Solution() l1 = ListNode(1) l2 = ListNode(3) l3 = ListNode(4) l4 = ListNode(6) m1 = ListNode(2) m2 = ListNode(5) m1.next = m2 l1.next = l2 l2.next = l3 l3.next = l4 p = s.mergeTwoLists(None,l1) while(p != None): print p.val p = p.next
9cd76f9d4d60443cefc3cf495b67cade9ee06fba
wenjie711/Leetcode
/python/070_climbing_stairs.py
538
3.9375
4
#!/usr/bin/env python #coding: utf-8 class Solution: # @param {integer} n # @return {integer} def climbStairs(self, n): c = n / 2 r = 0 for i in range(0, c + 1): j = (n - i * 2) + i r += self.C(i,j) return r def C(self, i, j): return self.factorial(j) / self.factorial(i) / self.factorial(j - i) def factorial(self, n): if(n == 1 or n == 0): return 1 return n * self.factorial(n - 1) s = Solution() print s.climbStairs(10)
5d105331052818558742bc74a88b8bc02978a40a
wenjie711/Leetcode
/python/137_single_Num2.py
452
3.78125
4
#!/usr/bin/env python #coding: utf-8 class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): one = 0 two = 0 three = 0 for i in range(len(nums)): two |= one & nums[i] one ^= nums[i] three = two & one one ^= three two ^= three return one s = Solution() print(s.singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2]))
39068a965cfff9d2ca75fdfe8135d25c52b13142
jovicamitrovic/ori-2016-siit
/vezbe/01-linreg/src/solutions/linreg_simple.py
1,645
3.578125
4
""" @author: SW 15/2013 Dragutin Marjanovic @email: dmarjanovic94@gmail.com """ from __future__ import print_function import random import matplotlib.pyplot as plt def linear_regression(x, y): # Provjeravamo da li su nam iste dimenzije x i y assert(len(x) == len(y)) # Duzina liste x i y n = len(x) # Racunamo srednju vrijednost x i y x_mean = float(sum(x))/n y_mean = float(sum(y))/n # X predstavlja (xi - x_mean) za svako X koje pripada listi 'x' X = [xi - x_mean for xi in x] Y = [yi - y_mean for yi in y] # Brojilac nagiba funkcije (b iz formule) numerator = sum([i*j for i, j in zip(X, Y)]) # Imenilac nagiba funkcije (b iz formule) denominator = sum([i**2 for i in X]) # TODO 1: implementirati linearnu regresiju # Koristimo formulu za b iz fajla 'ori-2016-siit-01-linreg.ipynb' slope = numerator/denominator intercept = y_mean - slope*x_mean return slope, intercept def predict(x, slope, intercept): # TODO 2: implementirati racunanje y na osnovu x i parametara linije return intercept + slope*x def create_line(x, slope, intercept): y = [predict(xx, slope, intercept) for xx in x] return y if __name__ == '__main__': x = range(50) # celobrojni interval [0,50] random.seed(1337) # da rezultati mogu da se reprodukuju y = [(i + random.randint(-5, 5)) for i in x] # y = x (+- nasumicni sum) slope, intercept = linear_regression(x, y) line_y = create_line(x, slope, intercept) plt.plot(x, y, '.') plt.plot(x, line_y, 'b') plt.title('Slope: {0}, intercept: {1}'.format(slope, intercept)) plt.show()
fd10e971ea57316b742f15932f0c0d17613e6e4f
jovicamitrovic/ori-2016-siit
/vezbe/01-linreg/src/bonus/birth_rate.py
1,521
3.625
4
# -*- coding: utf-8 -*- """ @author: Stefan Ristanović SW3/2013 @email: st.keky@gmail.com - Description: Birth Rates, per capita income, proportion (ratio?) of population in farming, and infant mortality during early 1950s for 30 nations. - Conclusion: In that period of time, the biggest impact on birth rate had the proportion of population in farming which is excpected result knowing history of that time. Slightly less influence had infant mortality, and per capita income had almost none of the impact (which is, one could say, a surprising result knowing nowadays situation). """ from __future__ import print_function import csv from sklearn import linear_model import numpy def read_csv(file_name): with open(file_name) as csvfile: birth_rate, per_cap_inc, prop_on_farms, infant_mort = [], [], [], [] csvreader = csv.reader(csvfile, delimiter=',') for row in csvreader: birth_rate.append(float(row[1])) per_cap_inc.append(float(row[2])) prop_on_farms.append(float(row[3])) infant_mort.append(float(row[4])) # create and transpose numpy array x = numpy.array([per_cap_inc, prop_on_farms, infant_mort]).transpose() return x, birth_rate if __name__ == '__main__': # read data from dataset x, y = read_csv('birth_rate.csv'); lm = linear_model.LinearRegression() lm.fit (x, y) print(lm.coef_) print(lm.intercept_)
afe9f6bb6ba3598cb26b52432df699531c19d968
ChihChiu29/ml_lab
/image_recognition/hotspot_on_noise_classification.py
4,037
4.0625
4
"""Academical examples on image classifications. This module is an experiment for classifying images. The goal is to train a model that can successfully identify images annotated in certain way. The annotation is a small image that's super-imposed on a background image. """ import keras import numpy from keras import layers from keras import models from keras import optimizers from matplotlib import pyplot as plt from sklearn import metrics from qpylib import logging from qpylib import t IMAGE_SIZE = 128 # Image array is a 3d float array; its 1st dimension is y and 2nd dimension # is x, and 3rd dimension has size 1 and it is the grey scale. This convention # is chosen to match pyplot.imshow. Image = numpy.array def CreateBlankImage( height: int, width: int, ) -> Image: """Creates a blank (0) image.""" return numpy.zeros((width, height, 1), dtype=float) def CreateBlankImageWithNoise( height: int, width: int, noise_strength: float = 0.1, ) -> Image: """Creates a almost blank (0) image.""" return numpy.random.uniform(0.0, noise_strength, (width, height, 1)) def AddBoxToImage(img: Image, y: int, x: int, size: int = 5): """Adds a box (color 1) to the image.""" img[y:y + size, x:x + size] = 1.0 def CreateImageData( num_blank_images: int, num_annotated_images: int, height: int = IMAGE_SIZE, width: int = IMAGE_SIZE, ) -> t.Tuple[numpy.array, numpy.array]: """Creates an image data set of given size. Args: num_blank_images: number of blank images to generate. num_annotated_images: number of annotated images. height: image height. width: image width. Returns: A tuple of images and labels (one-hot representation), order is randomized. """ images_and_labels = [] for _ in range(num_blank_images): images_and_labels.append( (CreateBlankImageWithNoise(height, width), numpy.array([1.0, 0.0]))) for _ in range(num_annotated_images): img = CreateBlankImageWithNoise(height, width) AddBoxToImage( img, y=numpy.random.randint(0, height - 1), x=numpy.random.randint(0, width - 1)) images_and_labels.append((img, numpy.array([0.0, 1.0]))) numpy.random.shuffle(images_and_labels) return ( numpy.array([e[0] for e in images_and_labels]), numpy.array([e[1] for e in images_and_labels])) def CreateDefaultOptimizer() -> optimizers.Optimizer: """Creates a default optimizer.""" # Ref: # https://jaromiru.com/2016/10/03/lets-make-a-dqn-implementation/ return optimizers.RMSprop(lr=0.00025) def CreateConvolutionModel( image_shape: t.Tuple[int, int, int], activation: t.Text = 'relu', optimizer: optimizers.Optimizer = None, ) -> keras.Model: if optimizer is None: optimizer = CreateDefaultOptimizer() model = models.Sequential() model.add(layers.Conv2D( 16, kernel_size=4, activation=activation, input_shape=image_shape, )) model.add(layers.Conv2D( 16, kernel_size=4, activation=activation)) model.add(layers.Flatten()) model.add(layers.Dense(units=2)) model.compile(loss='mse', optimizer=optimizer) return model def PlotImage(img: Image): y_size, x_size, _ = img.shape plt.imshow(img.reshape(y_size, x_size)) plt.show() def MainTest(): images, labels = CreateImageData(num_blank_images=5, num_annotated_images=5) for idx in range(5): logging.printf('Label %d: %s', idx, labels[idx]) PlotImage(images[idx]) def MainTrain(): images, labels = CreateImageData( num_blank_images=5000, num_annotated_images=5000, ) model = CreateConvolutionModel((IMAGE_SIZE, IMAGE_SIZE, 1)) model.fit(images, labels) images, labels = CreateImageData( num_blank_images=50, num_annotated_images=50, ) labels_argmax = labels.argmax(axis=1) predicted_labels = model.predict(images) predicted_labels_argmax = predicted_labels.argmax(axis=1) print(metrics.confusion_matrix(predicted_labels_argmax, labels_argmax)) if __name__ == '__main__': # MainTest() MainTrain()
12daf4f361701b49e3a14820d6bb91d337497de1
bjskkumar/Python_coding
/test.py
1,591
4.28125
4
# name = "Jhon Smith" # age = 20 # new_patient = True # # if new_patient: # print("Patient name =", name) # print("Patient Age = ", age) # # obtaining Input name = input("Enter your name ") birth_year = input (" Enter birth year") birth_year= int(birth_year) age = 2021 - birth_year new_patient = True if new_patient: print("Patient name =", name) print("Patient Age = ", age) # String # Name = "Saravana Kumar" # print(Name.find("Kumar")) # print(Name.casefold()) # print(Name.replace("Kumar", "Janaki")) # print("Kumar" in Name) # Arithmetic Operations # X = (10 +5) * 5 # print(X) # Comparison # X = 3 > 2 # # if X: # print("Greater") # Logical Operators # age = 25 # # print(age >10 and age <30) # # print(age>10 or age <30) # # print( not age > 30) # If statements # Temp = 30 # # if Temp >20: # print("its hot") # elif Temp < 15: # print("its cool") #while loops # i = 1 # while i <= 5: # print(i * '*') # i = i+1s # Lists # names = ["saravana", "Kumar", "Balakrishnan", "Janaki"] # print(names[0]) # print(names[1:4]) # for name in names: # print(name) # List functions # # names = ["saravana", "Kumar", "Balakrishnan", "Janaki"] # names.append("jhon") # print(names) # names.remove("jhon") # print(names) # print("Kumar" in names) # print(len(names)) # for loops # names = ["saravana", "Kumar", "Balakrishnan", "Janaki"] # # for name in names: # print(name) # # for name in range(4): # print(name) # # number = range(4,10) # for i in number: # print(i) # Tuples , immutable # numbers = (1,2,3) # print(numbers[0])
6f582a234b2c9264a2bf877047ac7c9a66b22ae4
dnackat/cs50x-intro-to-comp-sci
/sentimental/vigenere.py
1,727
4.03125
4
# vigenere.py import sys import string # Define a main function to match C code def main(): # Check if input is correct if len(sys.argv) == 1 or len(sys.argv) > 2 or not str.isalpha(sys.argv[1]): print("Usage ./vignere k") sys.exit(1) else: # Convert key to lowercase key = str.lower(sys.argv[1]) # Create a dictionary containing numerical shifts corresponding to alphabets shifts = {list(string.ascii_lowercase)[i]: i for i in range(26)} # Get plaintext from user p = input("plaintext: ") # Get ready to print cyphertext print("ciphertext: ", end="") # Loop over all letters and do shifts c = [] # Variable to keep track of position in keyword t = 0 for k in range(len(p)): # Check if letter is an alphabet if str.isalpha(p[k]): # Check if uppercase or lowercase if str.isupper(p[k]): # Shift by ASCII value (A = 0 instead of 65) s = ord(p[k]) - 65 # Apply the ciphering formula c.append(chr(((s + shifts[key[t % len(key)]]) % 26) + 65)) # Update keyword position t += 1 else: # Shift by ASCII value (a = 0 instead of 97) s = ord(p[k]) - 97 # Apply the ciphering formula c.append(chr(((s + shifts[key[t % len(key)]]) % 26) + 97)) # Update keyword position t += 1 else: c.append(p[k]) # Print ciphertext for ch in c: print(ch, end="") # Print newline print() # Return 0 if successful return 0 if __name__ == "__main__": main()
487e1b65563ee4502403216662ee64a4f119d78b
DmytroLopushanskyy/lab11_part2
/polynomial/polynomial.py
5,656
4.34375
4
""" Implementation of the Polynomial ADT using a sorted linked list. """ class Polynomial: """ Create a new polynomial object. """ def __init__(self, degree=None, coefficient=None): """ Polynomial initialisation. :param degree: float :param coefficient: float """ if degree is None: self._poly_head = None else: self._poly_head = _PolyTermNode(degree, coefficient) self._poly_tail = self._poly_head def degree(self): """ Return the degree of the polynomial. :return: """ if self._poly_head is None: return -1 return self._poly_head.degree def __getitem__(self, degree): """ Return the coefficient for the term of the given degree. :param degree: float :return: float """ assert self.degree() >= 0, "Operation not permitted on an empty polynomial." cur_node = self._poly_head while cur_node is not None and cur_node.degree >= degree: if cur_node.degree == degree: break cur_node = cur_node.next if cur_node is None or cur_node.degree != degree: return 0.0 return cur_node.coefficient def evaluate(self, scalar): """ Evaluate the polynomial at the given scalar value. :param scalar: :return: """ assert self.degree() >= 0, "Only non -empty polynomials can be evaluated." result = 0.0 cur_node = self._poly_head while cur_node is not None: result += cur_node.coefficient * (scalar ** cur_node.degree) cur_node = cur_node.next return result def __add__(self, rhs_poly): """ Polynomial addition: newPoly = self + rhs_poly. :param rhs_poly: Polynomial :return: Polynomial """ return self.calculate("add", rhs_poly) def __sub__(self, rhs_poly): """ Polynomial subtraction: newPoly = self - rhs_poly. :param rhs_poly: :return: """ return self.calculate("sub", rhs_poly) def calculate(self, action, rhs_poly): """ Calculate math expression on Polynomial. :param action: str :param rhs_poly: Polynomial :return: Polynomial """ degrees_set = set(self.get_all_degrees() + rhs_poly.get_all_degrees()) degrees_set = sorted(degrees_set, reverse=True) final_pol = Polynomial() for degree in degrees_set: if action == "add": coeff = self[degree] + rhs_poly[degree] else: coeff = self[degree] - rhs_poly[degree] final_pol._append_term(degree, coeff) return final_pol def get_all_degrees(self): """ Get all degrees in the polynomial :return: list """ degrees_list = [] next_node = self._poly_head while next_node is not None: degrees_list.append(next_node.degree) next_node = next_node.next return degrees_list def __mul__(self, rhs_poly): """ Polynomial multiplication: newPoly = self * rhs_poly. :param rhs_poly: :return: """ self_next = self._poly_head final_pol = Polynomial() polynom_dict = dict() while self_next is not None: rhs_poly_next = rhs_poly._poly_head while rhs_poly_next is not None: degree = self_next.degree + rhs_poly_next.degree coeff = self_next.coefficient * rhs_poly_next.coefficient if degree in polynom_dict: polynom_dict[degree] += coeff else: polynom_dict[degree] = coeff rhs_poly_next = rhs_poly_next.next self_next = self_next.next degrees_set = sorted(polynom_dict.keys(), reverse=True) for degree in degrees_set: final_pol._append_term(degree, polynom_dict[degree]) return final_pol def __str__(self): """ Polynomial string representation. :return: str """ output = "" if self._poly_head: output = str(self._poly_head) next_node = self._poly_head.next while next_node is not None: if str(next_node).startswith("- "): output += " " + str(next_node) else: output += " + " + str(next_node) next_node = next_node.next return output def _append_term(self, degree, coefficient): """ Add new link to polynomial. :param degree: float :param coefficient: float :return: None """ new_node = _PolyTermNode(degree, coefficient) if self._poly_tail is None: self._poly_head = new_node self._poly_tail = new_node else: self._poly_tail.next = new_node self._poly_tail = new_node class _PolyTermNode: """ Class for creating polynomial term nodes used with the linked list. """ def __init__(self, degree, coefficient): self.degree = degree self.coefficient = coefficient self.next = None def __str__(self): """ Prints the value stored in self. __str__: Node -> Str """ if self.coefficient < 0: return "- " + str(abs(self.coefficient)) + "x" + str(self.degree) return str(self.coefficient) + "x" + str(self.degree)
ee30fcac54df14dc48870f687033ce02266bb5c9
prasadnaidu1/django
/Adv python practice/QUESTIONS/14.py
125
3.859375
4
n=int(input("enter no :")) lst=[] for x in range(0,n): if x%2!=0: lst.append(x) else: pass print(lst)
cb25bb6cd9b6a5ef56ac747b131369787d0efa78
prasadnaidu1/django
/Adv python practice/method override/KV RAO OVERRIDE2.py
1,096
3.984375
4
class numbers(object): def __init__(self): print("i am base class constructor") def integers(self): self.a=int(input("enter a value : ")) self.b=int(input("enter b value : ")) self.a,self.b=self.b,self.a print("For swaping integers of a, b : ",self.a,self.b) print("For swaping integers of b, a : ",self.b,self.a) class strings(numbers): def __init__(self): super().__init__() print("i am derived class constructor") def put (self): while True: super().integers() self.s1=input("enter first string : ") self.s2=input("enter second string : ") self.s1,self.s2=self.s2,self.s1 print("For swaping strings of s1, s2 : ",self.s1,self.s2) print("For swaping strings of s2, s1 : ",self.s2,self.s1) ans = input("to continue press y:") if ans == 'y': continue else: break #calling block s=strings() s.put()
abb0668e938b64b6cf404a3d11aa50b2e4d1d463
prasadnaidu1/django
/Adv python practice/OOPS/constructer.py
798
3.78125
4
class sample: comp_name = "Sathya technologies" comp_adds = "Hyderabad" def __init__(self): while True: try: self.employee_id = int(input("Enter a No : ")) self.employee_name = input("Enter a Name : ") print("Company Name : ",sample.comp_name) print("Company Adds : ",sample.comp_adds) print("Employee Id : ", self.employee_id) print("Employee Name : ", self.employee_name) except: print("invalid input") ans=input("To Continue Press y : ") if ans=="y" or ans=="Y": continue else: break def display(self): pass #calling block s1 = sample() s1.display()
d463732ff9853cf2872192e16a3ff1dda5ba763c
prasadnaidu1/django
/Adv python practice/OOPS2.py
360
3.859375
4
#Write a program on class example without creating any object. class demo: comp_name="Prasad Technologies" Comp_adds="hyd" @staticmethod def dispaly(x,y): print("Company Name:",demo.comp_name) print("Company Adds :",demo.Comp_adds) i=x j=y print("The sum of above values is:",i+j) #calling block demo.dispaly(20,40)
e597d95e27d3968b8316fcb844a7ec26576dbca7
prasadnaidu1/django
/Adv python practice/sisco3.py
5,404
3.859375
4
lst = [] while True: name = input("Enter Name : ") lst.append(name) ans = input("Continue press y : ") if ans == "y": continue else: print(lst) res = len(lst) print(res) break class management: def putdetails(self): self.type=input("Enter Type Of Items(Type Veg/Nonveg/Both :") if self.type=="veg": self.no_of_items = int(input("Enter No Of Vegitems:")) vegbiryani = int(input("Enter your Veg biryni cost :")) vegprice=vegbiryani*self.no_of_items split_vegprice=vegprice/res if vegprice>=500: veg_discount=vegprice*0.05 total_veg_price=vegprice-veg_discount split_vegprice1 = total_veg_price / res print("----------------------------------------------") print("Your Choosing Item is :",self.type) print("Your Total Payment is :", total_veg_price) print("Your Discount is :", veg_discount) print("Your payble amount is :", total_veg_price-veg_discount) print("-------------------------------------------------------") print("Indivisual bills :") for x in lst: print(x, "---".format(lst), "---", split_vegprice1) else: print("----------------------------------") print("Your Choosing Item is :",self.type) print("Your Total Payment is :",vegprice ) print("----------------------------------") print("Indivisual bills :") for x in lst: print(x, "---".format(lst), "---", split_vegprice) if self.type=="nonveg": self.no_of_items=int(input("Enter No Of NonVegitems:")) nonvegcost = int(input("Enter NonVeg biryni cost :")) nonveg=nonvegcost*self.no_of_items split_nonveg=nonveg/res if nonveg>=1000: nonveg1=nonveg*0.05 total_nonveg_price=nonveg-nonveg1 split_nonveg1=total_nonveg_price/res print("--------------------------------------------------") print("Your Choosing Item is :", self.type) print("Your Total Payment is :",total_nonveg_price) print("Your Discount is :", nonveg1) print("Your Total Amount :", total_nonveg_price-nonveg1) print("------------------------------------------------------") for x in lst: print("Indivisual Bills :") print(x, "---".format(lst), "---", split_nonveg1) else: print("--------------------------------------") print("Your Choosing Item is :",self.type) print("Your Total Payment is :",nonveg ) print("-----------------------------------") print("Indivisual Bills :") for x in lst: print(x, "---".format(lst), "---", split_nonveg) if self.type=="both": self.no_of_vegitems=int(input("Enter No Of VegItems:")) vegbiryani = int(input("Enter your Veg cost :")) vegprice = vegbiryani * self.no_of_vegitems self.no_of_nonvegitems = int(input("Enter No Of NonVegItems:")) nonvegcost = int(input("Enter NonVeg Cost :")) nonveg=nonvegcost*self.no_of_nonvegitems total_bill=vegprice+nonveg split_totalbill=total_bill/res if total_bill>2000: discount=total_bill*0.10 total_cost=total_bill-discount split_totalcost=total_cost/res print("----------------------------") print("No of Veg Items : ",self.no_of_vegitems) print("Total Veg Amount is : ",vegprice) print("--------------------------------------") print("No Of NonVeg Items : ",self.no_of_nonvegitems) print("Total Veg Amount is : ", nonveg) print("-------------------------------------------") print("Your Total Bill Without Discount : ",total_bill) print("Your Discount is :",discount) print("Your Total Bill After Discount(Veg+NonVeg) is :",total_cost) print("----------------------------------------------") for x in lst: print(x, "---".format(lst), "---",split_totalcost ) else: print("----------------------------") print("No of Veg Items : ", self.no_of_vegitems) print("Total Veg Amount is : ", vegprice) print("--------------------------------------") print("No of Nonveg Items : ", self.no_of_nonvegitems) print("Total NonVeg Amount is : ", nonveg) print("-------------------------------------------") print("Your Total Bill Without Discount : ", total_bill) print("------------------------------------------------") for x in lst: print(x, "---".format(lst), "---",split_totalbill ) else: print("Thanks") #calling block #m=management() #m.putdetails()
7c4b8a424c943510052f6b15b10a06a402c06f08
prasadnaidu1/django
/Adv python practice/QUESTIONS/10.py
845
4.125
4
#Question: #Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. #Suppose the following input is supplied to the program: #hello world and practice makes perfect and hello world again #Then, the output should be: #again and hello makes perfect practice world #Hints: #In case of input data being supplied to the question, it should be assumed to be a console input. #We use set container to remove duplicated data automatically and then use sorted() to sort the data. str=input("enter the data :") lines=[line for line in str.split()] #print(" ".join(sorted(list(set((lines)))))) l1=sorted(lines) print(l1) l2=list(lines) print(l2) l3=sorted(l1) print(l3) l4=set(lines) print(l4) l5=" ".join(sorted(list(set(lines)))) print(l5)
ee21470f4fda9757bd0e754f2b3dceb80c6fe4af
prasadnaidu1/django
/Adv python practice/ASSIGNMENT2.py
3,046
3.953125
4
basic_salary = float(input("Enter Your Salary : ")) class employee: def salary(self): tax=input("If You Have Tax Expenses Press y/Y : ") if tax=="y": ta=float(input("Enter How much TaxExpenses You Have(In The Form Of Percentage): ")) ta_r=ta/100 self.taxes=basic_salary*ta_r else: self.taxes=0 cellphone = input("If Have You CellPhone Expenses Press y/Y : ") if cellphone=="y": ce=float(input("Enter How much CellPhoneExpenses You Have(In The Form Of Percentage) :")) ce_r=ce/100 self.cell_phone_expences=basic_salary*ce_r else: self.cell_phone_expences=0 food = input("If You Have Food Expenses Press y/Y :") if food=="y": fo = float(input("Enter How much FoodExpenses You Have(In The Form Of Percentage) : ")) fo_r = fo / 100 self.food_expences=basic_salary*fo_r else: self.food_expences=0 trans=input("If You Have Transpotation Expenses Press y/Y :") if trans=="y": tr = float(input("Enter How much TranpotationExpenses You Have(In The Form Of Percentage) :")) tr_r = tr / 100 self.transpotation_expences=basic_salary*tr_r else: self.transpotation_expences=0 cloths = input("If You Have Cloths Expenses Press y/Y : ") if cloths=="y": cl = float(input("Enter How much ClothsExpenses You Have(In The Form Of Percentage) :")) cl_r = cl / 100 self.clothing_expences=basic_salary*cl_r else: self.clothing_expences=0 medical=input("If You Have Medical Expenses Press y/Y :") if medical=="y": me = float(input("Enter How much ClothsExpenses You Have(In The Form Of Percentage) :")) me_r = me / 100 self.medical_expences=basic_salary*me_r else: self.medical_expences=0 self.total_expences = self.taxes + self.cell_phone_expences + self.food_expences + self.transpotation_expences + self.clothing_expences + self.medical_expences self.savings = basic_salary - self.total_expences def display(self): print("--------------------------------------------------------") print("Your Monthly Income And Expenses") print("Your Monthly Salary : ",basic_salary) print("Tax Expenses :", self.taxes) print("CellPhone Expenses :", self.cell_phone_expences) print("Food Expenses :", self.food_expences) print("Transpotation Expenses:", self.transpotation_expences) print("Clothing Expenses:", self.clothing_expences) print("Medical Expenses:", self.medical_expences) print("Total Monthly Expenses:", self.total_expences) print("After Expenses Your Saving Amount is:", self.savings) print("-------------------------------------------------------------") #calling block emp=employee() emp.salary() emp.display()
56431060c05fe0ab91e9b1e4c6ac3939d3936b47
prasadnaidu1/django
/Adv python practice/QUESTIONS/9.py
474
4.03125
4
#Question£º #Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. #Suppose the following input is supplied to the program: #Hello world #Practice makes perfect #Then, the output should be: #HELLO WORLD #PRACTICE MAKES PERFECT lst=[] while True: str=input("enter data :") if str: str1=lst.append(str.upper()) else: break for x in lst: print("".join(x))
f676db3d1fc4f349b7ddb2dec69723782cd4d1d2
jakeloria02/Python_AI
/Main.py
884
3.859375
4
import requests, json leave = {"exit", "leave", "end", "bye"} GREETINGS = {"hello", "hey", "yo", "boi", 'hey man', 'hey boi', 'hey 117', 'hey [117]', "heyo", "heyy"} GREETING_RESP = {"Hello", "Hey", "Hello, Sir!"} WEATHER = {'whats the weather today?', "weather", 'whats the weather?', 'whats the weather today', 'whats the weather'} resp = None print("[117] Welcome back!") print("[117] How may I help you?") while True: try: resp = raw_input(">>") except : print("Sorry, I didnt understand that.") continue if resp in leave: print("[117] Bye!") break elif resp in GREETINGS: print("[117] Hello Sir!") elif resp in WEATHER: print("....") import weather else: print("[117] sorry I dont have an answer to that question yet please try a different one!")
32fdb667ad72b8d13d7d844bde4491b0955165d4
thisislsj/smart-reservation
/logicpy.py
695
3.578125
4
msg=["02","07","3"] msgSimple="batman" print("msg is ",msgSimple) seatsAvailable=50 referencecode=5 while True: msgInput=input("Type the msg: ") print(msgInput) if msgInput=="superman": if seatsAvailable >0: referencecode=referencecode+1 seatsAvailable=seatsAvailable-1 print(seatsAvailable) reply="Your reference code is" , "MON", #referencecode print(reply) #replace with send SMS method else: reply="No seats available" print(reply) #replace with send SMS method else: reply="Your request is invalid" print(reply)
570740ed8b072e0b249309b15d33f27f2b94d158
nupur24/python-
/untitled4.py
592
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon May 21 14:16:32 2018 @author: HP """ while True: s = raw_input("enter string : ") if not s: break if s.count("@")!=1 and s.count(".")!=1: print "invalid" else: s = s.split("@") #print s usr = s[0] print usr web_ext = s[1].split(".") print web_ext if len(web_ext) == 2: web,ext = web_ext #print web #print ext print "valid" else: print "Failed"
47f0ab0709c616b62f4871047f350b935cc1a6e2
nupur24/python-
/nupur_gupta_12.py
303
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue May 15 12:01:08 2018 @author: HP """ def br(): s,b,g=a if g%5 > s: return False if s+b*5 >= g: return True else: return False a=input("enter numbers:") print br()
11b760a6ae93888c812d6d2912eb794d98e9c3e0
mohadesasharifi/codes
/pyprac/dic.py
700
4.125
4
""" Python dictionaries """ # information is stored in the list is [age, height, weight] d = {"ahsan": [35, 5.9, 75], "mohad": [24, 5.5, 50], "moein": [5, 3, 20], "ayath": [1, 1.5, 12] } print(d) d["simin"] = [14, 5, 60] d.update({"simin": [14, 5, 60]}) print(d) age = d["mohad"][0] print(age) for keys, values in d.items(): print(values, keys) d["ayath"] = [2] d.update("ayath") # Exercises # 1 Store mohad age in a variable and print it to screen # 2 Add simin info to the dictionary # 3 create a new dictionary with the same keys as d but different content i.e occupation # 4 Update ayath's height to 2 from 1.5 # 5 Write a for loop to print all the keys and values in d
76b21b47b0166c5a98529751abbba6323d8aef43
JacquesAucamp/Factorial-Digits
/JAucamp_factorial_digits.py
2,435
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 8 12:41:16 2021 @author: User-PC """ import sys #========================================================== # CALCULATION FUNCTION #========================================================== def SumOfFactorialDigits(x): digits_sum = 0 # Create array to store the numbers for the # factorial calculation. factorial_digits = [] factorial_digits.append(1) # adds 1 to the end #------------------------------------------------------ # FACTORIAL CALCULATION #------------------------------------------------------ # Calculate the factorial of the number # ie. 10! = 1*2*3...*10 for k in range (1, x+1): # need to only store on digit per location of # the digit vector. Therefore must carry over the # excess to the next location carry_value = 0 for j in range(len(factorial_digits)): # Calculate the leftover and the carry # from the previous calculation leftover = factorial_digits[j]*k + carry_value # Store the result carry_value = leftover//10 factorial_digits[j] = leftover%10 while (carry_value != 0): factorial_digits.append(carry_value%10) carry_value //= 10 #------------------------------------------------------ #------------------------------------------------------ # DIGIT SUM CALCULATION #------------------------------------------------------ # Calculate the sum of the digits of factorial_digits[] #------------------------------------------------------ for r in range(len(factorial_digits)): digits_sum += factorial_digits[r] return digits_sum #------------------------------------------------------ #========================================================== #========================================================== # MAIN #========================================================== if __name__ == "__main__": # Number to get factorial of factorial_number = int(sys.argv[1]) # Main Function that calculates the sum of the factorials sum_number = SumOfFactorialDigits(factorial_number) print(sum_number) #===========================================================
0c4c7448b192fe9f90938a8e3bceae6b10844fd8
henrylu518/LeetCode
/Best Time to Buy and Sell Stock III.py
1,342
3.828125
4
""" Author: henry, henrylu518@gmail.com Date: May 23, 2015 Problem: Best Time to Buy and Sell Stock III Difficulty: Medium Source: http://leetcode.com/onlinejudge#question_123 Notes: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Solution: dp. max profit = max profit of left + max profit of right """ class Solution: # @param {integer[]} prices # @return {integer} def maxProfit(self, prices): if prices == []: return 0 maxProfitLeft = [None] * len(prices) maxProfitRight = [None] * len(prices) minPrice, maxProfitLeft[0] = prices[0], 0 for i in xrange(1, len(prices)): minPrice = min(minPrice, prices[i]) maxProfitLeft[i] = max( maxProfitLeft[i - 1], prices[i] - minPrice ) maxPrice, maxProfitRight[-1] = prices[-1], 0 for i in xrange(len(prices) - 2, -1, -1): maxPrice = max(prices[i], maxPrice) maxProfitRight[i] = max(maxProfitRight[i + 1], maxPrice - prices[i]) return max([maxProfitLeft[i] + maxProfitRight[i] for i in xrange(len(prices))])
e92b6ffddca5f7d7764278e8fca08da691e8da5c
henrylu518/LeetCode
/Combinations.py
1,246
3.578125
4
""" Author: Henry, henrylu518@gmail.com Date: May 13, 2015 Problem: Combinations Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_77 Notes: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] Solution: DFS. """ class Solution: # @param {integer} n # @param {integer} k # @return {integer[][]} def combine_1(self, n, k): def combineRecur(result, current, m, remain): if remain == 0: result.append(current) return if m > 0: combineRecur(result, [m] + current , m - 1, remain - 1) combineRecur(result, current, m - 1, remain) result = [] combineRecur(result,[], n, k) return result def combine_2(self, n, k): def combineRecur(current, m, remain): if remain == 0: return [current] if m > 0: return combineRecur( [m] + current, m - 1, remain - 1) + \ combineRecur(current, m - 1, remain) return [] return combineRecur([], n, k )
f7ced0cc2205948a24e69d0aaf2ec99d2fd8a09e
henrylu518/LeetCode
/Sqrt(x).py
735
3.8125
4
""" Author: Henry, henrylu518@gmail.com Date: May 13, 2015 Problem: Sqrt(x) Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_69 Notes: Implement int sqrt(int x). Compute and return the square root of x. Solution: Binary search in range [0, x / 2 + 1]. There is also Newton iteration method. """ class Solution: # @param {integer} x # @return {integer} def mySqrt(self, x): if x < 0: return -1 low, high = 0, x while high >= low: middle = (high + low) / 2 if middle ** 2 == x: return middle elif middle ** 2 > x: high = middle - 1 else: low = middle + 1 return high
a4dd4cde4800d2071a460bb53d0c8a26b1b1f4d8
henrylu518/LeetCode
/Search Insert Position.py
456
3.671875
4
class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer} def searchInsert(self, nums, target): low, high = 0, len(nums) - 1 while low <= high: middle = (low + high) / 2 if nums[middle] == target: return middle elif nums[middle] < target: low = middle + 1 else: high = middle - 1 return low
66201819201c710b9bc3cb6b66eec783d1450b6b
henrylu518/LeetCode
/Remove Duplicates from Sorted List II.py
1,139
3.5
4
""" Author: Henry, henrylu518@gmail.com Date: May 14, 2015 Problem: Remove Duplicates from Sorted List II Difficulty: Easy Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ Notes: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3. Solution: iterative """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def deleteDuplicates(self, head): dummy = ListNode(None) dummy.next = head previous = dummy while head: while head and head.next and head.val == head.next.val: value = head.val while head and head.val == value: head = head.next previous.next = head previous = previous.next if head: head = head.next return dummy.next
00da27e1e70bac78566304625fe1cec186b7a587
henrylu518/LeetCode
/Jump Game II.py
1,513
3.546875
4
""" Date: May 18, 2015 Problem: Jump Game II Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_45 Notes: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,1,1,4] The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) Solution: Jump to the position where we can jump farthest (index + A[index]) next time. """ class Solution: # @param {integer[]} nums # @return {integer} def jump(self, nums): i, reachable, step = 0, 0, 0 while reachable < len(nums) - 1: nextReachable = reachable while i <= reachable and i < len(nums): nextReachable = max(i + nums[i], nextReachable) i += 1 reachable = nextReachable step += 1 return step def jump_2(self, nums): if len(nums) in [0, 1]: return 0 queue, visited = [(0, 0)], set() while queue: i,steps = queue.pop(0) if i not in visited: visited.add(i) for j in xrange(nums[i], 0, -1): if i + j >= len(nums) - 1: return steps + 1 queue.append((i + j, steps + 1))
ce9f6b1070b57982cc521fbe9672d18fced43a58
henrylu518/LeetCode
/Populating Next Right Pointers in Each Node.py
1,915
4.0625
4
""" Author: Henry, henrylu518@gmail.com Date: May 16, 2015 Problem: Populating Next Right Pointers in Each Node Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_116 Notes: Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). For example, Given the following perfect binary tree, 1 / \ 2 3 / \ / \ 4 5 6 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL Solution: 1. Iterative: Two 'while' loops. 3. Recursive: DFS. Defect: Use extra stack space for recursion. """ # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): while root and root.left: firstNode = root.left while root: root.left.next = root.right if root.next: root.right.next = root.next.left root = root.next root = firstNode def connect_2(self, root): if root is None: return if root.left: root.left.next = root.right if root.right and root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right)
d112900cddfe3b0bbef72efeeb697dfc6cbe86bb
zman0225/python_cryptography
/ciphers/detectEnglish.py
1,294
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: ziyuanliu # @Date: 2014-02-07 18:12:47 # @Last Modified by: ziyuanliu # @Last Modified time: 2014-02-07 21:23:50 UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n' def loadDictionary(): dictionaryFile = open('dictionary.txt') englishWords = {} for word in dictionaryFile.read().split('\n'): englishWords[word]=None dictionaryFile.close() return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches)/len(possibleWords) def removeNonLetters(message): lettersOnly = [] for char in message: if char in LETTERS_AND_SPACE: lettersOnly.append(char) return ''.join(lettersOnly) def isEnglish(message, wordPercentage = 20, letterPer = 85): wordsMatch = getEnglishCount(message)*100 >= wordPercentage numLetters = len(removeNonLetters(message)) msgLetterPercentage = float(numLetters)/len(message)*100 lettersMatch = msgLetterPercentage >= letterPer return wordsMatch and lettersMatch
b6ba17928cbcb5370f5d144e64353b9d0cd8fcbd
Mohsenabdn/projectEuler
/p004_largestPalindromeProduct.py
792
4.125
4
# Finding the largest palindrome number made by product of two 3-digits numbers import numpy as np import time as t def is_palindrome(num): """ Input : An integer number Output : A bool type (True: input is palindrome, False: input is not palindrome) """ numStr = str(num) for i in range(len(numStr)//2): if numStr[i] != numStr[-(i+1)]: return False return True if __name__ == '__main__': start = t.time() prods = (np.reshape(np.arange(100, 1000), (1, 900)) * np.reshape(np.arange(100, 1000), (900, 1)))[np.tril_indices(900)] prods = np.sort(prods)[::-1] for j in multiples: if is_palindrome(j): print(j) break end = t.time() print('Run time : ' + str(end - start))
82aff3d2c7f6ad8e4de6df39d481df878a7450f7
sree714/python
/printVowel.py
531
4.25
4
#4.Write a program that prints only those words that start with a vowel. (use #standard function) test_list = ["all", "love", "and", "get", "educated", "by", "gfg"] print("The original list is : " + str(test_list)) res = [] def fun(): vow = "aeiou" for sub in test_list: flag = False for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) fun() print("The extracted words : " + str(res))
8d6df43f43f157324d5ce3012252c3c89d8ffba4
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/gpa_calculator.py
688
4.15625
4
print "Hi,Yao! Let's calculate the students' GPA!" LS_grade = float(raw_input ("What is the LS grade?")) # define variable with a string and input, no need to use "print" here. G_grade = float(raw_input ("What is the G grade?")) # double (()) works RW_grade = float(raw_input ("What is the RW grade?")) Fin_grade = float(raw_input ("What is the Final exam grade?")) # raw_input deals with string. needs to be converted into a floating point number Avg_grade = float((LS_grade*1 + G_grade*2 + RW_grade*2 + Fin_grade*2)/7) # the outer () here is not necessary print ("The student's GPA is:"),Avg_grade # allows to show the variable directly
2de9b9b92b49f32c62e9d86b0c69985f8fb4bb85
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/ex39.py
1,069
3.953125
4
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(' ') # need to add space between the quotation marks. more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"] while len(stuff) != 10: next_one = more_stuff.pop() # removes and returns the last item in the list print "Adding:", next_one stuff.append(next_one) print "There's %d items now." % len(stuff) print "There we go:", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # the last item in the list. Negative numbers count from the end towards the beginning. print stuff.pop() print ' '.join(stuff) # need to add space between the quotation marks to give space between print-out words. Means: join 'stuff' with spaces between them. print '#'.join(stuff[3:5]) # extracts a "slice" from the stuff list that is from element 3 to element 4, meaning it does not include element 5. It's similar to how range(3,5) would work.
edfb7ae4988150d17c6fb84b68e44ecdc8d17806
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/ex40ss.py
322
3.609375
4
# experiment version 2 cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' for city in cities.items(): print "City:", city for state,city in cities.items(): print "Places to move:", (state,city)
a3ae3bea53a3b19012f0b93749ac8c8aaa6a2427
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/ex14s.py
649
4.0625
4
from sys import argv script, user_name = argv prompt = 'What you say?' # prompt could be random things. it shows up at line 9,12,15. print "Hi,%s!%s here :)" %(user_name,script) print "Need to ask you some questions." print "Do you eat pork,%s?" % user_name pork = raw_input(prompt) print "Do you like beef?" beef = raw_input(prompt) print "What do you think of %s?" % user_name username = raw_input(prompt) # if use 'user_name'to define variable here, then user_name becomes whatever you type in from now on. print ''' Ok. So, you said %r to pork; %r to beef; and %r to %s. ''' %(pork,beef,username,user_name)
66ec728580a3be763105fe44f399b5f98f3c449f
AndreyAD1/18_price_format
/format_price.py
837
3.640625
4
import argparse def get_console_arguments(): parser = argparse.ArgumentParser() parser.add_argument('price', type=float, help='Enter a price.') arguments = parser.parse_args() return arguments def format_price(price): if type(price) == bool: return None try: real_num_price = float(price) except (TypeError, ValueError): return None rounded_price = round(real_num_price, 2) if rounded_price.is_integer(): formatted_price = '{:,.0f}'.format(rounded_price).replace(',', ' ') else: formatted_price = '{:,}'.format(rounded_price).replace(',', ' ') return formatted_price if __name__ == '__main__': console_arguments = get_console_arguments() price = console_arguments.price formatted_price = format_price(price) print(formatted_price)
62d2ca63e780982a75df63ebba2853fa1a3de150
TylerGarlick/intermediate-python-course
/my_list.py
218
3.5625
4
def main(): r = [4, -2, 10, -18, 22] print(r[2:6]) print(f'len list of {r[-1]}') t = r.copy() print(f'is t the same as r? {t is r}') c = r[:] print(f'is t the same as r? {t is c}') main()
5476eab2b0b2834ebb789d623703fdded5e4fa3e
RomarioGit/AED_1
/AED26.py
1,351
4
4
class aluno: def __init__(self,nome,cpf,nota): self.nome = nome self.cpf = cpf self.nota = nota def get_nota(self): if not self.nota == 0: return True return False def cadastrar_aluno(lista_alunos): nome = input("Informe o nome: ") cpf = input("Informe o CPF: ") nota = float(input("Informe a Nota: ")) alunos = aluno(nome,cpf,nota) lista_alunos.append(alunos) lista_alunos = [] def listar_alunos(lista_alunos): for i in range(len(lista_alunos)): print('Aluno:{}'.format(i)) print("Nome:{}".format(lista_alunos[i].nome)) print("CPF:{}".format(lista_alunos[i].cpf)) if lista_alunos[i].get_nota(): print("Nota: {}".format(lista_alunos[i].nota)) def menu(): print("-----MENU------") print("1-Cadastrar Aluno;") print('2-Analisar Nota;') print("3-Listar Alunos;") print("4-Sair;") def main(): while True: menu() op = input("Opção>> ") if op == '1': cadastrar_aluno(lista_alunos) elif op == '2': analisa_nota(lista_alunos) elif op == '3': listar_alunos(lista_alunos) elif op == '4': print("Saindo do sistema...") break else: print("Opção inválida!") main()
15e2d34d87b113c8f3b48ae4e0478541f8af8960
chrisesharp/aoc-2018
/day25/constellation.py
1,682
3.609375
4
import sys def find_constellations(input): points = {} for line in input.split(): point = tuple(map(int, line.split(','))) assimilated = False linked = {} for known_point in list(points.keys()): if close_enough(known_point, point): points, linked = assimilate(point, known_point, points, linked) assimilated = True if not assimilated: points[point]=set(point) if linked: linked_constellations = list(linked.items()) first_point, constellation = linked_constellations.pop() for other_point, other_constellation in linked_constellations: constellation |= other_constellation points[other_point]=first_point return list(filter(lambda x: isinstance(x, set), points.values())) def find_constellation(entry, points): if isinstance(points[entry], set): return points[entry], entry return find_constellation(points[entry], points) def assimilate(point, known_point, points, links): entry, idx_pt = find_constellation(known_point, points) entry.add(point) points[point] = idx_pt if entry not in links.values(): links.update({idx_pt: entry}) return points, links def close_enough(A,B): (x1,y1,z1,t1) = A (x2,y2,z2,t2) = B return abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(t1-t2) <= 3 def main(file): with open(file, 'r') as myfile: input = myfile.read() constellations = find_constellations(input) print("No. of constellations: ", len(constellations)) if __name__ == "__main__": main(sys.argv[1])
9789e52489b57ddc65791d841e5f693c0e3924a4
selinali2010/hello-world
/oneRoundYahtzee.py
1,685
3.921875
4
from random import choice rolls = { 0:"None", 1: "Pair", 2: "Two Pairs", 3: "Three of a kind", 4: "Four of a kind", 5: "Yahtzee!", 6: "Full House", 7: "Large Straight" } dice = [] for x in range(5): dice.append(choice([1,2,3,4,5,6])) print "Dice %i: %i" % (x + 1, dice[x]) #find the number of repeated numbers in the roll def numOfRepeats(dice): repeats = [0,0,0,0,0,0] # each rep. one number (1-6) for x in dice: #loop through the dice values repeats[x-1] += 1 #add one to repeats for that number return repeats #find the number of groups of repeats in the roll (ex: 2:2 means 2 numbers are doubled aka 2 pairs) def numOfGroups(repeats): groups = {1:0, 2:0, 3:0, 4:0, 5:0} # keys are the number of repeats, values are the number of each group of repeats for x in repeats: #loop through the number of repeats if (x != 0): #as long as a number is repeated groups[x] += 1 #add one to the value under the appropriate key return groups def rollResults(dice, groups, rolls): dice.sort() #sort helps with straights if groups[5] == 1: #if a Yahzee return rolls[5] elif groups[4] == 1: #four of a kind return rolls[4] elif groups[3] == 1 and groups[2] == 1: #Full house(1 group of 3, 1 group of 2) return rolls[6] elif groups[3] == 1: #three of a kind return rolls[3] elif groups[2] == 2: #two pairs return rolls[2] elif groups[2] == 1: #one pair return rolls[1] else: #when no repeats exist if dice[4] == 5 or dice[0] == 2: return rolls[7] # straight of 1,2,3,4,5 or 2,3,4,5,6 else: return rolls[0] # no pattern print rollResults(dice, numOfGroups(numOfRepeats(dice)), rolls)
44f8726cd570bf4339a767dde3e62713463da2b5
Vladyslav92/Python_HW
/lesson_6/4_task.py
378
3.828125
4
# Поиск минимума с переменным числом аргументов в списке. # def min(*args): .... enter = [10, 20, 35, 5, 6, 2, 7, 15] def min(*args): base_list = args sorted_list = [] for i in base_list: for j in i: sorted_list.append(j) result = sorted(sorted_list) return result[0] print(min(enter))
86902979397a947dd5d85874129c8d1aab949ac6
Vladyslav92/Python_HW
/lesson_2/3_task.py
536
4.21875
4
# На ввод подается строка. Нужно узнать является ли строка палиндромом. # (Палиндром - строка которая читается одинаково с начала и с конца.) enter_string = input('Введите строку: ').lower() lst = [] for i in enter_string: lst.append(i) lst.reverse() second_string = ''.join(lst) if second_string == enter_string: print('Это Палиндром!') else: print('Это не Палиндром!')
3de9c9f7af71fd66a0b8336e9c0a4fdcbf538973
Vladyslav92/Python_HW
/lesson_7/2_task.py
616
3.625
4
# Реализовать примеры с functools - wraps и singledispatch from functools import singledispatch, wraps def dec_function(func): """Function in function""" @wraps(func) def wrapps(): """decorated function""" pass return wrapps @dec_function def a_function(): """Simple Function""" return 'Hello World!' @singledispatch def summer(a, b): pass @summer.register(str) def _(a, b): print(a + b) @summer.register(int) def _(a, b): print(a - b) summer('Hello', 'World!') summer(100, 50) print(a_function.__name__) print(a_function.__doc__)
1f84a5ede2aa4aa8d8fea4921dc1bc53e66e9d91
Vladyslav92/Python_HW
/lesson_11/3_task.py
1,024
4
4
# Реализовать класс который будет: # 3.a читать из ввода строку # 3.b проверять, что строка состоит только из скобочек “{}[]()<>” # 3.c проверять, что строка является правильной скобочной последовательностью - выводить вердикт class Brackets: def __init__(self): self.line = input('Enter a string: ') def read_lines(self): return self.line def check_elements(self): while '()' in self.line or '[]' in self.line or '{}' in self.line or '<>' in self.line: self.line = self.line.replace('()', '') self.line = self.line.replace('[]', '') self.line = self.line.replace('{}', '') self.line = self.line.replace('<>', '') return not self.line TEXT = Brackets() print(TEXT.read_lines()) print(TEXT.check_elements())
6cefa99cdb92c9ed5738d4a40855a78b22e23b1b
Vladyslav92/Python_HW
/lesson_8/1_task.py
2,363
4.34375
4
# mobile numbers # https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem # Let's dive into decorators! You are given mobile numbers. # Sort them in ascending order then print them in the standard format shown below: # +91 xxxxx xxxxx # The given mobile numbers may have +91, 91 or 0 written before the actual digit number. # Alternatively, there may not be any prefix at all. # Input Format # The first line of input contains an integer, the number of mobile phone numbers. # lines follow each containing a mobile number. # Output Format # Print mobile numbers on separate lines in the required format. # # Sample Input # 3 # 07895462130 # 919875641230 # 9195969878 # # Sample Output # +91 78954 62130 # +91 91959 69878 # +91 98756 41230 def phones_fixer(func): def wrapper(nlist): result_list = [] for numbr in nlist: result = list(numbr) if '+91' in numbr: if 10 < len(numbr) < 12: result.insert(3, ' ') result.insert(-5, ' ') else: return 'The number is not correct' elif len(numbr) == 11: result.insert(0, '+') result.insert(1, '9') result.insert(2, '1') result.insert(3, ' ') result.remove(result[4]) result.insert(-5, ' ') elif len(numbr) == 12: result.insert(0, '+') result.insert(3, ' ') result.insert(-5, ' ') elif len(numbr) == 10: result.insert(0, '+') result.insert(1, '9') result.insert(2, '1') result.insert(3, ' ') result.insert(-5, ' ') else: return 'The number is not correct' result_list.append(''.join(result)) return func(result_list) return wrapper @phones_fixer def sort_numbers(numbers_list): return '\n'.join(sorted(numbers_list)) def read_numbers(): n = int(input('Количество номеров: ')) numbers = [] for i in range(n): number = input('Введите номер: ') numbers.append(number) return numbers if __name__ == '__main__': numbers = read_numbers() print(sort_numbers(numbers))
d2f3d3b79ad81c34394ed3cfa336b07f5edaceff
viniandrd/Biodiesel-Simulator
/utils/logginprinter.py
656
3.625
4
import sys class LoggingPrinter: def __init__(self, filename): self.out_file = open(filename, "w") self.old_stdout = sys.stdout # this object will take over `stdout`'s job sys.stdout = self # executed when the user does a `print` def write(self, text): self.old_stdout.write(text) self.out_file.write(text) # executed when `with` block begins def __enter__(self): return self # executed when `with` block ends def __exit__(self, type, value, traceback): # we don't want to log anymore. Restore the original stdout object. sys.stdout = self.old_stdout
3f5e5c7307e293db831a422f71e762d559edee95
saravey2021/homework-week-11
/Homework week 11/fri2.py
347
3.96875
4
def getPrice(fruitName): if fruitName=="banana": return 2 if fruitName=="apple": return 5 if fruitName=="orange": return 1 print("banana price is:"+str(getPrice("banana"))+" dolars") print("Orange price is:"+str(getPrice("orange"))+" dolars") print("apple price is:"+str(getPrice("apple"))+" dolars")
1ac6e401e05a22f94610ceb0e2aee0d7350cd3c2
Zoranc1/boggle
/boggle.py
2,220
3.5625
4
from string import ascii_uppercase from random import choice def make_grid(colums,rows): return { (c,r) : choice(ascii_uppercase) for r in range(rows) for c in range(colums)} def potencial_neighbours(position): c, r = position return[(c-1,r-1),(c,r-1),(c+1,r-1), (c-1,r), (c+1,r ), (c-1,r+1),(c,r+1),(c+1,r+1)] def path_to_word(path,grid): word ="" for position in path: word += grid[position] return word def load_word_list(filename): with open(filename) as f: text = f.read().upper().split("\n") return set(text) def get_real_neighbours(grid): real_neighbours ={} for position in grid: pn = potencial_neighbours(position) on_the_grid=[p for p in pn if p in grid] real_neighbours[position] = on_the_grid return real_neighbours def is_a_real_word(word,dictionary): return word in dictionary def get_stems(word): return [word[:i] for i in range(1, len(word))] def get_stems_for_word_list(wl): stems = [] for word in wl: stems_for_word = get_stems(word) stems += stems_for_word return set(stems) def search(grid, dictionary): neighbours = get_real_neighbours(grid) stems = get_stems_for_word_list(dictionary) words = [] def do_search(path): word = path_to_word(path, grid) if is_a_real_word(word,dictionary): words.append(word) if word in stems: for next_pos in neighbours[path[-1]]: if next_pos not in path: do_search(path + [next_pos]) for position in grid: do_search([position]) return set(words) def display_words(words): for word in words: print(word) print("Found %s words" % len(words)) def main(): grid = make_grid(200, 200) word_list = load_word_list("words.txt") words = search(grid, word_list) display_words(words) main()
3aa3b572f2561c795397cc40a3ee0e6eb522f036
pranavvm26/RandomProblemCodes
/find_longest_palindrome.py
1,488
4.09375
4
import copy palindrome_list = [] def find_palindrome(palindrome_string): longest_current_palin = 0 list_p = list(palindrome_string) for i in range(2, len(list_p), 1): duplicate_string = copy.deepcopy(list_p) del duplicate_string[0:i] _set = list_p[0:i] res = "".join(_set) in "".join(duplicate_string) if res: longest_current_palin = _set #print(res, " with word ", "".join(_set)) if longest_current_palin != 0: print("The longest palindrome word in the current session is ", "".join(longest_current_palin)) return palindrome_string.replace("".join(longest_current_palin), ""), "".join(longest_current_palin) else: return "", "" if __name__ == "__main__": palindrome_string = input("Enter the string to find the palindrome from:") palindrome_string_modified, longest_palindrome_word = find_palindrome(palindrome_string) palindrome_list.append(longest_palindrome_word) while True: palindrome_string_modified, longest_palindrome_word = find_palindrome(palindrome_string_modified) palindrome_list.append(longest_palindrome_word) if len(list(palindrome_string_modified)) == 0: break if palindrome_list[0] != "": print("The longest palindrome words in the string are as follows :") for strings in palindrome_list: print(strings) else: print("No palindrome words in the given string")
66d4bc1aec1f41337454123409ef597b1ea9ae8d
timmywilson/pandas-practical-python-primer
/training/level-1-the-zen-of-python/dragon-warrior/peppy.py
836
4
4
""" This code (which finds the sume of all unique multiples of 3/5 within a given limit) breaks a significant number of PEP8 rules. Maybe it doesn't even work at all. Find and fix all the PEP8 errors. """ import os import sys import operator INTERESTED_MULTIPLES = [3, 5] # constants should be all caps with underscores def quicker_multiple_of_three_and_five(top_limit): multiplier = 1 multiples = set() while True: if multiplier * 5 < top_limit: multiples.add(multiplier * 5) if multiplier * 3 < top_limit: multiples.add(multiplier * 3) else: break multiplier += 1 return sum(multiples) print("The sum of all unique multiples of 3 and 5 which given an " "upper limit of X is to consider is: answer")
554db1fd0a01073381a9877a33c4d1859e6e2915
maralex2003/OlistDojo1
/dojo/ativ_1e2/categories.py
1,114
3.5
4
class Category: def __init__(self, id: int, name: str): self.__id = id self.__name = name def set_id(self, id: int) -> None: self.__id = int(id) def get_id(self) -> int: return self.__id def set_name(self, name: str) -> None: self.__name = name def get_name(self) -> str: return self.__name def __str__(self): return f""" Id: {self.get_id()} Name: {self.get_name()} """ class SubCategory(Category): def __init__(self, id: int, name: str, parent: Category): self.__parent = parent super().__init__(id, name) def get_parent(self) -> Category: return self.__parent def set_parent(self, parent: Category) -> None: self.__parent = parent def get_parent_name(self) -> str: return self.get_parent().get_name() def __str__(self): return f""" Id: {self.get_id()} Name: {self.get_name()} Mother: {self.get_parent_name()} """
68ece26086a0fdc492e49949c1ca30df1a784ec2
maralex2003/OlistDojo1
/aula016/05_assert_classes.py
1,304
4.09375
4
# Com assert podemos testar as classes e seus métodos # podendo verificar objetos da classe e # o resultado de seus comportamentos class Product: def __init__(self, name:str, price:float)->None: self.name = name self.price = price @property def name(self)->str: return self.__name @property def price(self)->float: return self.__price @name.setter def name(self, name:str)->None: self.__name = name @price.setter def price(self, price:float)->None: try: self.__price = float(price) except ValueError as e: raise ValueError('O valor nao pode ser convertido para float') from e nome = 'Comp' preco = 2000 prod1 = Product(nome, preco) # testando se o objeto da classe é do tipo esperado e assim tentando o construtor assert type(prod1) == Product assert isinstance(prod1, Product) # testando o get e o set de name assert prod1.name == nome assert type(nome) == type(prod1.name) assert prod1.name is nome # testando o get e o set de price assert prod1.price == preco assert isinstance(prod1.price, float) # testando se a exceção é gerada pelo setter do price preco = 'R$2000' try: prod1.price = preco except Exception as e: assert isinstance(e, ValueError)
b19a1447ed25ec4da8414b703a3aa433394eeb36
charliesan16/Python-Estudio-Propio
/cantidadFilasPiramide.py
226
3.9375
4
bloques = int(input("Ingrese el número de bloques de la piramide:")) altura=0 while bloques: altura=altura+1 bloques=bloques-altura if bloques <= altura: break print("La altura de la pirámide:", altura)
b6a922d94e92769c5ab73e7fa0bb9d200147e17b
charliesan16/Python-Estudio-Propio
/Hola Mundo.py
146
3.6875
4
def suma(a,b): return a+b a=int(input("ingrese el valor de a=")) b=int(input("ingrese el valor de b=")) s=suma(a,b) print("La suma es de=",s)
46bc1461ea1fa5794bfc6ec29b021550c54dc7d0
Ashutoshcoder/python-codes
/Aggregation/groupAccordingToStateAndMatching.py
1,741
3.78125
4
""" Author : Ashutosh Kumar Version : 1.0 Description : Grouping according to state and then finding state with population >100 Then we are finding the biggest city and smallest city in the State. Email : ashutoshkumardbms@gmail.com """ import pymongo import pprint myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['aggregation'] mycol = mydb['population'] result = mydb.population.insert_many( [ {"_id": 1, "city": "Pune", "state": "MH", "pop": 68}, {"_id": 2, "city": "Mumbai", "state": "MH", "pop": 240}, {"_id": 3, "city": "Nashik", "state": "MH", "pop": 22}, {"_id": 4, "city": "Nagour", "state": "MH", "pop": 28}, {"_id": 5, "city": "Bhopal", "state": "MP", "pop": 30}, {"_id": 6, "city": "Indore", "state": "MP", "pop": 45} ] ) # sum and then a condition(similar to having SQL having clause myOutput = mydb.population.aggregate( [ {"$group": {"_id": "$state", "totalPop": {"$sum": "$pop"}}}, {"$match": {"totalPop": {"$gte": 100}}} ] ) for doc in myOutput: pprint.pprint(doc) # least and most populated city in each state myOutput = mydb.population.aggregate( [ { "$group": { "_id": {"state": "$state", "city": "$city"}, "pop": {"$sum": "$pop"} } }, {"$sort": {"pop": 1}}, {"$group": { "_id": "$_id.state", "biggestCity": {"$last": "$_id.city"}, "biggestPop": {"$last": "$pop"}, "smallestCity": {"$first": "$_id.city"}, "smallestPop": {"$first": "$pop"} } } ] ) for doc in myOutput: pprint.pprint(doc)
ce2e70a9d3734bacde1fd864de4ade2c53734d17
Ashutoshcoder/python-codes
/user_nobash.py
769
3.671875
4
''' Author : Ashutosh Kumar PRN : 19030142009 Assignment: Read all the usernames from the /etc/passwd file and list users which do not have bash as their default shell ''' fp = "" try: # opening file in read mode fp = open('/etc/passwd', 'r') # extracting every user from the file for line in fp: # writing it to the new file if 'bash' not in line: print(line.split(':')[0]) except FileNotFoundError: print("File not Found ") except FileExistsError: print("File Already Exists") except PermissionError: print("Permissison to open file is not granted ") except IsADirectoryError: print("It is a directory") finally: try: fp.close() except AttributeError: print("File not opened ")
530bfb68b165b1948f17c85ad7853059150d4806
Ashutoshcoder/python-codes
/Mongo-Example-Implementation/Bank/employeeManager.py
2,770
3.609375
4
''' Author : Ashutosh Kumar Version : 1.0 Description : Creating a Employee Management Functions(Insert,Update,Delete) Email : ashutoshkumardbms@gmail.com ''' import sys import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['empolyeedata'] mycol = mydb['employees'] def main(): while 1: # select option to do CRUD operation selection = input('\n Select 1 to insert, 2 to update, 3 to read, 4 to delete , 5 to exit \n') if selection == '1': insert() elif selection == '2': update() elif selection == '3': read() elif selection == '4': delete() elif selection == '5': print('Exiting ... ') sys.exit() else: print('\n Invalid Selection \n') # Function to insert data def insert(): try: employeeId = input('Enter Employee id : ') employeeName = input('Enter Name : ') employeeAge = input('Enter age :') employeeCountry = input('Enter Country :') mydb.employees.insert_one( { "id": employeeId, "name": employeeName, "age": employeeAge, "country": employeeCountry } ) print("\n Inserted Data Successfully \n") except ValueError: print("Invalid Value") except TypeError: print("Invalid Type ") # Function to read values def read(): try: empcol = mydb.employees.find() print('\n All data from EmployeeData Database \n') for emp in empcol: print(emp) except ValueError: print("Invalid Value") except TypeError: print("Invalid Type ") # Function to update a record def update(): try: criteria = input('\n Enter id to update \n') name = input('\n Enter Name to update : \n') age = input('\nEnter age to update: \n') country = input('\nEnter Country to update :\n') mydb.employees.update_one( {"id": criteria}, { "$set": { "name": name, "age": age, "country": country } } ) print("\n Record Updated successfully \n") except ValueError: print("Invalid Value") except TypeError: print("Invalid Type ") # Function to delete record def delete(): try: criteria = input('\n Enter id to update \n') mydb.employees.delete_one({"id": criteria}) print("\n Deletion successfully \n") except ValueError: print("Invalid Value") except TypeError: print("Invalid Type ") if __name__ == '__main__': main()
2c9d97b447fc0a3aaf464660c88ac4b9264023e7
Ashutoshcoder/python-codes
/data-science/barGraph.py
518
3.5
4
""" Author : Ashutosh Kumar Version : 1.0 Description : Plotting bar graph in Python Email : ashutoshkumardbms@gmail.com """ import numpy as np import matplotlib.pyplot as plt city = ["Delhi", "Beijing", "Washingtion", "Tokyo", "Moscow"] pos = np.arange(len(city)) Happiness_index = [60, 40, 70, 65, 85] plt.bar(pos, Happiness_index, color='blue', edgecolor='black') plt.xticks(pos, city) plt.xlabel('City', fontsize=16) plt.ylabel('Happiness_index', fontsize=16) plt.title('Barchart - Happiness Index across cities', fontsize=20) plt.show()
2d9c35e286e33a57bb0a441324fa16fc1c9f9793
kozl-ek/module_0
/Kozlova.EV_1.py
2,018
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[6]: import numpy as np number = np.random.randint(1,100) # загадали число от 1 до 100 print ("Загадано число от 1 до 100") def change(a): #Задаем функцию, изменяющую размер шага. Размер шага не должен быть меньше одного, чтобы избежать зацикливания. if a!=1: a=a//2 return(a) def game_core_v1(number): #Задаем функцию,которая будет фиксировать число попыток угадать число thinknumber=50 # задаем число, с которым будем сравнивать число, которое загадал компьютер. Выбрала 50, потому что это ровно середина step=25 # устанавливаем размер шага- число, на которое мы будем менять thinknumber в зависимости от результата сравнения. i=0 # устанавливаем счетчик итераций while number!=thinknumber : i+=1 if number>thinknumber: thinknumber+=step step=change(step) elif number<thinknumber: thinknumber-=step step=change(step) return(i) def score_game(game_core): #Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число count_ls = [] np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим! random_array = np.random.randint(1,100, size=(1000)) for number in random_array: count_ls.append(game_core(number)) score = np.mean(count_ls) print(f"Ваш алгоритм угадывает число в среднем за {score} попыток") return(score) score_game(game_core_v1)
89d6646ac4c27cbd605a3c4d3459eb2762875229
ezefranca/hackerrank-30-days
/day6/day6.py
368
3.65625
4
#!/bin/python3 import sys n = int(input().strip()) strings = [] for i in range(0, n): string = input().strip() strings.append(string) arr = list(strings[i]) odd = [] even = [] for j in range(0, len(arr)): if j % 2 == 0: even.append(arr[j]) else: odd.append(arr[j]) print(''.join(even),''.join(odd))
3d2c01cd94f0aea380e3dd5605d501ab44a5fbaf
TR18052000/DAY-3-ASSIGNMENT
/list.py
159
3.75
4
list = [1, 2, 3, 4, 5, 6] print(list) list[2] = 10 print(list) list[1:3] = [89, 78] print(list) list[-1] = 25 print(list)
0f65ea15f4845b8b3e5f5117af59444a5a666cbe
thomaskost17/QHWSDGNCB
/src/models/lorenz.py
1,169
3.671875
4
''' File: lorenz.py Author: Thomas Kost Date: 08 August 2021 @breif function for lorenz chaotic system, and plotting script ''' import numpy as np import matplotlib.pyplot as plt def lorenz(x :np.array, beta: np.array)->np.array: ''' x: position state vector of lorenz system beta: vector of lorenz parameters return: derivative of state vector ''' dx = np.array([ beta[0]*(x[1]-x[0]), x[0]*(beta[1]-x[2])-x[1], x[0]*x[1]-beta[2]*x[2]]) return dx def step_lorenz(x:np.array, beta:np.array, dt:float)->np.array: next_x = x + lorenz(x,beta)*dt return next_x if __name__ == "__main__": dt = 0.001 t = np.arange(0,50,dt) x = np.zeros((3,len(t))) x_0 = np.array((0,1,20)) b = np.array((10,28,8/3.0)) for i in range(len(t)): if(i == 0): x[:,i] = x_0 else: x[:,i] = step_lorenz(x[:,i-1],b,dt) ax = plt.figure().add_subplot(projection='3d') ax.plot(x[0,:], x[1,:], x[2,:], lw=0.5) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_zlabel("Z Axis") ax.set_title("Lorenz Attractor") plt.show()
466900753c34afb3fb85f7a23563005515d2cd78
jacobdanovitch/COMP1005_TA_Portal
/solutions/a4/soln.py
3,269
3.578125
4
#Author: Andrew Runka #Student#: 100123456 #This program contains all of the solutions to assignment 4, fall2018 comp1005/1405 #and probably some other scrap I invented along the way def loadTextFile(filename): try: f = open(filename) text = f.read() f.close() return text except IOError: print(f"File {filename} not found.") return "" def countWords(filename): text = loadTextFile(filename) text = text.split() return len(text) def countCharacters(filename): text = loadTextFile(filename) return len(text) def countCharacter(text,key): count=0 for c in text: if c==key: count+=1 return count def countSentences(filename): text = loadTextFile(filename) count = 0 count+=countCharacter(text,'.') count+=countCharacter(text,'?') count+=countCharacter(text,'!') return count #return text.count(".")+text.count('?')+text.count('!') #also valid def removePunctuation(text): text = text.replace(".","") text = text.replace(",","") text = text.replace("!","") text = text.replace("?","") text = text.replace(";","") text = text.replace("-","") text = text.replace(":","") text = text.replace("\'","") text = text.replace("\"","") return text def wordFrequency(filename): text = loadTextFile(filename) text = removePunctuation(text.lower()) d = {} for w in text.split(): if w not in d: d[w]=1 else: d[w]+=1 return d def countUniqueWords(filename): dict = wordFrequency(filename) return len(dict.keys()) def countKWords(filename,k): dict = wordFrequency(filename) count=0 for key in dict.keys(): if key[0] == k: count+=1 return count def kWords(filename,k): dict = wordFrequency(filename) result = [] for word in dict.keys(): if word[0] == k: result.append(word) return result def longestWord(filename): text = loadTextFile(filename) text = removePunctuation(text).split() longest = "" for w in text: if len(w)>len(longest): longest=w return longest def startingLetter(filename): dict = wordFrequency(filename) #letters = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0} #26 counters, one for each letter letters = {} #count frequencies for key in dict: if key[0] in letters: letters[key[0]] +=1 else: letters[key[0]] = 1 #find largest largest='a' for key in letters.keys(): if letters[key]>letters[largest]: largest=key return largest def letterFrequency(filename): text = loadTextFile(filename) d = {} for c in text: if c in d: d[c]+=1 else: d[c]=1 return d def followsWord(filename, keyWord): keyWord = keyWord.lower() text = loadTextFile(filename) text = removePunctuation(text).lower() text = text.split() follows = [] for i in range(len(text)-1): if text[i] == keyWord: if text[i+1] not in follows: follows.append(text[i+1]) return follows def writeLines(filename,list): file = open(filename,'w') #out = "\n".join(list) out = "" for line in list: out+=line+"\n" file.write(out) file.close() def reverseFile(filename): text = loadTextFile(filename) #or readlines text = text.split("\n") text.reverse() writeLines("reversed_"+filename, text)
781fc5a0241560371636b46c096d0a476fce622d
henrypalacios/transactions_account
/backend_api/src/foundation/write_lock.py
1,196
3.875
4
from threading import Thread, Condition, current_thread, Lock class ReadersWriteLock: """ A lock object that allows many simultaneous "read locks", but only one "write lock." """ def __init__(self): self._read_ready = Condition(Lock()) self._readers = 0 def acquire_read_lock(self): """ Acquire a read lock. Blocks only if a thread has acquired the write lock. """ self._read_ready.acquire() try: self._readers += 1 finally: self._read_ready.release() def release_read_lock(self): """ Release a read lock. """ self._read_ready.acquire() try: self._readers -= 1 if not self._readers: self._read_ready.notifyAll( ) finally: self._read_ready.release( ) def acquire_write_lock(self): """ Acquire a write lock. Blocks until there are no acquired read or write locks. """ self._read_ready.acquire( ) while self._readers > 0: self._read_ready.wait( ) def release_write_lock(self): """ Release a write lock. """ self._read_ready.release( )
90be014b94c2b6a63f759e191759412965cc0acd
ModelPhantom/raspberrypython
/pygametest/hellopython.py
367
3.59375
4
import pygame width=640 height=480 radius=100 stroke=1 pygame.init() window=pygame.display.set_mode((width,height)) window.fill(pygame.Color(255,255,255)) while True: pygame.draw.circle(window,pygame.Color(255,0,0),(width/2,height/2),radius,stroke) pygame.display.update() if pygame.QUIT in [e.type for e in pygame.event.get()]: Break
0b40c91c5a9f2316d0bb16155a00f77857d74df1
soporte00/python_practice
/01_vacattion_system_for_rappi_employees.py
2,172
3.703125
4
import os ''' sections key section 1 A. clientes 2 Logística 3 Gerencia employees key time(years) vacations(days) 1 1 6 1 2-6 14 1 7 20 2 1 7 2 2-6 15 2 7 22 3 1 10 3 2-6 20 3 7 30 ''' while True: os.system("clear") print("**********************************************") print("* Sistema vacacional para empleados de rappi *") print("********************************************** \n") name = input("Ingresa el nombre del empleado: ") print("\n1)A. clientes 2)Logística 3)Gerencia ") employeeKey = int( input("\nIngresa el número correspondiente a su departamento: ") ) employeeYears = int( input("\nIngresa la antiguedad en años: ") ) print("\nLos datos ingresados son: \n",f"\n Nombre: {name}",f"\n Departamento: {employeeKey}",f"\n antiguedad: {employeeYears} años" ) agree = input("\n¿Los datos son correctos? escribe si o no: ") if agree == 'si': print("\n==================================\n") if employeeKey == 1: if employeeYears == 1: print(name+" tiene 6 dias de vacaciones") elif employeeYears >= 2 and employeeYears <=6: print(name+" tiene 14 dias de vacaciones") elif employeeYears >= 7: print(name+" tiene 20 dias de vacaciones") else: print("La antiguedad es incorrecta") elif employeeKey == 2: if employeeYears == 1: print(name+" tiene 7 dias de vacaciones") elif employeeYears >= 2 and employeeYears <=6: print(name+" tiene 15 dias de vacaciones") elif employeeYears >= 7: print(name+" tiene 22 dias de vacaciones") else: print("La antiguedad es incorrecta") elif employeeKey == 3: if employeeYears == 1: print(name+" tiene 10 dias de vacaciones") elif employeeYears >= 2 and employeeYears <=6: print(name+" tiene 20 dias de vacaciones") elif employeeYears >= 7: print(name+" tiene 30 dias de vacaciones") else: print("La antiguedad es incorrecta") else: print("\nEl departamento elegido no es correcto") action = input('\n ** Para repetir el programa presiona Enter o "q" para salir: ') if action == 'q': break
57c4893c2f0db4ad531c725146b92b5ee066f7ed
bmoser12/608-mod3
/custom-object.py
473
3.78125
4
#use this to figure out a bill total including tip and tax def tip_amount(total,tip_percent): return total*tip_percent def tax_amount(total, tax_percent): return total*tax_percent def bill_total(total,tax,tip): return total+tip_amount+tax_amount total = 100 tip_percent = .20 tax_percent = .075 tax = tax_amount(total,tax_percent) tip = tip_amount(total,tip_percent) print('Tip amount:',tip) print('Tax amount:', tax) print('Bill total:',total+tax+tip)
d21033c6e4ba17697dcbdf20072ab069d3e4779c
imrehg/coderloop
/missile/python/missile
1,760
3.84375
4
#!/usr/bin/python import sys def findlongest(nums): """ Dynamic programming: O(n^2) based on: http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence#Dynamic_Programming """ n = len(nums) if n == 0: return 0 length = [1]*n path = range(n) for i in xrange(1, n): for j in xrange(0, i): if (nums[i] > nums[j]) and (length[i] < (length[j]+1)): length[i] = length[j] + 1 path[i] = j return max(length) def findlongest2(nums): """ Clever solution O(n log n) based on: http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence#Faster_Algorithm """ n = len(nums) if n == 0: return 0 # Add the first index to the list # a[i] is the index of the smallest final value # for an increasing subsequence with length i a = [0] # Loop through all the other elemts for i in xrange(n): if (nums[a[-1]] < nums[i]): a.append(i) continue # Binary search to find which subsequent length this will be u = 0 v = len(a)-1 while u < v: c = (u + v) // 2 if (nums[a[c]] < nums[i]): u = c + 1 else: v = c # Replace the element in the helper list if smaller than we # had already if (nums[i] < nums[a[u]]): a[u] = i return len(a) def main(argv=None): if (argv==None): argv = sys.argv # Load information from file filename = argv[1] f = open(filename, 'r') nums = [] for line in f.readlines(): nums.append(int(line)) # # Dynamic programming # print findlongest(nums) # Test+Search print findlongest2(nums) if __name__ == "__main__": main()
f3032a78f96bd74011401e625d5f20c263cad637
TheGavinCorkery/BattleshipPythonGame
/Player.py
1,570
3.828125
4
from Board import Board class Player(): def __init__(self): self.my_board = Board() self.guess_board = Board() self.opponent_board = [] self.hits = 0 #Control all methods to guess a spot on opponents board def guess_spot(self): print('Here is your current guessing board') self.print_guess_board() guess_space = self.get_guess_space() #Update guess board with a hit or a miss hit_or_miss = self.space_hit_or_miss(guess_space) self.update_guess_board(guess_space, hit_or_miss) def print_guess_board(self): for row in self.guess_board.player_board: print(' '.join(row)) def space_hit_or_miss(self,guess_space): if self.opponent_board.player_board[guess_space[1]][guess_space[0]] == 'x': print ("Congrats, you sunk my battleship") self.hits += 1 return True else: print('You missed!') return False #Method to get input from user on their space to guess and returns it as a list def get_guess_space(self): guess_row = int(input('What row do you want to guess?: ')) guess_col = int(input('What column do you want to guess?: ')) return [guess_row, guess_col] def update_guess_board(self, guessed_space, did_it_hit): if did_it_hit == True: self.guess_board.player_board[guessed_space[1]][guessed_space[0]] = 'H' else: self.guess_board.player_board[guessed_space[1]][guessed_space[0]] = 'M'
6dd2950189bb6d780432ea24b884b5a01b6406cd
Joghur/modbus-reader
/data/queries.py
1,820
3.625
4
import sys from utils.files import import_config """Methods for manipulating a SQlite database Create and insert methods SQL queries are defined at top of file """ # getting database configurations config = import_config('config_database.json') # guard clause in case config file doesn't exist if not config: sys.exit(2) # defining SQL queries # create_table_query = f''' # CREATE TABLE {config['TABLE_NAME']} ( # {config['DATE_COLUMN_NAME']} timestamp NOT NULL PRIMARY KEY, # {config['SECRET_STRING_COLUMN_NAME']} text NOT NULL # ); # ''' # # parameterized query to avoid SQL injection # insert_data_query = f''' # INSERT INTO {config['TABLE_NAME']} # ( # {config['DATE_COLUMN_NAME']}, # {config['SECRET_STRING_COLUMN_NAME']} # ) # VALUES (?, ?) # ; # ''' def create_table_query(): return f''' CREATE TABLE {config['TABLE_NAME']} ( {config['DATE_COLUMN_NAME']} timestamp NOT NULL PRIMARY KEY, {config['SECRET_STRING_COLUMN_NAME']} text NOT NULL ); ''' def insert_data_query(): # parameterized query to avoid SQL injection return f''' INSERT INTO {config['TABLE_NAME']} ( {config['DATE_COLUMN_NAME']}, {config['SECRET_STRING_COLUMN_NAME']} ) VALUES (?, ?) ; '''
6cd9cc1bb0048fc3414916d3da5652c816258ba6
noah-daniel-mancino/algorithms-on-the-side
/max_line.py
804
3.546875
4
""" You can characterize each line by the m and b in y = mx + b. Do this for each pair of lines, and see which ones pops up the most. """ def max_points(points): lines = set() lines_frequency = {} for index, point in enumerate(points): other_points = points[index + 1:] print(other_points) for other_point in other_points: slope = (point[1] - other_point[1])/(point[0] - other_point[0]) y_intercept = point[1] - (slope * point[0]) if (slope, y_intercept) in lines: lines_frequency[(slope, y_intercept)] += 1 else: lines_frequency[(slope, y_intercept)] = 1 lines.add((slope, y_intercept)) return max(lines_frequency.values()) print(max_points([[1,1],[2,2],[3,3],[7,2]]))
198648ec4ed8b8019cbb6ce31ec4e561429f9600
TheSliceOfPi/Practice-Questions
/sumSquareDiff.py
551
4
4
''' The sum of the squares of the first ten natural numbers is, The square of the sum of the first ten natural numbers is, Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is . Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' def sumSqrDiff(num): add=0 sqr=0 for i in range(1,num+1): add+=i**2 sqr+=i sqr=sqr**2 diff=sqr-add return diff num=100 print(sumSqrDiff(num))
3ef4d753b1429f9cdb1ea4ed7a02fbe80387a3ac
Scarlett4431/LeetCode
/150.py
901
3.515625
4
#150. Evaluate Reverse Polish Notation class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack= [] for t in tokens: if t!='+' and t!='-' and t!='*' and t!='/': stack.append(t) else: b = int(stack.pop()) a = int(stack.pop()) if t=='+': r= a+b stack.append(r) if t=='-': r= a-b stack.append(r) if t=='*': r= a*b stack.append(r) if t=='/': if a*b <0: r= -(abs(a)//abs(b)) else: r= a//b stack.append(r) q= stack.pop() return q
27ea6e6eec457d29ee6f9cc7d147043649c9f5e8
shami09/IvLabs
/conditionex3.1.py
206
3.859375
4
hrs = input("Enter Hours:") h = float(hrs) rate=input("Enter Rate:") r=float(rate) if h > 40: nom=h*r ep=(h-40)*(r*0.5) pay=nom+ep else: pay=h*r print("Pay:",pay)
231f69494ca4939e8d1d698aa49559a526f7cc8a
DHSZ/igcse-pre-release-summer-2021-22
/task2.py
6,778
4.21875
4
""" Summer 2021 - Pre-release material Python project to manage a electric mountain railway system Author: Jared Rigby (JR) Most recent update: 19/03/2021 """ # Task 1 - Start of the day train_times_up = [900, 1100, 1300, 1500] # Train times for going up the mountain train_seats_up = [480, 480, 480, 480] # Number of seats available up the mountain money_up = [0, 0, 0, 0] # The amount of money made by each train up the mountain train_times_down = [1000, 1200, 1400, 1600] # Train times for going up the mountain train_seats_down = [480, 480, 480, 640] # Number of seats available up the mountain money_down = [0, 0, 0, 0] # The amount of money made by each train up the mountain RETURN_TICKET = 50 # CONSTANT - the price of a return ticket JOURNEYS_EACH_DAY = len(train_times_up) # CONSTANT - the number of return journeys each day # Reusable procedure which lists all train times and the seats available def display_board(): print("\n------------ Trains uphill ------------") for x in range(len(train_times_up)): print("Time:", train_times_up[x], "\tSeats:", train_seats_up[x]) print("----------- Trains downhill -----------") for x in range(len(train_times_down)): print("Time:", train_times_down[x], "\tSeats:", train_seats_down[x]) display_board() # Use the display_board() procedure to list all train times and seats for the day # Task 2 - Purchasing tickets customer_type = 0 # Stores the type of customer booking (single or group) tickets_needed = 0 # Stores the user input for the number of tickets needed free_tickets = 0 # Stores how many free tickets the user will receive total_price = 0 # Stores the total price of the transaction departure_time = 0 # Will store user input for time up the mountain return_time = 0 # Will store user input for time down the mountain departure_index = -1 # Stores the array element for the train up the mountain return_index = -1 # Stores the array element for the train down the mountain enough_seats_up = False # Flag variable for available seats enough_seats_down = False # Flag variable for available seats # Shopping loop - will run until the end of the day calculation is requested while customer_type != 3: customer_type = 0 # Reset customer_type for each transaction enough_seats_up = False # Reset flags for each transaction enough_seats_down = False # Reset flags for each transaction print("\nPlease make a selection") print("--------------------------") print("1 - Single customer booking") print("2 - Group customer booking") print("3 - To close the ticket booth and output today's totals\n") while customer_type != 1 and customer_type != 2 and customer_type != 3: customer_type = int(input("Please enter 1, 2 or 3: ")) # Validation loop - will only exit when the customer selects a possible number of tickets while enough_seats_up is False or enough_seats_down is False: # Reset all validation variables tickets_needed = 0 departure_index = -1 return_index = -1 if customer_type == 1: print("Single customer booking") tickets_needed = 1 # Single bookings only need 1 ticket elif customer_type == 2: # Input and validation for the number of tickets needed for a group booking print("Group customer booking") while tickets_needed < 2: tickets_needed = int(input("Please enter the number of tickets required... ")) else: print("Calculating today's totals") break # Input and validation of the train times while departure_index == -1 or return_index == -1: # Ask the user to enter train times departure_time = int(input("Please enter the departure time... ")) return_time = int(input("Please enter the return time... ")) # Check if the journey up the mountain exists for x in range(JOURNEYS_EACH_DAY): if departure_time == train_times_up[x]: print("Train at", departure_time, "found!") departure_index = x if departure_index == -1: print("No train found at", departure_time) # Check if the journey down the mountain exists for y in range(JOURNEYS_EACH_DAY): if return_time == train_times_down[y]: print("Train at", return_time, "found!") return_index = y if return_index == -1: print("No train found at", return_time) # Check the logical order of the journeys (up happens before down) if departure_time > return_time: return_index = -1 departure_index = -1 print("Error - you can't depart after you return") # Check enough seats are available if train_seats_up[departure_index] - tickets_needed < 0: print("Error - not enough seats available up the mountain") else: enough_seats_up = True if train_seats_down[return_index] - tickets_needed < 0: print("Error - not enough seats available down the mountain") else: enough_seats_down = True # Calculate the price if tickets_needed < 10: total_price = tickets_needed * RETURN_TICKET elif tickets_needed >= 10: free_tickets = tickets_needed // 10 if free_tickets > 8: # Set an upper limit for free tickets free_tickets = 8 total_price = (tickets_needed * RETURN_TICKET) - (free_tickets * RETURN_TICKET) # Do not show the invoice for customer type 3 if customer_type != 3: print("\n------ CUSTOMER INVOICE ------") print("Tickets:", tickets_needed) print("Total price:", total_price) print("Free tickets:", free_tickets) print("------------------------------\n") # Update the data for the display board train_seats_up[departure_index] = train_seats_up[departure_index] - tickets_needed train_seats_down[return_index] = train_seats_down[return_index] - tickets_needed # Update the arrays which store the amount of money received by each train service money_up[departure_index] = money_up[departure_index] + (total_price / 2) money_down[return_index] = money_down[return_index] + (total_price / 2) # Output the display board with the latest values display_board() print("Task 3 will happen here!")
f4a47627b293951f8f6c408628b7034809e5c68a
emildoychinov/Talus
/loader/cogs/ttt.py
6,769
3.671875
4
from discord.ext import commands import time #a util function that will be used to make a list into a string makeStr = lambda list : ''.join(list) class tictactoe(commands.Cog): def __init__(self, bot, comp_sign='x', p_sign='o'): self.bot = bot self.pos=0 self.p_move = -1 self.comp_move = 1 self.comp_sign = comp_sign self.p_sign = p_sign self.field = ['-']*9 #a function to represent the board and to make it ready for printing def represent(self, flag=0): fld = list(self.field) for i in range (0,9): if flag==0: fld[i]+=' ' if i%3 == 0 and flag==0: fld[i-1]+='\n' return makeStr(fld) #here we check if the game has been won def win (self, fld=None): if fld is None : fld = list(self.represent(1)) #the positions for winning winPos = [[0,1,2], [0,3,6], [0,4,8], [1,4,7], [2,4,6], [2,5,8], [3,4,5], [6,7,8]] #check for i in range(8): # if the player wins we return -1 and if the bot wins we return 1, that will be used in the algorithm for the bot if fld[winPos[i][0]] == fld[winPos[i][1]] and fld[winPos[i][0]] == fld[winPos[i][2]] and fld[winPos[i][0]]!='-': return -1 if fld[winPos[i][0]] == self.p_sign else 1 #if it is a draw or the game has not yet ended we return 0 return 0 #a utility function to edit a discord message async def edt (self, ctx, cnt, msg, auth_msg = None): if auth_msg is not None : await auth_msg.delete() await msg.edit(content = cnt) return msg #the bot algorithm def minimax(self, pl, fld = None): if fld is None: fld = list(self.represent(1)) #if the game has ended we return either -1 or 1, depending on who won end = self.win(fld) if end : return end*pl #we start from negative score : we prefer a move that could lead to a draw rather than a move that could lead to the opposing player winning score = -10 move=-10 for i in range(9): #we check if the position is available if fld[i] == '-': #test the position fld[i] = self.p_sign if pl==-1 else self.comp_sign #see how the position will look like for the opposing player moveScore = -self.minimax(-pl, fld) if moveScore > score : score = moveScore move = i #we return the field on the given position back to normal fld[i] = '-' #if no move has been made we return 0 if move == -10 : return 0 #if there has been a move made but no one has yet won we return the score return score #here we make a move based on the results from the minimax function (a full tree search of the tictactoe board) def makeMove(self): fld = list(self.represent(1)) score = -10 for i in range(9): #if available if fld[i] == '-': #test the move fld[i] = self.comp_sign #see how it will look like for the opposing player thisScore = -self.minimax(-self.comp_move, fld) fld[i] = '-' #if the score of the move is better than the current score we save it if thisScore>score : score = thisScore move = i #we return the move+1 return move+1 #a utility function for deleting a certain message async def delTrace (self, ctx, msg): await msg.delete() @commands.command() #here the game is played off async def game(self, ctx): self.field = ['-']*9 msg = await ctx.channel.send('```WELCOME TO THE GAME OF TICTACTOE!\n Do you want to be (f)irst or (s)econd?\n```') #we wait to see if the player wants to be first or second a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author) if (a.content == 'f'): flg = 0 self.p_sign = 'x' self.comp_sign = 'o' else : flg = 1 self.p_sign = 'o' self.comp_sign = 'x' for i in range(9): #if the game has been won if self.win(): #edit the board msg = await self.edt(ctx, '```THE GAME HAS ENDED! '+('I WIN!\n' if self.win()==1 else 'YOU WIN!\n')+self.represent()+'\n```', msg) time.sleep(1.5) #delete the board await self.delTrace(ctx, msg) return try : #a is an argument that is None by default, it's the player's message : if it doesn't exist we catch the exception and proceed without it #if it does, we delete it msg = await self.edt(ctx, '```\n'+self.represent()+'\n```', msg, a) except : msg = await self.edt(ctx, '```\n'+self.represent()+'\n```', msg) #flg is the flag for the player : if he is first it's 0, otherwise it's 1 if i%2 == flg: #we wait for the player's move a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author) #a cheeky easter egg :) if a.content == 'stop' : await ctx.channel.send('```\nOkay, I get it, human. You are too weak\n```') return #we check if the move is valid #if it is not, it becomes 0 pos = (int(a.content) if a.content.isdigit() else 0) if i%2==flg else self.makeMove() #while the move is invalid while pos > 9 or pos<=0 or self.field[pos-1]!='-': #we wait for a new one a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author) pos = int(a.content) #we make the move self.field[pos-1] = self.p_sign if i%2 == flg else self.comp_sign try : msg = await self.edt(ctx, '```THE GAME HAS ENDED! IT IS A DRAW!\n'+self.represent()+'\n```', msg, a) except : msg = await self.edt(ctx, '```THE GAME HAS ENDED! IT IS A DRAW!\n'+self.represent()+'\n```', msg) time.sleep(1.5) await self.delTrace(ctx, msg) #setting up the cog for the bot... def setup(bot): bot.add_cog(tictactoe(bot))
fb04a8d334283582cca10c9ae04126e97476f4f9
wchi619/Python-Assignment-1
/a1_wchi3.py
6,844
4.53125
5
#!/usr/bin/env python3 """ OPS435 Assignment 1 - Fall 2019 Program: a1_wchi3.py Author: William Chi This program will return the date in YYYY/MM/DD after the given day (second argument) is passed. This program requires 2 arguments with an optional --step flag. """ # Import package import sys def usage(): """Begin usage check. """ if len(sys.argv) != 3 or len(sys.argv[1]) != 10 or sys.argv[2].lstrip("-").isdigit() == False: #Argument parameter check print("Error: wrong date entered") exit() else: #If error check pass, continue program and return date and days date = str(sys.argv[1]) days = int(sys.argv[2]) return date, days def valid_date(date): """Validate the date the user inputs. This function will take a date in "YYYY/MM/DD" format, and return True if the given date is a valid date, otherwise return False plus an appropriate status message. This function will also call another function to double check that the days in month entered is correct. """ days_in_mon(date) # Begin date validation if int(date[0:4]) not in range(1, 2050): print("Error: wrong year entered") exit() elif int(date[5:7]) not in range(1, 13): print("Error: wrong month entered") exit() elif int(date[8:10]) not in range(1, 32): print("Error: wrong day entered") exit() elif leap_year(date) == False and date[5:7] == '02' and int(date[8:10]) in range(29,32): # If not leap year but date entered is Feb 29-31 print("Error: Invalid day entered (not a leap year).") exit() elif leap_year(date) == True and date[5:7] == '02' and int(date[8:10]) not in range(1,30): # If leap year, but date entered is Feb 30-31 print("Error: Invalid day entered (01-29 only).") exit() else: return True def days_in_mon(date): """Creates dictionary of the maximum number of days per month. This function will take a year in "YYYY" format and return a dictionary object which contains the total number of days in each month for the given year. The function will also call another function to check for leap year. """ leap_year(date) days_per_month = { '1' : 31, '2' : 28, '3' : 31, '4' : 30, '5' : 31, '6' : 30, '7' : 31, '8' : 31, '9' : 30, '10' : 31, '11' : 30, '12' : 31, } if leap_year(date) == True: days_per_month['2'] = 29 # Change Feb to 29 if leap year return days_per_month else: return days_per_month def leap_year(date): """Double check if the year entered is a leap year or not. This function will take a year in "YYYY" format and return True if the year is a leap year, otherwise return False. """ year = int(date[0:4]) # Grab year # Leap year test will only return True on 2 conditions: # 1. The century year is divisible by 400, OR # 2. The year is divisible by 4 AND IS NOT divisible by 100 (omit century years). if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))): return True else: return False def after(date, days): """Returns the final calculated value of the date. This function will take a date and a positive integer, add the integer as the amount of days to the date and return the final date. This function will also call on another function to retrieve a dictionary of the total number of days per each month (also accounting for leap years). """ dictionary = days_in_mon(date) year, month, day = date.split('/') year = int(year) month = int(month) day = int(day) # Define variables for the final month & day. nmonth = month nday = day for i in range(days): # Resets day to 1 if it exceeds the total days in a month. if nday >= dictionary[str(month)]: month = month + 1 nday = 1 nmonth = nmonth + 1 else: nday = nday + 1 # Resets month to 1 if it exceeds the total months in a year. if nmonth > 12: nmonth = 1 month = 1 year = year + 1 n = str(year) + "/" + str(nmonth).zfill(2) + "/" + str(nday).zfill(2) return n def before(date, days): """Returns the final calculated value of the date. This function will take a date and a negative integer, subtract the date with the amount of days and return the final date. This function will also call on another function to retrieve a dictionary of the total number of days per each month (also accounting for leap years). """ dictionary = days_in_mon(date) year, month, day = date.split('/') year = int(year) month = int(month) day = int(day) # Define variables for the final month & day. nmonth = month nday = day for i in range(days, 0): if nday <= 1: month = month - 1 if month == 0: month = 1 # Set the month to the highest value allowed in that month. nday = dictionary[str(month)] nmonth = nmonth - 1 else: nday = nday - 1 # Reset month to 12 if it is lower than the total months in a year. if nmonth < 1: nmonth = 12 month = 12 year = year - 1 n = str(year) + "/" + str(nmonth).zfill(2) + "/" + str(nday).zfill(2) return n def dbda(date, days): """Calls the correct function to calculate the date. This function will retrieve the validated date and days and depending on the value of the integer it will call 2 separate functions. """ if int(sys.argv[2]) >= 0: return after(date, days) else: before(date, days) return before(date, days) if __name__ == "__main__": # Executed first: figure out if --step option is present or not, and pop itif necessary. if sys.argv[1] == '--step': step = True sys.argv.pop(1) usage() else: step = False usage() # Argument initialization date = str(sys.argv[1]) days = int(sys.argv[2]) valid_date(date) # Begin date validation. # Call calculation function to print the final date. if step == True: if days > 0: # Loop to print positive date step by step. for i in range(1, days+1): final_date = dbda(date, i) print(final_date) else: # Loop to print negative date step by step (reverse order). for i in reversed(range(days, 0)): final_date = dbda(date, i) print(final_date) if step == False: # Loop to print normally if no --step option inputted. final_date = dbda(date,days) print(final_date)
4deb99f3c3c58525f632d85d77c748be62a7ce5b
juraj80/Python-Data-Stuctures
/10/romeo.py
430
3.8125
4
''' print the ten most common words in the text ''' import string handle=open('romeo-full.txt') counts=dict() for line in handle: line=line.translate(None,string.punctuation) line=line.lower() words=line.split() for word in words: if not word in counts: counts[word]=1 else: counts[word]=counts[word]+1 res=list() for k,v in counts.items(): res.append((v,k)) res.sort(reverse=True) for k,v in res[:10]: print v,k
cf8efc269f8d53acd9b41e2bc876a32f3b11c620
juraj80/Python-Data-Stuctures
/09/bigcountA.py
596
3.53125
4
name = raw_input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) emails=list() for line in handle: line=line.rstrip() if line=="":continue if not line.startswith("From:"):continue words=line.split() emails.append(words[1]) counts=dict() for email in emails: if not email in counts: counts[email]=1 else: counts[email]=counts[email]+1 print counts bigcount=None bigemail=None for email,count in counts.items(): if bigcount is None or count>bigcount: bigcount=count bigemail=email print bigemail,bigcount
4bd83144bd8246dd40fd063efb8ccb6808ab4abf
juraj80/Python-Data-Stuctures
/07/enterfile.py
171
3.59375
4
inp=raw_input("Enter a file:") try: file=open(inp) except: print "Error. Please Enter a File." exit() for line in file: line=line.rstrip() print line