From 74b1f300e51145657f218b0982af79c371dd7b6e Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Wed, 19 Jul 2023 22:48:56 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- Binary_tree/tree.py | 20 ++--- Caesar_Cipher/Caesar_cipher.py | 16 ++-- Caterpillar_Game/Caterpillar.py | 3 +- Chinese_FlashCard/app/models.py | 2 +- Converter/converter.py | 14 +-- Crud_in_flask/main.py | 2 +- Demerge_pdfs/demerging_pdfs.py | 90 +++++++++---------- Dice_Rolling_Stimulator/dice_stimulator.py | 18 ++-- Dictionary/dictionary.py | 6 +- Diff_Utility/diff.py | 17 ++-- Egg_Catcher/eggcatcher.py | 24 +++-- Email Slicer/EmailSlicer.py | 9 +- Encode_Morse.py/main.py | 26 +++--- .../execute_shell_command.py | 4 +- Face_Recognition/main.py | 6 +- Finding_Lanes/lanes.py | 6 +- Firebase_Authentication_Using_Flask/main.py | 4 +- Hangman_Game/hangman.py | 81 ++++++++--------- Lazy_Pong/pong.py | 6 +- Madlibs/madlibs.py | 26 ++++-- Mail_Checker/mail_checker.py | 16 ++-- Minesweeper_game/minesweeper.py | 13 ++- Password Generator/password_generator.py | 4 +- Rock_Paper_Scissors_Spock/main.py | 3 +- Screenpet/screenpet.py | 2 +- Shape_Recognition/main.py | 23 ++++- Slideshare to PDF/main.py | 4 +- Smart_Calculator/calculator.py | 4 +- Snake_game/main.py | 6 +- Speaking_Wikipedia/speaking_wikipedia.py | 6 +- Spinning Donut/spinningdonut.py | 15 ++-- Sqlite-crud/main.py | 6 +- Stack_structure/main.py | 4 +- Star_Pyramid/star_pyramid.py | 14 +-- Sudoku_solver/main.py | 21 ++--- TEXTVENTURE/game.py | 75 +++++++--------- TestTypingSpeed/TestTypingSpeed.py | 13 ++- Tic_Tac_Toe/tic_tac_toe.py | 67 +++++--------- Url_Shortener/url_shortner.py | 2 +- Wordle_Aid/main.py | 40 ++++----- Zombie_Game/zombie.py | 62 +++---------- infix_postfix_calculator/main.py | 41 ++++----- 42 files changed, 362 insertions(+), 459 deletions(-) diff --git a/Binary_tree/tree.py b/Binary_tree/tree.py index 8981a30f..194d6f61 100644 --- a/Binary_tree/tree.py +++ b/Binary_tree/tree.py @@ -18,22 +18,18 @@ def add(self, data): def _add(self, data, node): if data < node.data: - if node.left is not None: - self._add(data, node.left) - else: + if node.left is None: node.left = Node(data) - else: - if node.right is not None: - self._add(data, node.right) else: - node.right = Node(data) + self._add(data, node.left) + elif node.right is not None: + self._add(data, node.right) + else: + node.right = Node(data) # Method for find the data def find(self, data): - if self.root is not None: - return self._find(data, self.root) - else: - return None + return self._find(data, self.root) if self.root is not None else None def _find(self, data, node): if data == node.data: @@ -55,6 +51,6 @@ def printTree(self): def _printTree(self, node): if node is not None: self._printTree(node.left) - print(str(node.data) + ' ') + print(f'{str(node.data)} ') self._printTree(node.right) diff --git a/Caesar_Cipher/Caesar_cipher.py b/Caesar_Cipher/Caesar_cipher.py index ac514ef3..b5cad07a 100644 --- a/Caesar_Cipher/Caesar_cipher.py +++ b/Caesar_Cipher/Caesar_cipher.py @@ -25,17 +25,15 @@ def encrypt_string(self) -> str: return(output) def decrypt_string(self, string: str) -> str: - output = "" + output = "" string = string.lower() - string = string.strip() - if string == "": + if not (string := string.strip()): return(self.blank_string) - else: - for c in string: - for k,v in self.key.items(): - if v == c: - output += k - + for c in string: + for k,v in self.key.items(): + if v == c: + output += k + return(output) if __name__ == "__main__": diff --git a/Caterpillar_Game/Caterpillar.py b/Caterpillar_Game/Caterpillar.py index 4afc8538..bac52427 100644 --- a/Caterpillar_Game/Caterpillar.py +++ b/Caterpillar_Game/Caterpillar.py @@ -34,8 +34,7 @@ def outside_window(): top_wall = t.window_height()/2 bottom_wall = -t.window_height()/2 (x,y) = caterpillar.pos() - outside = x < left_wall or x > right_Wall or y > top_wall or y < bottom_wall - return outside + return x < left_wall or x > right_Wall or y > top_wall or y < bottom_wall def game_over(): caterpillar.color('yellow') diff --git a/Chinese_FlashCard/app/models.py b/Chinese_FlashCard/app/models.py index 32de5586..a10ab165 100644 --- a/Chinese_FlashCard/app/models.py +++ b/Chinese_FlashCard/app/models.py @@ -31,7 +31,7 @@ def create_dictionary(datalist=data_list()) -> dict: """ slice every 4 items return :: dict with sinograms as key """ - sino_list = datalist[0::4] + sino_list = datalist[::4] pinyin_list = datalist[1::4] role_list = datalist[2::4] def_list = datalist[3::4] diff --git a/Converter/converter.py b/Converter/converter.py index 2726bb45..dfe415aa 100644 --- a/Converter/converter.py +++ b/Converter/converter.py @@ -5,19 +5,19 @@ while res.lower() != "q": #program loop res = res.strip().split(" ") - - try: + + try: if len(res) == 1: print(options[res[0]]) #to display help menu - + elif len(res) == 4: for i in res[3].split(','): - value = round( eval( "{} * {}['{}'] / {}['{}']".format(res[2],res[0],i,res[0],res[1]) ) , 6 ) #calculating - print("{} \t : {}".format(i,value)) #displaying - + value = round(eval(f"{res[2]} * {res[0]}['{i}'] / {res[0]}['{res[1]}']"), 6) + print(f"{i} \t : {value}") + else: print("Invalid command") - + except: print("Invalid command") diff --git a/Crud_in_flask/main.py b/Crud_in_flask/main.py index 76c199af..00ceb8b9 100644 --- a/Crud_in_flask/main.py +++ b/Crud_in_flask/main.py @@ -74,7 +74,7 @@ def delete(id): conn.execute('DELETE FROM products WHERE id = ?', (id,)) conn.commit() conn.close() - flash('"{}" was successfully deleted!'.format(products['title'])) + flash(f""""{products['title']}" was successfully deleted!""") return redirect(url_for('index')) diff --git a/Demerge_pdfs/demerging_pdfs.py b/Demerge_pdfs/demerging_pdfs.py index 46247a70..56ec53c6 100644 --- a/Demerge_pdfs/demerging_pdfs.py +++ b/Demerge_pdfs/demerging_pdfs.py @@ -2,62 +2,54 @@ import re def check_valid_filename(filename): invalid_chars = r'[/\\:*?"<>|]' - if re.search(invalid_chars, filename): - print('A file name cannot contain any of these characters / \\ : * ? " < > |') - return False - else: + if not re.search(invalid_chars, filename): return True + print('A file name cannot contain any of these characters / \\ : * ? " < > |') + return False # Note: here instead of Python.pdf you should give the whole path to the pdf if the pdf is not present in the same directory where python program is present -merged_pdf = open('Python.pdf', mode='rb') - - -pdf = PyPDF2.PdfFileReader(merged_pdf) - -(u, ctr, x) = tuple([0]*3) -for i in range(1, pdf.numPages+1): - - if u >= pdf.numPages: - print("Successfully done!") - exit(0) - - while True: - name = input("Enter the name of the pdf: ") - if check_valid_filename(name) == True: - break - - while True: - ctr = input(f"Enter the number of pages for {name}: ") - try: - ctr = int(ctr) - if ctr > 0: +with open('Python.pdf', mode='rb') as merged_pdf: + pdf = PyPDF2.PdfFileReader(merged_pdf) + + (u, ctr, x) = tuple([0]*3) + for _ in range(1, pdf.numPages+1): + if u >= pdf.numPages: + print("Successfully done!") + exit(0) + + while True: + name = input("Enter the name of the pdf: ") + if check_valid_filename(name) == True: break - else: - raise ValueError - except ValueError: - print("Page number must be a positive integer") - - u += ctr - if u > pdf.numPages: - print('Limit exceeded! ') - break - # Note: In the braces you should give the desired path of where new files should be stored - base_path = '{}.pdf' - # If you want to store the new pdfs in the same directory, then leave the braces empty - path = base_path.format(name) - f = open(path, mode='wb') - pdf_writer = PyPDF2.PdfFileWriter() - - for j in range(x, x+ctr): - page = pdf.getPage(j) - pdf_writer.addPage(page) + while True: + ctr = input(f"Enter the number of pages for {name}: ") + try: + ctr = int(ctr) + if ctr > 0: + break + else: + raise ValueError + except ValueError: + print("Page number must be a positive integer") + + u += ctr + if u > pdf.numPages: + print('Limit exceeded! ') + break - x += ctr + # Note: In the braces you should give the desired path of where new files should be stored + base_path = '{}.pdf' + # If you want to store the new pdfs in the same directory, then leave the braces empty + path = base_path.format(name) + with open(path, mode='wb') as f: + pdf_writer = PyPDF2.PdfFileWriter() - pdf_writer.write(f) - f.close() + for j in range(x, x+ctr): + page = pdf.getPage(j) + pdf_writer.addPage(page) + x += ctr -merged_pdf.close() + pdf_writer.write(f) print("Successfully done!") diff --git a/Dice_Rolling_Stimulator/dice_stimulator.py b/Dice_Rolling_Stimulator/dice_stimulator.py index 7fa65607..5589d2b2 100644 --- a/Dice_Rolling_Stimulator/dice_stimulator.py +++ b/Dice_Rolling_Stimulator/dice_stimulator.py @@ -12,39 +12,39 @@ print("| |") print("===========") - if number == 2: + elif number == 2: print("===========") print("| |") print("| O O |") print("| |") print("===========") - if number == 3: + elif number == 3: print("===========") print("| O |") print("| O |") print("| O |") print("===========") - - if number == 4: + + elif number == 4: print("===========") print("| O O |") print("| |") print("| O O |") print("===========") - - if number == 5: + + elif number == 5: print("===========") print("| O O |") print("| O |") print("| O O |") print("===========") - - if number == 6: + + elif number == 6: print("===========") print("| O O |") print("| O O |") print("| O O |") print("===========") - + x = input("Press y to roll again ") \ No newline at end of file diff --git a/Dictionary/dictionary.py b/Dictionary/dictionary.py index 05912e6c..eb068274 100644 --- a/Dictionary/dictionary.py +++ b/Dictionary/dictionary.py @@ -7,18 +7,18 @@ def translate(word): if word in data: return data[word] elif word.title() in data: - return data[word.title()] + return data[word.title()] elif word.upper() in data: return data[word.upper()] elif len(get_close_matches(word, data.keys())) > 0: - print("did you mean %s instead" %get_close_matches(word, data.keys())[0]) + print(f"did you mean {get_close_matches(word, data.keys())[0]} instead") decide = input("press y for yes or n for no: ") if decide == "y": return data[get_close_matches(word, data.keys())[0]] elif decide == "n": return("pugger your paw steps on working keys ") else: - return("You have entered wrong input please enter just y or n") + return("You have entered wrong input please enter just y or n") else: print("You have entered wrong keys. Try again") diff --git a/Diff_Utility/diff.py b/Diff_Utility/diff.py index 9706d433..52d5ce01 100755 --- a/Diff_Utility/diff.py +++ b/Diff_Utility/diff.py @@ -37,12 +37,11 @@ if orignal_contents[line] == changed_contents[line]: # Ignore if the lines are same. continue - else: - # Display the changes on the respective lines of the files. - print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "") - print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}") - - # Show the additions [+] or deletions [-] for the file that is the largest. - if line == len(smallest_sloc) - 1: - for new_line in range(line + 1, len(largest_sloc)): - print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}") + # Display the changes on the respective lines of the files. + print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "") + print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}") + + # Show the additions [+] or deletions [-] for the file that is the largest. + if line == len(smallest_sloc) - 1: + for new_line in range(line + 1, len(largest_sloc)): + print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}") diff --git a/Egg_Catcher/eggcatcher.py b/Egg_Catcher/eggcatcher.py index 7130084f..5fda618d 100644 --- a/Egg_Catcher/eggcatcher.py +++ b/Egg_Catcher/eggcatcher.py @@ -30,10 +30,24 @@ catcher = c.create_arc(catcher_start_x ,catcher_start_y ,catcher_start_x2,catcher_start_y2 , start=200 , extent = 140 , style='arc' , outline=catcher_color , width=3) score = 0 -score_text = c.create_text(10,10,anchor='nw' , font=('Arial',18,'bold'),fill='darkblue',text='Score : ' + str(score)) +score_text = c.create_text( + 10, + 10, + anchor='nw', + font=('Arial', 18, 'bold'), + fill='darkblue', + text=f'Score : {score}', +) lives_remaning = 3 -lives_text = c.create_text(canvas_width-10,10,anchor='ne' , font=('Arial',18,'bold'),fill='darkblue',text='Lives : ' + str(lives_remaning)) +lives_text = c.create_text( + canvas_width - 10, + 10, + anchor='ne', + font=('Arial', 18, 'bold'), + fill='darkblue', + text=f'Lives : {lives_remaning}', +) eggs = [] @@ -57,13 +71,13 @@ def egg_dropped(egg): c.delete(egg) lose_a_life() if lives_remaning == 0: - messagebox.showinfo('GAME OVER!' , 'Final Score : ' + str(score)) + messagebox.showinfo('GAME OVER!', f'Final Score : {str(score)}') win.destroy() def lose_a_life(): global lives_remaning lives_remaning -= 1 - c.itemconfigure(lives_text , text='Lives : ' + str(lives_remaning)) + c.itemconfigure(lives_text, text=f'Lives : {lives_remaning}') def catch_check(): (catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher) @@ -80,7 +94,7 @@ def increase_score(points): score += points egg_speed = int(egg_speed * difficulty_factor) egg_interval = int(egg_interval * difficulty_factor) - c.itemconfigure(score_text , text='Score : ' + str(score)) + c.itemconfigure(score_text, text=f'Score : {str(score)}') def move_left(event): (x1,y1,x2,y2) = c.coords(catcher) diff --git a/Email Slicer/EmailSlicer.py b/Email Slicer/EmailSlicer.py index 54171bcf..f54c47b9 100644 --- a/Email Slicer/EmailSlicer.py +++ b/Email Slicer/EmailSlicer.py @@ -4,16 +4,13 @@ def isValidEmail(email): # Regular expression for validating an Email regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' - - if(re.fullmatch(regex, email)): - return True - else: - return False + + return bool((re.fullmatch(regex, email))) email = input("Enter your email id - ") if isValidEmail(email): - username = email[0:email.index('@')] + username = email[:email.index('@')] domain = email[email.index('@')+1: ] print("Username - ", username) print("Domain - ", domain) diff --git a/Encode_Morse.py/main.py b/Encode_Morse.py/main.py index ba088a0b..93b765e6 100644 --- a/Encode_Morse.py/main.py +++ b/Encode_Morse.py/main.py @@ -1,20 +1,18 @@ def encode_morse(message): char_to_dots = { - 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', - 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', - 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', - 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', - 'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----', - '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', - '6': '-....', '7': '--...', '8': '---..', '9': '----.', - '&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.', - ':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-', - '-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.' + 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', + 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', + 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', + 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', + 'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----', + '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', + '6': '-....', '7': '--...', '8': '---..', '9': '----.', + '&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.', + ':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-', + '-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.' } - string="" - for x in message: - string+=char_to_dots[x.upper()]+' ' - return string[0:-1] + string = "".join(f'{char_to_dots[x.upper()]} ' for x in message) + return string[:-1] #test run print("Morse code for Hello World!: ") print(encode_morse("Hello World!")) \ No newline at end of file diff --git a/Execute Shell Command/execute_shell_command.py b/Execute Shell Command/execute_shell_command.py index 077c370e..2dd4da41 100644 --- a/Execute Shell Command/execute_shell_command.py +++ b/Execute Shell Command/execute_shell_command.py @@ -8,10 +8,10 @@ def execute_shell_command(command): out, err = proc.communicate() return_code = proc.returncode if err: - print(str(err)) + print(err) return out, return_code except Exception as err: - print("Exception Occurred while executing module : %s", str(err)) + print("Exception Occurred while executing module : %s", err) return 105 if __name__ == '__main__': diff --git a/Face_Recognition/main.py b/Face_Recognition/main.py index d4abfb6e..fa8cac59 100644 --- a/Face_Recognition/main.py +++ b/Face_Recognition/main.py @@ -3,9 +3,11 @@ cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier( - cv2.data.haarcascades + "haarcascade_frontalface_default.xml") + f"{cv2.data.haarcascades}haarcascade_frontalface_default.xml" +) body_cascade = cv2.CascadeClassifier( - cv2.data.haarcascades + "haarcascade_fullbody.xml") + f"{cv2.data.haarcascades}haarcascade_fullbody.xml" +) while True: _, frame = cap.read() diff --git a/Finding_Lanes/lanes.py b/Finding_Lanes/lanes.py index 159ca500..2a0dbb65 100644 --- a/Finding_Lanes/lanes.py +++ b/Finding_Lanes/lanes.py @@ -43,8 +43,7 @@ def average_lines_intercept(image, lines): def canny(image): gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) - canny = cv2.Canny(blur, 50, 150) - return canny + return cv2.Canny(blur, 50, 150) def display_lines(image, lines): @@ -62,8 +61,7 @@ def roi(image): ]) mask = np.zeros_like(image) cv2.fillPoly(mask, polygons, 255) - masked_image = cv2.bitwise_and(image, mask) - return masked_image + return cv2.bitwise_and(image, mask) cap = cv2.VideoCapture("Finding_Lanes/video.mp4") diff --git a/Firebase_Authentication_Using_Flask/main.py b/Firebase_Authentication_Using_Flask/main.py index b9f1ef2b..278d1a2d 100644 --- a/Firebase_Authentication_Using_Flask/main.py +++ b/Firebase_Authentication_Using_Flask/main.py @@ -54,9 +54,7 @@ def login(): except Exception as e: abort(500, {'message': str(e)}) - if 'user' in session: - return redirect("/") - return render_template("login.html") + return redirect("/") if 'user' in session else render_template("login.html") ''' Main dashboard route which has to be protected diff --git a/Hangman_Game/hangman.py b/Hangman_Game/hangman.py index 04c2dd0e..e430855f 100644 --- a/Hangman_Game/hangman.py +++ b/Hangman_Game/hangman.py @@ -5,14 +5,11 @@ def hangman(): validletter = 'abcdefghijklmnopqrstuvwxyz' turns = 10 guessmade = '' + missed = 0 while len(word) > 0: main = "" - missed = 0 for letter in word: - if letter in guessmade: - main = main + letter - else: - main = main + "_" + " " + main = main + letter if letter in guessmade else f"{main}_ " if main == word: print(main) print("You win!") @@ -27,64 +24,64 @@ def hangman(): guess = input() if guess not in word: turns = turns - 1 - if turns == 9: - print("9 turns left") - print(" -------- ") - if turns == 8: - print("8 turns left") + if turns == 0: + print("You lose") + print("You let a kind man die") print(" --------- ") - print(" O ") - if turns == 7: - print("7 turns left") + print(" O_| ") + print(" /|\ ") + print(" / \ ") + break + elif turns == 1: + print("1 turns left") + print("Last breaths counting. Take care!") print(" --------- ") - print(" O ") + print(" \ O_|/ ") print(" | ") - if turns == 6: - print("6 turns left") + print(" / \ ") + + elif turns == 2: + print("2 turns left") print(" --------- ") - print(" O ") + print(" \ O /| ") print(" | ") - print(" / ") - if turns == 5: - print("5 turns left") + print(" / \ ") + elif turns == 3: + print("3 turns left") print(" --------- ") - print(" O ") + print(" \ O / ") print(" | ") print(" / \ ") - if turns == 4: + elif turns == 4: print("4 turns left") print(" --------- ") print(" \ O ") print(" | ") print(" / \ ") - if turns == 3: - print("3 turns left") + elif turns == 5: + print("5 turns left") print(" --------- ") - print(" \ O / ") + print(" O ") print(" | ") print(" / \ ") - if turns == 2: - print("2 turns left") + elif turns == 6: + print("6 turns left") print(" --------- ") - print(" \ O /| ") + print(" O ") print(" | ") - print(" / \ ") - if turns == 1: - print("1 turns left") - print("Last breaths counting. Take care!") + print(" / ") + elif turns == 7: + print("7 turns left") print(" --------- ") - print(" \ O_|/ ") + print(" O ") print(" | ") - print(" / \ ") - - if turns == 0: - print("You lose") - print("You let a kind man die") + elif turns == 8: + print("8 turns left") print(" --------- ") - print(" O_| ") - print(" /|\ ") - print(" / \ ") - break + print(" O ") + elif turns == 9: + print("9 turns left") + print(" -------- ") name = input("Enter your name: ") print(f"Welcome {name}") diff --git a/Lazy_Pong/pong.py b/Lazy_Pong/pong.py index 88579c40..a2a99ea0 100644 --- a/Lazy_Pong/pong.py +++ b/Lazy_Pong/pong.py @@ -23,8 +23,7 @@ def ball_start(): def player_movement(): player.y += player_speed - if player.top <= 0: - player.top = 0 + player.top = max(player.top, 0) if player.bottom >= screen_height: player.bottom = screen_height @@ -35,8 +34,7 @@ def opponent_ai(): if opponent.bottom > ball.y: opponent.y -= opponent_speed - if opponent.top <= 0: - opponent.top = 0 + opponent.top = max(opponent.top, 0) if opponent.bottom >= screen_height: opponent.bottom = screen_height diff --git a/Madlibs/madlibs.py b/Madlibs/madlibs.py index 07b68a24..6818e877 100644 --- a/Madlibs/madlibs.py +++ b/Madlibs/madlibs.py @@ -1,15 +1,15 @@ import random print("Title : Eat, Drink, And Be Sick") noun = [] -for i in range(4): +for _ in range(4): n = input("Enter noun : ") noun.append(n) plural = [] -for i in range(6): +for _ in range(6): pn = input("Enter plural noun : ") plural.append(pn) adjective = [] -for i in range(2): +for _ in range(2): a = input("Enter adjective : ") adjective.append(a) adverb = input("Enter adverb : ") @@ -17,7 +17,21 @@ body_part = input("Enter any body part : ") print("An inspector from the Department of Health and ", random.choice(noun) , " Services paid a surprise visit to our " , random.choice(adjective) , " school cafeteria.") print("The lunch special, prepared by our " , random.choice(adjective) , "dietician, was spaghetti and " , random.choice(noun) , " balls with a choice of either a " , random.choice(noun) , " salad or French " , random.choice(plural) , ".") -print("The inspector found the meat-" , random.choice(plural) , " to be overcooked and discovered a live " , random.choice(noun) , " in the fries,causing him to have a " + body_part + " ache.") +print( + "The inspector found the meat-", + random.choice(plural), + " to be overcooked and discovered a live ", + random.choice(noun), + f" in the fries,causing him to have a {body_part} ache.", +) print("In response, he threw up all over his " , random.choice(plural) , ".") -print("In his report, the inspector " + adverb + " recommended that the school cafeteria serve only nutritious " , random.choice(plural) , " as well as low-calorie " , random.choice(plural) , " and that all of the saturated " , random.choice(plural) , " be eliminated.") -print("He rated the cafeteria a " + letter + "-minus.") +print( + f"In his report, the inspector {adverb} recommended that the school cafeteria serve only nutritious ", + random.choice(plural), + " as well as low-calorie ", + random.choice(plural), + " and that all of the saturated ", + random.choice(plural), + " be eliminated.", +) +print(f"He rated the cafeteria a {letter}-minus.") diff --git a/Mail_Checker/mail_checker.py b/Mail_Checker/mail_checker.py index fcc21f12..57c15fce 100644 --- a/Mail_Checker/mail_checker.py +++ b/Mail_Checker/mail_checker.py @@ -17,29 +17,29 @@ def readMails(address): result, data = mail.search(None, '(FROM '+'"'+address+'")') #If you would like to view mails that are sent to another mail, change FROM into TO ids = data[0] # data is a list. - id_list = ids.split() + id_list = ids.split() latest_email_id = id_list[-1] # gets the latest mail from the particular user - + result, data = mail.fetch(latest_email_id, "(RFC822)") - + basic_email = data[0][1] # contains all information including payloads and html content index_start1 = basic_email.index(b'Subject') #Starting index for your subject index_end1 = index_start1 + 40 # Change the value of 40 into any other value to suit your preferences - + subject = basic_email[index_start1:index_end1] #seperating the subject alone from the rest of the basic email - - + + subject = subject.strip(b'b\'Subject:') #removing additional unneccessary data from the subject subject_end = subject.index(b'\r') - print('-------FROM '+address+'-------\n\n') #Printing the emails - print("Subject: ", subject[0:subject_end], '\n\n') + print(f'-------FROM {address}' + '-------\n\n') + print("Subject: ", subject[:subject_end], '\n\n') diff --git a/Minesweeper_game/minesweeper.py b/Minesweeper_game/minesweeper.py index 1c409a5c..4475a631 100644 --- a/Minesweeper_game/minesweeper.py +++ b/Minesweeper_game/minesweeper.py @@ -72,7 +72,7 @@ def __str__(self): visible_board[row][col] = str(self.board[row][col]) else: visible_board[row][col] = ' ' - + string_rep = '' widths = [] for idx in range(self.dim_size): @@ -84,21 +84,20 @@ def __str__(self): ) # print the csv strings - indices = [i for i in range(self.dim_size)] - indices_row = ' ' + indices = list(range(self.dim_size)) cells = [] for idx, col in enumerate(indices): - format = '%-' + str(widths[idx]) + "s" + format = f'%-{str(widths[idx])}s' cells.append(format % (col)) - indices_row += ' '.join(cells) + indices_row = ' ' + ' '.join(cells) indices_row += ' \n' - + for i in range(len(visible_board)): row = visible_board[i] string_rep += f'{i} |' cells = [] for idx, col in enumerate(row): - format = '%-' + str(widths[idx]) + "s" + format = f'%-{str(widths[idx])}s' cells.append(format % (col)) string_rep += ' |'.join(cells) string_rep += ' |\n' diff --git a/Password Generator/password_generator.py b/Password Generator/password_generator.py index 59be91c2..7e3b9787 100644 --- a/Password Generator/password_generator.py +++ b/Password Generator/password_generator.py @@ -18,7 +18,9 @@ def process(): all = lower + upper + num + special ran = random.sample(all,length) password = "".join(ran) - messagebox.showinfo('Result', 'Your password {} \n\nPassword copied to clipboard'.format(password)) + messagebox.showinfo( + 'Result', f'Your password {password} \n\nPassword copied to clipboard' + ) pyperclip.copy(password) string_pass = StringVar() diff --git a/Rock_Paper_Scissors_Spock/main.py b/Rock_Paper_Scissors_Spock/main.py index c2f9efb8..90c0b050 100644 --- a/Rock_Paper_Scissors_Spock/main.py +++ b/Rock_Paper_Scissors_Spock/main.py @@ -88,8 +88,7 @@ print("Invalid response \nComputron Wins!") computerPoints += 1 - # DRAW, SAME CHOICES - elif player == computer: + else: print("Draw, Player and Computron gets 1 point") playerPoints += 1 computerPoints += 1 diff --git a/Screenpet/screenpet.py b/Screenpet/screenpet.py index cb272791..e477ee9b 100644 --- a/Screenpet/screenpet.py +++ b/Screenpet/screenpet.py @@ -45,7 +45,7 @@ def cheeky(event): return def show_happy(event): - if(20 <= event.x and event.x < 350) and (20 <= event.y and event.y <= 350): + if 20 <= event.x < 350 and 20 <= event.y <= 350: c.itemconfigure(cheek_left, state = NORMAL) c.itemconfigure(cheek_right, state = NORMAL) c.itemconfigure(mouth_happy, state = NORMAL) diff --git a/Shape_Recognition/main.py b/Shape_Recognition/main.py index 3d836e3f..7c7c65cf 100644 --- a/Shape_Recognition/main.py +++ b/Shape_Recognition/main.py @@ -18,14 +18,29 @@ x, y, w, h = cv2.boundingRect(cnt) ratio = float(w)/h if ratio >= 0.9 and ratio <= 1.1: - IMAGE = cv2.drawContours(IMAGE, [cnt], -1, (0,255,0), 3) SQUARES = SQUARES + 1 else: - IMAGE = cv2.drawContours(IMAGE, [cnt], -1, (0,255,0), 3) RECTANGLES = RECTANGLES + 1 -cv2.putText(IMAGE, 'Number of SQUARES: ' + str(SQUARES), (h+500, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) -cv2.putText(IMAGE, 'Number of RECTANGLES: ' + str(RECTANGLES), (h+500, 200), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) + IMAGE = cv2.drawContours(IMAGE, [cnt], -1, (0,255,0), 3) +cv2.putText( + IMAGE, + f'Number of SQUARES: {str(SQUARES)}', + (h + 500, 50), + cv2.FONT_HERSHEY_SIMPLEX, + 0.6, + (0, 255, 0), + 2, +) +cv2.putText( + IMAGE, + f'Number of RECTANGLES: {str(RECTANGLES)}', + (h + 500, 200), + cv2.FONT_HERSHEY_SIMPLEX, + 0.6, + (0, 255, 0), + 2, +) cv2.imshow("Shapes", IMAGE) cv2.waitKey(0) diff --git a/Slideshare to PDF/main.py b/Slideshare to PDF/main.py index b111e05e..9627d5b6 100644 --- a/Slideshare to PDF/main.py +++ b/Slideshare to PDF/main.py @@ -34,7 +34,7 @@ def get_pdf(): # List to store all the image objects imagesJPG = [] - for index, link in enumerate(imgSRC): + for link in imgSRC: try: # Get image content from the image url im = requests.get(link) @@ -57,7 +57,7 @@ def get_pdf(): ) info_label_2.configure(text=f"File Downloaded to\n{path}") else: - info_label_2.configure(text=f"Please provide a valid link") + info_label_2.configure(text="Please provide a valid link") # Basic Tkinter window setup diff --git a/Smart_Calculator/calculator.py b/Smart_Calculator/calculator.py index 2c46b4eb..f8d47a21 100644 --- a/Smart_Calculator/calculator.py +++ b/Smart_Calculator/calculator.py @@ -17,7 +17,7 @@ def mod(a,b): def lcm(a,b): if a<0 or b<0: return - L = a if a > b else b + L = max(a, b) while L <= a * b: if L%a == 0 and L%b ==0: return L @@ -25,7 +25,7 @@ def lcm(a,b): def hcf(a,b): if a<0 or b<0: return - H = a if a= 1: if a%H == 0 and b%H ==0: return H diff --git a/Snake_game/main.py b/Snake_game/main.py index 2ae08f22..ba81cc98 100644 --- a/Snake_game/main.py +++ b/Snake_game/main.py @@ -27,7 +27,7 @@ def score(score): # Size and font of score label (Top-Left) score_font = pygame.font.SysFont("arial", 15) - value = score_font.render(" Score: " + str(score), True, white) + value = score_font.render(f" Score: {str(score)}", True, white) display.blit(value, [0, 0]) # Render Snake body @@ -124,9 +124,7 @@ def gameLoop(): pygame.draw.rect( display, red, [foodx, foody, snake_block, snake_block]) - snake_Head = [] - snake_Head.append(x1) - snake_Head.append(y1) + snake_Head = [x1, y1] snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: diff --git a/Speaking_Wikipedia/speaking_wikipedia.py b/Speaking_Wikipedia/speaking_wikipedia.py index 3f14e084..74424abb 100644 --- a/Speaking_Wikipedia/speaking_wikipedia.py +++ b/Speaking_Wikipedia/speaking_wikipedia.py @@ -10,9 +10,7 @@ def page(title: str, sentences = 2): :return: (str) the summary of the Wikipedia page """ - content = wikipedia.summary(title, sentences = sentences) - - return content + return wikipedia.summary(title, sentences = sentences) def voicing_text(text): @@ -43,7 +41,7 @@ def main(): specify_num_of_sentences = input("Do you want to specify the number of sentences (default is 2)? (y/n): ") - if specify_num_of_sentences == "y" or specify_num_of_sentences == "Y": + if specify_num_of_sentences in ["y", "Y"]: num_of_sentences = input("Enter the number of sentences to include in the summary: ") diff --git a/Spinning Donut/spinningdonut.py b/Spinning Donut/spinningdonut.py index ac6ba1b2..0361f14c 100644 --- a/Spinning Donut/spinningdonut.py +++ b/Spinning Donut/spinningdonut.py @@ -73,11 +73,11 @@ def text_display(letter, x_start, y_start): t = c * h * g - f * e x = int(x_offset + 40 * D * (l * h * m - t * n)) # 3D x coordinate after rotation y = int(y_offset + 20 * D * (l * h * n + t * m)) # 3D y coordinate after rotation - o = int(x + columns * y) + o = int(x + columns * y) N = int(8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n)) # luminance index if rows > y and y > 0 and x > 0 and columns > x and D > z[o]: z[o] = D - b[o] = chars[N if N > 0 else 0] + b[o] = chars[max(N, 0)] if y_start == rows * y_separator - y_separator: y_start = 0 @@ -85,16 +85,11 @@ def text_display(letter, x_start, y_start): for i in range(len(b)): A += 0.00004 # for faster rotation change to bigger value B += 0.00002 # for faster rotation change to bigger value - if i == 0 or i % columns: - text_display(b[i], x_start, y_start) - x_start += x_separator - else: + if i != 0 and not i % columns: y_start += y_separator x_start = 0 - text_display(b[i], x_start, y_start) - x_start += x_separator - - + text_display(b[i], x_start, y_start) + x_start += x_separator pygame.display.update() hue += 0.005 diff --git a/Sqlite-crud/main.py b/Sqlite-crud/main.py index be1003ea..ad1d0fb9 100644 --- a/Sqlite-crud/main.py +++ b/Sqlite-crud/main.py @@ -93,7 +93,7 @@ def add_product(self): query = 'INSERT INTO product VALUES(NULL, ?, ?)' parameters = (self.name.get(), self.price.get()) self.run_query(query, parameters) - self.message['text'] = 'Product {} added Successfully'.format(self.name.get()) + self.message['text'] = f'Product {self.name.get()} added Successfully' self.name.delete(0, END) self.price.delete(0, END) else: @@ -111,7 +111,7 @@ def delete_product(self): name = self.tree.item(self.tree.selection())['text'] query = 'DELETE FROM product WHERE name = ?' self.run_query(query, (name, )) - self.message['text'] = 'Record {} deleted Successfully'.format(name) + self.message['text'] = f'Record {name} deleted Successfully' self.get_products() def edit_product(self): @@ -149,7 +149,7 @@ def edit_records(self, new_name, name, new_price, old_price): parameters = (new_name, new_price,name, old_price) self.run_query(query, parameters) self.edit_wind.destroy() - self.message['text'] = 'Record {} updated successfylly'.format(name) + self.message['text'] = f'Record {name} updated successfylly' self.get_products() if __name__ == '__main__': diff --git a/Stack_structure/main.py b/Stack_structure/main.py index 722718ad..b1cbc6a9 100644 --- a/Stack_structure/main.py +++ b/Stack_structure/main.py @@ -11,7 +11,7 @@ def push(self, data): print(f"Adding {data} to the top of the stack") # If there is no data, we add the value in the top element and return - if self.top == None: + if self.top is None: self.top = Node(data) return new_node = Node(data) @@ -20,7 +20,7 @@ def push(self, data): def pop(self): # If there is no data in the top node, we return - if self.top == None: + if self.top is None: print ("There is no item on the stack to unstack") return diff --git a/Star_Pyramid/star_pyramid.py b/Star_Pyramid/star_pyramid.py index 9356d745..c6952b18 100644 --- a/Star_Pyramid/star_pyramid.py +++ b/Star_Pyramid/star_pyramid.py @@ -8,18 +8,18 @@ i = 1 k = num - while i < (num + 1) : + while i < k + 1: print(" " * k, end = "") j = 0 - + while j <= t: print("*", "", end="") - j = j + 1 - - i = i + 1 + j += 1 + + i += 1 t = t + 1 - k = k - 1 - + k -= 1 + print() cont = input("Are you want to continue? (Enter 'y' to continue or 'q' to quit : ").lower() \ No newline at end of file diff --git a/Sudoku_solver/main.py b/Sudoku_solver/main.py index c9affafa..045a5e17 100644 --- a/Sudoku_solver/main.py +++ b/Sudoku_solver/main.py @@ -3,7 +3,7 @@ def generate_board(num): base = 3 - side = base * base + side = base**2 def pattern(r, c): return (base * (r % base) + r // base + c) % side @@ -15,7 +15,7 @@ def shuffle(s): rBase = range(base) rows = [g * base + r for g in shuffle(rBase) for r in shuffle(rBase)] cols = [g * base + c for g in shuffle(rBase) for c in shuffle(rBase)] - nums = shuffle(range(1, base * base + 1)) + nums = shuffle(range(1, base**2 + 1)) # randomized baseline board_tmp = [[nums[pattern(r, c)] for c in cols] for r in rows] @@ -26,12 +26,7 @@ def shuffle(s): # remove numbers of the board squares = side * side - if num == 0: - # default number of empty slots - empties = squares * 3 // 4 - else: - # given number of empty slots - empties = 81 - num + empties = squares * 3 // 4 if num == 0 else 81 - num # looping a randomized board for the amount of empty mubers for p in sample(range(squares), empties): # set nubers to 0 of the randomized board @@ -82,7 +77,7 @@ def print_board(bo): print(bo[i][j]) else: # printing each character with spaces - print(str(bo[i][j]) + " ", end="") + print(f"{str(bo[i][j])} ", end="") print("") @@ -123,13 +118,11 @@ def next_empty(bo): def solve(bo): - # searching for next empty solt - slot = next_empty(bo) - if not slot: + if slot := next_empty(bo): + row, col = slot + else: # return True if there is no empty slot return True - else: - row, col = slot # looping number 1 to 9 for i in range(1, 10): # check if the number is possible in this location diff --git a/TEXTVENTURE/game.py b/TEXTVENTURE/game.py index 3fadb533..bb65687d 100644 --- a/TEXTVENTURE/game.py +++ b/TEXTVENTURE/game.py @@ -330,50 +330,39 @@ def main_screen(): def player_interact(action): if ZONE_MAP[player.location]["SOLVED"]: print("\nYou visited this place earlier. Move further!\n") - return - - else: - if action == 'inspect': - print("\n" + ZONE_MAP[player.location]["DESCRIPTION"]) - return - - elif action == 'examine' or action == 'interact': - print("\n" + ZONE_MAP[player.location]["EXAMINATION"]) - return - - elif action == 'look': + elif action == 'inspect': + print("\n" + ZONE_MAP[player.location]["DESCRIPTION"]) + elif action in ['examine', 'interact']: + print("\n" + ZONE_MAP[player.location]["EXAMINATION"]) + elif action == 'look': # Display effects if there are any. - if len(player.effects) > 0: - print("\nYou have entitled with the following effects:") - for effect in player.effects: - sys.stdout.write("\t" + effect + "\n") - sys.stdout.flush() - time.sleep(0.5) - - return + if len(player.effects) > 0: + print("\nYou have entitled with the following effects:") + for effect in player.effects: + sys.stdout.write("\t" + effect + "\n") + sys.stdout.flush() + time.sleep(0.5) - else: - print("\nYou have no effects.\n") - return + else: + print("\nYou have no effects.\n") + else: + print("\nI don't understand that command.\nPlease enter a valid command. ⚠️\n") - else: - print("\nI don't understand that command.\nPlease enter a valid command. ⚠️\n") - return + return # Movement Handler def movement_handler(destination): if destination == '': print("\nYou cannot go that way.\n") - return - else: print("\n" + "You moved to the " + destination + ".") player.location = destination ZONE_MAP [player.location]["SOLVED"] = True show_location() - return + + return # Player Movement def player_move(myAction): @@ -407,7 +396,7 @@ def player_move(myAction): # Player Location def show_location(): print("\n" + ("#" * (4 + len(player.location))) ) - print("# " + player.location.upper() + " #") + print(f"# {player.location.upper()} #") print("# " + ZONE_MAP[player.location]["DESCRIPTION"] + " #") print("\n" + ("#" * (4 + len(player.location))) ) @@ -438,11 +427,7 @@ def prompt(): the game will end and the player will be congratulated. """ def ifSolved(): - count = 0 - - for obj in ZONE_MAP: - if obj["SOLVED"]: count += 1 - + count = sum(1 for obj in ZONE_MAP if obj["SOLVED"]) if count == len(ZONE_MAP): player.game_over = True # Main Game Loop @@ -506,7 +491,7 @@ def setup_game(): sys.stdout.write(char) sys.stdout.flush() time.sleep(0.02) - + # wait for user to press enter print("\nPress any key on the keyboard to continue. ") input("\n> ") @@ -543,17 +528,17 @@ def setup_game(): player.mp = 0 player.effects = ['Medieval', 'Colonial', 'Futuristic'] - elif player.trade == 'miner': - player.hp = 130 - player.mp = 0 - player.effects = ['Staircasing', 'Blast', 'Sea'] - elif player.trade == 'fighter': player.hp = 150 player.mp = 50 player.effects = ['Pillager Power', 'Warden Garden', 'Nether Nomad'] - + + elif player.trade == 'miner': + player.hp = 130 + player.mp = 0 + player.effects = ['Staircasing', 'Blast', 'Sea'] + # Welcoming the player O1 = "\nWelcome, " + player.name + "! The " + player.trade.upper() + "\n" for char in O1: @@ -566,7 +551,7 @@ def setup_game(): sys.stdout.flush() time.sleep(0.03) - O2 = player.username + " is your username" + ".\n" + O2 = f"{player.username} is your username" + ".\n" for char in O2: if char == " ": sys.stdout.write(char) @@ -577,7 +562,7 @@ def setup_game(): sys.stdout.flush() time.sleep(0.03) - O3 = "Your health is " + str(player.hp) + ".\n" + O3 = f"Your health is {str(player.hp)}" + ".\n" for char in O3: if char == " ": sys.stdout.write(char) @@ -589,7 +574,7 @@ def setup_game(): time.sleep(0.03) - O4 = "Your magic points are " + str(player.mp) + "." + O4 = f"Your magic points are {str(player.mp)}." for char in O4: if char == " ": sys.stdout.write(char) diff --git a/TestTypingSpeed/TestTypingSpeed.py b/TestTypingSpeed/TestTypingSpeed.py index 981fa391..57859266 100644 --- a/TestTypingSpeed/TestTypingSpeed.py +++ b/TestTypingSpeed/TestTypingSpeed.py @@ -36,12 +36,11 @@ def typing_speed(): if __name__ == "__main__": - print("Let's Start") + print("Let's Start") typing_speed() - while True : - if input("Do you want to try again? (y/n): ")=="y": - print("\n") - typing_speed() - else: - break \ No newline at end of file + while True: + if input("Do you want to try again? (y/n): ") != "y": + break + print("\n") + typing_speed() \ No newline at end of file diff --git a/Tic_Tac_Toe/tic_tac_toe.py b/Tic_Tac_Toe/tic_tac_toe.py index 25cec8b2..c5a37870 100644 --- a/Tic_Tac_Toe/tic_tac_toe.py +++ b/Tic_Tac_Toe/tic_tac_toe.py @@ -2,8 +2,8 @@ #new version import os -#initialize -board = [' ' for x in range(10)] +#initialize +board = [' ' for _ in range(10)] FirstRun = True #insert tic tac toe symbol to screen @@ -15,17 +15,14 @@ def spaceIsFree(pos): return board[pos] == ' ' def printBoard(board): - print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) + print(f' {board[1]} | {board[2]} | {board[3]}') print('-----------') - print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) + print(f' {board[4]} | {board[5]} | {board[6]}') print('-----------') - print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) + print(f' {board[7]} | {board[8]} | {board[9]}') def isBoardFull(board): - if board.count(' ') >= 2: - return False - else: - return True + return board.count(' ') < 2 def IsWinner(b,l): @@ -67,30 +64,13 @@ def computerMove(): boardcopy = board[:] boardcopy[i] = let if IsWinner(boardcopy, let): - move = i - return move - - cornersOpen = [] - for i in possibleMoves: - if i in [1, 3, 7, 9]: - cornersOpen.append(i) - - if len(cornersOpen) > 0: - move = selectRandom(cornersOpen) - return move - + return i + if cornersOpen := [i for i in possibleMoves if i in [1, 3, 7, 9]]: + return selectRandom(cornersOpen) if 5 in possibleMoves: - move = 5 - return move - - edgesOpen = [] - for i in possibleMoves: - if i in [2, 4, 6, 8]: - edgesOpen.append(i) - - if len(edgesOpen) > 0: - move = selectRandom(edgesOpen) - return move + return 5 + if edgesOpen := [i for i in possibleMoves if i in [2, 4, 6, 8]]: + return selectRandom(edgesOpen) def selectRandom(li): import random @@ -100,7 +80,7 @@ def selectRandom(li): def StartTheGame(): global board - board = [' ' for x in range(10)] + board = [' ' for _ in range(10)] CleanScreen() print('-------------------------') GamePlay() @@ -119,10 +99,11 @@ def CleanScreen(): #check Tie Game condition def TieGame(): - if isBoardFull(board) and (not((IsWinner(board, 'X')) or (IsWinner(board, 'O')))): - return True - else: - return False + return bool( + isBoardFull(board) + and not (IsWinner(board, 'X')) + and not (IsWinner(board, 'O')) + ) #Score Count scorecount = 0 @@ -132,13 +113,11 @@ def GamePlay(): if scorecount == 0: #if the game is first time ran print("Welcome to the game!") - if scorecount < 0: - #if the score is negative, set it to 0 - scorecount = 0 + scorecount = max(scorecount, 0) printBoard(board) while not(isBoardFull(board)): - + if not(IsWinner(board, 'O')) : playerMove() CleanScreen() @@ -168,13 +147,13 @@ def GamePlay(): FirstRun=False StartTheGame() - else : + else: if TieGame(): print("It's a tie!") x = input("Do you want to play again? (y/n)") - if x.lower() == 'y' or x.lower() =='yes': + if x.lower() in ['y', 'yes']: StartTheGame() - + else: print("GLHF") break \ No newline at end of file diff --git a/Url_Shortener/url_shortner.py b/Url_Shortener/url_shortner.py index a69b84b7..75b81296 100644 --- a/Url_Shortener/url_shortner.py +++ b/Url_Shortener/url_shortner.py @@ -9,7 +9,7 @@ } data = {"long_url": UI} -for i in range(3): +for _ in range(3): result = requests.post("https://api-ssl.bitly.com/v4/shorten", headers=headers, data=json.dumps(data)) if result.status_code == 200: break diff --git a/Wordle_Aid/main.py b/Wordle_Aid/main.py index fdf8c8a2..7364333d 100644 --- a/Wordle_Aid/main.py +++ b/Wordle_Aid/main.py @@ -7,7 +7,7 @@ def find_possible_words(guessed, colors_list, answer_words): possible_words = [] - + @@ -15,11 +15,11 @@ def find_possible_words(guessed, colors_list, answer_words): listword = list(word) #the colons are placeholders so the line marked XYXYXYXY doesn't fail to complete bc theoretical list isn't long enough theoretical_list = [':', ':', ':', ':', ';'] - + for i in range(5): if listword[i] == guessed[i]: theoretical_list[i] = ("green") - listword[i] = ("." + guessed[i]) + listword[i] = f".{guessed[i]}" elif guessed[i] in listword[i]: theoretical_list[i] = ("green") for j in range(5): @@ -28,29 +28,21 @@ def find_possible_words(guessed, colors_list, answer_words): elif guessed[i] in listword: theoretical_list[i] = ("yellow") mini_index = listword.index(guessed[i]) - listword[mini_index] = ("." + guessed[i]) + listword[mini_index] = f".{guessed[i]}" else: theoretical_list[i] = ("gray") - + print(theoretical_list) print(colors_list) print(listword) - + if theoretical_list == colors_list: possible_words.append(word) - - - return(possible_words) - - - - - possible_answers = answer_words -for i in range(6): - + return(possible_words) +for _ in range(6): guessed = list(input("Enter guess: ")) first_letter = input("first letter: ") second_letter = input("second letter: ") @@ -58,15 +50,13 @@ def find_possible_words(guessed, colors_list, answer_words): fourth_letter = input("fourth letter: ") fifth_letter = input("fifth letter: ") - colors_list = [] - colors_list.append(first_letter) - colors_list.append(second_letter) - colors_list.append(third_letter) - colors_list.append(fourth_letter) - colors_list.append(fifth_letter) - - - + colors_list = [ + first_letter, + second_letter, + third_letter, + fourth_letter, + fifth_letter, + ] possible_answers = (find_possible_words(guessed, colors_list, possible_answers)) print(possible_answers) print(len(possible_answers)) diff --git a/Zombie_Game/zombie.py b/Zombie_Game/zombie.py index 398678ac..d7028371 100644 --- a/Zombie_Game/zombie.py +++ b/Zombie_Game/zombie.py @@ -39,11 +39,7 @@ if answer == "1": score += random.randint(10,20) -if answer == "2": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "2" else 3 print("") # ---- question 2 ---- @@ -56,11 +52,7 @@ if answer == "2": score += random.randint(10,20) -if answer == "4": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "4" else 3 print("") # ---- question 3 ---- @@ -73,11 +65,7 @@ if answer == "2": score += random.randint(10,20) -if answer == "1": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "1" else 3 print("") # ---- question 4 ---- @@ -90,11 +78,7 @@ if answer == "1": score += random.randint(10,20) -if answer == "3": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "3" else 3 print("") # ---- question 5 ---- @@ -107,11 +91,7 @@ if answer == "1": score += random.randint(10,20) -if answer == "4": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "4" else 3 print("") # ---- question 6 ---- @@ -124,11 +104,7 @@ if answer == "2": score += random.randint(10,20) -if answer == "1": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "1" else 3 print("") # ---- question 7 ---- @@ -141,11 +117,7 @@ if answer == "2": score += random.randint(10,20) -if answer == "3": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "3" else 3 print("") # ---- question 8 ---- @@ -158,11 +130,7 @@ if answer == "3": score += random.randint(10,20) -if answer == "4": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "4" else 3 print("") # ---- question 9 ---- @@ -175,11 +143,7 @@ if answer == "1": score += random.randint(10,20) -if answer == "2": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "2" else 3 print("") # ---- question 10 ---- @@ -192,16 +156,12 @@ if answer == "3": score += random.randint(10,20) -if answer == "4": - score += random.randint(5,10) -else: - score += 3 - +score += random.randint(5,10) if answer == "4" else 3 print("") # ---- end ---- print("The results are in!") -print("You scored a {}%".format(score)) +print(f"You scored a {score}%") if score == (0,5): print('You would be one of the first peopple to die in the apocalypse.\nYou panic at the sight of a zombie and have no survival skills, getting eaten within an hour.\nPathetic.') diff --git a/infix_postfix_calculator/main.py b/infix_postfix_calculator/main.py index f76f11cb..a5cf28eb 100644 --- a/infix_postfix_calculator/main.py +++ b/infix_postfix_calculator/main.py @@ -9,7 +9,7 @@ def parse_infix(input): if not input[i + 1].isdigit() and input[i + 1] != '.': ret += " " else: - ret += tmp + " " + ret += f"{tmp} " return ret @@ -21,31 +21,23 @@ def convert_to_postfix(infix): for token in infix_arr: if token == "(": s.append(token) - elif token == "+": - while s and s[-1] in ["+", "-", "*", "/"]: - ret += s.pop() + " " - s.append(token) - elif token == "-": - while s and s[-1] in ["+", "-", "*", "/"]: - ret += s.pop() + " " - s.append(token) - elif token == "*": - while s and s[-1] in ["*", "/"]: - ret += s.pop() + " " - s.append(token) - elif token == "/": - while s and s[-1] in ["*", "/"]: - ret += s.pop() + " " - s.append(token) elif token == ")": while s and s[-1] != "(": - ret += s.pop() + " " + ret += f"{s.pop()} " if s and s[-1] == "(": s.pop() + elif token in ["*", "/"]: + while s and s[-1] in ["*", "/"]: + ret += f"{s.pop()} " + s.append(token) + elif token in ["+", "-"]: + while s and s[-1] in ["+", "-", "*", "/"]: + ret += f"{s.pop()} " + s.append(token) else: - ret += token + " " + ret += f"{token} " while s: - ret += s.pop() + " " + ret += f"{s.pop()} " return ret @@ -58,18 +50,17 @@ def calculate_postfix(postfix): if token in ["+", "-", "*", "/"]: b = s.pop() a = s.pop() - if token == "+": + if token == "*": + s.append(a * b) + elif token == "+": s.append(a + b) elif token == "-": s.append(a - b) - elif token == "*": - s.append(a * b) elif token == "/": s.append(a / b) else: s.append(float(token)) - ret = str(s.pop()) - return ret + return str(s.pop()) from tkinter import *