blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
d4686acca2d88d7307d3ee688c718aa9812f217b
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/fillWithZeros.py
460
3.859375
4
def main(): msg = "This program will take a number and change last 2 digits to zero if is greater than 99." msg = msg + "\n Otherwise, the number will be returned without any particular change." print(msg) strAmount = input("Please type in your amout: ") if int(strAmount) > 99: print(f"New Number is: {strAmount[:-2]}00") else: print(f"The Number remained the same: {strAmount} ") if __name__ == "__main__": main()
d7762178460e77a2d4a468fccf7ab93a1c63ed1d
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/AR_TURTLE.py
528
3.6875
4
import turtle import random colours = { 0: 'green', 1: 'gold', 2: 'orange', 3: 'blue', 4: 'navy', 5: 'violet', 6: 'cyan', 7: 'yellow', 8: 'red', 9: 'light blue', } t = turtle.Turtle() s = turtle.Screen() s.bgcolor('black') t.pencolor('white') a = 0 b = 0 t.speed(0) t.penup() t.goto(0,200) t.pendown() while True: t.pencolor(random.choice(list(colours.values()))) t.forward(a) t.right(b) a+=3 b+=1 if b == 210: break t.hideturtle() turtle.done()
e4550b3253ee04830024ad04a076e48b92354ba0
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/roman_numerals_helper.py
1,883
3.515625
4
romans_dict = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900, "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def from_roman(roman_num): try: numeric_value = 0 roman_key = "" roman_double_key = "" for n in range(len(roman_num)): roman_key = romans_dict.get(roman_num[n]) roman_double_key = romans_dict.get(roman_num[n:n+2]) if(roman_double_key != None): print(f"Double: {n} => {roman_double_key} Glyph: {roman_num[n]}") numeric_value += roman_double_key n += 1 elif(roman_key != None): print(f"One: {roman_double_key} Glyph: {roman_num[n]}") numeric_value += roman_key n += 1 else: print("Entro al Else") pass print(f"Number for {roman_num} is : {numeric_value}") print("-"*45) except KeyError: pass def to_roman(num): numbers_dict = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1} roman_value = "" init_number = num while (num > 0): for k, val in numbers_dict.items(): if(val <= num): roman_value = roman_value + k num -= val break else: pass print(f"Number for {init_number} is : {roman_value}") from_roman('I') # 1 from_roman('III') # 3 from_roman('IV') # 4 from_roman('XXI') # 21 from_roman('MMVIII') # 2008 # from_roman('MMVII') # 2007 # from_roman('MDCLXIX') # 1669 # to_roman(1000) # M # to_roman(1990) # MCMXC # to_roman(4) # 'IV' # to_roman(1) # 'I' # to_roman(1991) # 'MCMXCI' # to_roman(2006) # 'MMVI' # to_roman(2020) # 'MMXX'
2c5248348bc7cfa59f6cac6887176bfe922f6b90
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/Working with text Files/textFiles.py
1,795
4.09375
4
# This function will generate a random string with a lenght based on user input number. # This can be useful for temporary passwords or even for some temporary login tokens. # The information is saved afterwards in a text file with the date and the username # of the person who requested the creation of the new password. # may you have questions of comments, reach out to me at alvison@gmail.com import random import time from datetime import date def main(): today = date.today() print("░░░░░░░░░░░░░░░░ Password Generator Tool ░░░░░░░░░░░░░░░") username = input("Enter user name: ") numCharacters = int(input("Insert the desired number of characters: ")) if numCharacters > 70: print ("The entered amount is too big, number has to be less than 70") else: baseString = list ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*+&^%$#!") strResult = "" generated_list = random.sample(baseString, numCharacters) for character in generated_list: strResult += character print("Generating new password, please hold...") time.sleep(1) print("The new password is: {} created by {} on {}".format(strResult, username,today.strftime("%b-%d-%Y"))) f=open("mypwdfile.txt", "a+") f.write("\nThe new password is: {} created by {} on {}".format(strResult, username,today.strftime("%b-%d-%Y"))) f.close() print("Passwords were successfully updated on the mypwdfile.txt as well.".format(username)) print("░░░░░░░░░░░░░░░░ Powered by Alvison Hunter ░░░░░░░░░░░░░░░") if __name__== "__main__": main()
1e8270231129139869e687fbab776af985abdacb
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/guess_random_num.py
871
4.34375
4
# ------------------------------------------------------------------------- # Basic operations with Python 3 | Python exercises | Beginner level # Generate a random number, request user to guess the number # Made with ❤️ in Python 3 by Alvison Hunter Arnuero - June 4th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # ------------------------------------------------------------------------- import random attempts = 0 rnd_num = random.randint(1, 10) player = input("Please Enter Your Name: ") while True: attempts += 1 num = int(input("Enter the number: \n")) print(f"Attempts: {attempts}") if (num == rnd_num): print( f"Well done {player}, you won! {rnd_num} was the correct number!") print( f" You got this in {attempts} Attempts.") break else: pass print("End of Game")
e3ae1adfb9306b0d81504716aab521373f427a42
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/liam_birthday_cake.py
657
3.5625
4
import turtle as t import math as m import random as r def drawX(a, i): angle = m.radians(i) return a * m.cos(angle) def drawY(b, i): angle = m.radians(i) return b * m.sin(angle) t.bgcolor("#d3dae8") t.setup(1000, 800) t.penup() t.goto(150, 0) t.pendown() t.pencolor("white") t.begin_fill() for i in range(360): x = drawX(150, i) y = drawY(60, i) t.goto(x, y) t.fillcolor("#fef5f7") t.end_fill() t.begin_fill() for i in range(180): x = drawX(150, -i) y = drawY(70, -i) t.goto(x, y) for i in range(180, 360): x = drawX(150, i) y = drawY(60, i) t.goto(x, y) t.fillcolor("#f2d7dd") t.end_fill()
5913c4bf968dd46bbf3f0552a61c1855264a4782
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/TURTLE PROJECTS/TURTLE EXAMPLES/multi_circles.py
462
3.5
4
import turtle import random colours = { 0: 'green', 1: 'gold', 2: 'orange', 3: 'blue', 4: 'navy', 5: 'violet', 6: 'cyan', 7: 'yellow', 8: 'red', 9: 'light blue', } # t = turtle.Turtle() #turtle.Screen().bgcolor("black") #t.pensize(2) # t.hideturtle() # turtle.tracer(2) # n = 0 # while True: # t.color(random.choice(list(colours.values()))) # t.circle(5 + n) # n += 2 # if n > 40: # break
9fa15e00d4b8b91a607277992f09681deed7b89c
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/strips_input.py
1,176
3.734375
4
# Made with ❤️ in Python 3 by Alvison Hunter - December 31st, 2020 def find_solution(string, markers): lst_rows = string.split("\n") for index_num, elem in enumerate(lst_rows): for marker in markers: ind = elem.find(marker) if (ind != -1): elem = elem[:ind] lst_rows[index_num] = elem.rstrip(' ') print("\n".join(lst_rows)) print('-'*65) return("\n".join(lst_rows)) find_solution("apples, pears\ngrapes\nbananas !", ["#", "!"]) find_solution( "apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # "apples, pears\ngrapes\nbananas" find_solution("a #b\nc\nd $e f g", ["#", "$"]) # "a\nc\nd" # 'avocados lemons avocados oranges strawberries\n\nwatermelons cherries avocados strawberries' find_solution('avocados lemons avocados oranges strawberries\n.\nwatermelons cherries avocados strawberries', [ '#', "'", '.', '!', ',', '^']) find_solution("! pears avocados oranges\nstrawberries cherries lemons lemons cherries watermelons\n' - oranges oranges\ncherries ! bananas bananas strawberries\noranges cherries cherries", ['-', "'", '!', '@', '^'])
2e515aa55f3994049bfa5e5da33753b927c54374
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/find_positive_neg_numbers.py
944
4.03125
4
# --------------------------------------------------------------------------------------------- # Get 10 numbers, find out if they are all positive, minor or equal to 99 & if 99 was typed. # Made with ❤️ in Python 3 by Alvison Hunter - May 17th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # --------------------------------------------------------------------------------------------- cardinals = [ "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", ] tmp_lst = [] print("Enter 10 positive numbers: \n") [tmp_lst.append(int(input(f"Enter {cardinals[i]} Number: "))) for i in range(10)] [ print(f"{el} is positive.") if (el >= 0) else print(f"{el} is negative.") for el in tmp_lst ] [ print("Positive number 99 was typed.") if (any(e == 99 for e in tmp_lst)) else print("Positive number 99 was NOT typed.") ]
5c92d100afaeff3c941bb94bd906213b11cbd0bd
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/tower_builder.py
644
4.3125
4
# Build Tower by the following given argument: # number of floors (integer and always greater than 0). # Tower block is represented as * | Python: return a list; # Made with ❤️ in Python 3 by Alvison Hunter - Friday, October 16th, 2020 def tower_builder(n_floor): lst_tower = [] pattern = '*' width = (n_floor * 2) - 1 for items in range(1, 2 * n_floor, 2): asterisks = items * pattern ln = asterisks.center(width) lst_tower.append(ln) print(lst_tower) return lst_tower #let's test it out! tower_builder(1)# ['*', ]) tower_builder(2)# [' * ', '***']) tower_builder(3)# [' * ', ' *** ', '*****'])
9030b8aa3ca6e00f598526efe02f28e3cc8c8fca
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/user_details_cls.py
2,565
4.28125
4
# -------------------------------------------------------------------------------- # Introduction to classes using a basic grading score for an student # Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- class UserDetails: user_details = { 'name':None, 'age': None, 'phone':None, 'post':None } # Constructor and Class Attributes def __init__(self): self.name = None self.age = None self.phone = None self.post = None # Regular Methods def display_divider(self, arg_char = "-", line_length=100): print(arg_char*line_length) def fill_user_details(self): self.user_details['name'] = self.name self.user_details['age'] = self.age self.user_details['phone'] = self.phone self.user_details['post'] = self.post # GETTER METHODS # a getter function, linked to parent level properties @property def name(self): print("getting the name") return self.__name # a getter to obtain all of the properties in a whole method def get_user_details(self): self.fill_user_details() self.display_divider() print(self.user_details) # SETTER METHODS # a setter function, linked to parent level properties @name.setter def name(self, name): self.__name = name # a setter to change all the properties in a whole method def set_user_details(self,name, age, phone, post): if(name==None or age==None or phone==None or post==None): print("There are missing or empty parameters on this method.") else: self.name = name self.age = age self.phone = phone self.post = post self.display_divider() print(f"We've successfully register the user details for {self.name}.") # Let us create the instances now new_user_01 = UserDetails() new_user_01.set_user_details('Alvison Hunter',40,'8863-8751','The Life of a Web Developer') new_user_01.get_user_details() # Using the setter to update one property from parent, in this case the name new_user_01.name = "Lucas Arnuero" new_user_01.get_user_details() # Another instance only working with the entire set of properties new_user_02 = UserDetails() new_user_02.set_user_details('Onice Acevedo',29,'8800-0088','Working From Home Stories') new_user_02.get_user_details()
57214b69ac361ea4a28d62f1d9da29879a895215
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/bike_rental_payment.py
1,728
3.796875
4
# -------------------------------------------------------------------------------- # Bike rentals. 100 mins = 7xmin, 101 > 1440 = 50 x min, 1440 > 96000 # Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- def bike_rental_payment(): REGULAR_RATE = 7 OVERTIME_RATE = 50 regular_charge = 0 overtime_charge = 0 exceeding_charge = 0 total = 0 while True: # Error handling try...except init block try: usage_time = int(input("Please enter total amount of rented minutes: \n")) if(usage_time<=0): print("Invalid amount of rented minutes. Please try again.") continue if(usage_time <= 100): regular_charge = usage_time * REGULAR_RATE elif(usage_time>100 and usage_time <= 1440): regular_charge = 100 * REGULAR_RATE overtime_charge = (usage_time - 100) * OVERTIME_RATE else: regular_charge = 100 * REGULAR_RATE overtime_charge = 1300 * OVERTIME_RATE exceeding_charge = 0 if usage_time < 1440 else 96000 # Error handling exceptions except ValueError: print ("ValueError: This value should be a number.") continue except: print("Uh oh! Something went really wrong!. Please try again.") quit else: total = regular_charge + overtime_charge + exceeding_charge print(f"Invoice Total: U${total}.") break bike_rental_payment()
f229b5e567fb0243c3c8b32acc730c11dfcf3856
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/TURTLE PROJECTS/TURTLE EXAMPLES/spirograph_sphere.py
694
3.640625
4
# --------------------------------------------------------------------------- # Let's built a multi-colored lines Spirograph using python and turtle module # Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2022 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # --------------------------------------------------------------------------- import turtle as tt tt.setup(800,800) tt.pensize(2) tt.speed(0) wn = tt.Screen() wn.title("Build a SpiroGraph!") wn.bgcolor("black") for i in range(12): for c in ['red','magenta','blue','cyan','green','white','yellow']: tt.color(c) tt.circle(120) tt.left(15) tt.hideturtle() wn.mainloop()
ea028ebf1fdb4f74028315e52ebf4e8658ceb927
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/people_in_your_life.py
655
4.4375
4
# -------------------------------------------------------------------------------- # Introduction to classes using a basic grading score for an student # Made with ❤️ in Python 3 by Alvison Hunter - March 6th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- people_dict = {12:"Critican", 10:"Chismosos", 6:"Creen En Ti", 3:"Te Motivan", 1:"Ayudan"} def display_people_in_your_life(): print("Asi Son Las Personas En Tu Vida:") for key, value in people_dict.items(): print(f"Los que {value}: {'‍🏃'*key}") display_people_in_your_life()
2b586de4cf57c5cea9060af113a9d97d047952b4
Ziles131/PyCourseStepik
/1.6_inheritance_class_3.py
321
3.625
4
import time class Loggable: def log(self, msg): print(str(time.ctime()) + ": " + str(msg)) class LoggableList(list, Loggable): def append(self, v): super(LoggableList, self).append(v) super(LoggableList, self).log(v) l = LoggableList() print(l) l.append(17) l.append(1) l.append(89) l.append(9) l.append(35)
e917dbbac09b04a21d97e7a322597eac8e86fa41
Ziles131/PyCourseStepik
/Standard_Language_Facilities_2/Errors_and_exceptions_2.3.py
214
3.53125
4
class NonPositiveError(Exception): pass class PositiveList(list): def append(self, x): if int(x) > 0: y = super(PositiveList, self).append(x) return y else: raise NonPositiveError("incorrect number")
13739cc96abe84a26a355655e16e5e4885bbbb33
leofeen/Translator_Web
/translator/translator_web/translate.py
16,771
3.96875
4
def translate(input_data: str, language: str): """ Keywords are case insensitive. Commands are case sensitive. """ output_data = '' language_reference = get_language_reference(language) # Every programm should have main block: # starts with 'begin' token, # ends with 'end' token - checking on it if not (input_data.upper().find(language_reference['begin']) != -1 and input_data.upper().find(language_reference['end']) != -1): raise SyntaxError('Expected main block of program') input_data = input_data.split('\n') # Count number og lines for tracebacks line_count = 0 # Parse all enters to one string in output input_string = '' first_input = True while input_data[0].upper().find(language_reference['begin']) == -1: line_count += 1 input_string_line = input_data[0] input_string_line = input_string_line.strip().strip('\t') if input_string_line != '': if not input_string_line.upper().startswith(language_reference['enter']): raise SyntaxError(f'Unexpected keyword at line {line_count}: {input_string_line}') enter_keyword, string_element, number_of_repetition = input_string_line.split() if first_input: first_input = False else: input_string += ' + ' if int(number_of_repetition) > 1: input_string += f'\'{string_element}\'*{number_of_repetition}' elif int(number_of_repetition) == 1: input_string += f'\'{string_element}\'' # Do not write 'a'*1 else: raise SyntaxError(f'Type Error at line {line_count}: expected positive number of string element repetition, but {number_of_repetition} was given') del input_data[0] if input_string != '': output_data += f'string = {input_string}\n' output_data += '\n' # Every programm should have main block: # starts with 'begin' token, # ends with 'end' token - this is at least 2 lines if len(input_data) < 2: raise SyntaxError(f'Unexpected pseudocode structure after line {line_count}') # Parse main block of pseudocode programm number_of_spaces = 0 in_while = 0 in_if = 0 # Trying to output good-looking code, # so excluding two or more blank line in a row previous_line_is_blank = False while input_data[0].upper().strip().strip('\t') != language_reference['end']: line_count += 1 # Preformating line to handle parsing more easily line = input_data[0] line = line.strip().strip('\t') while line.find(language_reference['find'] + ' ') != -1 or line.find(language_reference['replace'] + ' ') != -1: line = line.replace(language_reference['find'] + ' ', language_reference['find']) line = line.replace(language_reference['replace'] + ' ', language_reference['replace']) while line.find('( ') != -1 or line.find(' )') != -1: line = line.replace('( ', '(') line = line.replace(' )', ')') if line.upper() == language_reference['begin']: pass elif line.startswith('//'): output_data += ' '*number_of_spaces + '#' + line[2:] + '\n' elif line.upper() == language_reference['end_while']: number_of_spaces -= 4 if not in_while: raise SyntaxError(f'Unexpected end of while block at line {line_count}') in_while -= 1 if not previous_line_is_blank: output_data += '\n' previous_line_is_blank = True elif line.upper() == language_reference['end_if']: number_of_spaces -= 4 if not in_if: raise SyntaxError(f'Unexpected end of if block at line {line_count}') in_if -= 1 if not previous_line_is_blank : output_data += '\n' previous_line_is_blank = True elif line.upper().startswith(language_reference['while']): previous_line_is_blank = False in_while += 1 output_data += ' '*number_of_spaces + 'while' number_of_spaces += 4 conditions = line[len(language_reference['while']):].split() for condition in conditions: if not (condition.startswith(language_reference['find']) or condition.upper() == language_reference['or'] or condition.upper() == language_reference['and'] or condition.upper() == language_reference['not']): raise SyntaxError(f'Unexpected keyword at line {line_count}: {condition}') if condition.upper() == language_reference['or']: output_data += ' or' elif condition.upper() == language_reference['and']: output_data += ' and' elif condition.upper() == language_reference['not']: output_data += ' not' else: arg = condition[len(language_reference['find'])+1:-1] output_data += f' string.find(\'{arg}\') != -1' output_data += ':\n' elif line.upper().startswith(language_reference['if']): previous_line_is_blank = False in_if += 1 output_data += ' '*number_of_spaces + 'if' number_of_spaces += 4 conditions = line[len(language_reference['if']):].split() for condition in conditions: if not (condition.startswith(language_reference['find']) or condition.upper() == language_reference['or'] or condition.upper() == language_reference['and'] or condition.upper() == language_reference['not']): raise SyntaxError(f'Unexpected keyword at line {line_count}: {condition}') if condition.upper() == language_reference['or']: output_data += ' or' elif condition.upper() == language_reference['and']: output_data += ' and' elif condition.upper() == language_reference['not']: output_data += ' not' else: arg = condition[len(language_reference['find'])+1:-1] output_data += f' string.find(\'{arg}\') != -1' output_data += ':\n' elif line.upper().startswith(language_reference['then']): previous_line_is_blank = False command = line[len(language_reference['then'])+1:] if command != '': if not command.startswith(language_reference['replace']): raise SyntaxError(f'Unexpected command at line {line_count}: {command}') args = command[len(language_reference['replace'])+1:-1].split(',') if len(args) != 2: raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given') output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n' elif line.upper().startswith(language_reference['else']): previous_line_is_blank = False output_data += ' '*(number_of_spaces-4) + 'else:\n' command = line[len(language_reference['else'])+1:] if command != '': if not command.startswith(language_reference['replace']): raise SyntaxError(f'Unexpected command at line {line_count}: {command}') args = command[len(language_reference['replace'])+1:-1].split(',') if len(args) != 2: raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given') output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n' elif line.startswith(language_reference['replace']): previous_line_is_blank = False args = line[len(language_reference['replace'])+1:-1].split(',') if len(args) != 2: raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given') output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n' elif line.upper() == language_reference['str_out']: previous_line_is_blank = False output_data += ' '*number_of_spaces + 'print(string)\n' elif line.upper() == language_reference['len_out']: previous_line_is_blank = False output_data += ' '*number_of_spaces + 'print(len(string))\n' elif line.upper() == language_reference['sum_out']: previous_line_is_blank = False output_data += ' '*number_of_spaces + 'summ = 0\n' output_data += ' '*number_of_spaces + 'for element in string:\n' output_data += ' '*(number_of_spaces + 4) + 'if element.isnumeric(): summ += int(element)\n' output_data += ' '*number_of_spaces + 'print(summ)\n' else: raise SyntaxError(f'Unexpected keyword at line {line_count}: {line}') del input_data[0] # Every 'if' or 'while' token should have closing 'end_if' and # 'end_while' tokens respectfully if in_if: raise SyntaxError('Expected end of if block, but got EOF') # End-Of-File if in_while: raise SyntaxError('Expected end of while block, but got EOF') # End-Of-File return output_data def get_language_reference(language: str): # Languge reference keywords must be in upper case if language == 'ru': language_reference = { 'begin': 'НАЧАЛО', 'enter': 'ВВОД', 'end': 'КОНЕЦ', 'find': 'нашлось', 'replace': 'заменить', 'end_while': 'КОНЕЦ ПОКА', 'end_if': 'КОНЕЦ ЕСЛИ', 'if': 'ЕСЛИ', 'while': 'ПОКА', 'or': 'ИЛИ', 'and': 'И', 'not': 'НЕ', 'then': 'ТО', 'else': 'ИНАЧЕ', 'str_out': 'ВЫВОД СТРОКИ', 'len_out': 'ВЫВОД ДЛИНЫ', 'sum_out': 'ВЫВОД СУММЫ', } elif language == 'en': language_reference = { 'begin': 'BEGIN', 'enter': 'ENTER', 'end': 'END', 'find': 'find', 'replace': 'replace', 'end_while': 'END WHILE', 'end_if': 'END IF', 'if': 'IF', 'while': 'WHILE', 'or': 'OR', 'and': 'AND', 'not': 'NOT', 'then': 'THEN', 'else': 'ELSE', 'str_out': 'OUTPUT STRING', 'len_out': 'OUTPUT LENGTH', 'sum_out': 'OUTPUT SUM', } else: raise ValueError(f'Unsopported language: {language}') return language_reference def get_language_description(language: str): if language == 'ru': language_description = { 'НАЧАЛО ... КОНЕЦ': 'Операторные скобки для основного блока программы.', 'ВВОД str number': 'Добавляет <code class="code-snippet">number</code> раз к строке для обработки подстроку <code class="code-snippet">str</code>. Может идти только перед <code class="code-snippet">НАЧАЛО</code>.', 'нашлось(str)': 'Проверяет наличие подстроки <code class="code-snippet">str</code> в строке для обработки. Возвращает True, если подстрока найдена. Иначе возвращает False.', 'заменить(old, new)': 'Заменяет первую слева подстроку <code class="code-snippet">old</code> на подстроку new в строке для обработки. Если подстрока old отсутствует, то команда не выполняется.', 'ПОКА condition ... КОНЕЦ ПОКА': 'Объявление блока цикла Пока. Выполняются строки внутри блока, пока <code class="code-snippet">condition</code> возвращает True.', 'ЕСЛИ condition ТО ... ИНАЧЕ ... КОНЕЦ ЕСЛИ': 'Объявление блока Если/То/Иначе. Если <code class="code-snippet">condition</code> возвращает True, то выполняются строка с <code class="code-snippet">ТО</code> или строки между <code class="code-snippet">ТО</code> и <code class="code-snippet">ИНАЧЕ</code>/<code class="code-snippet">КОНЕЦ ЕСЛИ</code>, иначе выполняется строка с <code class="code-snippet">ИНАЧЕ</code> или строки между <code class="code-snippet">ИНАЧЕ</code> и <code class="code-snippet">КОНЕЦ ЕСЛИ</code>, если такие присутствуют.', 'ВЫВОД СТРОКИ': 'Печатает строку для обработки в текущем состоянии.', 'ВЫВОД ДЛИНЫ': 'Печатает длину строки для обработки в текущем состоянии.', 'ВЫВОД СУММЫ': 'Печатет сумму всех цифр в строке для обработки в текущем состоянии.', '// ...': 'Строка, начинающаяся с <code class="code-snippet">//</code>, является комментарием, не влияющим на исполнение кода.', 'И, ИЛИ, НЕ': 'Логические операторы, использующиеся в <code class="code-snippet">condition</code> в <code class="code-snippet">ЕСЛИ</code> и <code class="code-snippet">ПОКА</code> между несколькими <code class="code-snippet">нашлось()</code>.', } elif language == 'en': language_description = { 'BEGIN ... END': 'Declaration of main block of the program.', 'ENTER str number': 'Appends substring <code class="code-snippet">str</code> to input string <code class="code-snippet">number</code> times. This must go before <code class="code-snippet">BEGIN</code> statement.', 'find(str)': 'Check if substing <code class="code-snippet">str</code> is a part of input string. Returns True if <code class="code-snippet">str</code> was found. Returns False otherwise.', 'replace(old, new)': 'Replace first from the left substring <code class="code-snippet">old</code> by substring <code class="code-snippet">new</code> in input string. If there is no inclusion of substring <code class="code-snippet">old</code> in input string, than nothing happens.', 'WHILE condition ... END WHILE': 'Declaration of While block. Lines inside block will be executed, while <code class="code-snippet">condition</code> returns True.', 'IF condition THEN ... ELSE ... END IF': 'Declaration of If/Then/Else block. If <code class="code-snippet">condition</code> returns True, then line with <code class="code-snippet">THEN</code> or lines between <code class="code-snippet">THEN</code> and <code class="code-snippet">ELSE</code>/<code class="code-snippet">END IF</code> will be executed, else line with <code class="code-snippet">ELSE</code> or lines between <code class="code-snippet">ELSE</code> and <code class="code-snippet">END IF</code> will be executed, if there is one.', 'OUTPUT STRING': 'Print input string in current state of processing.', 'OUTPUT LENGTH': 'Print length input string in current state of processing.', 'OUTPUT SUM': 'Print sum of all digits in input string in current state of processing.', '// ...': 'Line that starts with <code class="code-snippet">//</code>, considered a сomment and does not affect program execution.', 'AND, OR, NOT': 'Logic operands that used in <code class="code-snippet">condition</code> inside <code class="code-snippet">IF</code> and <code class="code-snippet">WHILE</code> statements between several <code class="code-snippet">find()</code>.', } else: raise ValueError(f'Unsopported language: {language}') return language_description
805e604bebdab27987ca0939a06dee8475e9bd82
yellowsimulator/data-centric-software-application
/examples/3 - data-storage/database_operations.py
1,873
3.8125
4
""" Implemets databases operations such as - creates database - creates table - inssert rows into a table - drop a table Uses local host by default. """ import psycopg2 as psg from sql_queries import create_table_queries from sql_queries import drop_table_queries def connect_to_database(): """Creates a connection. """ conn = psg.connect(host='127.0.0.1', dbname='music_library', \ user='postgres', password='admin') cursor = conn.cursor() return cursor, conn def create_database(database_name: str, username: str, password: str): """Creates a database Args: database_name: the target database name. username: the username password: the password """ conn = psg.connect(host='127.0.0.1', user='postgres', password='admin') cursor = conn.cursor() conn.set_session(autocommit=True) cursor.execute(f'DROP DATABASE IF EXISTS {database_name}') cursor.execute(f'CREATE DATABASE {database_name} WITH ENCODING "utf8" TEMPLATE template0') conn.close() def create_table(conn, cursor): for query in create_table_queries: cursor.execute(query) conn.commit() conn.close() def drop_tables(conn, cursor): for query in drop_table_queries: cursor.execute(query) conn.commit() conn.close() # def run_task(task='create_tables'): # """[summary] # Args: # task (str, optional): [description]. Defaults to 'create_tables'. # """ # cursor, conn = connect_to_database() # tasks = {'create_tables': create_table(conn, cursor), \ # 'drop_tables': drop_tables(conn, cursor)} # tasks[task] if __name__ == '__main__': database_name = 'music_library' username = 'postgres' password = 'admin' #create_database(database_name, username, password) create_table()
9edc52e38c8638524b6d9174eefa07228892ec13
Irziii-Hasan/ttd
/MainMenu.py
3,738
3.984375
4
""" Game rules: -The goal of blackjack is to beat the dealer's hand without going over 21. -Face cards are worth 10. Aces are worth 1 or 11, whichever makes a better hand. -Each player starts with two cards, one of the dealer's cards is hidden until the end. -To 'Hit' is to ask for another card. To 'Stand' is to hold your total and end your turn. -If you go over 21 you bust, and the dealer wins regardless of the dealer's hand. -If you are dealt 21 from the start (Ace & 10), you got a blackjack. -Dealer will hit until his/her cards total 17 or higher. Instructions: When the program starts running, it opens a main menu window with 2 buttons. One can close the window and exit the program and the other button let's start the game itself. The Play button opens a new window where the game works. the game is started by pressing the large image / button in the window, which above reads DEAL. The player and dealer are then dealt the first cards. The player has both cards visible and the dealer again, the first card appears normally and the second shows only the back. The program also has a function where the back of the card changes each time you play. Even when the program is running. When the player and the dealer have The cards dealt to the player have two options Hit or Stand. When you press Hit- option the player gets a new card. The hit button can be pressed as long as player score <= 21 but it doesn't always make sense to ask for a new one cards but keep the current hand. This function can be performed by pressing Stand button. Once the player has pressed the stand button, the dealer begins turn. As the rules read the dealer must hit whenever his the value of his hand is <= 16 and must be fixed when it is> 16. If neither is "busted" i.e. the value of the hand has exceeded 21 so we see the dealer's turn after which one has won. The winner can also be seen in special situations in the past, for example, if either has "blackjack" or cards the value is 21 when 2 cards are dealt to both. When the program is announced the winner can the player press the "new game" button that appears on the screen to start a new game. """ from tkinter import * from Game import Blackjack class Mainmenu: # the main menu window is created in init def __init__(self): self.__mainmenu = Tk() imagename1 = "images/Menu.png" self.__canvas = Canvas(self.__mainmenu, width=1230, height=762) self.__canvas.pack() img1 = PhotoImage(file=imagename1) self.__canvas.background = img1 self.__canvas.create_image(0, 0, anchor=NW, image=img1) self.__img2 = PhotoImage(file="images/Play.png") self.__img3 = PhotoImage(file="images/Quit.png") self.__playbutton = Button( self.__canvas, justify=LEFT, command=self.play ) self.__playbutton.config(image=self.__img2) self.__playbutton.place(x=420, y=480) self.__quitbutton = Button( self.__canvas, command=self.quit, justify=LEFT ) self.__quitbutton.config(image=self.__img3) self.__quitbutton.place(x=420, y=620) def play(self): """ Destroys the main menu window and opens the game window :return: """ self.__mainmenu.destroy() Blackjack(Tk()).start() def quit(self): """ Destroys the main menu window :return: """ self.__mainmenu.destroy() def start(self): """ Open the main menu window :return: """ self.__mainmenu.mainloop() def main(): Mainmenu().start() if __name__ == "__main__": main()
8d518deff2e20738be27d935dde0a2f63021c251
gonium/statsintro
/Code3/pythonFunction.py
817
3.84375
4
'''Demonstration of a Python Function author: thomas haslwanter, date: May-2015 ''' import numpy as np def incomeAndExpenses(data): '''Find the sum of the positive numbers, and the sum of the negative ones.''' income = np.sum(data[data>0]) expenses = np.sum(data[data<0]) return (income, expenses) if __name__=='__main__': testData = np.array([-5, 12, 3, -6, -4, 8]) # If only real banks would be so nice ;) if testData[0] < 0: print('Your first transaction was a loss, and will be dropped.') testData = np.delete(testData, 0) else: print('Congratulations: Your first transaction was a gain!') (myIncome, myExpenses) = incomeAndExpenses(testData) print('You have earned {0:5.2f} EUR, and spent {1:5.2f} EUR.'.format(myIncome, -myExpenses))
f2bc3ca82085bcc512b5a69c878c1c5159371267
pyotel/tensorflow_example
/Day_02_02_slicing.py
522
3.71875
4
# Day_02_02_slicing.py a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] print(a[0], a[-1]) print(a[3:7]) # 시작, 종료 print(a[0:len(a)//2]) print(a[len(a)//2:len(a)]) print(a[:len(a)//2]) print(a[len(a)//2:]) # 문제 # 짝수 번째만 출력해 보세요. # 홀수 번째만 출력해 보세요. # 거꾸로 출력해 보세요. print(a[::]) print(a[::2]) print(a[1::2]) print(a[3:4]) print(a[3:3]) print(a[len(a)-1:0:-1]) print(a[-1:0:-1]) print(a[-1:-1:-1]) print(a[-1::-1]) print(a[::-1])
f476ccc1026447d2f41ca07d5c5e6de5468018c6
jonathf/adventofcode
/2019/06/run.py
7,045
4.21875
4
""" --- Day 6: Universal Orbit Map --- You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the local orbits (your puzzle input). Except for the universal Center of Mass (COM), every object in space is in orbit around exactly one other object. An orbit looks roughly like this: \ \ | | AAA--> o o <--BBB | | / / In this diagram, the object BBB is in orbit around AAA. The path that BBB takes around AAA (drawn with lines) is only partly shown. In the map data, this orbital relationship is written AAA)BBB, which means "BBB is in orbit around AAA". Before you use your map data to plot a course, you need to make sure it wasn't corrupted during the download. To verify maps, the Universal Orbit Map facility uses orbit count checksums - the total number of direct orbits (like the one shown above) and indirect orbits. Whenever A orbits B and B orbits C, then A indirectly orbits C. This chain can be any number of objects long: if A orbits B, B orbits C, and C orbits D, then A indirectly orbits D. For example, suppose you have the following map: COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L Visually, the above map of orbits looks like this: G - H J - K - L / / COM - B - C - D - E - F \ I In this visual representation, when two objects are connected by a line, the one on the right directly orbits the one on the left. Here, we can count the total number of orbits as follows: - D directly orbits C and indirectly orbits B and COM, a total of 3 orbits. - L directly orbits K and indirectly orbits J, E, D, C, B, and COM, a total of 7 orbits. - COM orbits nothing. The total number of direct and indirect orbits in this example is 42. What is the total number of direct and indirect orbits in your map data? --- Part Two --- Now, you just need to figure out how many orbital transfers you (YOU) need to take to get to Santa (SAN). You start at the object YOU are orbiting; your destination is the object SAN is orbiting. An orbital transfer lets you move from any object to an object orbiting or orbited by that object. For example, suppose you have the following map: COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN Visually, the above map of orbits looks like this: YOU / G - H J - K - L / / COM - B - C - D - E - F \ I - SAN In this example, YOU are in orbit around K, and SAN is in orbit around I. To move from K to I, a minimum of 4 orbital transfers are required: - K to J - J to E - E to D - D to I Afterward, the map of orbits looks like this: G - H J - K - L / / COM - B - C - D - E - F \ I - SAN \ YOU What is the minimum number of orbital transfers required to move from the object YOU are orbiting to the object SAN is orbiting? (Between the objects they are orbiting - not between YOU and SAN.) """ from typing import Dict, List, Tuple from collections import defaultdict def count_orbits( name: str, graph: Dict[str, List[str]], parent_count: int = 0, ) -> int: """ Recursively count the number of direct and indirect orbits. Simple sum of itself and sum of its children, where each child is worth one more than the parent. Args: name: Name of the current item. graph: A one-to-many directed graph where keys are name of parents, and values are names of all its children. parent_count: The number of direct and indirect orbits to current item. Returns: The sum of all direct and indirect orbits for all (connected) items in `graph`. Examples: >>> graph = {"COM": ["B"], "B": ["C", "G"], "G": ["H"], "H": [], ... "C": ["D"], "D": ["E", "I"], "I": ["SAN"], "SAN": [], ... "E": ["F", "J"], "F": [], "J": ["K"], ... "K": ["L", "YOU"], "L": [], "YOU": []} >>> count_orbits("COM", graph=graph) 54 >>> count_orbits("E", graph=graph) 10 >>> count_orbits("I", graph=graph) 1 """ return sum(count_orbits(child, graph, parent_count+1) for child in graph[name]) + parent_count def find_santa(name: str, graph: Dict[str, List[str]]) -> Tuple[str, int]: """ Recursively locate items "YOU" and "SAN" and sum up the number of transfers needed between them. Args: name: Name of the current item. graph: A one-to-many directed graph where keys are name of parents, and values are names of all its children. Returns: status: String representing what has been found. Either "" (nothing is found), "SAN" (Santa is found), "YOU" (you are found), or "SANYOU" (both you and Santa are found). count: If both Santa and you are found, then return the number of orbital transfers needed to get you and santa in the same orbit. If only one of them are found, return the number of orbital transfers back to start. Else return 0. Examples: >>> graph = {"COM": ["B"], "B": ["C", "G"], "G": ["H"], "H": [], ... "C": ["D"], "D": ["E", "I"], "I": ["SAN"], "SAN": [], ... "E": ["F", "J"], "F": [], "J": ["K"], "K": ["L", "YOU"], ... "L": [], "YOU": []} >>> find_santa("COM", graph) ('SANYOU', 4) >>> find_santa("E", graph) ('YOU', 3) >>> find_santa("I", graph) ('SAN', 1) >>> find_santa("G", graph) ('', 0) """ # Leaf handle if not graph[name]: # only consider YOU and SAN status = name if name in ("SAN", "YOU") else "" return status, 0 # gather results from children statuses, counts = zip(*[ find_santa(child, graph) for child in graph[name]]) status = "".join(sorted(statuses)) # add to count only if SAN or YOU is found, but not both count = sum(counts) + (status in ("SAN", "YOU")) return status, count if __name__ == "__main__": GRAPH = defaultdict(list) with open("input") as src: for line in src.read().strip().split(): center, periphery = line.split(")") graph[center].append(periphery) print("solution part 1:", count_orbits("COM", GRAPH)) # solution part 1: 117672 print("solution part 2:", find_santa("COM", GRAPH)[1]) # solution part 2: 277
cf31bb2cfe70b1bb00ba4045a1482ac568f76fa5
jonathf/adventofcode
/2019/04/run.py
3,597
4.125
4
""" --- Day 4: Secure Container --- You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out. However, they do remember a few key facts about the password: * It is a six-digit number. * The value is within the range given in your puzzle input. * Two adjacent digits are the same (like 22 in 122345). * Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). Other than the range rule, the following are true: * 111111 meets these criteria (double 11, never decreases). * 223450 does not meet these criteria (decreasing pair of digits 50). * 123789 does not meet these criteria (no double). How many different passwords within the range given in your puzzle input meet these criteria? --- Part Two --- An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. Given this additional criterion, but still ignoring the range rule, the following are now true: * 112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long. * 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444). * 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22). How many different passwords within the range given in your puzzle input meet all of the criteria? Your puzzle input is 357253-892942. """ from typing import Iterator def increasing_numbers(start: int, stop: int) -> Iterator[str]: """ Iterate all numbers in a range that is increasing in digits. Args: start: The first number to check in range. stop: The last number (inclusive) to check. Yields: Numbers with increasing digits, represented as strings. Examples: >>> list(increasing_numbers(60, 80)) ['66', '67', '68', '69', '77', '78', '79'] >>> list(increasing_numbers(895, 999)) ['899', '999'] """ for number in range(start, stop+1): number = str(number) consecutives = zip(number[:-1], number[1:]) if all(int(digit1) <= int(digit2) for digit1, digit2 in consecutives): yield number def part1(start: int, stop: int) -> int: """Do part 1 of the assignment.""" count = 0 for number in increasing_numbers(start, stop): consecutives = zip(number[:-1], number[1:]) count += any(digit1 == digit2 for digit1, digit2 in consecutives) return count def part2(start: int, stop: int) -> int: """Do part 2 of the assignment.""" count = 0 for number in increasing_numbers(start, stop): consecutive_digits = zip(number[:-1], number[1:]) matches = [digit1 == digit2 for digit1, digit2 in consecutive_digits] # Pad values to allow for consecutive numbers at the beginning and end of number. matches = [False] + matches + [False] consecutive_matches = zip(matches[:-2], matches[1:-1], matches[2:]) # A match surrounded by non-matches. count += any(triplet == (False, True, False) for triplet in consecutive_matches) return count if __name__ == "__main__": START = 357253 STOP = 892942 print("solution part 1:", part1(START, STOP)) # solution part 1: 530 print("solution part 2:", part2(START, STOP)) # solution part 2: 324
9a79519d12b3d7dbdbb68c14cc8f764b40db1511
ChristianECG/30-Days-of-Code_HackerRank
/09.py
1,451
4.40625
4
# ||-------------------------------------------------------|| # ||----------------- Day 9: Recursion 3 ------------------|| # ||-------------------------------------------------------|| # Objective # Today, we're learning and practicing an algorithmic concept # called Recursion. Check out the Tutorial tab for learning # materials and an instructional video! # Recursive Method for Calculating Factorial # / 1 N ≤ 1 # factorial(N) | # \ N x factorial( N - 1 ) otherwise # Task # Write a factorial function that takes a positive integer, N # as a parameter and prints the result of N! (N factorial). # Note: If you fail to use recursion or fail to name your # recursive function factorial or Factorial, you will get a # score of 0. # Input Format # A single integer, N (the argument to pass to factorial). # Constraints # 2 ≤ N ≤ 12 # Your submission must contain a recursive function named # factorial. # Output Format # Print a single integer denoting N!. # -------------------------------------------------------------- import math import os import random import re import sys # Complete the factorial function below. def factorial(n): if (n == 1 or n == 0): return 1 else: return n * factorial(n-1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = factorial(n) fptr.write(str(result) + '\n') fptr.close()
7405e9613731ccfdc5da27bf26cf12059e8b4899
ChristianECG/30-Days-of-Code_HackerRank
/11.py
1,745
4.28125
4
# ||-------------------------------------------------------|| # ||---------------- Day 11: 2D Arrays --------------------|| # ||-------------------------------------------------------|| # Objective # Today, we're building on our knowledge of Arrays by adding # another dimension. Check out the Tutorial tab for learning # materials and an instructional video! # Context # Given a 6 x 6 2D Array, A: # 1 1 1 0 0 0 # 0 1 0 0 0 0 # 1 1 1 0 0 0 # 0 0 0 0 0 0 # 0 0 0 0 0 0 # 0 0 0 0 0 0 # We define an hourglass in A to be a subset of values with # indices falling in this pattern in A's graphical # representation: # a b c # d # e f g # There are 16 hourglasses in A, and an hourglass sum is the # sum of an hourglass' values. # Task # Calculate the hourglass sum for every hourglass in A, then # print the maximum hourglass sum. # Input Format # There are 6 lines of input, where each line contains 6 # space-separated integers describing 2D Array A; every value # in will be in the inclusive range of to -9 to 9. # Constraints # -9 ≤ A[i][j] ≤ 9 # 0 ≤ i,j ≤ 5 # Output Format # Print the largest(maximum) hourglass sum found in A. # ------------------------------------------------------------- import math import os import random import re import sys if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) max_reloj_sum = -math.inf for i in range(4): for j in range(4): reloj_sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] reloj_sum += arr[i+1][j+1] reloj_sum += arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] max_reloj_sum = max(max_reloj_sum, reloj_sum) print(max_reloj_sum)
1723f2e6d0885e6abc7dadf890fef8fd63062ae4
William-McKee/udacity-data-analyst
/Enron_Fraud_POI_Identifier/explore_dataset.py
3,896
3.703125
4
""" Explore basic information about the data set """ import numpy as np def explore_basics(dataset): '''Print basic statistics about dataset''' print("Data Set Basics") print("Number of employees/vendors? ", len(dataset)) print("Number of persons of interest (POIs)? ", get_feature_valid_points_count(dataset, 'poi', 0)) print("How many features?", get_feature_count(dataset)) def get_feature_count(dataset): '''How many features?''' dataset_keys = dataset.keys() #dataset_values = dataset.values() any_key = next(iter(dataset_keys)) return len(dataset[any_key]) def get_feature_valid_points_count(dataset, feature, bad_value): ''' How many points in data set? dataset: dictionary containing list of people, where each person is represented by dictionary feature: feature for which to find valid data points bad_value: for valid point, feature != this value ''' count=0 dataset_keys = dataset.keys() for item in dataset_keys: if dataset[item][feature] != bad_value: count += 1 return count def get_bad_value(feature): '''Return bad value for feature''' if feature == 'poi': return 0 else: return 'NaN' def explore_features(dataset): '''Get and print count of all features of dataset''' # Get the list of features dataset_keys = dataset.keys() any_key = next(iter(dataset_keys)) features = dataset[any_key].keys() # Loop through features for feature in features: bad_value = get_bad_value(feature) count = get_feature_valid_points_count(dataset, feature, bad_value) print(str(feature) + ": " + str(count)) def explore_metrics(dataset): '''Get and print metrics of all features of dataset''' # Get the list of features dataset_keys = dataset.keys() any_key = next(iter(dataset_keys)) features = dataset[any_key].keys() # Loop through features for feature in features: feature_list = [] bad_value = get_bad_value(feature) for item in dataset: if dataset[item][feature] != bad_value: feature_list.append(dataset[item][feature]) np_feature = np.array(feature_list) if (feature != 'email_address' and np_feature.size > 0): print(feature + ": " + str(np_feature.size) + " / " + str(np_feature.min()) + " / " + str(np_feature.mean()) + " / " + str(np_feature.max())) else: print(feature + ": 0 / 0.000 / 0.000 / 0.000") def dataset_basics(dataset): '''Explore top level information about the dataset, including POI and non-POI''' # Print dataset information print("\n") explore_basics(dataset) print("\n") print("How many known values for each feature?") explore_features(dataset) # Split data set into POI and non-POI poi_dataset = {} nonpoi_dataset = {} for item in dataset: if dataset[item]['poi'] == 1: poi_dataset[item] = dataset[item] else: nonpoi_dataset[item] = dataset[item] print("\n") print("How many known values for each feature for POIs?") explore_features(poi_dataset) print("\n") print("How many known values for each feature for non-POIs?") explore_features(nonpoi_dataset) print("\n") print("### METRICS ###") print("Field: Min / Mean / Max") explore_metrics(dataset) print("\n") print("### POI METRICS ###") print("Field: Min / Mean / Max") explore_metrics(poi_dataset) print("\n") print("### NON-POI METRICS ###") print("Field: Min / Mean / Max") explore_metrics(nonpoi_dataset) print("\n")
7af39c66eba7f0299a47f3674f199233923b4ba9
abasired/Data_struct_algos
/DSA_Project_2/file_recursion_problem2.py
1,545
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 28 19:21:50 2020 @author: ashishbasireddy """ import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ file_name = os.listdir(path) path_list = [] for name in file_name: if os.path.isdir(os.path.join(path, name)): temp_list = find_files(suffix ,os.path.join(path, name)) path_list = path_list + temp_list elif os.path.isfile(os.path.join(path, name)): if suffix in name: path_list.append(os.path.join(path, name)) return path_list #use appropiate path while verifying this code. This path is local path path = os.environ['HOME'] + "/testdir" #recursion based search #print(find_files(".c", path)) # search for .c files #print(find_files(".py", path)) # search for .py files print(find_files(".h", path)) # search for .h files #loops to implement a simialr search. os.chdir(path) for root, dirs, files in os.walk(".", topdown = False): for name in files: if '.h' in name: print(os.path.join(root, name))
7320949169efef2b15c71d9fcc44eb366b4fdc3c
JankovicNikola/python
/basics/settype.py
312
3.53125
4
s={10,20,30,'XYZ', 10,20,10} print(s) print(type(s)) s.update([88,99]) print(s) #print(s*3) s.remove (30) print(s) #nema duplikata, ne radi indexind, slicing, repetition ali rade update i remove1 f=frozenset(s) f.update(20) #frozenset ne moze update i remove, nema menjanja samo gledanje
ba3a81a69f5c609bdae6c134e0e08916f107cea6
webappDEV0001/python_datetime_util
/utils.py
622
3.546875
4
from datetime import datetime, timedelta def datetime_converter(value): if isinstance(value, datetime): return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') def normalize_seconds(seconds): seconds = int(seconds) (days, remainder) = divmod(seconds, 86400) (hours, remainder) = divmod(remainder, 3600) (minutes, seconds) = divmod(remainder, 60) if days > 0: return f'{days} days {hours} hrs' elif hours > 0: return f'{hours} hrs {minutes} minutes' elif minutes > 0: return f'{minutes} minutes {seconds} seconds' else: return f'{seconds} seconds'
06788574fddaacde210956943be373cfaac91fa9
zolars/dashboard-ocr
/packages/opencv/main.py
11,746
3.671875
4
# -*- coding: UTF-8 -*- import cv2 import numpy as np import math from datetime import datetime as dt def avg_circles(circles, b): avg_x = 0 avg_y = 0 avg_r = 0 for i in range(b): # optional - average for multiple circles (can happen when a dashboard is at a slight angle) avg_x = avg_x + circles[0][i][0] avg_y = avg_y + circles[0][i][1] avg_r = avg_r + circles[0][i][2] avg_x = int(avg_x / (b)) avg_y = int(avg_y / (b)) avg_r = int(avg_r / (b)) return avg_x, avg_y, avg_r def dist_2_pts(x1, y1, x2, y2): return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) def calibrate(img): ''' This function should be run using a test image in order to calibrate the range available to the dial as well as the units. It works by first finding the center point and radius of the dashboard. Then it draws lines at hard coded intervals (separation) in degrees. It then prompts the user to enter position in degrees of the lowest possible value of the dashboard, as well as the starting value (which is probably zero in most cases but it won't assume that). It will then ask for the position in degrees of the largest possible value of the dashboard. Finally, it will ask for the units. This assumes that the dashboard is linear (as most probably are). It will return the min value with angle in degrees (as a tuple), the max value with angle in degrees (as a tuple), and the units (as a string). ''' # cv2.imwrite('./out/image_origin.jpg', img) height, width = img.shape[:2] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to gray # gray = cv2.GaussianBlur(gray, (5, 5), 0) # gray = cv2.medianBlur(gray, 5) # for testing, output gray image # cv2.imwrite('./out/%s-bw.%s' % (0, 'jpg'), gray) # apply thresholding which helps for finding lines mean_value = gray.mean() if mean_value >= 200: hist = cv2.calcHist([gray], [0], None, [256], [0, 256]) min_value, max_value, min_index, max_index = cv2.minMaxLoc(hist) ret, image_edge = cv2.threshold(gray, int(max_index[1]) - 7, 255, cv2.THRESH_BINARY_INV) else: mean, stddev = cv2.meanStdDev(gray) ret, image_edge = cv2.threshold(gray, mean_value, 255, cv2.THRESH_BINARY_INV) # image_edge = cv2.adaptiveThreshold(gray, 255, # cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # cv2.THRESH_BINARY_INV, 11, # 0) # found Hough Lines generally performs better without Canny / blurring, though there were a couple exceptions where it would only work with Canny / blurring image_edge = cv2.medianBlur(image_edge, 5) image_edge = cv2.Canny(image_edge, 50, 150) image_edge = cv2.GaussianBlur(image_edge, (5, 5), 0) cv2.imwrite('./out/image_edge.jpg', image_edge) # detect circles # restricting the search from 35-48% of the possible radii gives fairly good results across different samples. Remember that # these are pixel values which correspond to the possible radii search range. # 霍夫圆环检测 # image:8位, 单通道图像 # method:定义检测图像中圆的方法. 目前唯一实现的方法cv2.HOUGH_GRADIENT. # dp:累加器分辨率与图像分辨率的反比. dp获取越大, 累加器数组越小. # minDist:检测到的圆的中心, (x,y) 坐标之间的最小距离. 如果minDist太小, 则可能导致检测到多个相邻的圆. 如果minDist太大, 则可能导致很多圆检测不到. # param1:用于处理边缘检测的梯度值方法. # param2:cv2.HOUGH_GRADIENT方法的累加器阈值. 阈值越小, 检测到的圈子越多. # minRadius:半径的最小大小 (以像素为单位). # maxRadius:半径的最大大小 (以像素为单位). circles = cv2.HoughCircles(image_edge, cv2.HOUGH_GRADIENT, 1, 20, np.array([]), 100, 50, int(height * 0.35), int(height * 0.48)) # average found circles, found it to be more accurate than trying to tune HoughCircles parameters to get just the right one a, b, c = circles.shape #获取圆的坐标x,y和半径r x, y, r = avg_circles(circles, b) return x, y, r def draw_calibration(img, x, y, r): # draw center and circle cv2.circle(img, (x, y), r, (0, 0, 255), 3, cv2.LINE_AA) # draw circle cv2.circle(img, (x, y), 2, (0, 255, 0), 3, cv2.LINE_AA) # draw center of circle # for calibration, plot lines from center going out at every 10 degrees and add marker separation = 10.0 # in degrees interval = int(360 / separation) p1 = np.zeros((interval, 2)) # set empty arrays p2 = np.zeros((interval, 2)) p_text = np.zeros((interval, 2)) for i in range(0, interval): for j in range(0, 2): if (j % 2 == 0): p1[i][j] = x + 0.5 * r * np.cos( separation * i * math.pi / 180) # point for lines else: p1[i][j] = y + 0.5 * r * np.sin(separation * i * math.pi / 180) text_offset_x = 10 text_offset_y = 5 for i in range(0, interval): for j in range(0, 2): if (j % 2 == 0): p2[i][j] = x + r * np.cos(separation * i * math.pi / 180) p_text[i][j] = x - text_offset_x + 1.1 * r * np.cos( (separation) * (i + 9) * math.pi / 180 ) # point for text labels, i+9 rotates the labels by 90 degrees else: p2[i][j] = y + r * np.sin(separation * i * math.pi / 180) p_text[i][j] = y + text_offset_y + 1.1 * r * np.sin( (separation) * (i + 9) * math.pi / 180 ) # point for text labels, i+9 rotates the labels by 90 degrees # add the lines and labels to the image for i in range(0, interval): cv2.line(img, (int(p1[i][0]), int(p1[i][1])), (int(p2[i][0]), int(p2[i][1])), (0, 255, 0), 2) cv2.putText(img, '%s' % (int(i * separation)), (int(p_text[i][0]), int(p_text[i][1])), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 1, cv2.LINE_AA) return img def get_current_value(img, min_angle, max_angle, min_value, max_value, x, y, r): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding which helps for finding lines mean_value = gray.mean() if mean_value >= 200: hist = cv2.calcHist([gray], [0], None, [256], [0, 256]) min_value, max_value, min_index, max_index = cv2.minMaxLoc(hist) ret, image_edge = cv2.threshold(gray, int(max_index[1]) - 7, 255, cv2.THRESH_BINARY_INV) else: mean, stddev = cv2.meanStdDev(gray) ret, image_edge = cv2.threshold(gray, mean_value + 15, 255, cv2.THRESH_BINARY_INV) # image_edge = cv2.adaptiveThreshold(gray, 255, # cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # cv2.THRESH_BINARY_INV, 11, # 0) # for testing, show image after thresholding # cv2.imwrite('./out/%s-bin.%s' % (0, 'jpg'), image_edge) # found Hough Lines generally performs better without Canny / blurring, though there were a couple exceptions where it would only work with Canny / blurring # image_edge = cv2.medianBlur(image_edge, 5) # image_edge = cv2.Canny(image_edge, 50, 150) # image_edge = cv2.GaussianBlur(image_edge, (5, 5), 0) # find lines minLineLength = 10 maxLineGap = 0 lines = cv2.HoughLinesP( image=image_edge, rho=3, theta=np.pi / 180, threshold=100, minLineLength=minLineLength, maxLineGap=0 ) # rho is set to 3 to detect more lines, easier to get more then filter them out later # for testing purposes, show all found lines # for i in range(0, len(lines)): # for x1, y1, x2, y2 in lines[i]: # cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) # cv2.imwrite('./out/%s-lines-test.%s' % (0, 'jpg'), img) # remove all lines outside a given radius final_line_list = [] diff1LowerBound = 0 # diff1LowerBound and diff1UpperBound determine how close the line should be from the center diff1UpperBound = 0.5 diff2LowerBound = 0 # diff2LowerBound and diff2UpperBound determine how close the other point of the line should be to the outside of the dashboard diff2UpperBound = 2 for i in range(0, len(lines)): for x1, y1, x2, y2 in lines[i]: # x, y is center of circle diff1 = dist_2_pts(x, y, x1, y1) diff2 = dist_2_pts(x, y, x2, y2) # set diff1 to be the smaller (closest to the center) of the two, makes the math easier if (diff1 > diff2): temp = diff1 diff1 = diff2 diff2 = temp # check if line is within an acceptable range if (((diff1 < diff1UpperBound * r) and (diff1 > diff1LowerBound * r) and (diff2 < diff2UpperBound * r)) and (diff2 > diff2LowerBound * r)): line_length = dist_2_pts(x1, y1, x2, y2) # add to final list final_line_list.append([x1, y1, x2, y2]) # testing only, show all lines after filtering max_length = 0 xx1, yy1, xx2, yy2 = 0, 0, 0, 0 for final_line in final_line_list: x1 = final_line[0] y1 = final_line[1] x2 = final_line[2] y2 = final_line[3] if dist_2_pts(x1, y1, x2, y2) > max_length: xx1, yy1, xx2, yy2 = x1, y1, x2, y2 max_length = dist_2_pts(x1, y1, x2, y2) # cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2) # assumes the longest line is the best one x1, y1, x2, y2 = xx1, yy1, xx2, yy2 # cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 2) # cv2.imwrite('./out/%s-lines-filter.%s' % (0, 'jpg'), img) # find the farthest point from the center to be what is used to determine the angle dist_pt_0 = dist_2_pts(x, y, x1, y1) dist_pt_1 = dist_2_pts(x, y, x2, y2) if (dist_pt_0 > dist_pt_1): x_begin, x_end = x1, x2 y_begin, y_end = y1, y2 else: x_begin, x_end = x2, x1 y_begin, y_end = y2, y1 x_angle = x_begin - x_end y_angle = y_end - y_begin # take the arc tan of y/x to find the angle res = np.arctan(np.divide(float(y_angle), float(x_angle))) # these were determined by trial and error res = np.rad2deg(res) if x_angle > 0 and y_angle > 0: # in quadrant I final_angle = 270 - res elif x_angle < 0 and y_angle > 0: # in quadrant II final_angle = 90 - res elif x_angle < 0 and y_angle < 0: # in quadrant III final_angle = 90 - res elif x_angle > 0 and y_angle < 0: # in quadrant IV final_angle = 270 - res else: raise UserWarning('Pointer was not detected.') old_min = float(min_angle) old_max = float(max_angle) new_min = float(min_value) new_max = float(max_value) old_value = final_angle old_range = (old_max - old_min) new_range = (new_max - new_min) new_value = (((old_value - old_min) * new_range) / old_range) + new_min return new_value if __name__ == '__main__': pass
078782bd9138dd1d925474a07b829431101ac648
vsehgal1/automate_boring_stuff_python
/ch7/strip.py
589
3.921875
4
# strip.py # automatetheboringstuff.com Chapter 7 # Vikram Sehgal import re def strip(strn, chars): if chars == '': reg_space = re.compile(r'^(\s*)(\S*)(\s*)$') #regex for whitespace new_strn = reg_space.search(strn).group(2) return new_strn else: reg = re.compile(r'(^[%s]+)(.+?)([%s]+)$' % (chars,chars)) #regex for character list new_strn = reg.search(strn).group(2) return new_strn if __name__ == '__main__': strn = input('Enter string: ') chars = input('Enter char to strip (Optional): ') print(strip(strn, chars))
782b07d8fc6ca8ee98695353aa91f9d6794ea9ca
Delrorak/python_stack
/python/fundamentals/function_basic2.py
2,351
4.34375
4
#Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). #Example: countdown(5) should return [5,4,3,2,1,0] def add(i): my_list = [] for i in range(i, 0-1, -1): my_list.append(i) return my_list print(add(5)) #Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second. #Example: print_and_return([1,2]) should print 1 and return 2 my_list = [6,10] def print_return(x,y): print(x) return y print("returned: ",print_return(my_list[0],my_list[1])) #First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. #Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) def first_plus_length(list): return list[0] + len(list) print (first_plus_length([1,2,3,4,5])) #Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False #Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] #Example: values_greater_than_second([3]) should return False def values_greater_than_second(list): new_list=[] for i in range(0,len(list), 1): if list[i] >= list[2]: new_list.append(list[i]) if len(new_list) < 2: return False else: return ("length of new list: " + str(len(new_list))), ("new list values: " + str(new_list)) print(values_greater_than_second([5,2,3,2,1,4])) print(values_greater_than_second([5,2,6,2,1,4])) #This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value. #Example: length_and_value(4,7) should return [7,7,7,7] #Example: length_and_value(6,2) should return [2,2,2,2,2,2] def L_V(size,value): my_list = [] for size in range(size): my_list.append(value) return my_list print(L_V(4,7)) print(L_V(6,2))
aa4f667f7f4dcb01282041cb3231caf2accaa0d3
maheshphutane/stegonography
/stegonography.py
998
3.765625
4
from PIL import Image import stepic def encode(): img = input("Enter image name(with extension): ") image = Image.open(img) data = input("Enter data to be encoded : ") if (len(data) == 0): raise ValueError('Data is empty') #converting string to bytes format data1 = bytes(data, encoding="ascii") im1 = stepic.encode(image, data1) im1.save( input("Enter the name of new image:- ")) def decode(): img = input("Enter image name(with extension):- ") image = Image.open(img) data1 = stepic.decode(image) return data1 def main(): a = int(input(":: Welcome to Steganography ::\n" "1. Encode\n2. Decode\n")) if (a == 1): encode() elif (a == 2): print("Decoded word- " + decode()) else: raise Exception("Enter correct input") # Driver Code if __name__ == '__main__': # Calling main function main()
06779614e3f152ca83124f26e610af400b21c1d0
cegasa89/Python-Courses
/data/dataFrames.py
885
3.5
4
import numpy as np import pandas as pd A = [1, 2, 3, 4] B = [5, 6, 7, 8] C = [9, 0, 1, 2] D = [3, 4, 5, 6] E = [7, 8, 9, 0] df = pd.DataFrame([A, B, C, D, E], ['a', 'b', 'c', 'd', 'e'], ['W', 'X', 'Y', 'Z']) # create a new column print("-----------------------------") df['P'] = df['Y'] + df['Z'] # remove a row print("-----------------------------") df = df.drop('e') # remove a column print("-----------------------------") df1 = df.drop('P' , axis = 1) print(df1.loc['a']) print(df1.loc['a','Y']) #condicional acessing print("-----------------------------") print( df > 3) print( df[df['W'] > 8][['W']]) d = {'a':[1,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[0,1,2,np.nan,np.nan]} df = pd.DataFrame(d) print(df) #drop all row with any na print("-----------------------------") print(df.dropna(axis=0)) print(df.fillna(1)) #missing data print("-----------------------------")
2d28873dbc86e5dbdac27ffac8e42c1c1d96524b
Chahbouni-Chaimae/Atelier1-2
/python/fact.py
341
3.953125
4
def factorial(x): if x==1: return 1 else: return(x*factorial(x-1)) num=5 print("le factorial de ", num, "est" , factorial(num)) def somme_factorial(s,x): s=0 s=s+(factorial(x)/x) n=int(input("entrez un nombre:")) for x in range(0,n-1): print("la somme des séries est:" , somme_factorial(x))
886c8f7719475fdf6723610d3fb07b1a6566e825
Chahbouni-Chaimae/Atelier1-2
/python/invr_chaine.py
323
4.4375
4
def reverse_string(string): if len(string) == 0: return string else: return reverse_string(string[1:]) + string[0] string = "is reverse" print ("The original string is : ",end="") print (string) print ("The reversed string is : ",end="") print (reverse_string(string))
be3cee09655a2fc4851125186fbb587d63f02f97
cathoderay/gtsimulator
/util/geometry.py
2,165
3.859375
4
import random class Element: def __init__(self, center, size): """Basic element of the world. Size zero is the special case where the element is a pixel.""" self.center = center self.centerx = center[0] self.centery = center[1] self.left = center[0] - size self.right = center[0] + size self.top = center[1] - size self.bottom = center[1] + size def distance(self, e): """Return Manhattam distance between 2 elements.""" distance = 0 correction = 0 if e.left > self.right: distance += e.left - self.right - 1 correction += 1 if e.right < self.left: distance += self.left - e.right - 1 correction += 1 if e.top > self.bottom: distance += e.top - self.bottom - 1 correction += 1 if e.bottom < self.top: distance += self.top - e.bottom - 1 correction += 1 if correction == 2: distance += 1 #case where it collides if correction == 0: return -1 return distance def direction_to(self, e): """Return a valid direction to another Element""" delta_x = delta_y = 0 if self.right < e.left: delta_x += 1 if e.right < self.left: delta_x -= 1 if self.top > e.bottom: delta_y -= 1 if self.bottom < e.top: delta_y += 1 if delta_y != 0 and delta_x != 0: return random.choice([[delta_x, 0], [0, delta_y]]) return [delta_x, delta_y] def collide(self, e): """Check for colllision between 2 Elements""" if self.distance(e) < 0: return True return False class Vector: @classmethod def random_direction(cls): """Return a valid direction randomly""" return random.choice([[1, 0], [0, 1], [-1, 0], [0, -1] ]) @classmethod def add(cls, v1, v2): """Return the sum of 2 vectors""" return [v1[0] + v2[0], v1[1] + v2[1]]
0913ec4362f45464137b5b06569c14aadd126034
minjjjae/pythoncode
/sqlite/sqliteclass.py
2,212
3.734375
4
import sqlite3 class Book: def create_conn(self): conn=sqlite3.connect('sqlite/my_books.db') return conn def create_table(self): conn = self.create_conn() c = conn.cursor() sql = ''' create table if not exists books( title text, published_date text, publisher text, pages integer, recommend integer )''' c.execute(sql) conn.commit() c.close() conn.close() def insert_book(self,item): conn=self.create_conn() c = conn.cursor() sql='insert into books values(?,?,?,?,?)' c.execute(sql,item) conn.commit() c.close() conn.close() def insert_books(self,items): conn=self.create_conn() c=conn.cursor() sql='insert into books values(?,?,?,?,?)' c.executemany(sql,items) conn.commit() c.close() conn.close() def all_books(self): conn=self.create_conn() c=conn.cursor() sql='select * from books' c.execute(sql) books = c.fetchall() #print(books) return books def one_book(self,title): conn = self.create_conn() c=conn.cursor() sql='select * from books where title=?' c.execute(sql,title) book = c.fetchone() return book def select_book(self,title): conn = self.create_conn() c=conn.cursor() sql='select * from books where title like ?' c.execute(sql, title) book = c.fetchone() return book if __name__ == '__main__': dbo=Book() dbo.create_table() item=('데이터분석실무','2020-7-13','위키북스',300,10) dbo.insert_book(item) items=[ ('빅데이터','2020-7-13','이지퍼블리싱',599,67), ('안드로이드','2020-7-14','삼성',128,8), ('spring','2020-7-15','위키북스',566,10) ] dbo.insert_books(items) dbo.all_books() book =dbo.one_book(('안드로이드',)) print(book) book = dbo.select_book(('%s%',)) print(book)
ce86f7c872f79a9aea96fff7dec144762f436d3e
sireesha98/siri
/siri.py
210
3.875
4
i=raw_input("") p=['a','e','i','o','u','A','E','I','O','U'] if (i>='a' and i<='z' or i>='A' and i<='Z'): if (i in p): print("Vowel") else: print("Consonant") else: print("invalid")
941fe47ca8313a8f1329985bf58eda81771b8619
ivanklimuk/py_crepe
/utils.py
1,931
3.578125
4
import string import numpy as np import pandas as pd from keras.utils.np_utils import to_categorical def load_train_data(path, labels_path=None): ''' Load the train dataset with the labels: - either as the second value in each row in the read_csv - or as a separate file ''' train_text = np.array(pd.read_csv(path, header=None)) if labels_path: train_labels = np.array(pd.read_csv(labels_path, header=None)) else: train_labels, train_text = train_text[:, 0], train_text[:, 1] train_labels = to_categorical(train_labels) return (train_text, train_labels) def text_to_array(text, maxlen, vocabulary): ''' Iterate over the loaded text and create a matrix of size (len(text), maxlen) Each character is encoded into a one-hot array later at the lambda layer. Chars not in the vocab are encoded as -1, into an all zero vector. ''' text_array = np.zeros((len(text), maxlen), dtype=np.int) for row, line in enumerate(text): for column in range(min([len(line), maxlen])): text_array[row, column] = vocabulary.get(line[column], -1) # if not in vocabulary_size, return -1 return text_array def create_vocabulary_set(ascii=True, digits=True, punctuation=True): ''' This alphabet is 69 chars vs. 70 reported in the paper since they include two '-' characters. See https://github.com/zhangxiangxiao/Crepe#issues. ''' alphabet = [] if ascii: alphabet += list(string.ascii_lowercase) if digits: alphabet += list(string.digits) if punctuation: alphabet += list(string.punctuation) + ['\n'] alphabet = set(alphabet) vocabulary_size = len(alphabet) vocabulary = {} reverse_vocabulary = {} for ix, t in enumerate(alphabet): vocabulary[t] = ix reverse_vocabulary[ix] = t return vocabulary, reverse_vocabulary, vocabulary_size, alphabet
a3035208563797b6d6e40fd0441b6bc51aba495b
PSY31170CCNY/Class
/Stephanie Bodden/Assignment 1.py
661
3.609375
4
class Person: def __init__(self,firstname='', lastname='',email=''): self.firstname = firstname self.lastname = lastname self.email = email e=open("names.txt","r") names=e.readlines() for line in names: #Decide if it's blank, name, or email line. #If the length of line is zero than it's blank. (Skip it)(Continues loop) if len (line)== 0: continue x=line.split() if len (x)==2: firstname=x[0] lastname=x[1] p=Person(firstname, lastname, email='') if len (x)==1 p.email=x email=x[1] p=Person(firstname, lastname, email)
d17f62b713eec8210603b4451bb656fe5b60d6fa
PSY31170CCNY/Class
/Daniel Coumswang/Assignment set 1 part 1.py
305
3.796875
4
#Assignment set 1 part 1 x = True while x: print("Please enter your information.") A = input("Enter your first name:") b = input("Enter your last name:") c = input("Enter your Email:") d = open('emaillist.csv','a') e = '"'+A+'", "' +b+'", "'+c+"\n" d.write(e)
ac6d6abe694e280fdf08930ec914e1b08fe75498
PSY31170CCNY/Class
/Jamin Chowdhury/Assignment 1.py
1,247
3.96875
4
#Locate and Create #---------------------------------------- Destination = "C:/Users/Jamin/Desktop/PythAss1/" Filename = "Email List.csv" File = Destination + Filename #---------------------------------------- #Header #---------------------------------------- z1 = ('First Name') z2 = ('Last Name') z3 = ('Email Address') v0 = str('"'+z1+'",'+'"'+z2+'",'+z3+'\n') f = open(File,"a") #append f.writelines(v0) #---------------------------------------- #Program #---------------------------------------- List = True while List: v1 = input("Would you like to contribute to the Email List? Y/N") if v1 in 'Nono': print("It would be really helpful if you did!") while v1 in "Yesyes": v2 = input("Person's last name.") if v2 == "": break v3 = input("Person's first name.") if v3 == "": break v4 = input("Person's email address.") if v4 == "": break v5 = str('"'+v3+'",'+'"'+v2+'",'+v4+'\n') # First Name, Last Name, Email Address formatting f = open(File,"a") #append f.writelines(v5) f.close() continue #------------------------------------------
0a0b49b0bbaf60cc0a85dcc877dea0f6bd44fa07
PSY31170CCNY/Class
/Breona Couloote/assignment1.py
2,751
4.0625
4
#assignment class Person: def __init__(self,firstname='',lastname='',email=''): self.firstname = firstname self.lastname = lastname self.email = email def hello(self): print("hi",self.name) def askdata(self): self.firstname = input("enter first name") if self.firstname= '' return self.lastname = input("enter last name") self.email = input ("enter email") people=[] while True: p=Person() p.askdata() if p.firstname="": break people.append(p) drive='C:/Users/bcouloo000/Desktop/' e=open(drive+'emaillist.csv','a') for member in people: l='"'+member.name+'", "'+member.email+'"\n' e.writelines(l) e.close() e=open(drive+'emaillist.csv','a') print(".......\nread one line at a time and print it:") print("each entry has a newline at the end, and the print function adds another one.") for l in e: print(l) e.close() print ("------\nthe whole file as a list:") e=open(drive+'emaillist.csv','r') emails=e.readlines() print (emails) e.close() e=open(drive+'emaillist.csv','r') peopledict = {} for p in e: print('text string of this line:',p) print('length of text string:',len(p)) pvals = p.split(',') print('Now the text string is made into a list separated by commas:',pvals) print('The full read-in entry text line is now a list of',len(pvals),'items long') peopledict[p[0]] = p[1] e.close() print("\nThe raw peopledict is:\n",peopledict) print("---- now displayed by key-value pairs:") for p in peopledict.keys(): print("lookup key:",p,"value:",peopledict[p][0:-1]) print('===\n') n='' while n == '': n=input("Go ahead, enter a name to look up their data (or q to quit):") if n in'Qq': break try: print("Error: ",n,"not found in peopledict. Try again or q to quit.") except: print("Error: ",n,"not found in peopledict. Try again or q to quit.") n='' def getpersondata(data ={'lastname':'','firstname':'','email':''}): fields=['lastname','firstname','email'] for field in fields: if len(data[field]>0): x=input("change "+field+ " from "+data[field]+"(Y/N)") if x not in 'Yy': continue data[field]=input("enter the person's "+field ) return data while True: pname = input('enter the name of the person to find:') pdata = persons[pname] try: pdata = persons[pname] except: addnew = input(pname+' not found. Add as new (Y/N)?') if addnew in 'Yy': persons[pname] = [pname] else: contnue data=getpersondata(pdata)
b327a86ce9abee36e12397ef8de85a19217596fc
PSY31170CCNY/Class
/Jamin Chowdhury/Final Exam.py
3,056
4.15625
4
#PSY31170 Winter Session 2019 Final Exam 1. Fix this expression without changing any numbers, so x evaluates to 28: x = 7 * 2 **2 -------------------------------------- Answer: x = 7 * (2 **2) #----------------------------------------------------------------- 2. initialize p correctly so it prints 10 p= ??? for x in range(3): p = p + x print(p) -------------------------------------- Answer: p = 7 #Initial value p = p +x p1 = 7 + 0 = 7 p2 = 7 + 1 = 8 p3 = 8 + 2 = 10 print(p) = 10 #----------------------------------------------------------------- 3. fix the syntax and logic errors in this code snippet so it prints 101 z= true y=1 while z: y+=10 if y = 100: z=false print(y) ------------ Answer: z = True y = 1 while z: y += 10 print(y) if y == 101: z = False #-------------------------------------------------------------------------- 4. Using these variables with the built-in string function str.upper() and string slicing, put an expression into the print statement that outputs exactly this: The quick brown fox jumps over the lazy dog named Rover s=”the quick brown” f=[‘animal’, ‘fox’, ‘puppy’] j=’jumps over “Rover” the lazy dog’ print (?????) ------------------------- Answer: print(s + f[2] + j[3:5] + 'named' + j[2]) #--------------------------------------------------------------------- 5. What command must be executed before you can use the the csv.reader() function to read in a text file of values separated by commas? Demonstrate by writing a very short program to read in a csv file named “data.csv” using the csv.reader() function. -------------- Answer: File = FinalExam.csv open(File, newline='') as csvfile: datareader = csv.reader #----------------------------------------------------------------------- 6. Debug this program so it runs correctly, print out the resulting file with at least 6 users' data and upload the file to your github Class folder: # finalexamproblem6.py # Asks user for their information and adds it to a text file while True print(Enter your name,, address and phone, please) f = open(“textfile.txt”,’w’) name = ‘input(Your name’) addr = input’((Your address’) phone=’input(Your phone)’ f.writelines(name,add,phone) f.close() if name=’’: break Answer: ----------------------------------------------------------------- Answer: Destination: "C:/Users/Jamin/Desktop/" Filename: "Problem_6.txt/" textfile = Destination + Filename #Must create textfile before running the program. print("Enter your name,, address and phone, please") f = open(textfile, 'w') name = input("Your name") addr = input("Your address") phone= input('Your phone') f.writelines(name,add,phone) f.close() if name == "" : break
9da6e7f67b9c9c6cb1ae477313bbd5faa3d39b63
PSY31170CCNY/Class
/Ariell Lugo/Personclass.py
3,906
4
4
# Personclass.py class Person: def __init__(self,name=' ',address=' ',phone='',email=''): self.name = name self.address = address self.phone = phone self.email = email def hello(self): print("Hi there! My name is ",self.name) Sally = Person('Sally','1 Any Way','123-4567','sally@gmail') print(Sally.name) Sally.hello() #instantiate a Person in the variable Bob, named "Robert" Bob = Person("Robert",'1234 Drive',email='bob@gmail') Bob.hello() #make a list of the People objects: people=[Bob,Sally] drive='/Downloads/Personclass.py #write the name and emails of the people to a csv file for Excel: e=open('/media/dave/PSY31170/emaillist.csv','w') #open the file for member in people: # construct the text line for each member: # put the attributes in quotes separated by a comma, # like this: "Dave","dave@gmail" # add a newline at the end so each entry is on a new line l='"' + member.name + '"' + ',"' +member.email+ '"\n' e.writelines(l) e.close() # now read the file and see what it looks like: e=open('/media/dave/PSY31170/emaillist.csv','r') print("......\nread one line at a time and print it:") print("each entry has a newline at the end, and the print function adds another one.") for l in e: #e is a file object, so this reads the file one line at a time print (l) # show the line that was just read e.close() # close the file to keep the operating system happy # or print ("------\nthe whole file as a list:") e=open('/media/dave/PSY31170/emaillist.csv','r') # notice 'r' for read, not 'w' for write emails=e.readlines() # gets all the lines into memory, for small files print (emails) # or print ("-----\none item in the list at a time (without the newlines):") for l1 in emails: # each l1 is one line print(l1[0:-1]) # slice off the last char to remove the trailing newline e.close() # close the file to keep the operating system happy # let's read the file in as a python dictionary, so we can look up entries by name e=open('/media/dave/PSY31170/emaillist.csv','r') peopledict = {} # initialize an empty dictionary for p in e: # each p is one line from the excel format csv filefile # so it is a text string of a list of attribute values: print('text string of this line:',p) print('length of text string:',len(p)) # use split to separate the values: pvals = p.split(',') # separates by commas # use the first one as the key to look up by and the second as the # value that the key is associated with: print('Now the text string is made into a list separated by commas:',pvals) print('The full read-in entry text line is now a list of',len(pvals),'items long') # now put the entry into the dictionary: peopledict[pvals[0]] = pvals[1] #pvals[0] is the name, pvals[1] is the email e.close() # now see what we have in the dictionary peopledict: print("\nThe raw peopledict is:\n",peopledict) print ("--- now displayed by key-value pairs:") for p in peopledict.keys(): print ("lookup key:",p,"value:",peopledict[p][0:-1]) #take off trailing \n print('===\n') n='' while n == '': n=input("Go ahead, enter a name to look up their email:") try: # the try-except block catches errors without crashing the program print(peopledict['"'+n+'"']) # add the quotes present for csv format except: print("Error: ",n,"not found in peopledict. Try again.") n='' # === TO DO: === """ 1. Add a user data entry loop to allow more names and emails to be entered. Include the entry of the other data attributes of a Person 2. Add more attributes,but leave the data entry for now 3. add a loop to let the user look up an entry by name, and then enter a value for another attribute if the dictionary entry is found. 4. After any new data is entered, re-write the csv file to save the data. """
d5f8ef92bfdaca49a9d3a6028b9f9cf79dec5ad6
nathang21/CNT-4603
/Project 6/Submission/Source/zipcode.py
625
3.953125
4
''' Created on Dec 6, 2015 @author: Nathan Guenther ''' import re # Ask user for input file fileName = input('Please enter the name of the file containing the input zipcodes: ') # Read and save file contents fileObj = open(fileName, 'r') allLines = fileObj.readlines() fileObj.close() # Regular Expression test = '^\d{5}(?:[-\s]\d{4})?$' print('\n\n') # Check each zip code for eachLine in allLines: #Regex check if re.search(test, eachLine): print("Match found - valid U.S. zipcode: ", eachLine) else: print("Error - no match - invalid U.S. zipcode: ", eachLine)
c0c4f7738c75c36dcecbce841d3c432d81530184
zhengxiang1994/JIANZHI-offer
/test1/bubble_sort.py
316
3.796875
4
class Solution: def bubblesort(self, L): for i in range(len(L)-1): for j in range(len(L)-i-1): if L[j+1] < L[j]: L[j], L[j+1] = L[j+1], L[j] return L if __name__ == "__main__": s = Solution() print(s.bubblesort([1, 3, 5, 7, 2, 4, 6]))
79af3c8cf80c6788daffeb7558688fd68326a4bd
zhengxiang1994/JIANZHI-offer
/test1/demo19.py
784
3.84375
4
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here result = [] while matrix: result += matrix[0] if not matrix or not matrix[0]: break matrix.pop(0) if matrix: matrix = self.rotate(matrix) return result def rotate(self, matrix): height = len(matrix) width = len(matrix[0]) newmat = [] for i in range(width): newmat.append([m[width-i-1] for m in matrix]) return newmat if __name__ == "__main__": s = Solution() a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print(s.printMatrix(a))
2600e0f77da5149418d0211182bb74b7f1f0e954
zhengxiang1994/JIANZHI-offer
/test1/demo32.py
568
3.828125
4
# -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here # 类似冒泡排序 for i in range(len(numbers)-1): for j in range(len(numbers)-i-1): if int(str(numbers[j])+str(numbers[j+1])) > int(str(numbers[j+1])+str(numbers[j])): numbers[j], numbers[j+1] = numbers[j+1], numbers[j] s = "" return s.join(list(map(str, numbers))) if __name__ == "__main__": s = Solution() arr = [3, 32, 321] print(s.PrintMinNumber(arr))
accfb44d8e1b173c48550e18aa9d1845f181e996
zhengxiang1994/JIANZHI-offer
/test1/demo22.py
1,031
3.90625
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here ls = [] queue = [] if not root: return ls queue.append(root) while queue: temp = queue.pop(0) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) ls.append(temp.val) return ls if __name__ == "__main__": root0 = TreeNode(8) root1 = TreeNode(6) root2 = TreeNode(10) root3 = TreeNode(5) root4 = TreeNode(7) root5 = TreeNode(9) root6 = TreeNode(11) root0.left = root1 root0.right = root2 root1.left = root3 root1.right = root4 root2.left = root5 root2.right = root6 s = Solution() print(s.PrintFromTopToBottom(root0))
7b7c9250218d1f36284181b38d93c2ce594a3837
arvind2608/python-
/desktop background change app.py
1,910
3.734375
4
# import modules from tkinter import * from tkinter import filedialog from wallpaper import set_wallpaper # user define funtion def change_wallpaper(): # set your wallpaper try: set_wallpaper(str(path.get())) check = "DONE" except: check = "Wallpaper not available" result.set(check) def browseFiles(): filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("jpeg files", "*.jpg") ,("all files", "*.*"))) path.set(filename) # Change label contents label_file_explorer.configure(text="File Opened: "+filename) return filename # object of tkinter # and background set master = Tk() master.configure(bg='orange') # Variable Classes in tkinter result = StringVar() path = StringVar() label_file_explorer = Label(master, text="Select a image", width=100, fg="black",bg="white") # Creating label for each information # name using widget Label Label(master, text="Select image : ",fg="black", bg="white").grid(row=0, sticky=W) Label(master, text="Status :",fg="black", bg="white").grid(row=3, sticky=W) # Creating label for class variable # name using widget Entry Label(master, text="", textvariable=result, bg="white").grid(row=3, column=1, sticky=W) # creating a button using the widget # Button that will call the submit function b = Button(master, text="Open", command=browseFiles, bg="white") b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5,) label_file_explorer.grid(column=1, row=1) c = Button(master, text="Apply", command=change_wallpaper, bg="white") c.grid(row=2, column=2, columnspan=2, rowspan=2, padx=5, pady=5,) mainloop()
1d01da0f3867b5d86f5cabbacbdb505c50a137f4
tobhuber/rateme
/core/Song.py
1,332
3.578125
4
class Song: def __init__(self, name = "", album = None, raters = {}, rating = -1): self.name = name self.album = album self.rating = rating self.raters = raters self.hash = f"{self.name}#{self.album.interpret[0]}" self.updateRating() def __str__(self): return f""" Song object with: name: {self.name} album: {self.album.title} rating: {self.rating} raters: {self.raters} hash: {self.hash} """ def updateRating(self): result = 0 for rating in self.raters.values(): result += rating self.rating = -1 if len(self.raters) == 0 else round(result / len(self.raters), 2) def addRating(self, rater, rating): if rater not in self.raters: self.raters[rater] = rating self.updateRating() self.album.addRater(rater) self.album.updateRating() else: self.raters[rater] = rating self.updateRating() self.album.updateRating() def removeRater(self, rater): if rater in self.raters: del self.raters[rater] self.updateRating() self.album.updateRating() self.album.updateRaters()
a4d6aa8406a45aa04ec44f12bea28c132fc0adb5
ZL-Zealous/ZL-study
/py_study_code/循环/while.py
211
3.734375
4
prompt='\n please input something:' prompt+='\n enter "quit" to end\n' message='' active=True while active: message=input(prompt) if message=='quit': active=False else: print(message)
58c1b6b2a960dcedfa0317f9276b87daa6dc895e
ZL-Zealous/ZL-study
/py_study_code/文件与异常/json.number.py
273
3.578125
4
import json filename='number.json' try: with open(filename) as f_obj: a=json.load(f_obj) print("i konw the number is "+a) except: number = input('enter your favorite number:\n') with open(filename,'w') as f_obj: json.dump(number,f_obj)
fdad762c31dc9a9b52f9c0fe9f5e2fb333faa415
gokulmurali/sicp_exercises
/sicp/1-17.py
314
3.8125
4
def double(x): return x + x def halve(x): return (x/2) def even(x): if x % 2 == 0: return True else: return False def mul(a, b): if b == 0: return 0 elif even(b): return (double(a * halve(b))) else: return (a + (a * (b-1))) print mul(2, 3) print mul(2, 4)
a474bbf23356b820d0ec28c9d5616fc996c9a964
gokulmurali/sicp_exercises
/sicp/1-18.py
384
3.765625
4
def double(x): return x + x def halve(x): return (x / 2) def even(x): if x % 2 == 0:return True else:return False def muliter(a, b, aa): if b == 0: return aa elif even(b): return muliter(double(a), halve(b), aa) else: return muliter(a, b-1, (aa + a)) def mul(a, b): return muliter(a, b , 0) print mul(2, 3) print mul(2, 4)
6c77d7dc7e8f789dab2c2aefdf4f2f0f16ac9352
luisfrancisco62/Transparent-Splash-Screen-Tk
/splash.py
640
3.796875
4
""" Splash Screen Demonstration Author: Israel Dryer Modified: 2020-05-22 """ import tkinter as tk # create the main window root = tk.Tk() # disable the window bar root.overrideredirect(1) # set trasparency and make the window stay on top root.attributes('-transparentcolor', 'white', '-topmost', True) # set the background image psg = tk.PhotoImage(file='splash-logo.png') tk.Label(root, bg='white', image=psg).pack() # move the window to center root.eval('tk::PlaceWindow . Center') # schedule the window to close after 4 seconds root.after(4000, root.destroy) # run the main loop root.mainloop()
3d2826426b2a6328fc4d5e63ca958c554d722cc2
La-Ola/Year-10-
/driving.py
897
3.984375
4
print (" Welcome to DVLA driving test.") print ("**************************************************************") years = int(input("How many years have you been driving for?")) points = int(input("How many penalty point do you have?")) if years <=2 and points >=6: #engulfs numbers including and below 2 and including and above 6 print("-------------LICENCE SUMMARY-------------") print(" YOUR LICENCE HAS BEEN DISQUALIFIED.") print("-----------------------------------------") elif years >=2 and points >=12: print("-------------LICENCE SUMMARY-------------") print(" YOUR LICENCE HAS BEEN TIME-BANNED.") print("-----------------------------------------") else: print("-------------LICENCE SUMMARY-------------") print(" YOUR LICENCE IS OKAY, CONTINUE.") print("-----------------------------------------")
6f8cb30a116ef9a5ccaf5a33177ef512790e78ae
La-Ola/Year-10-
/ODDS AND EVENS.py
367
4.03125
4
#Odds and Evens print ("*****ODDS AND EVENS BETWEEN YOUR CHOSEN NUMBER AND 50*****") num = int(input("Choose a number between 1 and 50.")) print("****THE EVENS****") x = num while x < 50: if x%2 == 0: print (x) x = x + 1 print("****AND NOW THE ODDS****") x = num while x < 50: if x%2 == 1: print (x) x = x + 1
9d364d2297350eb501de9c099b8f20c6b2502435
WolfAuto/Maths-Pro
/NEA Programming/random.py
3,204
3.78125
4
import tkinter as tk # python3 TITLE_FONT = ("Helvetica", 18, "bold") class SampleApp(tk.Tk): # create a class that takes in a parameter of a tkinter GUI screen def __init__(self, *args, **kwargs): # instalise the class with the parameters self with tk.Tk.__init__(self, *args, **kwargs) # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} self.frames["StartPage"] = StartPage(parent=container, controller=self) self.frames["PageOne"] = PageOne(parent=container, controller=self) self.frames["PageTwo"] = PageTwo(parent=container, controller=self) self.frames["StartPage"].grid(row=0, column=0, sticky="nsew") self.frames["PageOne"].grid(row=0, column=0, sticky="nsew") self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(self, page_name): '''Show a frame for the given page name''' frame = self.frames[page_name] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self._canvas = tk.Canvas(self, bg='blue', width=900, height=900, scrollregion=(0, 2800, 100, 800)) self._canvas.pack() self._canvas.create_text(100, 10, fill="darkblue", font="Times 20 italic bold", text="Click the bubbles that are multiples of two.") label = tk.Label(self, text="This is the start page", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) button1 = tk.Button(self, text="Go to Page One", command=lambda: controller.show_frame("PageOne")) button2 = tk.Button(self, text="Go to Page Two", command=lambda: controller.show_frame("PageTwo")) button1.pack() button2.pack() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is page 1", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("StartPage")) button.pack() class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is page 2", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("StartPage")) button.pack() if __name__ == "__main__": app = SampleApp() app.mainloop()
8de6eedf90b3c7fd5ff34e0780ee44240049d0ef
WolfAuto/Maths-Pro
/NEA Testing/remake_register.py
9,940
3.65625
4
from tkinter import messagebox # module for error messages on the tkinter page import string import re import bcrypt from validate_email import validate_email import yagmail from create_connection import cursor, cursor1, db shared_data = {"firstname": "blank", # dictionary that stores the user register information "surname": "blank", # through using the controller we can pass these variables "age": 0, # to different frames "Class": "blank", "gender": "blank", } create_student_table = ("""CREATE TABLE IF NOT EXISTS Students(ID INTEGER PRIMARY KEY, Forename VARCHAR(30), Surname VARCHAR(30) , Age INTEGER , class VARCHAR (3), Gender VARCHAR (30) , Username VARCHAR(30),Password VARCHAR(80), Email VARCHAR(30))""") create_teacher_table = ("""CREATE TABLE IF NOT EXISTS Teachers( ID INTEGER PRIMARY KEY, Forename VARCHAR(30) , Surname VARCHAR(30) , Age INTEGER , Class VARCHAR (3) , Gender VARCHAR (30), Username VARCHAR(30), Password VARCHAR(80), Email VARCHAR(30))""") # Sql statment to create the table where the user information will be stored cursor.execute(create_student_table) # executes the sql statement # Sql statment to create the table where the user information will be stored cursor.execute(create_teacher_table) # executes the sql statement db.commit() # saves changes made to the sql file def register1(firstname, surname, age, school_class, var, var1): # Function for registration if firstname.isalpha() is True: firstname.title() if surname.isalpha() is True: surname.title() try: age1 = int(age) if school_class.isalnum() is True: if var == 1: # changing the var to a gender either male or female depending on value if (var1 == 1) or (var1 == 2): shared_data["firstname"] = firstname shared_data["surname"] = surname shared_data["age"] = age1 shared_data["gender"] = "Male" shared_data["Class"] = school_class return True else: messagebox.showerror( "School", "Please choose either Student or Teacher") return False elif var == 2: if (var1 == 1) or (var1 == 2): shared_data["firstname"] = firstname shared_data["surname"] = surname shared_data["age"] = age1 shared_data["gender"] = "Female" shared_data["Class"] = school_class return True else: messagebox.showerror( "School", "Please choose either Student or Teacher") return False else: messagebox.showerror("Gender", "Gender option cannot be left blank") return False else: messagebox.showerror("Class", "Class option cannot be left blank") except ValueError: messagebox.showerror("Age", "Please enter a number") else: messagebox.showerror("Surname", "Please enter a Proper Surname") else: messagebox.showerror("First Name", "Please enter a proper First Name") def username_check(username): # function for username vaildation # Checking the length of username is more than 6 charcters if len(username) >= 6: # sql statement for checking existing users # Checks student database for username fetchstudents = ("SELECT DISTINCT Students.Username from Students WHERE Username = ?") # Checkes teacher databaase for username fetchteachers = ("SELECT DISTINCT Teachers.Username from Teachers WHERE Username = ?") cursor.execute(fetchstudents, [(username)]) # executes the above query on the student table cursor1.execute(fetchteachers, [(username)]) # execute the above query on the teacher table checking = cursor.fetchall() # stores the result of sql search checking1 = cursor1.fetchall() if checking or checking1: messagebox.showerror("Username", "That username has been taken please try another one") else: return True else: messagebox.showerror( "Username", "Username has to be 6 or more characters") def password_check(password, password_confirm): # function for password vaildation if password == password_confirm: if len(password) >= 8: # checks whether the password length is 8 chracterslong # checks for letters in the password if len(set(string.ascii_lowercase).intersection(password)) > 0: # checks for numbers or special characters in the password if (len(set(string.ascii_uppercase).intersection(password)) > 0): # checks for uppercase characters if (len(set(string.digits).intersection(password))) > 0: if (len(set(string.punctuation).intersection(password))) > 0: return True else: messagebox.showerror( "Password", "Password doesn't contain a special character") return False else: # tkinter error message messagebox.showerror( "Password", "Password don't contain numbers") return False else: messagebox.showerror( "Password", "Password don't contain any uppercase characters") # tkinter error message return False else: messagebox.showerror( "Password", "Password don't contain any lowercase letters") # tkinter error message return False else: messagebox.showerror( "Password", "Password is not 8 characters long") # tkinter error message return False else: messagebox.showerror( "Password", "Password don't match") # tkinter error message return False def email_check(email): # function for email vaildation match = re.match( '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) is_valid = validate_email(email, verify=True) if match is None: messagebox.showerror("Email", "Please enter a valid email address ") if is_valid is not True: messagebox.showerror( "Email", "Email address doesn't exist please try another email address") else: return True def register2(username, password, confirm_password, email, var1): # checks whether a existing username with the username enter exists if username_check(username): # ensures the password passes all the vaildations if password_check(password, confirm_password): password_store = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt()) if email_check(email): # ensures the email passes the vaildation if var1 == 1: # inserts one whole record into student table insert_student = ( "INSERT INTO Students(Forename,Surname,Age,Class,Gender,Username,Password,Email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") cursor.execute(insert_student, [(shared_data["firstname"]), (shared_data["surname"]), (shared_data["age"]), (shared_data["Class"]), (shared_data["gender"]), (username), (password_store), (email)]) send_email(email, username) elif var1 == 2: # inserts one whole record into the teacher table insert_teacher = ( "INSERT INTO Teachers(Forename,Surname,Age,Class,Gender,Username,Password,Email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") cursor.execute(insert_teacher, [(shared_data["firstname"]), (shared_data["surname"]), (shared_data["age"]), (shared_data["Class"]), (shared_data["gender"]), (username), (password_store), (email)]) send_email(email, username) db.commit() # saves the changes to the database file return True else: return False else: return False else: return False def send_email(email, username): yag = yagmail.SMTP("mathspro0@gmail.com", oauth2_file="~/oauth2_creds1.json") send_mail = (" Email Confirmation From Maths Pro", " First Name:" + shared_data["firstname"], "Surname:" + shared_data["surname"], " Age:" + str(shared_data["age"]), "Class: " + shared_data["Class"], "Gender:" + shared_data["gender"], "username:" + username) yag.send(to=email, subject="Maths Pro Email Confirmation", contents=send_mail)
9907161a049b3e6088bd04f1f807fc2b2664b087
WolfAuto/Maths-Pro
/Maths-Pro-NEA-TESTING/NEA Testing/login page.py
7,788
3.8125
4
import sqlite3 import tkinter as tk from tkinter import ttk title_font = ("Times New Roman", 50) medium_font = ("Times New Roman", 26) class MathsPro(tk.Tk): # Creating a class that inherits from tk.Tk def __init__(self, *args, **kwargs): # intialises the object # intialises the object as a tkinter frame tk.Tk.__init__(self, *args, **kwargs) # tk.Tk.iconbitmap(self, default="") # Sets the title of each page to be Maths Pro tk.Tk.wm_title(self, "Maths Pro") # defined a container for all the framesto be kept container = tk.Frame(self) # The containter is filled with a bunch of frames container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) # After the page being packed this allows it to be displayed correctly container.grid_columnconfigure(0, weight=1) self.frames = {} # Empty dictionary where all the frames are kept # contains all the pages being used #this will not work without pages for F in (Main_Menu, StudentArea, TeacherArea): # Defines the frame from the for loop which contains all the pages frame = F(container, self) # Sets the top frame to be the current frame self.frames[F] = frame # This allows the frame to be displayed and streched frame.grid(row=0, column=0, sticky="nsew") # sets the first frame to be shown is a register page self.show_frame(Main_Menu) def show_frame(self, cont): # method that takes in cont as a controller # Defines the frame from the chosen frame in the dictionary frame = self.frames[cont] frame.tkraise() # Brings the frame to the top for the user to see class Main_Menu(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Maths Pro", bg="blue", font=title_font) label.pack(pady=10, padx=10) label_1 = tk.Label(self, text="Username") label_1.pack() username_entry = tk.StringVar() entry_1 = tk.Entry(self, textvariable=username_entry) entry_1.pack() label_2 = tk.Label(self, text="Password") label_2.pack() password_entry = tk.StringVar() entry_2 = tk.Entry(self, textvariable=password_entry) entry_2.pack() button = ttk.Button(self, text="Login") button.pack() button1 = ttk.Button(self, text="Student Area", command=lambda: controller.show_frame(StudentArea)) button1.pack() button2 = ttk.Button(self, text="Teacher Area", command=lambda: controller.show_frame(TeacherArea)) button2.pack() photo = tk.PhotoImage(file="button.png") help_button = tk.Button(self, text="Help Button", image=photo) help_button.config(border="0") help_button.place(x=0, y=730) help_button.image = photo logout_button = tk.Button(self, text="Log out", command=lambda: controller.show_frame(Main_Menu)) logout_button.config(height=3, width=10, bg="blue", fg="white") logout_button.place(x=1050, y=750) quit_button = tk.Button(self, text="Exit", command=lambda: quit(self)) quit_button.config(fg="white", bg="blue", height=3, width=10) quit_button.place(x=1200, y=750) def vaildate_account(self, controller, username, password): if vaildate_account(username, password) == True: pass class StudentArea(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.config(self, bg="grey") label = tk.Label(self, text="Student Area", font=title_font) label.config(bg="blue", fg="white") label.pack(pady=10, padx=10, side="top", anchor="nw") teacher_button = tk.Button(self, text="Teacher Area", command=lambda: controller.show_frame(TeacherArea)) teacher_button.pack(side="right", anchor="e") info_text = tk.Label( self, text="Welcome Student please choose from the following", font=medium_font, bg="grey") info_text.place(x=350, y=100) account_button = tk.Button(self, text="View Account Infomation") account_button.config(height=5, width=30, bg="blue") account_button.place(x=400, y=450) info_button = tk.Button(self, text="View Maths Information") info_button.config(height=5, width=30, bg="blue") info_button.place(x=750, y=450) math_button1 = tk.Button(self, text="AS Maths") math_button1.config(height=5, width=30, bg="blue") math_button1.place(x=400, y=250) math_button2 = tk.Button(self, text="A2 Maths") math_button2.config(height=5, width=30, bg="blue") math_button2.place(x=750, y=250) help_button = tk.Button(self, text="Help Button") help_button.config(height=3, width=10, bg="blue") help_button.place(x=0, y=750) logout_button = tk.Button(self, text="Log out", command=lambda: controller.show_frame(Main_Menu)) logout_button.config(height=3, width=10, bg="blue", fg="white") logout_button.place(x=1050, y=750) quit_button = tk.Button(self, text="Exit", command=lambda: quit(self)) quit_button.config(height=3, width=10, bg="blue") quit_button.place(x=1200, y=750) class TeacherArea(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.config(self, bg="grey") label_text = tk.Label(self, text="Teacher Area", font=title_font) label_text.config(bg="blue", fg="white") label_text.pack(pady=10, padx=10, anchor="nw") info_text = tk.Label( self, text="Welcome Teacher please choose from the following", font=medium_font, bg="grey") info_text.place(x=350, y=100) button1 = tk.Button(self, text="Student Area", command=lambda: controller.show_frame(StudentArea)) button1.pack() button2 = tk.Button(self, text="View Account Information") button2.config(height=5, width=30, bg="blue", fg="white") button2.place(x=750, y=450) button3 = tk.Button(self, text="View Student/Class Information") button3.place(x=400, y=250) button3.config(height=5, width=30, bg="blue", fg="white") button4 = tk.Button(self, text="View Flagged Students") button4.place(x=750, y=250) button4.config(height=5, width=30, bg="blue", fg="white") button5 = tk.Button(self, text="Set Test Date") button5.place(x=400, y=450) button5.config(height=5, width=30, bg="blue", fg="white") help_button = tk.Button(self, text="Help Button") help_button.config(height=3, width=10, bg="blue", fg="white") help_button.place(x=0, y=750) logout_button = tk.Button(self, text="Log out", command=lambda: controller.show_frame(Main_Menu)) logout_button.config(height=3, width=10, bg="blue", fg="white") logout_button.place(x=1050, y=750) quit_button = tk.Button(self, text="Exit", command=lambda: quit(self)) quit_button.config(fg="white", bg="blue", height=3, width=10) quit_button.place(x=1200, y=750) root = MathsPro() # this runs the Maths Pro class root.geometry("1280x800") # changes the size of the window root.resizable(width=False, height=False) root.mainloop() # As MathsPro inherited from tkinter this function can be moved
00d264591a57a5b69b759be8d6ac75b603ee0a5f
WolfAuto/Maths-Pro
/Maths-Pro-NEA-TESTING/NEA Programming/Stage 1 Creating GUI/learning.py
1,589
3.890625
4
import random import sqlite3 with sqlite3.connect("datalearn.db") as db: cursor = db.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS details(userID INTEGER PRIMARY KEY, firstname VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL , age INTEGER NOT NULL, class VARCHAR(3) NOT NULL, school VARCHAR(20) NOT NULL, username VARCHAR(20) NOT NULL, password VARCHAR(20) NOT NULL);") cursor.execute("INSERT INTO details(firstname,surname,age,class,school,username,password)VALUES('testname','name',21,'12D','Student','test_user','test_password')") db.commit() listfirst = ["john", "mary", "alice", "rias", "sam", "luke", "gerald"] listsurname = ["Sky", "Mac", "Smith", "Snow", "Stark", "Jona", "Scarlet"] listage = [18, 21, 49, 30, 25, 16, 17] listclass = ["13C", "12A", "12B", "12C", "13L", "13D", "13A"] listschool = ["Student", "Teacher"] listuser = ["test1", "test2", "test3", "test4", "test5", "test6", "test7"] listpassword = ["pass1", "pass2", "pass3", "pass4", "pass5", "pass6", "pass7"] def dynamic_entry(): a = random.randint(0, 6) b = random.randint(0, 1) first= str(listfirst[a]) surname = str(listsurname[a]) age= int(listage[a]) clas = str(listclass[a]) school = str(listschool[b]) user = str(listuser[a]) passw = str(listpassword[a]) cursor.execute("INSERT INTO details(firstname, surname, age , class, school, username, password) VALUES (?, ?, ?, ?, ?, ?, ?)", (first, surname, age, clas, school, user, passw)) for i in range(10): dynamic_entry() cursor.close() db.close()
d57a13ede4aba6274abe58dc902d09d61261acfa
seansaito/Number-Theory
/pingala.py
816
3.921875
4
import sys def main(argv): a = int(argv[0]) e = int(argv[1]) m = int(argv[2]) print pingala(a,e,m) # Computes a to the power of e in mod m context def pingala(a,e,m): # Converts the exponent into a binary form e_base2 = bin(e)[2:] # This keeps track of the final answer answer = 1 # A for loop that iterates through each digit # of the binary form of the exponent for t in range(len(e_base2)): signal = e_base2[t] # Squares the current answer answer = answer**2 # If the current digit of the binary form # is "on" (or equal to one), then multiply # answer by a if signal == '1': answer = answer*a #Return the answer in modulo return answer % m if __name__ == '__main__': main(sys.argv[1:])
ac73ef5689da1cc08123d76dcb3d1edc31d05ec5
drbuche/HackerRank
/Python/01_Introduction/005_Write_a_function.py
355
3.921875
4
# Problem : https://www.hackerrank.com/challenges/write-a-function/problem # Score : 10 points(MAX) def is_leap(year): """ :param year: Recebe um valor referente ao ano. :return: Retorna se o ano é bissexto ou não em forma de boolean. """ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) print(is_leap(int(input())))
70bb2017ba78e0cd36a3fc50e6dbd59403c20001
drbuche/HackerRank
/Python/01_Introduction/001_Python_If_Else.py
477
4.03125
4
# Problem : https://www.hackerrank.com/challenges/py-if-else/problem # Score : 10 points(MAX) def wierd(n): """ :param n: Recebe um valor inteiro 'n' :return: Retona um print contendo 'Weird' caso o numero seja impar ou esteja entre 6 e 20. Caso contrario retorna 'Not Weird'. """ print('Weird' if (n % 2 == 1) or (6 <= n <= 20) else 'Not Weird') wierd(int(input())) # Executa a função 'wierd' utilizando como parametro um input inteiro.
828b7b647572c21ef035b7fe77764ed99ca775a5
drbuche/HackerRank
/Python/03_Strings/005_String_Validators.py
1,313
4.1875
4
# Problem : https://www.hackerrank.com/challenges/string-validators/problem # Score : 10 points(MAX) # O método .isalnum() retorna True caso haja apenas caracteres alfabéticos e numéricos na string. # O método .isalpha() retorna True caso todos os caracteres sejam caracteres alfabéticos. # O método .isdigit() retorna True caso todos os caracteres sejam numéricos alfabéticos. # O método .islower() retorna True caso todos os caracteres sejam caracteres alfabéticos minúsculos. # O método .isupper() retorna True caso todos os caracteres sejam caracteres alfabéticos maiúsculos. # Leia a palavra e retorne True caso qualquer letra que ela possua retorne True nos métodos acima. if __name__ == '__main__': s = input() [print(any(eval('letra.' + metodo) for letra in s)) for metodo in ('isalnum()', 'isalpha()', 'isdigit()', 'islower()', 'isupper()')] # imprima na tela True or False utilizando os métodos da lista em cada letra da palavra digitada # Método any retorna True caso algum elemento seja True. # [print(list(eval('letra.' + metodo) for letra in s)) for metodo in ('isalnum()', 'isalpha()', 'isdigit()', 'islower()', 'isupper()')] # Caso troque o any por list(), notará que as listas que possuem ao menos 1 True foram retornadas como True pelo any()
18e86788373b6bbba4cbd1d8e2084caebcb9dee5
drbuche/HackerRank
/Python/04_Sets/003_Set.add().py
426
3.75
4
# Problem : https://www.hackerrank.com/challenges/py-set-add/problem # Score : 10 points(MAX) loops = input() # Quantidade de valores que entrarão grupo = [] # Grupo para alocar esses valores [grupo.append(input()) for i in range(int(loops))] # para cada loop adicione a palavra no grupo dist print(len(set(grupo))) # Transforme a lista em um set para remover os valores repetidos e depois retorne o tamanho do set
98cf8b7d7a5f6c0753fc8812a38eb3e7a8b52590
dsiah/Villanova-Python-Workshop
/scripts/maleGenerator.py
628
3.90625
4
""" A male first name generator. The program sifts through a list of about 3,800 male names from english speaking countries. User is asked to enter the (integer) number of first names they would like to have generated. Credit for the list of names goes to Grady Ward (Project Gutenberg) See the aaPG-Readme.txt in the directory for more information. David Siah 5/29/14 """ import random lines = open('MaleNames.txt').read().splitlines() def chooseM(iter): for i in range(iter): chosenName = random.choice(lines) print chosenName raw = int(raw_input("How many first names would you like?\n")) chooseM(raw)
7f0539c1b232551296487c24c5a1885a73c8b42a
dsiah/Villanova-Python-Workshop
/Python-Exercises/regex.py
951
3.953125
4
import re """ pattern = 'this' text = 'Does this text match the pattern?' match = re.search(pattern, text) s = match.start() e = match.end() print 'Found "%s"\nin "%s"\nfrom %d to %d("%s")' %\ (match.re.pattern, match.string, s, e, text[s:e]) regexes = [re.compile(p) for p in ["this", "that"] ] print 'Text: %r\n' % text for regex in regexes: print "Searching for", regex.pattern if regex.search(text): print 'Match!' else: print 'No match!' """ newString = 'This is the best string ever!' def seeker(patt): thePattern = patt Chill = re.search(thePattern, newString) if Chill: print '%r is in the string!' % thePattern elif not Chill: print '%r is not in the string :(' % thePattern print "This is the string you are going to search through:\n" print newString, '\n' entry = raw_input('What would you like to search this string for?\n') seeker(entry)
b4bc00af23adb5e933ca8429a6ef53e079ac3b86
dsiah/Villanova-Python-Workshop
/scripts/howto.py
669
3.984375
4
# how to snippets of code that serve as patterns to use when programming condition = True condition2 = False #if if (condition): #do stuff print "Stuff" #if/elif/else if (condition): print condition elif (condition2): print condition2 else: print "Catch all" #defining functions def nameofFunc (argument): # argument is optional # do stuff with argument print argument # This can get confusing -- a list can hold lists and dictionaries # they index at 0 list1 = ["hi", [1, 2, 3], 4] # Woah this is a pretty loaded expression # for [ variable name ] in [ set ]: # do stuff --> then x gets incremented for x in range(0, len(list1)): print list1[x]
207404ca1e3a25f6a9d008ddbed2c7ca827c789b
eigenric/euler
/euler004.py
763
4.125
4
# author: Ricardo Ruiz """ Project Euler Problem 4 ======================= A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import itertools def is_palindrome(number): return str(number)[::-1] == str(number) def largest_palindrome_product(digits): possible_products = itertools.product(range(1, 10**digits), repeat=2) largest = 0 for a, b in possible_products: product = a * b if is_palindrome(product) and product > largest: largest = product return largest if __name__ == '__main__': print(largest_palindrome_product(3))
e8042f82196ee8eaecf800fc86ab3e04c788510a
yangahh/daliy-algorithm
/week04/answer04.py
171
3.5
4
def maxSubArray(nums): dp = [0] * len(nums) dp[0] = nums[0] for i in range(1, len(nums)): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp)
f71257aa717a5d2684f65505c488f1d9b6262e67
yangahh/daliy-algorithm
/week05/answer03.py
124
4
4
def reverseString(str): if len(str) == 1: return str else: return str[-1] + reverseString(str[:-1])
25e1b8449981327950a7895d0f16d56c4a045065
Vkomini/cs181-s18-homeworks
/T3/code/problem2.py
1,464
3.515625
4
# CS 181, Harvard University # Spring 2016 import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as c from Perceptron import Perceptron # Implement this class class KernelPerceptron(Perceptron): def __init__(self, numsamples): self.numsamples = numsamples # Implement this! # def fit(self, X, Y): # Implement this! # def predict(self, X): # Implement this class class BudgetKernelPerceptron(Perceptron): def __init__(self, beta, N, numsamples): self.beta = beta self.N = N self.numsamples = numsamples # Implement this! # def fit(self, X, Y): # Implement this! # def predict(self, X): # Do not change these three lines. data = np.loadtxt("data.csv", delimiter=',') X = data[:, :2] Y = data[:, 2] # These are the parameters for the models. Please play with these and note your observations about speed and successful hyperplane formation. beta = 0 N = 100 numsamples = 20000 kernel_file_name = 'k.png' budget_kernel_file_name = 'bk.png' # Don't change things below this in your final version. Note that you can use the parameters above to generate multiple graphs if you want to include them in your writeup. k = KernelPerceptron(numsamples) k.fit(X,Y) k.visualize(kernel_file_name, width=0, show_charts=True, save_fig=True, include_points=True) bk = BudgetKernelPerceptron(beta, N, numsamples) bk.fit(X, Y) bk.visualize(budget_kernel_file_name, width=0, show_charts=True, save_fig=True, include_points=True)
d4d673ef94eca4ddfd5b6713726e507dad1849d6
abhaj2/Phyton
/sample programs_cycle_1_phyton/13.py
285
4.28125
4
#To find factorial of the given digit factorial=1 n=int(input("Enter your digit")) if n>0: for i in range(1,n+1): factorial=factorial*i else: print(factorial) elif n==0: print("The factorial is 1") else: print("Factorial does not exits")
047d6aa0dd53e1adaf6989cd5a977f07d346c73c
abhaj2/Phyton
/sample programs_cycle_1_phyton/11.py
235
4.28125
4
#to check the entered number is +ve or -ve x=int(input("Enter your number")) if x>0: print("{0} is a positive number".format(x)) elif x==0: print("The entered number is zero") else: print("{0} is a negative number".format(x))
afad18bd31239b95dd4fd00ea0b8f66c668fd1a6
abhaj2/Phyton
/sample programs_cycle_1_phyton/12.py
374
4.1875
4
#To find the sum of n natural numbers n=int(input("Enter your limit\n")) y=0 for i in range (n): x=int(input("Enter the numbers to be added\n")) y=y+x else: print("The sum is",y) #To find the sum of fist n natural numbers n=int(input("Enter your limit\n")) m=0 for i in range (1,n): m=m+i else: print("The sum of first m natural numbers are", m)
16631b78995f655cf7a84b6628f19c067d42680e
abhaj2/Phyton
/cycle-2/19.py
164
3.890625
4
import math num1=int(input("Enter the 1st number\n")) num2=int(input("Enter the 2st number\n")) g=math.gcd(num1,num2) print("The greatest common divisor is", g)
daa95e1d0332847f4d8352cd704faa809e55ab8a
abhaj2/Phyton
/sample programs_cycle_1_phyton/17.py
124
4.0625
4
#To count the number of digits in an integer c=0 x=int(input("Enter the digit")) while x!=0: x=x//10 c=c+1 print(c)
5bd43106071a675af17a6051c9de1f0cee0e0aec
abhaj2/Phyton
/cycle-2/3_c.py
244
4.125
4
wordlist=input("Enter your word\n") vowel=[] for x in wordlist: if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x): vowel.append(x) print(vowel)
b1369e3aa1af6e9af13e8376f8955bd1d4a64419
abhaj2/Phyton
/sample programs_cycle_1_phyton/16.py
218
3.984375
4
x=int(input("Enter the first number\n")) y=int(input("Enter the first number\n")) if (x>y): min=x else: min=y while (1): if(min%x==0 and min%y==0): print("LCM of two numbers is",min) break min=min+1
460436876ac4dbeafc3b4e7abc9ba4bb0b211ac5
abhaj2/Phyton
/cycle-2/20.py
115
3.859375
4
integer=[2,0,1,5,41,3,22,10,33] list=[] for x in integer: if(x%2!=0): list.append(x) print(list)
11eba6924a3dd4c84b02172ba5335e918b6af738
juliaviolet/Python_For_Everybody
/Chapter_9/Exercise_9.4_Final.py
509
3.578125
4
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) emails = handle.read() words=list() counts=dict() maximumvalue = None maximumkey = None for line in handle: if not line.startswith('From: '): continue line = line.split() words.append(line[1]) for word in words: counts[word] = counts.get(word, 0) + 1 for key,value in counts.items() : if value > maximumvalue: maximumvalue = value maximumkey=key print (maximumkey, maximumvalue)
a1a9fc369a0b994c99377dc6af16d00612a68f3b
juliaviolet/Python_For_Everybody
/Overtime_Pay_Error.py
405
4.15625
4
hours=input("Enter Hours:") rate=input("Enter Rate:") try: hours1=float(hours) rate1=float(rate) if hours1<=40: pay=hours1*rate1 pay1=str(pay) print('Pay:'+'$'+pay1) elif hours1>40: overtime=hours1-40.0 pay2=overtime*(rate1*1.5)+40.0*rate1 pay3=str(pay2) print('Pay:'+'$'+pay3) except: print('Error, please enter numeric input')
7320b834151d83c83268ecb7d9d5a72ca64fbccc
AdilAsanbekov/homework
/laboratory_work.py
1,107
3.5
4
from random import randint from abc import ABC, abstractmethod from math import floor class Characted(ABC): def __init__(self, name,level=1, strength=8, dexterity=8, intelligence=8, wisdom=8, charisma=8,constitution=8): self.level = level self.strength = strength self.dexterity = dexterity self.physique = physique self.intelligence = intelligence self.wisdom = wisdom self.charisma = charisma self.max_hp = 10 + floor((self.constitution - 10) / 2) + randint(1, 11) * self.level self.hp = self.max_hp self.armour_class = 15 + floor((self.dexterity - 10) / 2) self.initiative = randint(1, 21) + floor(((self.dexterity - 10) / 2)) def attack(self): return randint(1, 13) + floor(((self.strength - 10) / 2)) def save_throw(self, attribute): return randint(1, 21) + floor(((attribute - 10) / 2)) @abstractmethod def perk(self): pass class Hero(Characted): def perk(self): return randint(1, 17) + floor(((self.wisdom - 10) / 2)) class Dragon(Characted): def perk(self): return randint(1, 17) + floor(((self.strength - 10) / 2))
a48f5fdb04a1ad05b3613fef58f605c5b02ecc3b
abdiazizf/Chexers
/convert_json_to_board_dict.py
799
3.859375
4
# Converts a JSON into a dictionary of tuples(board co-ordinates) as keys with values to be printed # e.g {[0,2]: 'R',[0,0]:'BLK'} def convert_json_to_board_dict(file): # Reads colour from the JSON, compares it to a dictionary of values and # sets the correct symbol colour_dict = {'red' : 'R','blue': 'B','green':'G'} player_colour = colour_dict[file['colour']] # Creates an empty dict and constructs an entry for each tuple in JSON, using # predetermined player colour for player pieces and a block otherwise board_dict = {} for coordinate in file['pieces']: board_dict[tuple(coordinate)] = player_colour for coordinate in file['blocks']: board_dict[tuple(coordinate)] = 'BLK' #return dict return board_dict
ddc84b9fe6cd1914fcaf55063d7df0dc9c8f7443
rajvseetharaman/Hackerrank---Data-Structures-and-Algorithms
/Tries-Contacts.py
1,161
3.59375
4
class Node: def __init__(self,children,endofword,countofword): self.children=children self.endofword=endofword self.countofword=countofword def contact_add(contact,root): pointer=root for i,letter in enumerate(contact): if letter not in pointer.children.keys(): if i<len(contact)-1: pointer.children[letter]=Node({},False,0) else: pointer.children[letter]=Node({},True,0) pointer = pointer.children[letter] else: pointer=pointer.children[letter] pointer.countofword+=1 def contact_find(contact,root): pointer=root counter=0 for i,letter in enumerate(contact): if letter in pointer.children.keys(): pointer=pointer.children[letter] else: return 0 return(pointer.countofword) n = int(input().strip()) root=Node({},False,0) for a0 in range(n): op, contact = input().strip().split(' ') if op == 'add': contact_add(contact,root) if op == 'find': print(contact_find(contact,root))
8f5b0df594cd45f91cb61f6afbcb6e9aa2edcafa
saintcoder14/JARVIS
/jarvis.py
2,252
3.5
4
import pyttsx3 #for output voice kinda import datetime import speech_recognition as sr import wikipedia import webbrowser import os engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice',voices[0].id) def speak(audio): # Imp function used to convert a text into audio engine.say(audio) engine.runAndWait() def take_command(): # takes in audio from microphone and returns string as o/p r = sr.Recognizer() with sr.Microphone() as source: print("Listening..") r.pause_threshold = 1.2 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language='en-IN') print(f"User said:{query}\n") except Exception: speak("Please, say that again") return "None" return query def wish_me(): #func to wish me on the basis of 'hour' print("Welcome Back, sir") speak("Jarvis, at your Service Sir!") hour=int(datetime.datetime.now().hour) if hour>=5 and hour <12: speak("Good Morning darling") elif hour>=12 and hour <5: speak("Good afternoon darling") else: speak("Good evening darling") speak("How may I help u?") if __name__ == "__main__": # main function wish_me() while True: query=take_command().lower() if 'wiki' in query: speak('Searching Wikipedia') query=query.replace('wikipedia','') results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) speak(results) elif 'open google' in query: webbrowser.open("google.com") elif 'open youtube' in query: webbrowser.open("youtube.com") #elif 'what is the time' or 'whats the time' in query: # strtime=datetime.datetime.now() # speak("Sir, the time is %d %d" %(strtime.hour,strtime.minute)) elif 'who is your master' in query: speak('It is one and only Master Sammridh') elif 'okay bye' or 'bye' in query: exit()
360b8fda90ac1651976268e9cf4205d7ec59f687
ikhebgeenaccount/MusicBeeStats
/mbp/tagtracker.py
4,884
4.09375
4
class TagTracker: """A TagTracker tracks a certain tag. Arguments: tag - the tag to be tracked, can be either a str or a function which takes a Track and outputs some value tag_data - the data tag to be tracked grouped under tag, can be either a str or a function which takes a Track and outputs some value unique - boolean, True means each instance will be tracked separately, False means that an attempt will be made to add the data up, but this will only work for int or float type data case_sensitive - boolean, whether to track differently capitalized strings together or separately Examples: Counts the number of tracks for each artist separately: TagTracker('artist') Note: it counts the number of occurrences of each separate artist, since we have a list of songs with tags artist this constitutes the number of songs of each artist in the library Counts the play count for each artist separately: TagTracker('artist', 'play_count', unique=False) Note: in the above example, if unique is not passed the play_counts of each song will not be summed Counts the play count for each genre separately: TagTracker('genre', 'play_count', unique=False) Sums the total play time of songs per artist: TagTracker('artist', 'total_time', unique=False) Calculates the total time played for each artist: TagTracker('artist', tag_data=lambda t: t.get('play_count') * t.get('total_time'), unique=False) Counts the number of songs that start with a particular letter: TagTracker(tag=lambda t: t.get('name')[0]) """ def __init__(self, tag, tag_data=None, unique=True, case_sensitive=False): if isinstance(tag, str): self.tag = lambda t: t.get(tag) else: self.tag = tag if isinstance(tag_data, str): self.tag_data = lambda t: t.get(tag_data) else: self.tag_data = tag_data self.data = {} self.case_map = {} self.unique = unique self.case_sensitive = case_sensitive def evaluate(self, track): """Evaluates the given Track for the sought after tag. If the tag is found, and there is data in tag_data, it is added to the tracker. """ if self.tag_data: # If the track has the tag that we are tracking and it has the relevant data, add it key = self.tag(track) value = self.tag_data(track) if key is not None and value is not None: # is not None because if value returns False for value = 0 if not self.case_sensitive and isinstance(key, str) and key.lower() in self.case_map.keys(): key = self.case_map[key.lower()] elif not self.case_sensitive and isinstance(key, str): self.case_map[key.lower()] = key # Check if this is a new tag we track if key in self.data.keys(): # If not, add up if it's a number, otherwise append to list if not self.unique and (isinstance(value, int) or isinstance(value, float)): self.data[key] += value else: self.data[key].append(value) else: # It's a new tag, add as a new number or list if not self.unique and (isinstance(value, int) or isinstance(value, float)): self.data[key] = value else: self.data[key] = [value] else: value = self.tag(track) if value is not None: if not self.case_sensitive and isinstance(value, str) and value.lower() in self.case_map.keys(): value = self.case_map[value.lower()] elif not self.case_sensitive and isinstance(value, str): self.case_map[value.lower()] = value if value in self.data.keys(): if not self.unique and (isinstance(value, int) or isinstance(value, float)): self.data[value] += value else: self.data[value] += 1 else: if not self.unique and (isinstance(value, int) or isinstance(value, float)): self.data[value] = value else: self.data[value] = 1 def reset(self): """ Resets the TagTracker to an empty state, as if no evaluate() has been called yet. Properties are maintained. :return: """ self.data = {} self.case_map = {} # TODO: add arithmetic functions def __sub__(self, other): new_data = {} # Subtract related entries for i in self.data: new_data[i] = self.data[i] - other.data[i] if i in other.data else self.data[i] # Add -count for every entry not in self.data for i in other.data: if i not in self.data: new_data[i] = -1 * other.data[i] ret_tt = TagTracker(self.tag, self.tag_data, self.unique, self.case_sensitive) ret_tt.data = new_data return ret_tt def __rsub__(self, other): return self.return_self() def __add__(self, other): pass def __radd__(self, other): return self.return_self() def __div__(self, other): pass def __rdiv__(self, other): return self.return_self() def __mul__(self, other): pass def __rmul__(self, other): return self.return_self() def return_self(self): r = TagTracker(self.tag, self.tag_data, self.unique, self.case_sensitive) r.data = self.data return r
4bdaa4b30be65fa22cbf64265123484375d2c924
Juttiz/cs50
/pset6/vigenere.py
1,096
3.828125
4
from cs50 import get_string from sys import argv import sys def main(): while True: if len(sys.argv) ==2: break print("usage: python crack.py keyword") exit(1) cipher = [] n = 0 for i in range(len(argv[1])): # cipher[i] = if argv[1][i].isupper(): cipher.append(ord(argv[1][i]) - 65) elif argv[1][i].islower(): cipher.append(ord(argv[1][i]) - 97) else: print("usage: python crack.py keyword") exit(1) s = get_string("plaintext: ") print("ciphertext: ") for c in s: if c.isalpha(): if c.isupper(): x = n%len(argv[1]) l = ((ord(c)-65) + cipher[x])%26 +65 print(f"{chr(l)}",end = "") n+=1 elif c.islower(): x = n%len(argv[1]) l = ((ord(c)-97) + cipher[x])%26 +97 print(f"{chr(l)}", end = "") n+=1 else: print(c,end = "") print("") if __name__ == "__main__" : main()
565e52b6beea00de278a0a46d24237839419748f
Juanma1909/scientific-computing
/Entrega Diferenciacion e Integracion/labdif.py
7,693
4.15625
4
import numpy as np import matplotlib.pyplot as plt from time import time def printA(f,x): """ Entrada: una funcion f y un arreglo x de números reales Salida: un arreglo y de numeros reales correspondientes a la evaluacion de f(x) Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo x, en cada iteracion se evalua dicho valor en la función f y su resultado se almacena en el arreglo y """ y = [] for a in x: ans = f(a) y.append(ans) return y def printD(met,x,h,f): """ Entrada: un metodo met, un arreglo x de numeros reales, un numero h y un funcion f Salida: un arrelgo correspondiente a la evaluación del metodo escogido con el h y un valor perteneciente a x Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo x, en cada iteracion se evalua dicho valor en la metodología met con la función f y el h determinado, el resultado se almacena en el arreglo y """ y = [] for a in x: ans = met(f,a,h) y.append(ans) return y def errores(yReal, yAT,yAD,yCE): """ Entrada: 4 arreglos de numeros reales yReal, yAT, yAD y yCE el primero hace referencia a los valores obtenidos con la derivada analitica y los utlimos 3 hacen referencia a los valores obtenidos mediante los metodos diferecias finitas hacia atras,adelante y centrada respectivamente Salida: 3 arreglos de numeros reales los cuales hacen referencia a los errores absolutos de los metodos diferecias finitas hacia atras,adelante y centrada respectivamente Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arreglo yReal, en cada iteracion halla la diferencia absoluta con respecto a cada método, posteriormente dicahas diferencias se almacenan en su arreglo a retornar correspondiente """ n = len(yReal) ErAT,ErAD,ErCE = [],[],[] for i in range(n): ErAT.append(abs(yReal[i] - yAT[i])) ErAD.append(abs(yReal[i] - yAD[i])) ErCE.append(abs(yReal[i] - yCE[i])) return ErAT,ErAD,ErCE def ptime(tAD,tAT,tCE): """ Entrada: 3 tiempos de ejecución tAD,tAT y tCE los cuales hacen referencia a los tiempos de ejecucion de los metodos diferecias finitas hacia adelante,atras y centrada respectivamente Salida: se muestra en cosola los tiempos en cuestión Funcionamiento: se realiza un print de los tiempos """ print("Tiempos de ejecucion:") print("Adelante: " + str(tAD)) print("Atras: " + str(tAT)) print("Centrado: " + str(tCE)) return def perror(err): """ Entrada: err es un arreglo que hace referencia a los errores absolutos de uno de los metodos. Salida: Una impresion más organizada de el error medio y la desviacion estandar Funcionamiento: primero se halla tanto el error medio como la desviacion estandar de los errores absolutos posteriormente lo que se hace es imprimir 2 lineas de texto, una que contiene "Error Medio:" seguido de su valor numerico correspondiente, y la otra que contiene "Desviacion Estandar:" seguido de su valor numerico correspondiente. """ mean = np.mean(err) devia = np.std(err) print("Error Medio: " + str(mean)) print("Desviación Estándar: " + str(devia)) return """ Este grupo de funciones hacen referencia a las funciones reales y sus derivadas analiticas correspondientes, estas reciben un numero real x y retornal el valor de su imagen, de acuerdo a la evaluacion que se realice, para su creacin se hizo uso de la librería numpy """ def seno2(x): return np.sin(2*x) def logaritmo(x): return np.log(x) def expo2(x): return np.exp(2*x) def devseno2(x): return 2*np.cos(2*x) def devlog(x): return 1/x def devexpo2(x): return 2*np.exp(2*x) def derAtras(f,x,h): """ Entrada:Una funcion f,un valor h y un valor x Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el metodo de Diferencias finitas hacia atras """ ans = f(x) - f(x-h) ans = ans/h return ans def derAdelante(f,x,h): """ Entrada:Una funcion f,un valor h y un valor x Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el metodo de Diferencias finitas hacia adelante """ ans = f(x+h) - f(x) ans=ans/h return ans def derCentro(f,x,h): """ Entrada:Una funcion f,un valor h y un valor x Salida: el valor aporximado de la derivada de la funcion f a traves del metodo en cuestion Funcionamiento: Se toman los valores de x y h y se evaluan con respecto a lo que dicta el metodo de Diferencias finitas centrada """ ans = f(x+h)-f(x-h) ans = ans/(2*h) return ans def main(): """ en la funcion main se realiza un for donde en cada iteracion el valor de h se divide entre 10 y así tienda más a 0, en cada ciclo se hallan los valores de las derivadas aproximadas así como el valor de la derivada analitica para un conjunto de puntos x, posteriormente se hallan los errores medios para cada uno de los metodos, eso se hace para cada una de las funciones reales escogidas """ x = np.linspace(0.5,10,200) print("Funcion Seno(2x)") ySinA = printA(devseno2,x) h = 1 for i in range(4): if i != 0: h/=10 print(str(h)) tsAD = time() ySinAD = printD(derAdelante,x,h,seno2) totalsAD = time() - tsAD tsAT = time() ySinAT = printD(derAtras,x,h,seno2) totalsAT = time() - tsAT tsCE = time() ySinCE = printD(derCentro,x,h,seno2) totalsCE = time() - tsCE errAT,errAD,errCE=errores(ySinA,ySinAT,ySinAD,ySinCE) perror(errAT) perror(errAD) perror(errCE) ptime(totalsAD,totalsAT,totalsCE) plt.title("Funcion Seno") plt.plot(x,ySinA, label = "Derivada Analitica") plt.plot(x,ySinAD, label = "Adelante") plt.plot(x,ySinAT, label = "Atras") plt.plot(x,ySinCE, label = "Centrada") plt.grid() plt.legend() plt.show() print("Funcion logaritmo(x)") x = np.linspace(1.1,10,200) yLogA = printA(devlog,x) h = 1 for i in range(4): if i != 0: h/=10 print(str(h)) tlAD = time() yLogAD = printD(derAdelante,x,h,logaritmo) totallAD = time() - tlAD tlAT = time() yLogAT = printD(derAtras,x,h,logaritmo) totallAT = time() - tlAT tlCE = time() yLogCE = printD(derCentro,x,h,logaritmo) totallCE = time() - tlCE errAT,errAD,errCE=errores(yLogA,yLogAT,yLogAD,yLogCE) perror(errAT) perror(errAD) perror(errCE) ptime(totallAD,totallAT,totallCE) plt.title("Funcion Logaritmo") plt.plot(x,yLogA, label = "Derivada Analitica") plt.plot(x,yLogAD, label = "Adelante") plt.plot(x,yLogAT, label = "Atras") plt.plot(x,yLogCE, label = "Centrada") plt.grid() plt.legend() plt.show() x = np.linspace(0.5,10,200) print("Funcion e^(2x)") yEA = printA(devexpo2,x) h = 1 for i in range(4): if i != 0: h/=10 print(str(h)) teAD = time() yEAD = printD(derAdelante,x,h,expo2) totaleAD = time() - teAD teAT = time() yEAT = printD(derAtras,x,h,expo2) totaleAT = time() - teAT teCE = time() yECE = printD(derCentro,x,h,expo2) totaleCE = time() - teCE errAT,errAD,errCE=errores(yEA,yEAT,yEAD,yECE) perror(errAT) perror(errAD) perror(errCE) ptime(totaleAD,totaleAT,totaleCE) plt.title("Funcion e") plt.plot(x,yEA, label = "Derivada Analitica") plt.plot(x,yEAD, label = "Adelante") plt.plot(x,yEAT, label = "Atras") plt.plot(x,yECE, label = "Centrada") plt.grid() plt.legend() plt.show() return main()
b0ac70b3510ec9bab0f2ca5b49abdf9d2ccabc23
gutsergey/PythonSamples
/Fedorov/5 Strings/strings1.py
910
3.59375
4
def strings1(): a = "qwerty" b = 'qwerty123' c = '''comment1 text1 text2 text3 ---- text 4 end of comment1------- ''' d = """comment 2 text 1 text2 text3 ----- end of comment 2 --------- ''' """ e = " somebody says: 'Hello' " f = ' somebody says: "Hello" ' print (a) print (b) print (c) print (d) print (e) print (f) print("type of variable f:", type(f)) print(''' escape sequences \\n - переход на новую строку \\t - знак табуляции \\\\ - наклонная черта влево \\' - символ одиночной кавычки \\" - символ двойной кавычки ''') import sys print ("Hello", " ", 'World', "!", sep=' ', end='\n', file=sys.stdout, flush=False) print ("Hello", " ", 'World', "!", sep='-', end='*\n', file=sys.stdout, flush=False) print ("------");
28fe9d2012c336a30119abc523ecd17c5dc41aed
gutsergey/PythonSamples
/Fedorov/4/averageofthreenumbers2.py
184
3.578125
4
def averageofthreenumbers2(a=2, b=4, c=7): return (a + b + c)/3 print(averageofthreenumbers2()) print(averageofthreenumbers2(5, 7, 2)) print(averageofthreenumbers2(c=3, a=4))
687453f6803bea6331dc6513208bc8c7de45bf22
yeraydiazdiaz/lunr.py
/lunr/vector.py
5,295
4.125
4
from math import sqrt from lunr.exceptions import BaseLunrException class Vector: """A vector is used to construct the vector space of documents and queries. These vectors support operations to determine the similarity between two documents or a document and a query. Normally no parameters are required for initializing a vector, but in the case of loading a previously dumped vector the raw elements can be provided to the constructor. For performance reasons vectors are implemented with a flat array, where an elements index is immediately followed by its value. E.g. [index, value, index, value]. TODO: consider implemetation as 2-tuples. This allows the underlying array to be as sparse as possible and still offer decent performance when being used for vector calculations. """ def __init__(self, elements=None): self._magnitude = 0 self.elements = elements or [] def __repr__(self): return "<Vector magnitude={}>".format(self.magnitude) def __iter__(self): return iter(self.elements) def position_for_index(self, index): """Calculates the position within the vector to insert a given index. This is used internally by insert and upsert. If there are duplicate indexes then the position is returned as if the value for that index were to be updated, but it is the callers responsibility to check whether there is a duplicate at that index """ if not self.elements: return 0 start = 0 end = int(len(self.elements) / 2) slice_length = end - start pivot_point = int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] while slice_length > 1: if pivot_index < index: start = pivot_point elif pivot_index > index: end = pivot_point else: break slice_length = end - start pivot_point = start + int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] if pivot_index == index: return pivot_point * 2 elif pivot_index > index: return pivot_point * 2 else: return (pivot_point + 1) * 2 def insert(self, insert_index, val): """Inserts an element at an index within the vector. Does not allow duplicates, will throw an error if there is already an entry for this index. """ def prevent_duplicates(index, val): raise BaseLunrException("Duplicate index") self.upsert(insert_index, val, prevent_duplicates) def upsert(self, insert_index, val, fn=None): """Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (callable, optional): An optional callable taking two arguments, the current value and the passed value to generate the final inserted value at the position in case of collision. """ fn = fn or (lambda current, passed: passed) self._magnitude = 0 position = self.position_for_index(insert_index) if position < len(self.elements) and self.elements[position] == insert_index: self.elements[position + 1] = fn(self.elements[position + 1], val) else: self.elements.insert(position, val) self.elements.insert(position, insert_index) def to_list(self): """Converts the vector to an array of the elements within the vector""" output = [] for i in range(1, len(self.elements), 2): output.append(self.elements[i]) return output def serialize(self): # TODO: the JS version forces rounding on the elements upon insertion # to ensure symmetry upon serialization return [round(element, 3) for element in self.elements] @property def magnitude(self): if not self._magnitude: sum_of_squares = 0 for i in range(1, len(self.elements), 2): value = self.elements[i] sum_of_squares += value * value self._magnitude = sqrt(sum_of_squares) return self._magnitude def dot(self, other): """Calculates the dot product of this vector and another vector.""" dot_product = 0 a = self.elements b = other.elements a_len = len(a) b_len = len(b) i = j = 0 while i < a_len and j < b_len: a_val = a[i] b_val = b[j] if a_val < b_val: i += 2 elif a_val > b_val: j += 2 else: dot_product += a[i + 1] * b[j + 1] i += 2 j += 2 return dot_product def similarity(self, other): """Calculates the cosine similarity between this vector and another vector.""" if self.magnitude == 0 or other.magnitude == 0: return 0 return self.dot(other) / self.magnitude
65ff4a78f9cc6d7254418df1489c95eb0acbe98f
cfung/machine-learning
/projects/smartcab/smartcab/agent.py
11,289
3.71875
4
import random import math from environment import Agent, Environment from planner import RoutePlanner from simulator import Simulator from collections import defaultdict from helper import calculate_safety, calculate_reliability, evaluate_results class LearningAgent(Agent): """ An agent that learns to drive in the Smartcab world. This is the object you will be modifying. """ def __init__(self, env, learning=False, epsilon=1.0, alpha=0.5): super(LearningAgent, self).__init__(env) # Set the agent in the evironment self.planner = RoutePlanner(self.env, self) # Create a route planner self.valid_actions = self.env.valid_actions # The set of valid actions # Set parameters of the learning agent self.learning = learning # Whether the agent is expected to learn self.Q = dict() # Create a Q-table which will be a dictionary of tuples self.epsilon = epsilon # Random exploration factor self.alpha = alpha # Learning factor ########### ## TO DO ## ########### # Set any additional class parameters as needed self.max_trail = 10 #20 self.prev_state = None self.prev_action = None self.prev_reward = None self.def_Q = 0 self.trial_number = 0 def reset(self, destination=None, testing=False): """ The reset function is called at the beginning of each trial. 'testing' is set to True if testing trials are being used once training trials have completed. """ # Select the destination as the new location to route to self.planner.route_to(destination) self.trial_number += 1 print "trial_number is...", self.trial_number ########### ## TO DO ## ########### # Update epsilon using a decay function of your choice # Update additional class parameters as needed # If 'testing' is True, set epsilon and alpha to 0 if testing: self.epsilon = 0 self.alpha = 0 else: self.epsilon -= 0.05 # this is used for default learning agent #self.epsilon = math.exp(-self.alpha * self.trial_number) # other decay functions that were tried # self.epsilon = math.cos(0.15*self.trial_number) # self.epsilon = 1/(t^2) # self.epsilon = float(1)/(math.exp(float( 0.1 * self.trial_number))) self.gamma = 0.1 # gamma determines how much future reward is valued. 0 means immediate reward self.prev_state = None self.prev_action = None self.prev_reward = None return None def build_state(self): """ The build_state function is called when the agent requests data from the environment. The next waypoint, the intersection inputs, and the deadline are all features available to the agent. """ # Collect data about the environment waypoint = self.planner.next_waypoint() # The next waypoint inputs = self.env.sense(self) # Visual input - intersection light and traffic deadline = self.env.get_deadline(self) # Remaining deadline ########### ## TO DO ## ########### # Set 'state' as a tuple of relevant data for the agent # Set the state as a tuple and inlcude 'light status', 'oncoming traffic' and 'waypoint' self.state = (inputs['light'], inputs['oncoming'], inputs['left'], waypoint) return self.state def get_maxQ(self, state): """ The get_max_Q function is called when the agent is asked to find the maximum Q-value of all actions based on the 'state' the smartcab is in. """ ########### ## TO DO ## ########### # Calculate the maxmimum Q-value of all actions for a given state maxQ_action = None maxQ_value = 0 ''' print "******** GET_MAXQ ********" print "what is whole self.Q..", self.Q print "what is state (get_maxQ)...", state print "what is self.state (get_maxQ)...", self.state print "MAX_Q: action and value" + str(maxQ_action) + ',' + str(maxQ_value) print "MAX_Q: what is self.Q[self.state]...", self.Q[self.state] print "length of self.Q..", len(self.Q) print "length of self.Q[state]", len(self.Q[state]) #print "??? test max ???", max(self.Q[self.state].values()) print "******** ***** ** ************" ''' if len(self.Q[state]) > 0: print "(get_maxQ) result...", max(self.Q[state].values()) maxQ_value = max(self.Q[state].values()) else: maxQ_value = 0 #print ("what is maxQ_value..", maxQ_value) return maxQ_value def createQ(self, state): """ The createQ function is called when a state is generated by the agent. """ ########### ## TO DO ## ########### # When learning, check if the 'state' is not in the Q-table # If it is not, create a new dictionary for that state # Then, for each action available, set the initial Q-value to 0.0 # We'll use defaultdict and by default it is initialized to 0 if self.learning: if state not in self.Q.keys(): self.Q[state] = defaultdict(int) return def choose_action(self, state): """ The choose_action function is called when the agent is asked to choose which action to take, based on the 'state' the smartcab is in. """ # Set the agent state and default action self.state = state self.next_waypoint = self.planner.next_waypoint() action = None ########### ## TO DO ## ########### # When not learning, choose a random action # When learning, choose a random action with 'epsilon' probability # Otherwise, choose an action with the highest Q-value for the current state # a valid action is one of None, (do nothing) 'Left' (turn left), 'Right' (turn right), or 'Forward' (go forward) # Note that you have access to several class variables that will help you write this functionality, such as 'self.learning' and 'self.valid_actions if self.learning == False: # choose a action = random.choice(self.valid_actions) else: # when learning # choose a random action with 'ipsilon' probability if self.epsilon > random.random(): action = random.choice(self.valid_actions) else: # get action with highest Q-value for the current state maxQ = self.get_maxQ(state) best_actions = [] print "choose_action..self.Q[state]..", self.Q[state] for act in self.Q[state]: print "choose_action..act..", act if self.Q[state][act] == maxQ: best_actions.append(act) if (len(best_actions) > 0): action = random.choice(best_actions) print "action taken in choose_action...", str(action) return action def learn(self, state, action, reward): """ The learn function is called after the agent completes an action and receives an award. This function does not consider future rewards when conducting learning. """ ########### ## TO DO ## ########### # When learning, implement the value iteration update rule # Use only the learning rate 'alpha' (do not use the discount factor 'gamma') next_state = self.build_state() if self.learning: print "(learn)what is self.state (learn)..", self.state print "(learn)what is state (learn)..", state print "(learn)what is action (learn)..", action currentQ = self.Q[state][action] print "(learn) what is currentQ....?", currentQ self.Q[state][action] = reward*self.alpha + currentQ*(1-self.alpha) print "(learn), what is after learning...", self.Q[state][action] return def update(self): """ The update function is called when a time step is completed in the environment for a given trial. This function will build the agent state, choose an action, receive a reward, and learn if enabled. """ state = self.build_state() # Get current state self.createQ(state) # Create 'state' in Q-table action = self.choose_action(state) # Choose an action reward = self.env.act(self, action) # Receive a reward self.learn(state, action, reward) # Q-learn return def run(): """ Driving function for running the simulation. Press ESC to close the simulation, or [SPACE] to pause the simulation. """ ############## # Create the environment # Flags: # verbose - set to True to display additional output from the simulation # num_dummies - discrete number of dummy agents in the environment, default is 100 # grid_size - discrete number of intersections (columns, rows), default is (8, 6) env = Environment(verbose=True, grid_size=(8,6)) ############## # Create the driving agent # Flags: # learning - set to True to force the driving agent to use Q-learning # * epsilon - continuous value for the exploration factor, default is 1 # * alpha - continuous value for the learning rate, default is 0.5 agent = env.create_agent(LearningAgent, learning = True, alpha = 0.5, epsilon = 1.0) #0.8 (epsilon) #0.01 (alpha) #agent.learning = True #agent.epsilon = 1 #agent.alpha = 0.5 ############## # Follow the driving agent # Flags: # enforce_deadline - set to True to enforce a deadline metric env.set_primary_agent(agent, enforce_deadline = True) env.testing = True #env.enforce_deadline = True ############## # Create the simulation # Flags: # update_delay - continuous time (in seconds) between actions, default is 2.0 seconds # display - set to False to disable the GUI if PyGame is enabled # log_metrics - set to True to log trial and simulation results to /logs # optimized - set to True to change the default log file name sim = Simulator(env, update_delay = 0.01, log_metrics = True, display = False, optimized = False) sim.testing = True #sim.update_delay = 0.01, 2.0 #sim.log_metrics = True #sim.display = False #sim.optimized = True ############## # Run the simulator # Flags: # tolerance - epsilon tolerance before beginning testing, default is 0.05 # n_test - discrete number of testing trials to perform, default is 0 #sim.n_test = agent.max_trail sim.run(tolerance = 0.05, n_test = agent.max_trail) # sim.run(tolerance = 0.6, n_test = agent.max_trail if __name__ == '__main__': #get_opt_result() run()
d387a110a9578f1fcf92811f2efc64161feddbf4
faisalsupriansyah/praxis-academy
/novice/01-02/data_type_convertion/arrayvlist.py
1,164
3.53125
4
import numpy as np arr_a = np.array([3, 6, 9]) arr_b = arr_a/3 # Performing vectorized (element-wise) operations print(arr_b) arr_ones = np.ones(4) print(arr_ones) multi_arr_ones = np.ones((3,4)) # Creating 2D array with 3 rows and 4 columns print(multi_arr_ones) stack = [1,2,3,4,5] stack.append(6) # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 (Top) print(stack) stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 (Top) stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 (Top) print(stack) graph = { "a" : ["c", "d"], "b" : ["d", "e"], "c" : ["a", "e"], "d" : ["a", "b"], "e" : ["b", "c"] } def define_edges(graph): edges = [] for vertices in graph: for neighbour in graph[vertices]: edges.append((vertices, neighbour)) return edges print(define_edges(graph)) class Tree: def __init__(self, info, left=None, right=None): self.info = info self.left = left self.right = right def __str__(self): return (str(self.info) + ', Left child: ' + str(self.left) + ', Right child: ' + str(self.right)) tree = Tree(1, Tree(2, 2.1, 2.2), Tree(3, 3.1)) print(tree)
6995eed67a401cd363dcfa60b2067ef13732becb
ha1fling/CryptographicAlgorithms
/3-RelativePrimes/Python-Original2017Code/Task 3.py
1,323
4.25
4
while True: #while loop for possibility of repeating program while True: #integer check for input a try: a= input ("Enter a:") a= int(a) break except ValueError: print ("Not valid, input integers only") while True: #integer check for input b try: b= input ("Enter b:") b= int(b) break except ValueError: print ("Not valid, input integers only") def gcd(a,b): #define function c=abs(a-b) #c = the absolute value of a minus b if (a-b)==0: # if a-b=0 return b #function outputs b else: return gcd(c,min(a,b)) #function outputs smallest value out of a,b and c d=gcd(a,b) #function assigned to value d if d==1: print ("-They are relative primes") #if the gcd is one they are relative primes else: print ("-They are not relative primes") #else/ if the gcd is not one they are not relative primes print () v=input("Would you like to repeat the relative prime identifier? Enter y or n.") #while loop for repeating program print () if v == "y": #y repeats program continue elif v == "n": #n ends program break
bd1db01726f5373dadb80c3da3f29b4ec1f8ad88
TiagoArrazi/Python-HOME
/FileProcessor.py
588
3.59375
4
import os import csv def main(): arq = input('Insira o nome do arquivo ') name, ext = os.path.splitext(arq) if ext == '.txt': processaTxt(arq) elif ext == '.csv': processaCsv(arq) else: print('ERRO!') def processaTxt(arq): with open(arq,'r') as f: content = f.read() print(content) def processaCsv(arq): with open(arq, newline = '') as f: content = csv.reader(f) for row in content: print(row) main()