diff --git a/1)knapsack_recursive.py b/1)knapsack_recursive.py index f0dd81b5..1933aa67 100644 --- a/1)knapsack_recursive.py +++ b/1)knapsack_recursive.py @@ -1,11 +1,10 @@ def knapsack_recursive(wt,val,W,n): if n==0 or W==0: return 0 + if wt[n-1]<=W: + return max(val[n-1]+knapsack_recursive(wt,val,W-wt[n-1],n-1),knapsack_recursive(wt,val,W,n-1)) else: - if wt[n-1]<=W: - return max(val[n-1]+knapsack_recursive(wt,val,W-wt[n-1],n-1),knapsack_recursive(wt,val,W,n-1)) - elif wt[n-1]>W: - return knapsack_recursive(wt,val,W,n-1) + return knapsack_recursive(wt,val,W,n-1) W = 6 wt = [1,2,3,6] val = [1,2,4,6] diff --git a/2048game.py b/2048game.py index 868279e8..c4cacbab 100644 --- a/2048game.py +++ b/2048game.py @@ -10,13 +10,7 @@ # at the start def start_game(): - # declaring an empty list then - # appending 4 list each with four - # elements as 0. - mat =[] - for i in range(4): - mat.append([0] * 4) - + mat = [[0] * 4 for _ in range(4)] # printing controls for user print("Commands are as follows : ") print("'W' or 'w' : Move Up") @@ -75,19 +69,17 @@ def get_current_state(mat): # cell then also game is not yet over for i in range(3): for j in range(3): - if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]): + if mat[i][j] in [mat[i + 1][j], mat[i][j + 1]]: return 'GAME NOT OVER' for j in range(3): if(mat[3][j]== mat[3][j + 1]): return 'GAME NOT OVER' - for i in range(3): - if(mat[i][3]== mat[i + 1][3]): - return 'GAME NOT OVER' - - # else we have lost the game - return 'LOST' + return next( + ('GAME NOT OVER' for i in range(3) if (mat[i][3] == mat[i + 1][3])), + 'LOST', + ) # all the functions defined below # are for left swap initially. @@ -101,13 +93,7 @@ def compress(mat): # any change happened or not changed = False - # empty grid - new_mat = [] - - # with all cells empty - for i in range(4): - new_mat.append([0] * 4) - + new_mat = [[0] * 4 for _ in range(4)] # here we will shift entries # of each cell to it's extreme # left row by row @@ -119,13 +105,13 @@ def compress(mat): # in respective row for j in range(4): if(mat[i][j] != 0): - + # if cell is non empty then # we will shift it's number to # previous empty cell in that row # denoted by pos variable new_mat[i][pos] = mat[i][j] - + if(j != pos): changed = True pos += 1 diff --git a/ATM.py b/ATM.py index da2c64ab..b4e8201b 100644 --- a/ATM.py +++ b/ATM.py @@ -16,7 +16,7 @@ print("Please Press 2 To Make a Withdrawl.") print("Please Press 3 To Pay in.") print("Please Press 4 To Return Card.") - + option = int(input("\nWhat Would you like to Choose?: ")) if option == 1: @@ -31,7 +31,7 @@ option2 = ("y") withdrawl = float(input("\nHow Much Would you like to withdraw? 10, 20, 40, 60, 80, 100 for other enter 1: ")) - if withdrawl in [10, 20, 40, 60, 80, 100]: + if withdrawl in {10, 20, 40, 60, 80, 100}: balance = balance - withdrawl print(f"\nYour balance after the withdrawl is ${balance}") restart = input("\nWould You like to do something else? ") @@ -73,9 +73,9 @@ print("\nPlease enter a correct number.\n") restart = ("y") - elif pin != (1234): + else: print("\nINCORRECT PIN!!\n") - chances = chances - 1 + chances -= 1 if chances == 0: print("Calling the Police...\n") diff --git a/Age Calculator.py b/Age Calculator.py index af545f45..d4ccb099 100644 --- a/Age Calculator.py +++ b/Age Calculator.py @@ -18,7 +18,7 @@ def main(): age = calculate_age(datetime.date(year, month, day)) # Print the age - print("Your age is: {}".format(age)) + print(f"Your age is: {age}") if __name__ == '__main__': main() \ No newline at end of file diff --git a/Areas.py b/Areas.py index 80518366..8b67c0d9 100644 --- a/Areas.py +++ b/Areas.py @@ -3,21 +3,17 @@ import math def square(side): - area = side * side - return area + return side * side def rectangle(length, breadth): - area = length * breadth - return area + return length * breadth def triangle(side1, side2, side3): s = (side1 + side2 + side3)/2 - area = math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) - return area + return math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) def circle(radius): - area = 3.14 * radius * radius - return area + return 3.14 * radius * radius final_area = 0.0 print("Choose the shape you want to calculate area of: ") diff --git a/ArmstrongNumberCheck.py b/ArmstrongNumberCheck.py index 1cfa836c..d6eeddf6 100644 --- a/ArmstrongNumberCheck.py +++ b/ArmstrongNumberCheck.py @@ -1,9 +1,5 @@ print("An Armstrong Number is a number which is equal to the sum of the cubes of it's digits.") inputNumber = input("Enter a number to check if it's an Armstrong Number or not: ") -sumOfCubes=0 - -for digit in inputNumber: - sumOfCubes+=int(digit)**3 - +sumOfCubes = sum(int(digit)**3 for digit in inputNumber) if sumOfCubes==int(inputNumber): print(inputNumber,"is an Armstrong Number.") else: print(inputNumber,"is NOT an Armstrong Number.") diff --git a/Average.py b/Average.py index da6f0da3..ae617b5b 100644 --- a/Average.py +++ b/Average.py @@ -1,6 +1,6 @@ n=int(input("Enter the number of elements to be inserted: ")) a=[] -for i in range(0,n): +for _ in range(0,n): elem=int(input("Enter element: ")) a.append(elem) avg=sum(a)/n diff --git a/BankGame.py b/BankGame.py index 6560f87e..cb41334e 100644 --- a/BankGame.py +++ b/BankGame.py @@ -2,14 +2,14 @@ import random class BankGame : @staticmethod - def main( args) : + def main( args): print("---WELCOME TO ELIX BANKING SERVICES---") print("") print("________________________") print("Enter your name: ") name = input() # I am inserting do loop to make the program run forever under correct inputs. - print("Hi, " + name + "\bWelcome to my program!") + print(f"Hi, {name}" + "\bWelcome to my program!") print("____________________________") print("Do you want to start/repeat the program?") print("Enter Y for Yes and N for No: ") @@ -20,14 +20,12 @@ def main( args) : print("If you don\'t know the password refer the first line of the program") print("Please enter the password: ") # Condition when the statement goes true i.e.- temp equals 1 - while True : - if (temp == 'Y' or temp == 'y') : - if (passw == 4758) : + while True: + if temp in ['Y', 'y']: + if (passw == 4758): print("") print("Your initial account balance is Rs. 10000") - # Using for statement to perform 5 operation on each login - x = 0 - while (x <= 6) : + for _ in range(7): print("0. Exit") print("1. Deposit") print("2. Withdraw") @@ -41,57 +39,56 @@ def main( args) : print(captha) print("Enter the number shown above: ") verify = int(input()) - if (verify == captha) : + if (verify == captha): # If captha gets matched, then these switch statements are executed. - if (choice==0): - print("BYE!......" + name + " HAVE A NICE DAY!") + if choice == 0: + print(f"BYE!......{name} HAVE A NICE DAY!") print("__________________________") print("@author>[@programmer-yash") print("Please comment here or open an issue if you have any queries or suggestions!") print("") print("#hacktoberfest") return 0 - elif(choice==1): + elif choice == 1: print("You have chosen to deposit.") print("Enter the amount to deposit : ") deposit = int(input()) bal = bal + deposit - print(str(deposit) + " has been deposited to your account.") - print("Left balance is " + str(bal)) - elif(choice==2): + print(f"{deposit} has been deposited to your account.") + print(f"Left balance is {str(bal)}") + elif choice == 2: print("You have chosen to withdraw.") print("Enter the amount to be withdrawn") withdraw = int(input()) - print(str(+withdraw) + " has been withdrawn from your account.") + print(f"{str(+withdraw)} has been withdrawn from your account.") bal = bal - withdraw print("Check the cash printer.") - print("Left balance is " + str(bal)) - elif(choice==3): + print(f"Left balance is {str(bal)}") + elif choice == 3: print("You have chosen to change passcode.") print("Enter the current passcode: ") check = int(input()) - if (check == passw) : + if (check == passw): print("Enter the new passcode") newP = int(input()) passw = newP - print("Your new password is " + str(newP)) - else : + print(f"Your new password is {passw}") + else: print("Wrong passcode!") - elif(choice==4): + elif choice == 4: print("You have chosen to check balanace.") - print("Your current account balance is " + str(bal)) - elif(choice==5): + print(f"Your current account balance is {str(bal)}") + elif choice == 5: print("You have chosen for customer care.") print("Contact us at:") print(" Email: yash197911@gmail.com") else: print("Wrong choice!!! Choose again...!") - else : + else: print("xCAPTHA NOT CORRECTx") - x += 1 continue - elif(temp == 'N' or temp == 'n') : - print("BYE!......" + name + " HAVE A NICE DAY!") + elif temp in ['N', 'n']: + print(f"BYE!......{name} HAVE A NICE DAY!") print("__________________________") print("@author>[@programmer-offbeat]") print("Please comment here if you have any queries or suggestions!") @@ -101,14 +98,14 @@ def main( args) : print() print("HAPPY CODING!:-)") return 0 - else : + else: print("Err!..... You have entered a wrong choice!") print("Try again....!") # Comdition if password mismatches. if (passw != 4758) : print("You have entered wrong password.....Try again!") - if((temp < 100) == False) : - break + if temp >= 100: + break if __name__=="__main__": diff --git a/Bifurcation diagram .py b/Bifurcation diagram .py index aeac4f41..d41752ea 100644 --- a/Bifurcation diagram .py +++ b/Bifurcation diagram .py @@ -47,14 +47,14 @@ def bif(x0, r): if __name__ == '__main__': # create and configure the process pool with Pool(4) as p: - + for i,ch in enumerate(p.map(bif1,r,chunksize=2500)) : x1=np.ones(len(ch))*r[i] X.append(x1) Y.append(ch) - print("--- %s seconds ---" % (time.time() - start_time)) + print(f"--- {time.time() - start_time} seconds ---") - plt.style.use('dark_background') + plt.style.use('dark_background') plt.plot(X,Y, ".w", alpha=1, ms=1.2) figure = plt.gcf() # get current figure figure.set_size_inches(1920 / 40, 1080 / 40) diff --git a/Blackjack.py b/Blackjack.py index d81e3907..f8c35326 100644 --- a/Blackjack.py +++ b/Blackjack.py @@ -13,15 +13,10 @@ print(logo) cards=[11,2,3,4,5,6,7,8,9,10,10,10,10] -player=[] -computer=[] - player_sum=0 computer_sum=0 -player.append(random.choice(cards)) - - +player = [random.choice(cards)] rand = random.choice(cards) if (rand == 11 and rand + computer_sum > 21): player.append(1) @@ -29,9 +24,7 @@ player.append(rand) -computer.append(random.choice(cards)) - - +computer = [random.choice(cards)] randco = random.choice(cards) if (rand == 11 and rand + computer_sum > 21): computer.append(1) @@ -41,21 +34,21 @@ player_sum+=player[0]+player[1] computer_sum+=computer[0]+computer[1] -while(player_sum<=21): +while (player_sum<=21): print(f"Your cards : {player} ,current score : {player_sum}") print(f"Computer's first card : {computer[0]}") accept=input("Type y to get another card , Type n to pass : ") - if(accept=='y'): - rand=random.choice(cards) - if(rand==11 and rand+player_sum>21): - player_sum+=1 - player.append(1) - else: - player_sum+=rand - player.append(rand) - else:break + if accept != 'y': + break + rand=random.choice(cards) + if(rand==11 and rand+player_sum>21): + player_sum+=1 + player.append(1) + else: + player_sum+=rand + player.append(rand) if player_sum>21: print(f"Your cards : {player} ,current score : {player_sum}") print("You Lost") diff --git a/Count_Number_of_Vowels_in_a_File.py b/Count_Number_of_Vowels_in_a_File.py index 8fb6e6ad..15c34553 100644 --- a/Count_Number_of_Vowels_in_a_File.py +++ b/Count_Number_of_Vowels_in_a_File.py @@ -5,21 +5,17 @@ # Convert the name to string and open the file in read mode fileName = str(input()) -fileHandle = open(fileName, "r") +with open(fileName, "r") as fileHandle: + # Declare a variable to store the number of vowels. Initally it is zero. + count = 0 -# Declare a variable to store the number of vowels. Initally it is zero. -count = 0 + # create an array of all the vowels (upper and lower case) that can be used to compare and determine if a character is a vowel + vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] -# create an array of all the vowels (upper and lower case) that can be used to compare and determine if a character is a vowel -vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] - -# Read each character and compare it to the characters in the array. If found in the vowels array, then increase count. -for char in fileHandle.read(): - if char in vowels: - count = count+1 - -# Close the file -fileHandle.close() + # Read each character and compare it to the characters in the array. If found in the vowels array, then increase count. + for char in fileHandle.read(): + if char in vowels: + count = count+1 # Print the count to the screen for the user to see. print("\nThe total number of vowels in the text are:") diff --git a/DjikistraAlgorithm.py b/DjikistraAlgorithm.py index 65238794..34891dd8 100644 --- a/DjikistraAlgorithm.py +++ b/DjikistraAlgorithm.py @@ -23,11 +23,8 @@ def dijsktra(graph, initial): min_node = None for node in nodes: if node in visited: - if min_node is None: + if min_node is None or visited[node] < visited[min_node]: min_node = node - elif visited[node] < visited[min_node]: - min_node = node - if min_node is None: break diff --git a/Extracting_Numbers_from_textString.py b/Extracting_Numbers_from_textString.py index fcd50640..aad125d7 100644 --- a/Extracting_Numbers_from_textString.py +++ b/Extracting_Numbers_from_textString.py @@ -2,19 +2,13 @@ sentence="Ramu have 150 Apples and 10 bananas" sentence2="Ramu Sell 1 Apple at 15.5 Rupees" -list1=[] -list2=[] - sum=0 sum2=0 # split is used to split sentence # This code is not fit for Decimal Nos. print("---------------EXTRACTING NUMBER FROM STRING---------------\n") -for word in sentence.split(): - if word.isdigit(): - list1.append(word) - +list1 = [word for word in sentence.split() if word.isdigit()] print("New List",list1) @@ -25,11 +19,7 @@ print("No. without Fraction \nsum=",sum,"\n") -# If Decimal Numbers occured in the Sentence -for word2 in sentence2.split(): - if not word2.isalpha(): - list2.append(word2) - +list2 = [word2 for word2 in sentence2.split() if not word2.isalpha()] print("New List",list2) # Calculating the SUM diff --git a/GUI_Tic_Tac_Toe_pvp.py b/GUI_Tic_Tac_Toe_pvp.py index 5e600a40..a1bc957a 100644 --- a/GUI_Tic_Tac_Toe_pvp.py +++ b/GUI_Tic_Tac_Toe_pvp.py @@ -61,7 +61,7 @@ def Retry(): for i in ('row1','row2','row3'): for j in range(3): - globals()[i+str(j+1)].configure(text=f' ') + globals()[i+str(j+1)].configure(text=' ') globals()[i+str(j+1)]['state']='active' finish.rtry.pack_forget() player_win.pack_forget() @@ -83,12 +83,9 @@ def win_check(): ): - if Xcount>Ocount: - string='Player 1(X) won' - else: - string='Player 2(O) won' + string = 'Player 1(X) won' if Xcount>Ocount else 'Player 2(O) won' finish(string) - + if not game_over: if (Xcount==5 and Ocount==4 or Xcount==4 and Ocount==5): @@ -108,7 +105,12 @@ def win_check(): for i in ('row1','row2','row3'): for j in range(3): - vars()[i+str(j+1)]=tk.Button(vars()[i], text=f' ',bd='1',command=partial(clicked,i+' '+str(j+1))) + vars()[i + str(j + 1)] = tk.Button( + vars()[i], + text=' ', + bd='1', + command=partial(clicked, f'{i} {str(j + 1)}'), + ) vars()[i+str(j+1)].pack(side='left') diff --git a/Guessnumber.py b/Guessnumber.py index 278b02cd..da0ad97e 100644 --- a/Guessnumber.py +++ b/Guessnumber.py @@ -21,7 +21,7 @@ def guessNUmber(number, num , level): while True: - if(level!="hard" and level!="easy"): + if level not in ["hard", "easy"]: print("Invalid Choice") else:break diff --git a/HangmanGame.py b/HangmanGame.py index c9d9d07e..71467eff 100644 --- a/HangmanGame.py +++ b/HangmanGame.py @@ -63,10 +63,10 @@ print(f"The chosen word is {word}") blank_list = [] -for i in range(len(word)): +for _ in range(len(word)): blank_list += "_" end_game=False -while end_game == False: +while not end_game: guess = input("Guess a letter\n") if guess not in word: diff --git a/Human_Readable_Time.py b/Human_Readable_Time.py index 88d8961e..727e9afb 100644 --- a/Human_Readable_Time.py +++ b/Human_Readable_Time.py @@ -2,13 +2,13 @@ def make_readable(seconds): #Function converts an amount of seconds into hours:m seconds = int(seconds) #converts seconds into integer - hour = int(seconds/3600) #Gets hours - minute = int(seconds/60) - (hour*60) #Gets remanining minutes + hour = seconds // 3600 + minute = seconds // 60 - hour*60 second = seconds - (minute*60) - (hour*3600) #Gets remaining seconds - hour = str(hour) if len(str(hour)) > 1 else '0' + str(hour) #adds 0 if the hours,minutes or seconds are only one charachter long - second = str(second) if len(str(second)) > 1 else '0' + str(second) - minute = str(minute) if len(str(minute)) > 1 else '0' + str(minute) + hour = str(hour) if len(str(hour)) > 1 else f'0{str(hour)}' + second = str(second) if len(str(second)) > 1 else f'0{str(second)}' + minute = str(minute) if len(str(minute)) > 1 else f'0{str(minute)}' return f"{hour}:{minute}:{second}" #returns the value diff --git a/Indianflag-Turtle.py b/Indianflag-Turtle.py index 71744244..08b40a77 100644 --- a/Indianflag-Turtle.py +++ b/Indianflag-Turtle.py @@ -1,18 +1,18 @@ import turtle from turtle import* - + #screen for output screen = turtle.Screen() - + # Defining a turtle Instance t = turtle.Turtle() speed(0) - + # initially penup() t.penup() t.goto(-400, 250) t.pendown() - + # Orange Rectangle #white rectangle t.color("orange") @@ -25,7 +25,7 @@ t.end_fill() t.left(90) t.forward(167) - + # Green Rectangle t.color("green") t.begin_fill() @@ -35,7 +35,7 @@ t.left(90) t.forward(167) t.end_fill() - + # Big Blue Circle t.penup() t.goto(70, 0) @@ -44,7 +44,7 @@ t.begin_fill() t.circle(70) t.end_fill() - + # Big White Circle t.penup() t.goto(60, 0) @@ -53,13 +53,13 @@ t.begin_fill() t.circle(60) t.end_fill() - + # Mini Blue Circles t.penup() t.goto(-57, -8) t.pendown() t.color("navy") -for i in range(24): +for _ in range(24): t.begin_fill() t.circle(3) t.end_fill() @@ -67,7 +67,7 @@ t.forward(15) t.right(15) t.pendown() - + # Small Blue Circle t.penup() t.goto(20, 0) @@ -80,11 +80,11 @@ t.goto(0, 0) t.pendown() t.pensize(2) -for i in range(24): +for _ in range(24): t.forward(60) t.backward(60) t.left(15) - + #to hold the #output window turtle.done() \ No newline at end of file diff --git a/JumpSearch.py b/JumpSearch.py index d5b7e0e3..9181f443 100644 --- a/JumpSearch.py +++ b/JumpSearch.py @@ -6,7 +6,7 @@ def jumpSearch( arr , x , n ): # Finding block size to be jumped step = math.sqrt(n) - + # Finding the block where element is # present (if it is present) prev = 0 @@ -15,22 +15,19 @@ def jumpSearch( arr , x , n ): step += math.sqrt(n) if prev >= n: return -1 - + # Doing a linear search for x in # block beginning with prev. while arr[int(prev)] < x: prev += 1 - + # If we reached next block or end # of array, element is not present. if prev == min(step, n): return -1 - + # If element is found - if arr[int(prev)] == x: - return prev - - return -1 + return prev if arr[int(prev)] == x else -1 # Driver code to test function arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, diff --git a/Levenshtein_distance.py b/Levenshtein_distance.py index 710a3910..667ff76f 100644 --- a/Levenshtein_distance.py +++ b/Levenshtein_distance.py @@ -20,11 +20,7 @@ def levenshtein_distance(word_1, chars_1, word_2, chars_2): # if last characters of the string match, the cost of # operations is 0, i.e. no changes are made - if word_1[chars_1 - 1] == word_2[chars_2 - 1]: - cost = 0 - else: - cost = 1 - + cost = 0 if word_1[chars_1 - 1] == word_2[chars_2 - 1] else 1 # calculating the numbers of operations recursively deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1 insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1 diff --git a/Linear_Search.py b/Linear_Search.py index a1b14e77..7c288c29 100644 --- a/Linear_Search.py +++ b/Linear_Search.py @@ -4,10 +4,7 @@ def linearSearch(array, n, x): - for i in range(0, n): - if (array[i] == x): - return i - return -1 + return next((i for i in range(0, n) if (array[i] == x)), -1) array = [2, 4, 0, 1, 9] diff --git a/Minesweeper_Game.py b/Minesweeper_Game.py index 2de12f51..9a69a45c 100644 --- a/Minesweeper_Game.py +++ b/Minesweeper_Game.py @@ -3,9 +3,9 @@ # Generate a random map to start the game. def randomMap(n, k): - arr = [[0 for row in range(0,n)] for column in range(0,n)] + arr = [[0 for _ in range(0,n)] for _ in range(0,n)] - for num in range(0,k): + for _ in range(0,k): x = random.randint(0,n-1) y = random.randint(0,n-1) arr[y][x] = 'X' @@ -21,7 +21,7 @@ def randomMap(n, k): if (x >= 1 and x <= n-1) and (y >= 1 and y <= n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 # top left - + if (x >= 0 and x <= n-2) and (y >= 1 and y <= n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 # top right @@ -29,7 +29,7 @@ def randomMap(n, k): if (x >= 0 and x <= n-1) and (y >= 1 and y <= n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 # top center - + if (x >=0 and x <= n-2) and (y >= 0 and y <= n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 # bottom right @@ -45,8 +45,7 @@ def randomMap(n, k): # Generate the map for the player. def playerMap(n): - arr = [['-' for row in range(0,n)] for column in range(0,n)] - return arr + return [['-' for _ in range(0,n)] for _ in range(0,n)] # Display the map on the screen. def showMap(map): @@ -66,9 +65,7 @@ def checkWin(map): def checkContinue(score): print("Your score: ", score) isContinue = input("Do you want to try again? (y/n) :") - if isContinue == 'n': - return False - return True + return isContinue != 'n' # MINESWEEPER GAME def Game(): diff --git a/OTP generator.py b/OTP generator.py index f9d64c6c..c5a5874c 100644 --- a/OTP generator.py +++ b/OTP generator.py @@ -3,11 +3,9 @@ import random import smtplib digits = "012456789" -OTP = "" -for i in range(4): - OTP += digits[math.floor(random.random() * 10)] -msg = str(OTP) + "Your OTP is" - +OTP = "".join(digits[math.floor(random.random() * 10)] for _ in range(4)) +msg = f"{OTP}Your OTP is" + s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() diff --git a/PasswordGenerator.py b/PasswordGenerator.py index ae774e82..f54f0219 100644 --- a/PasswordGenerator.py +++ b/PasswordGenerator.py @@ -20,34 +20,31 @@ def easy_version(): password = "" - for i in range(no_letters): + for _ in range(no_letters): ran=random.randint(0,len(letters)) password+=letters[ran] - for i in range(no_numbers): + for _ in range(no_numbers): ran=random.randint(0,len(numbers)) password+=str(numbers[ran]) - for i in range(no_symbols): + for _ in range(no_symbols): ran=random.randint(0,len(symbols)) password+=str(symbols[ran]) print(password) def hard_version(): password_list=[] - password="" - for i in range(no_letters): + for _ in range(no_letters): ran=random.randint(0,len(letters)-1) password_list+=letters[ran] - for i in range(no_numbers): + for _ in range(no_numbers): ran=random.randint(0,len(numbers)-1) password_list+=str(numbers[ran]) - for i in range(no_symbols): + for _ in range(no_symbols): ran=random.randint(0,len(symbols)-1) password_list+=str(symbols[ran]) random.shuffle(password_list) - for i in password_list: - password+=i - + password = "".join(password_list) print(password) diff --git a/Password_generator.py b/Password_generator.py index 62d3368a..7aa3f41c 100644 --- a/Password_generator.py +++ b/Password_generator.py @@ -7,17 +7,17 @@ def easy_pass(nr_letters,nr_symbols,nr_numbers): random_letters = "" - for i in range(0,nr_letters): + for _ in range(0,nr_letters): random_letter = r.choice(letters) random_letters += random_letter random_symbols = "" - for i in range(0,nr_symbols): + for _ in range(0,nr_symbols): random_symbol = r.choice(symbols) random_symbols += random_symbol random_numbers = "" - for i in range(0,nr_numbers): + for _ in range(0,nr_numbers): random_number = r.choice(numbers) random_numbers += random_number @@ -28,17 +28,17 @@ def easy_pass(nr_letters,nr_symbols,nr_numbers): def hard_pass(nr_letters,nr_symbols,nr_numbers): random_letters = [] - for i in range(0,nr_letters): + for _ in range(0,nr_letters): random_letter = r.choice(letters) random_letters.append(random_letter) random_symbols = [] - for i in range(0,nr_symbols): + for _ in range(0,nr_symbols): random_symbol = r.choice(symbols) random_symbols.append(random_symbol) random_numbers = [] - for i in range(0,nr_numbers): + for _ in range(0,nr_numbers): random_number = r.choice(numbers) random_numbers.append(random_number) @@ -46,11 +46,7 @@ def hard_pass(nr_letters,nr_symbols,nr_numbers): r.shuffle(final_password_list) - #Hard Level - Order of characters randomised: - #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P - final_pass_in_str = "" - for char in final_password_list: - final_pass_in_str += char + final_pass_in_str = "".join(final_password_list) print(f"Here is your hard password : {final_pass_in_str}") diff --git a/Player.py b/Player.py index 7b28c746..84b2afcc 100644 --- a/Player.py +++ b/Player.py @@ -18,7 +18,7 @@ def get_move(self, game): valid_square = False val = None while not valid_square: - square = input(self.player + ' turn. Please introduce a move (1-9): ') + square = input(f'{self.player} turn. Please introduce a move (1-9): ') try: val = int(square) - 1 if val not in game.remaining_moves(): @@ -34,8 +34,7 @@ def __init__(self, player): super().__init__(player) def get_move(self, game): - square = random.choice(game.remaining_moves()) - return square + return random.choice(game.remaining_moves()) class SmartComputer(Player): @@ -43,11 +42,11 @@ def __init__(self, player): super().__init__(player) def get_move(self, game): - if len(game.remaining_moves()) == 9: - square = random.choice(game.remaining_moves()) - else: - square = self.minimax(game, self.player)['position'] - return square + return ( + random.choice(game.remaining_moves()) + if len(game.remaining_moves()) == 9 + else self.minimax(game, self.player)['position'] + ) def minimax(self, state, player): max_player = self.player @@ -75,10 +74,11 @@ def minimax(self, state, player): state.actual_winner = None sim_score['position'] = possible_move - if player == max_player: - if sim_score['score'] > best['score']: - best = sim_score - else: - if sim_score['score'] < best['score']: - best = sim_score + if ( + player == max_player + and sim_score['score'] > best['score'] + or player != max_player + and sim_score['score'] < best['score'] + ): + best = sim_score return best diff --git a/Pong_Game.py b/Pong_Game.py index e2afeede..61d19f7d 100644 --- a/Pong_Game.py +++ b/Pong_Game.py @@ -74,14 +74,14 @@ def rightpaddledown(): window.onkeypress(leftpaddledown,'s') window.onkeypress(rightpaddleup,'Up') window.onkeypress(rightpaddledown,'Down') - + while True: window.update() - + #moving the ball ball.setx(ball.xcor()+ballxdirection) ball.sety(ball.ycor()+ballxdirection) - + #border set up if ball.ycor()>290: ball.sety(290) @@ -89,32 +89,38 @@ def rightpaddledown(): if ball.ycor()<-290: ball.sety(-290) ballydirection=ballydirection*-1 - + if ball.xcor() > 390: ball.goto(0,0) ball_dx = ball_dx * -1 player_a_score = player_a_score + 1 pen.clear() - pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + pen.write( + f"Player A: {player_a_score} Player B: {player_b_score} ", + align="center", + font=('Monaco', 24, "normal"), + ) os.system("afplay wallhit.wav&") - - - - if(ball.xcor()) < -390: # Left width paddle Border + + + + if (ball.xcor()) < -390: # Left width paddle Border ball.goto(0,0) ball_dx = ball_dx * -1 player_b_score = player_b_score + 1 pen.clear() - pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + pen.write( + f"Player A: {player_a_score} Player B: {player_b_score} ", + align="center", + font=('Monaco', 24, "normal"), + ) os.system("afplay wallhit.wav&") - - # Handling the collisions with paddles. - + if(ball.xcor() > 340) and (ball.xcor() < 350) and (ball.ycor() < rightpaddle.ycor() + 40 and ball.ycor() > rightpaddle.ycor() - 40): ball.setx(340) ball_dx = ball_dx * -1 os.system("afplay paddle.wav&") - + if(ball.xcor() < -340) and (ball.xcor() > -350) and (ball.ycor() < leftpaddle.ycor() + 40 and ball.ycor() > leftpaddle.ycor() - 40): ball.setx(-340) ball_dx = ball_dx * -1 diff --git a/Queue.py b/Queue.py index a1397f65..98361e92 100644 --- a/Queue.py +++ b/Queue.py @@ -4,12 +4,11 @@ def enqueue(self,item): self.arr.append(item) def dequeue(self): - if len(self.arr) > 0: - ditem = self.arr[0] - del self.arr[0] - return ditem - else: + if len(self.arr) <= 0: return #queue is empty + ditem = self.arr[0] + del self.arr[0] + return ditem def dispaly(self): print(self.arr) diff --git a/Random Team Generator.py b/Random Team Generator.py index 73d6d3b5..e902f6d9 100644 --- a/Random Team Generator.py +++ b/Random Team Generator.py @@ -2,7 +2,7 @@ y = list(map(str,input().split())) t1 = [] t2 = [] -while (len(y) != 0): +while y: x = random.choice(y) if (len(t1) == len(t2)): t1.append(x) diff --git a/RockPaperScissors.py b/RockPaperScissors.py index 2bb0ddd1..bd31bb01 100644 --- a/RockPaperScissors.py +++ b/RockPaperScissors.py @@ -2,7 +2,7 @@ randomInteger=random.randint(0,2) userInput=int(input("What do you choose ? Type 0 for Rock,1 for Paper or 2 for Scissors\n")) -if(userInput!=0 and userInput!=1 and userInput!=2): +if userInput not in [0, 1, 2]: print("Wrong choise") exit() diff --git a/SankeGame_GUI.py b/SankeGame_GUI.py index dae1921d..962d5486 100644 --- a/SankeGame_GUI.py +++ b/SankeGame_GUI.py @@ -97,23 +97,26 @@ def move(): time.sleep(1) head.goto(0, 0) head.direction = "stop" - + #hiding segments of snake for segment in segments: segment.goto(1000,1000) #clearing the segments segments.clear() - + #reset score score = 0 - + #reset delay delay = 0.1 - + pen.clear() - pen.write("Score : {} High Score : {} ".format( - score, high_score), align="center", font=("Times New Roman", 24, "bold")) - + pen.write( + f"Score : {score} High Score : {high_score} ", + align="center", + font=("Times New Roman", 24, "bold"), + ) + #checking collision with food if head.distance(food) < 20: x = random.randint(-270, 270) @@ -125,8 +128,8 @@ def move(): e = ["circle","square","triangle"] shapes = random.choice(e) food.shape(shapes) - - + + #adding new segment new_segment = turtle.Turtle() new_segment.speed(0) @@ -134,45 +137,51 @@ def move(): new_segment.shape("square") new_segment.penup() segments.append(new_segment) - + delay -= 0.001 score += 10 - + if score>high_score: high_score = score pen.clear() - pen.write("Score : {} High Score : {} ".format( - score, high_score), align="center", font=("Times New Roman", 24, "bold")) - + pen.write( + f"Score : {score} High Score : {high_score} ", + align="center", + font=("Times New Roman", 24, "bold"), + ) + #moving segments in reverse order for i in range(len(segments)-1,0,-1): x = segments[i-1].xcor() y = segments[i-1].ycor() segments[i].goto(x,y) - if len(segments) > 0: + if segments: x = head.xcor() y = head.ycor() segments[0].goto(x, y) - + move() - + #Checking collisions with body for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" - + #hide segments for segment in segments: segment.goto(1000,1000) segment.clear() - + score = 0 delay = 0.1 pen.clear() - pen.write("Score : {} High Score : {} ".format( - score, high_score), align="center", font=("Times New Roman", 24, "bold")) + pen.write( + f"Score : {score} High Score : {high_score} ", + align="center", + font=("Times New Roman", 24, "bold"), + ) time.sleep(delay) turtle.done() diff --git a/Sieve_of _Eratosthenes.py b/Sieve_of _Eratosthenes.py index e23ea370..aa2e8bce 100644 --- a/Sieve_of _Eratosthenes.py +++ b/Sieve_of _Eratosthenes.py @@ -1,19 +1,13 @@ def SieveOfEratosthenes(n): numbers = {i: True for i in range(2, n+1)} - primes = [] - p = 2 - + while p**2 < n : if numbers[p] : for i in range(p**2, n+1, p): numbers[i] = False p+=1 - for i in range(2, n+1) : - if numbers[i] : - primes.append(i) - - return primes + return [i for i in range(2, n+1) if numbers[i]] def main() : n = int(input("Enter value of n to find primes between 1 and n (inclusive):")) diff --git a/Spy_number.py b/Spy_number.py index 9c46d15a..9b8ea188 100644 --- a/Spy_number.py +++ b/Spy_number.py @@ -2,14 +2,14 @@ sum=0 product=1 num1 = num - -while(num>0): + +while (num>0): d=num%10 sum=sum+d product=product*d - num=num//10 - -if(sum==product): - print("{} is a Spy number!".format(num1)) + num //= 10 + +if (sum==product): + print(f"{num1} is a Spy number!") else: - print("{} is not a Spy number!".format(num1)) + print(f"{num1} is not a Spy number!") diff --git a/Story-generator-game.py b/Story-generator-game.py index 7242fda0..b1cfb685 100644 --- a/Story-generator-game.py +++ b/Story-generator-game.py @@ -10,7 +10,7 @@ name=input('Player Name :- ') print('\n') -print('Welcome ' + name + '. Let''s play Hangman') +print(f'Welcome {name}. Lets play Hangman') print('') time.sleep(1) @@ -28,7 +28,7 @@ elif choose==3: word=random.choice(ramaayan) -print('HINT : Starts with' + word[0]) +print(f'HINT : Starts with{word[0]}') print('\n') print("Start guessing...") time.sleep(0.5) @@ -44,15 +44,14 @@ print('_') fail+=1 if fail==0: - print('You Won ' + name + ' !') + print(f'You Won {name} !') print('\n') print('Here is your story - ') theme=random.choice(["real world","high fantasy","space sci-fi","alt-history","cyberpunk"]) if theme == "real world": subsetting=random.choice(["the Ayodhya","Kishkindha","Lanka","Panchvati","Janakpuri"]) setting=random.choice(["a small town in ","a big city in ","a farm in ","a school in ","the ocean","the entire world"]) - if setting != "the ocean" or "the entire world": - setting=setting+subsetting + setting=setting+subsetting age=random.choice(["newborn ","toddler ","child ","teenager ","young adult ","adult ","middle aged ","elder "]) race=random.choice(["ayodhyan ","janakis ","lankan ","indian "]) gengender=random.randint(0,100) @@ -112,7 +111,7 @@ figure=random.choice(figures) antagonist=random.choice(figures) afigure=("figure known as ") - protagonist= afigure+figure + protagonist= afigure+figure if theme == "cyberpunk": setting=random.choice(["high-tech Tokyo","New New York","a dystopia","a utopia","a computer simulation","the SuperWeb","Mega Silicon Valley","an underwater city","an extensive underground facility"]) gender=random.choice(["male ","male ","female ","female ","robogender ","unigender ","agender ","mega genderfluid ","third gender "]) @@ -126,14 +125,14 @@ break - + guesses=input('Guess a character :- ') guess=guess+guesses if guesses not in word: turn-=1 - print('Wrong. You have ' + str(turn) + ' more guesses.') + print(f'Wrong. You have {turn} more guesses.') if turn==0: - print('You lose ! The word was ' + word + '. Sorry, you don''t get the story.') + print(f'You lose ! The word was {word}. Sorry, you dont get the story.') print('\n') print('Write your story on your own.') #Winstoryhangman diff --git a/TicTacToe.py b/TicTacToe.py index 04329745..957d886a 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -5,9 +5,21 @@ def button(f): - button1 = Button(f, text=" ", fg="Black", font="Arial 20 bold", height=1, width=2, padx=25, pady=20, bg="White", borderwidth=0, - activebackground="White", cursor="hand2", state=NORMAL) - return button1 + return Button( + f, + text=" ", + fg="Black", + font="Arial 20 bold", + height=1, + width=2, + padx=25, + pady=20, + bg="White", + borderwidth=0, + activebackground="White", + cursor="hand2", + state=NORMAL, + ) def full(): @@ -62,9 +74,7 @@ def click(event, param1, param2): if sign == 0: unchecked = [] for row in range(3): - for col in range(3): - if b[row][col]['text'] == " ": - unchecked.append([row, col]) + unchecked.extend([row, col] for col in range(3) if b[row][col]['text'] == " ") index = r.sample(unchecked, 1) b[index[0][0]][index[0][1]].config(text="X", state=DISABLED) com_checked.append((index[0][0], index[0][1])) @@ -74,8 +84,6 @@ def click(event, param1, param2): empty() user_checked.clear() com_checked.clear() - else: - pass root = Tk() diff --git a/Tic_tac_toe_game_in_python.py b/Tic_tac_toe_game_in_python.py index 0049a4ba..e117694d 100644 --- a/Tic_tac_toe_game_in_python.py +++ b/Tic_tac_toe_game_in_python.py @@ -15,9 +15,9 @@ def printBoard(xState, zState): eight = 'X' if xState[8] else ('0' if zState[8] else 8) nine = 'X' if xState[9] else ('0' if zState[9] else 9) print(f"{one} | {two} | {three} ") - print(f"--|---|---") + print("--|---|---") print(f"{four} | {five} | {six} ") - print(f"--|---|---") + print("--|---|---") print(f"{senven} | {eight} | {nine} ") def checkWin(xState, zState): diff --git a/TowerOfHanoi.py b/TowerOfHanoi.py index e3f76e49..c789b156 100644 --- a/TowerOfHanoi.py +++ b/TowerOfHanoi.py @@ -1,9 +1,9 @@ def TowerOfHanoi(Disks, source, temp, destination): - if(Disks == 1): - print("Move Disk 1 From {} to {}".format(source, destination)) - return - TowerOfHanoi(Disks - 1, source, destination, temp) - print("Move Disk {} From {} to {}".format(Disks, source, destination)) + if (Disks == 1): + print(f"Move Disk 1 From {source} to {destination}") + return + TowerOfHanoi(Disks - 1, source, destination, temp) + print(f"Move Disk {Disks} From {source} to {destination}") TowerOfHanoi(Disks - 1, temp, source, destination) Disks = int(input("Enter Number of Disks: ")) diff --git a/an4gram.py b/an4gram.py index 6188034e..4c54afcc 100644 --- a/an4gram.py +++ b/an4gram.py @@ -25,14 +25,9 @@ def isanagram(s1,s2): else: freq2[char] = 1 - # for every key in dictionary freq1 we are comparing it with the key in dictionary freq2 - # if the key is not found then it will return false - # and simillarly the values from both the dictionaries are being compared - # if any one of the condition is false it will return false "or" is being used - for key in freq1: - if key not in freq2 or freq1[key]!=freq2[key]: - return False - return True + return not any( + key not in freq2 or value != freq2[key] for key, value in freq1.items() + ) diff --git a/arrayReverse.py b/arrayReverse.py index 6a083581..d5a484f4 100644 --- a/arrayReverse.py +++ b/arrayReverse.py @@ -17,7 +17,7 @@ def userInput(): arr = [] n = int(input("Enter number of elements:")) print("Enter the elements") - for i in range(0,n): + for _ in range(0,n): element = int(input()) arr.append(element) diff --git a/automorphic.py b/automorphic.py index b80fc21d..e9127119 100644 --- a/automorphic.py +++ b/automorphic.py @@ -1,14 +1,14 @@ -print("Enter the number you want to check:") -num=int(input()) -square=num*num -flag=0 -while(num>0): +print("Enter the number you want to check:") +num=int(input()) +square = num**2 +flag=0 +while (num>0): if(num%10!=square%10): print("No, it is not an automorphic number.") flag=1 break - - num=num//10 - square=square//10 + + num //= 10 + square=square//10 if(flag==0): print("Yes, it is an automorphic number.") diff --git a/banking_system.py b/banking_system.py index c729cc91..c76d758d 100644 --- a/banking_system.py +++ b/banking_system.py @@ -45,12 +45,11 @@ def withdraw(self,amount): if self.amount < self.balance: self.balance -= self.amount print(f"Successfully Withdrawn ${self.amount}") - print(f"Current Balance : ${self.balance}") - print() else: - print("Not Enough Balance!!!") - print(f"Current Balance : ${self.balance}") - print() + print("Not Enough Balance!!!") + + print(f"Current Balance : ${self.balance}") + print() def view_balance(self): self.show_details() diff --git a/binarySearch.py b/binarySearch.py index c6cd336e..7e353fee 100644 --- a/binarySearch.py +++ b/binarySearch.py @@ -16,7 +16,7 @@ def userInput(): arr = [] n = int(input("Enter number of elements: ")) print("Enter the elements") - for i in range(0,n): + for _ in range(0,n): element = int(input()) arr.append(element) print(arr) diff --git a/camelCase-to-snake_case.py b/camelCase-to-snake_case.py index f4833605..07e523d3 100644 --- a/camelCase-to-snake_case.py +++ b/camelCase-to-snake_case.py @@ -4,6 +4,6 @@ for char in name: if char.isupper(): - print("_" + char.lower(), end = "") + print(f"_{char.lower()}", end = "") else: print(char, end = "") \ No newline at end of file diff --git a/collatz_sequence.py b/collatz_sequence.py index 564afaf8..799d5520 100644 --- a/collatz_sequence.py +++ b/collatz_sequence.py @@ -6,13 +6,10 @@ def collatz(initial_number): num = initial_number - print(f'Initial number is: {initial_number}') + print(f'Initial number is: {num}') while num != 1: print(num) - if num % 2 == 0: - num = int(num / 2) - else: - num = int(3 * num + 1) + num = int(num / 2) if num % 2 == 0 else int(3 * num + 1) else: print(num) print('Finally!') \ No newline at end of file diff --git a/csvgen.py b/csvgen.py index 0485bded..71ebe343 100644 --- a/csvgen.py +++ b/csvgen.py @@ -4,13 +4,9 @@ import random as rd; minNum = 0; -maxNum = 1000; #maximum number in array -lengthOfItems= 500; #this will generate 500 random numbers. - -file = open("newFile.csv", "a") # creates a new file named newFile.csv - feel free to edit file name - -for i in range(lengthOfItems): - file.write(str(str(rd.randint(minNum,maxNum)) + ",")) - -file.close() +maxNum = 1000 +lengthOfItems= 500 +with open("newFile.csv", "a") as file: + for _ in range(lengthOfItems): + file.write(str(f"{str(rd.randint(minNum, maxNum))},")) #note - you will have to split first line at "," and convert to int diff --git a/decimal_to_binary.py b/decimal_to_binary.py index 2ab6f584..61b42a20 100644 --- a/decimal_to_binary.py +++ b/decimal_to_binary.py @@ -1,5 +1,5 @@ -def dec_to_bin(n:int)->int: - return int(str(bin(n))[2:]) +def dec_to_bin(n:int) -> int: + return int(bin(n)[2:]) #bin() is a function that takes in a string and converts it to binary provided the string is purely integer populated diff --git a/dfs.py b/dfs.py index 25244444..87fe33b9 100644 --- a/dfs.py +++ b/dfs.py @@ -1,13 +1,9 @@ #DFS n = int(input("Enter the number of nodes : ")) graph = {}; -for i in range(n): +for _ in range(n): temp = list(map(str, input().split())) - if len(temp) > 1: - graph[temp[0]] = temp[1:] - else: - graph[temp[0]] = [] - + graph[temp[0]] = temp[1:] if len(temp) > 1 else [] visited = set(); def dfs(visited, graph, node): diff --git a/dice.py b/dice.py index 2198ce88..1fb0819a 100644 --- a/dice.py +++ b/dice.py @@ -73,9 +73,8 @@ def parse_input(input_string): """ if input_string.strip() in {"1", "2", "3", "4", "5", "6"}: return int(input_string) - else: - print("Please enter a number from 1 to 6.") - raise SystemExit(1) + print("Please enter a number from 1 to 6.") + raise SystemExit(1) def roll_dice(num_dice): @@ -112,23 +111,17 @@ def generate_dice_faces_diagram(dice_values): width = len(dice_faces_rows[0]) diagram_header = " RESULTS ".center(width, "~") - dice_faces_diagram = "\n".join([diagram_header] + dice_faces_rows) - return dice_faces_diagram + return "\n".join([diagram_header] + dice_faces_rows) def _get_dice_faces(dice_values): - dice_faces = [] - for value in dice_values: - dice_faces.append(DICE_ART[value]) - return dice_faces + return [DICE_ART[value] for value in dice_values] def _generate_dice_faces_rows(dice_faces): dice_faces_rows = [] for row_idx in range(DIE_HEIGHT): - row_components = [] - for die in dice_faces: - row_components.append(die[row_idx]) + row_components = [die[row_idx] for die in dice_faces] row_string = DIE_FACE_SEPARATOR.join(row_components) dice_faces_rows.append(row_string) return dice_faces_rows diff --git a/dice_roller.py b/dice_roller.py index c981a987..3b18eddd 100644 --- a/dice_roller.py +++ b/dice_roller.py @@ -7,15 +7,11 @@ def die(sides=6): seed() - result = randint(1, sides) - return result + return randint(1, sides) # This function defines a dice roll. # If no specific side and number of dies are defined, it 'rolls' a six-sided die. #Returns a list of ints with the dice rolls. def dice(number_of_die=1, sides=6): - rolls = [] - for roll in range(0, number_of_die): - rolls.append(die(sides)) - return rolls \ No newline at end of file + return [die(sides) for _ in range(0, number_of_die)] \ No newline at end of file diff --git a/disarium.py b/disarium.py index 8f60eb66..68295534 100644 --- a/disarium.py +++ b/disarium.py @@ -5,16 +5,16 @@ def calculateLength(n): n = n//10; return length; -num = 175; -rem = sum = 0; -len = calculateLength(num); -n = num; -while(num > 0): - rem = num%10; - sum = sum + int(rem**len); - num = num//10; - len = len - 1; -if(sum == n): - print(str(n) + " is a disarium number"); +num = 175; +rem = sum = 0; +len = calculateLength(num); +n = num; +while (num > 0): + rem = num%10; + sum = sum + int(rem**len); + num //= 10; + len = len - 1; +if (sum == n): + print(f"{n} is a disarium number"); else: - print(str(n) + " is not a disarium number"); + print(f"{n} is not a disarium number"); diff --git a/disjoint_set_union.py b/disjoint_set_union.py index 83f360c0..8e95c274 100644 --- a/disjoint_set_union.py +++ b/disjoint_set_union.py @@ -1,13 +1,12 @@ N = 1000 -P = [i for i in range(0,N+1)] # parent -S = [1 for i in range(0,N+1)] # size of set +P = list(range(0,N+1)) +S = [1 for _ in range(0,N+1)] def find(u): if u == P[u]: return u - else: - P[u] = find(P[u]) - return P[u] + P[u] = find(P[u]) + return P[u] def union(u,v): u = find(u) diff --git a/emi-calculator.py b/emi-calculator.py index e9b570d8..93d6e2a1 100644 --- a/emi-calculator.py +++ b/emi-calculator.py @@ -6,10 +6,9 @@ def emi_calculator(p:float, r:float, t:float): r - interest rate per month t - time period (in years) """ - r = r / (12 * 100) # one month interest - t = t * 12 # one month period - emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) - return emi + r /= 12 * 100 + t *= 12 + return (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) principal = float(input("Enter principal amount (in ₹):")) diff --git a/factorial.py b/factorial.py index 2f57f159..1aa5dd1c 100644 --- a/factorial.py +++ b/factorial.py @@ -1,6 +1,6 @@ def factorial(n): - return 1 if (n==1 or n==0) else n * factorial(n - 1); + return 1 if n in [1, 0] else n * factorial(n - 1); num = int(input("Enter a number: ")); diff --git a/fast_recursive_fibonacci.py b/fast_recursive_fibonacci.py index 46fb7cab..f66203b0 100644 --- a/fast_recursive_fibonacci.py +++ b/fast_recursive_fibonacci.py @@ -7,10 +7,7 @@ def fast_rec_fib_helper(n): prev = (hprv ** 2) + (hcur **2) curr = hcur * (2 * hprv + hcur) next = prev + curr - if n % 2 == 0: - return (prev, curr) - else: - return (curr, next) + return (prev, curr) if n % 2 == 0 else (curr, next) def fast_rec_fib(n): if n==0: diff --git a/fibonacci.py b/fibonacci.py index 1ae5cf8f..5d821a6b 100644 --- a/fibonacci.py +++ b/fibonacci.py @@ -1,6 +1,4 @@ def fibonacci_of(n): - if n in {0, 1}: - return n - return fibonacci_of(n - 1) + fibonacci_of(n - 2) + return n if n in {0, 1} else fibonacci_of(n - 1) + fibonacci_of(n - 2) for i in range(1,100): print(fibonacci_of(i)) diff --git a/get_coordinates.py b/get_coordinates.py index 33e634ff..1ba4f76f 100644 --- a/get_coordinates.py +++ b/get_coordinates.py @@ -3,8 +3,7 @@ your_address = str(input()) geolocator = Nominatim(user_agent="basic_app") -location = geolocator.geocode(your_address) -if location: +if location := geolocator.geocode(your_address): print((location.latitude, location.longitude)) else: print("Can not find your address!") \ No newline at end of file diff --git a/hangman.py b/hangman.py index f2ceff93..324e34fd 100644 --- a/hangman.py +++ b/hangman.py @@ -12,7 +12,7 @@ print('WELCOME TO MY HANGMAN GAME\n') cc = random.choice(guess_list).upper() guesses = len(cc)+4 -repw = ['_' for i in range(len(cc))] +repw = ['_' for _ in range(len(cc))] while guesses > 0: print(f'WORD: {" ".join(repw)}') ug = input('Guess a letter:').upper() @@ -25,5 +25,5 @@ print('Tries remain:',guesses-1,'\n') guesses-=1 - + print('\nYou WIN🎉\n') if repw.count('_')==0 else print('\nYou LOSE💔') \ No newline at end of file diff --git a/huffmantree.py b/huffmantree.py index ccbc6324..d35e1218 100644 --- a/huffmantree.py +++ b/huffmantree.py @@ -20,6 +20,5 @@ def getHuffmanTree(txt): left,right=hpp(pq),hpp(pq); newFreq=left.freq+right.freq hppu(pq,Node(None,newFreq,left,right)) - root=pq[0] - return root + return pq[0] diff --git a/image_compress.py b/image_compress.py index 162e8eb6..ccf41459 100644 --- a/image_compress.py +++ b/image_compress.py @@ -5,7 +5,7 @@ def compressMe(file, verbose = False): filepath = os.path.join(os.getcwd(), file) picture = Image.open(filepath) - picture.save("Compressed_"+file, "JPEG", optimize = True, quality = 10) + picture.save(f"Compressed_{file}", "JPEG", optimize = True, quality = 10) return def main(): diff --git a/img_to_pencil.py b/img_to_pencil.py index fc4b9c9e..7d165178 100644 --- a/img_to_pencil.py +++ b/img_to_pencil.py @@ -3,7 +3,7 @@ name = input() print("Enter output file name without extension") out = input() -out = out+".png" +out = f"{out}.png" image = cv2.imread(name) grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) diff --git a/kadanes_algorithm.py b/kadanes_algorithm.py index d719823a..649c6bd3 100644 --- a/kadanes_algorithm.py +++ b/kadanes_algorithm.py @@ -2,6 +2,7 @@ This algorithm is used to find the largest sum in the given array in O(n) Time complexity """ + arr=[-1,0,3,4,2,6,-10,5,-9] max_sum=0 @@ -10,9 +11,6 @@ for i in arr: curr_sum += i max_sum=max(max_sum,curr_sum) - - if curr_sum<0: - curr_sum=0 - + curr_sum = max(curr_sum, 0) print(max_sum) \ No newline at end of file diff --git a/madlibs.py b/madlibs.py index d2dae4a2..dd6070f4 100644 --- a/madlibs.py +++ b/madlibs.py @@ -1,9 +1,6 @@ -loop = 1 - -while (loop < 10): - +for _ in range(1, 10): # All the questions that the program asks the user noun = input("Choose a noun: ") @@ -36,8 +33,4 @@ print ("Well it is.") - print ("------------------------------------------") - - # Loop back to "loop = 1" - - loop = loop + 1 \ No newline at end of file + print ("------------------------------------------") \ No newline at end of file diff --git a/mask_email_address.py b/mask_email_address.py index 5cdbd8ea..756bc614 100644 --- a/mask_email_address.py +++ b/mask_email_address.py @@ -28,8 +28,8 @@ def main(): def mask_email(email): lo = email.find('@') domain_extension = email.rfind('.') - word_count = len(email) if lo > 0: + word_count = len(email) return "{0}#####{1}@{2}###{3}".format(email[0], email[lo-1], email[lo+1], diff --git a/medianOf2SortedArray.py b/medianOf2SortedArray.py index 5162d202..38a02e11 100644 --- a/medianOf2SortedArray.py +++ b/medianOf2SortedArray.py @@ -13,7 +13,7 @@ def findMedianSortedArrays(A, B): med1 = med2 = i = j = 0 n = len(A) + len(B) - + while (i + j) <= n / 2: if i < len(A) and j < len(B): med2 = med1 @@ -32,10 +32,7 @@ def findMedianSortedArrays(A, B): med1 = B[j] j += 1 - if n % 2 == 0: - return (med1 + med2) / 2.0 - else: - return med1 + return (med1 + med2) / 2.0 if n % 2 == 0 else med1 diff --git a/menu-based_student_record.py b/menu-based_student_record.py index 2d892f77..c16aaf77 100644 --- a/menu-based_student_record.py +++ b/menu-based_student_record.py @@ -15,13 +15,10 @@ #append def appendStudent(): global studList - singlr = [] studName=input('enter your name') Rollno=input('enter your Rollno') cgpa=int(input('cgpa :')) - singlr.append(studName) - singlr.append(Rollno) - singlr.append(cgpa) + singlr = [studName, Rollno, cgpa] studList.append(singlr) diff --git a/merge_sort.py b/merge_sort.py index 63e46241..7cd7d8df 100644 --- a/merge_sort.py +++ b/merge_sort.py @@ -21,7 +21,7 @@ def merge(left_half,right_half): res.append(right_half[0]) right_half.remove(right_half[0]) if len(left_half) == 0: - res = res + right_half + res += right_half else: res = res + left_half return res diff --git a/novowels.py b/novowels.py index 0fdceb7f..24735569 100644 --- a/novowels.py +++ b/novowels.py @@ -1,14 +1,14 @@ def main(): sts = str(input("Input: ")) without_vowels = shorten(sts) - print("Output: " + without_vowels) + print(f"Output: {without_vowels}") def shorten(word): - lttr = "" - for letter in word: - if not letter.lower() in ['a', 'e', 'i', 'o', 'u']: - lttr += letter - return lttr + return "".join( + letter + for letter in word + if letter.lower() not in ['a', 'e', 'i', 'o', 'u'] + ) if __name__ == "__main__": main() \ No newline at end of file diff --git a/paranthesis_checker.py b/paranthesis_checker.py index aa9e510e..76bf956c 100644 --- a/paranthesis_checker.py +++ b/paranthesis_checker.py @@ -11,30 +11,28 @@ def parenthesis_check(parenthesis_array): stack = [] for parenthesis in parenthesis_array: - if parenthesis == '}': - if len(stack) == 0: + if parenthesis == ')': + if not stack: return False prev_parenthesis = stack.pop() - if prev_parenthesis != '{': + if prev_parenthesis != '(': return False elif parenthesis == ']': - if len(stack) == 0: + if not stack: return False prev_parenthesis = stack.pop() if prev_parenthesis != '[': return False - elif parenthesis == ')': - if len(stack) == 0: + elif parenthesis == '}': + if not stack: return False prev_parenthesis = stack.pop() - if prev_parenthesis != '(': - return False - else: stack.append(parenthesis) - - if len(stack) > 0: - return False - else: - return True + if prev_parenthesis != '{': + return False + else: + stack.append(parenthesis) + + return len(stack) <= 0 str = input("Input: ") arr = list(str) diff --git a/parse_csv.py b/parse_csv.py index c3525697..a37eed4e 100644 --- a/parse_csv.py +++ b/parse_csv.py @@ -1,18 +1,17 @@ import csv #read from csv -fields=list() -rows=list() +fields = [] +rows = [] with open('employee.csv','r') as csv_file: csv_reader=csv.reader(csv_file) fields=next(csv_reader) #csv reader object - for row in csv_reader: - rows.append(row) - print("Total no. of rows={}".format(csv_reader.line_num)) -print("Field Names are:"+",".join(field for field in fields)) + rows.extend(iter(csv_reader)) + print(f"Total no. of rows={csv_reader.line_num}") +print("Field Names are:" + ",".join(fields)) print("First 5 rows are:\n") for row in rows[:5]: for col in row: - print("{}".format(col),end=" "), + (print(f"{col}", end=" "), ) print("\n") #write to csv flds=['Name','Branch','Year','CGPA'] diff --git a/power_of_a_number.py b/power_of_a_number.py index 6c94b267..c2bd0a38 100644 --- a/power_of_a_number.py +++ b/power_of_a_number.py @@ -1,7 +1,5 @@ def power_of_a_linear(x, n): - if n == 0: - return 1 - return x * power_of_a_linear(x, n-1) + return 1 if n == 0 else x * power_of_a_linear(x, n-1) x = int(input("Enter the number:")) n = int(input("Enter the power:")) diff --git a/prime.py b/prime.py index 2a0517c0..47978df6 100644 --- a/prime.py +++ b/prime.py @@ -1,9 +1,7 @@ def prime(x, y): prime_list = [] for i in range(x, y): - if i == 0 or i == 1: - continue - else: + if i not in [0, 1]: for j in range(2, int(i/2)+1): if i % j == 0: break diff --git a/print_star_using_loops.py b/print_star_using_loops.py index 66fc5663..3b62bdf0 100644 --- a/print_star_using_loops.py +++ b/print_star_using_loops.py @@ -3,13 +3,14 @@ print("Type 1 Or 0") two = int(input()) new =bool(two) -if new == True: - for i in range(1,one+1): - for j in range(1,i+1): - print("*",end=" ") - print() -elif new ==False: +if not new: for i in range(one,0,-1): - for j in range(1,i+1): + for _ in range(1,i+1): print("*", end="") print() + +else: + for i in range(1,one+1): + for _ in range(1,i+1): + print("*",end=" ") + print() diff --git a/radixSort.py b/radixSort.py index ae4955fd..839c52ea 100644 --- a/radixSort.py +++ b/radixSort.py @@ -54,7 +54,7 @@ def radixSort(arr): arr = [ 170, 45, 75, 90, 802, 24, 2, 66] radixSort(arr) -for i in range(len(arr)): - print(arr[i],end=" ") +for item in arr: + print(item, end=" ") diff --git a/random_password_generator.py b/random_password_generator.py index c7a12fae..49925567 100644 --- a/random_password_generator.py +++ b/random_password_generator.py @@ -12,10 +12,7 @@ # generate password meeting constraints while True: - pwd = '' - for i in range(pwd_length): - pwd += ''.join(secrets.choice(alphabet)) - + pwd = ''.join(''.join(secrets.choice(alphabet)) for _ in range(pwd_length)) if (any(char in special_chars for char in pwd) and sum(char in digits for char in pwd) >= 2): break diff --git a/reverse32bitsignedint.py b/reverse32bitsignedint.py index 986604c2..93548c0a 100644 --- a/reverse32bitsignedint.py +++ b/reverse32bitsignedint.py @@ -14,6 +14,4 @@ def reverse32bitsignedint(n): limit = 1 << 31 if is_negative: ans = -ans - if (ans <= -limit) or (ans >= limit - 1): - return 0 - return ans + return 0 if (ans <= -limit) or (ans >= limit - 1) else ans diff --git a/rupiah_budgeting_plan.py b/rupiah_budgeting_plan.py index ecb1b6e3..51324f1f 100644 --- a/rupiah_budgeting_plan.py +++ b/rupiah_budgeting_plan.py @@ -20,17 +20,16 @@ def transform_to_rupiah_format(value): temp_result = temp_reverse_value[::-1] - return "Rp " + temp_result + ",0" + before_decimal + return f"Rp {temp_result},0{before_decimal}" def formatrupiah(uang): y = str(uang) if len(y) <= 3: - return 'Rp ' + y - else: - p = y[-3:] - q = y[:-3] - return formatrupiah(q) + '.' + p + return f'Rp {y}' + p = y[-3:] + q = y[:-3] + return f'{formatrupiah(q)}.{p}' # default budgeting percentage (single) @@ -60,18 +59,21 @@ def formatrupiah(uang): print('========================================================') for x in percentage: - print('Checking Persen Budgeting '+'{}'.format(sum)+' %'+' (Checking)') + print(f'Checking Persen Budgeting {sum} % (Checking)') time.sleep(2) sum += x -print('Checking Persen Budgeting '+'{}'.format(percent_budget)+'%'+' (Done)') +print(f'Checking Persen Budgeting {percent_budget}% (Done)') time.sleep(2) -print('Budgeting anda adalah sebesar {}'.format(formatrupiah(budget))+',00') -print('Pemasukan anda untuk kebutuhan hidup adalah\t: {}'.format( - transform_to_rupiah_format(budget_living))) - -print('Pemasukan anda untuk kegiatan adalah\t\t: {}'.format( - transform_to_rupiah_format(budget_playing))) -print('Pemasukan anda untuk tabungan adalah\t\t: {}'.format( - transform_to_rupiah_format(budgett_saving))) +print(f'Budgeting anda adalah sebesar {formatrupiah(budget)},00') +print( + f'Pemasukan anda untuk kebutuhan hidup adalah\t: {transform_to_rupiah_format(budget_living)}' +) + +print( + f'Pemasukan anda untuk kegiatan adalah\t\t: {transform_to_rupiah_format(budget_playing)}' +) +print( + f'Pemasukan anda untuk tabungan adalah\t\t: {transform_to_rupiah_format(budgett_saving)}' +) print('========================================================') diff --git a/simple_custom_hash_map_implementation.py b/simple_custom_hash_map_implementation.py index 83a70919..690f56f2 100644 --- a/simple_custom_hash_map_implementation.py +++ b/simple_custom_hash_map_implementation.py @@ -9,9 +9,7 @@ def __init__(self, max_size=10): # function will return index in the array based on the key def _hash_function(self, key): if type(key) == str: - hash_val = 0 - for i in range(len(key)): - hash_val += ((i+1)*ord(key[i])) + hash_val = sum(((i+1)*ord(key[i])) for i in range(len(key))) else: hash_val = int(key) @@ -23,35 +21,32 @@ def add(self, key, val): idx = self._hash_function(key) if self.map[idx] is None: self.map[idx] = [[key, val]] + elif self.is_present(key): + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + self.map[idx][i][1] = val else: - if self.is_present(key): - for i in range(len(self.map[idx])): - if self.map[idx][i][0] == key: - self.map[idx][i][1] = val - else: - self.map[idx].append([key, val]) + self.map[idx].append([key, val]) # returns value if key exits # else raises an error def get(self, key): - if self.is_present(key): - idx = self._hash_function(key) - for key_val in self.map[idx]: - if key_val[0] == key: - return key_val[1] - else: - raise KeyError("Key: {} doesn't exist".format(key)) + if not self.is_present(key): + raise KeyError(f"Key: {key} doesn't exist") + idx = self._hash_function(key) + for key_val in self.map[idx]: + if key_val[0] == key: + return key_val[1] # deletes a value if key exists # else raises error def delete(self, key): - if self.is_present(key): - idx = self._hash_function(key) - for i in range(len(self.map[idx])): - if self.map[idx][i][0] == key: - del self.map[idx][i] - else: - raise KeyError("Key: {} doesn't exist".format(key)) + if not self.is_present(key): + raise KeyError(f"Key: {key} doesn't exist") + idx = self._hash_function(key) + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + del self.map[idx][i] # returns True if key exists # else False @@ -61,11 +56,7 @@ def is_present(self, key): if self.map[idx] is None: return False - for key_val in self.map[idx]: - if key_val[0] == key: - return True - - return False + return any(key_val[0] == key for key_val in self.map[idx]) if __name__ == '__main__': diff --git a/simple_vending_machine.py b/simple_vending_machine.py index b9582807..49d11c89 100644 --- a/simple_vending_machine.py +++ b/simple_vending_machine.py @@ -1,5 +1,5 @@ a=dict() -key_list=list() +key_list = [] def readFile(): with open("vendingitems.txt",'r') as f: for line in f: @@ -12,23 +12,21 @@ def vendingMachine(): readFile() while True: item=input("Enter item name\n") - if(item in a.keys()): + if (item in a.keys()): print("Valid Item Name") #break cash=int(input("Enter money to deposit\n")) - if(isinstance(cash,int)==False): - print("Bad Input {}\n Try Again!".format(str(cash))) - #continue + if not isinstance(cash, int): + print(f"Bad Input {cash}\n Try Again!") + #continue + elif (cash>a[item]): + print("Thank you for your purchase.Enjoy\n") + print(f"Do not forget to collect your change,{cash - a[item]} Rs") + break else: - if(cash>a[item]): - print("Thank you for your purchase.Enjoy\n") - print("Do not forget to collect your change,{} Rs".format(cash-a[item])) - break - else: - print("Not enough Money to but the item\n") - continue + print("Not enough Money to but the item\n") else: - print("Available Items are {} ,\nTry Again!".format(a.keys())) + print(f"Available Items are {a.keys()} ,\nTry Again!") continue diff --git a/soundex.py b/soundex.py index 9cca031c..4986a90d 100644 --- a/soundex.py +++ b/soundex.py @@ -3,16 +3,15 @@ text = 'AMANMADHUKAR' ##Enter your text here plain = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ## This is the plain text code = '01230120022455012623010202' ## Here I have assigned the code value respective to the alphabet -l=[] ## Create empty list -l.append(text[0]) ## So first character goes as it is (here it will be A) +l = [text[0]] for i in range(1,len(text)): ## Traversing from 1st Index i.e. M to R over here that is the last character if(code[plain.index(text[i-1])]!=code[plain.index(text[i])]): ## Removing Zeroes from the list if (code[plain.index(text[i])] != '0'): ## If not zero l.append(code[plain.index(text[i])]) ## then append into list -for i in range(4): ## Soundex considers only Four characters therefore traversing only four times - if (len(l)<4): ## Suppose the Character less than four then we append 0 in last - l.append('0') - +for _ in range(4): + if (len(l)<4): ## Suppose the Character less than four then we append 0 in last + l.append('0') + print(l) ##printing list print(''.join(l[:4])) ##lastly merging the list diff --git a/strong.py b/strong.py index 13cf2dc5..410147ac 100644 --- a/strong.py +++ b/strong.py @@ -1,15 +1,15 @@ sum1=0 num=int(input("Enter a number:")) temp=num -while(num): +while num: i=1 f=1 r=num%10 - while(i<=r): + while (i<=r): f=f*i - i=i+1 + i += 1 sum1=sum1+f - num=num//10 + num //= 10 if(sum1==temp): print("The number is a strong number") else: diff --git a/subtitle_synchronizer.py b/subtitle_synchronizer.py index 65d55991..027b1c42 100644 --- a/subtitle_synchronizer.py +++ b/subtitle_synchronizer.py @@ -6,8 +6,7 @@ def convertToMilliseconds(time): mm = int(mm) ms = int(ms) - milliseconds = hh*3600000+mm*60000+ms - return milliseconds + return hh*3600000+mm*60000+ms def synchronize(time,shift): return time-shift @@ -16,21 +15,24 @@ def convertToTime(milliseconds): hh = milliseconds//3600000 milliseconds = milliseconds%3600000 hh = str(hh) - if len(hh) < 2: hh = "0"+hh + if len(hh) < 2: + hh = f"0{hh}" mm = milliseconds//60000 milliseconds = milliseconds%60000 mm = str(mm) - if len(mm) < 2: mm = "0"+mm + if len(mm) < 2: + mm = f"0{mm}" ss = milliseconds//1000 milliseconds = milliseconds%1000 ss = str(ss) - if len(ss) < 2: ss = "0"+ss + if len(ss) < 2: + ss = f"0{ss}" milliseconds = str(milliseconds) while len(milliseconds) < 3: - milliseconds = "0"+milliseconds + milliseconds = f"0{milliseconds}" return f"{hh}:{mm}:{ss},{milliseconds}" diff --git a/turtle race.py b/turtle race.py index 4693c252..985d84f4 100644 --- a/turtle race.py +++ b/turtle race.py @@ -29,7 +29,7 @@ krishna.goto(-180,10) krishna.pendown() -for movement in range(100): +for _ in range(100): aman.forward(randint(1,5)) swati.forward(randint(1, 5)) ram.forward(randint(1, 5)) diff --git a/video_jpeg_converter.py b/video_jpeg_converter.py index 268f44c9..dabe79bd 100644 --- a/video_jpeg_converter.py +++ b/video_jpeg_converter.py @@ -11,23 +11,23 @@ # Path for output JPEG images outPath = str(input("Copy the path to your output folder storing the JPEG images and paste it here: ")) +currentframe = 0 +# a variable to set how many frames you want to skip +frame_skip = 5 # Since the videos are in 30 FPS, and we want 10 frames per clip + for classPath in os.listdir(dataPath): clipPaths = os.listdir(dataPath + "\\" + classPath) os.mkdir((outPath + '\\' + classPath)) - + k = 1 for clips in clipPaths: os.mkdir((outPath + '\\' + classPath + '\\' + clips)) os.chdir((outPath + '\\' + classPath + '\\' + clips)) - + f = dataPath + "\\" + classPath + "\\" + clips cam = cv2.VideoCapture(f) ret, frame = cam.read() - currentframe = 0 i = 0 - - # a variable to set how many frames you want to skip - frame_skip = 5 # Since the videos are in 30 FPS, and we want 10 frames per clip while cam.isOpened(): ret, frame = cam.read() @@ -35,7 +35,7 @@ if not ret: break if (i > frame_skip - 1): - cv2.imwrite(classPath + '_' + clips + '_' + str(k) +'.jpg', frame) + cv2.imwrite(f'{classPath}_{clips}_{k}.jpg', frame) i = 0 continue i += 1 diff --git a/weather_gui.py b/weather_gui.py index 20c9fdf7..6dc13f65 100644 --- a/weather_gui.py +++ b/weather_gui.py @@ -5,8 +5,8 @@ def getWeather(canvas): city = textField.get() - api = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=06c921750b9a82d8f5d1294e1586276f" - + api = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=06c921750b9a82d8f5d1294e1586276f" + json_data = requests.get(api).json() condition = json_data['weather'][0]['main'] temp = int(json_data['main']['temp'] - 273.15) @@ -18,7 +18,7 @@ def getWeather(canvas): sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600)) sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600)) - final_info = condition + "\n" + str(temp) + "°C" + final_info = condition + "\n" + str(temp) + "°C" final_data = "\n"+ "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str(max_temp) + "°C" +"\n" + "Pressure: " + str(pressure) + "\n" +"Humidity: " + str(humidity) + "\n" +"Wind Speed: " + str(wind) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset label1.config(text = final_info) label2.config(text = final_data) diff --git a/webscraper.py b/webscraper.py index 24907aeb..46b05406 100644 --- a/webscraper.py +++ b/webscraper.py @@ -4,13 +4,7 @@ page = requests.get("Paste a Domain here") soup = BeautifulSoup(page.content, 'html.parser') -# Create all_h1_tags as empty list -all_h1_tags = [] - -# Set all_h1_tags to all h1 tags of the soup -for element in soup.select('h1'): - all_h1_tags.append(element.text) - +all_h1_tags = [element.text for element in soup.select('h1')] print(all_h1_tags) # give you all h1 tags \ No newline at end of file