diff --git a/.gitignore b/.gitignore index e2cee02848f..3d94d2325c2 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ print(lower+upper+odd+even) # thumbnail cache on Windows Thumbs.db + +__pycache__ +*.sqlite3 \ No newline at end of file diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py index 88adeef443f..e7b18776a26 100644 --- a/1 File handle/File handle binary/Update a binary file2.py +++ b/1 File handle/File handle binary/Update a binary file2.py @@ -9,7 +9,7 @@ def update(): value = pickle.load(File) found = False roll = int(input("Enter the roll number of the record")) - + for i in value: if roll == i[0]: print(f"current name {i[1]}") diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py index bf84e9824ec..b9c6b63947f 100644 --- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -8,6 +8,7 @@ """ + # also find no. of children who got top marks import pickle diff --git a/1 File handle/File handle text/counter.py b/1 File handle/File handle text/counter.py index 1019eeacae8..abbaf293c02 100644 --- a/1 File handle/File handle text/counter.py +++ b/1 File handle/File handle text/counter.py @@ -5,9 +5,10 @@ - Code readability """ + class Counter: - def __init__(self, text:str) -> None: + def __init__(self, text: str) -> None: self.text = text # Define the initial count of the lower and upper case. @@ -16,7 +17,7 @@ def __init__(self, text:str) -> None: self.count() def count(self) -> None: - + for char in self.text: if char.lower(): self.count_lower += 1 @@ -24,7 +25,7 @@ def count(self) -> None: self.count_upper += 1 return (self.count_lower, self.count_upper) - + def get_total_lower(self) -> int: return self.count_lower @@ -32,4 +33,4 @@ def get_total_upper(self) -> int: return self.count_upper def get_total(self) -> int: - return self.count_lower + self.count_upper \ No newline at end of file + return self.count_lower + self.count_upper diff --git a/1 File handle/File handle text/file handle 12 length of line in text file.py b/1 File handle/File handle text/file handle 12 length of line in text file.py index d14ef16a4ea..5495fdec1ee 100644 --- a/1 File handle/File handle text/file handle 12 length of line in text file.py +++ b/1 File handle/File handle text/file handle 12 length of line in text file.py @@ -1,10 +1,11 @@ - import os import time -file_name= input("Enter the file name to create:- ") + +file_name = input("Enter the file name to create:- ") print(file_name) + def write_to_file(file_name): if os.path.exists(file_name): @@ -15,16 +16,17 @@ def write_to_file(file_name): while True: text = input("enter any text to add in the file:- ") - F.write( f"{text}\n" ) + F.write(f"{text}\n") choice = input("Do you want to enter more, y/n").lower() if choice == "n": break - + + def longlines(): - with open(file_name, encoding='utf-8') as F: + with open(file_name, encoding="utf-8") as F: lines = F.readlines() - lines_less_than_50 = list( filter(lambda line: len(line) < 50, lines ) ) + lines_less_than_50 = list(filter(lambda line: len(line) < 50, lines)) if not lines_less_than_50: print("There is no line which is less than 50") @@ -32,7 +34,8 @@ def longlines(): for i in lines_less_than_50: print(i, end="\t") + if __name__ == "__main__": write_to_file(file_name) time.sleep(1) - longlines() \ No newline at end of file + longlines() diff --git a/1 File handle/File handle text/input,output and error streams.py b/1 File handle/File handle text/input,output and error streams.py index cecd268979b..41bd1e5a6f6 100644 --- a/1 File handle/File handle text/input,output and error streams.py +++ b/1 File handle/File handle text/input,output and error streams.py @@ -4,13 +4,18 @@ sys.stdout.write("Enter the name of the file") file = sys.stdin.readline() -with open(file.strip(), ) as F: +with open( + file.strip(), +) as F: while True: ch = F.readlines() - for (i) in ch: # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words + for ( + i + ) in ( + ch + ): # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words print(i, end="") else: sys.stderr.write("End of file reached") break - diff --git a/1 File handle/File handle text/question 2.py b/1 File handle/File handle text/question 2.py index cbb84fcd13f..e3d68ba18fc 100644 --- a/1 File handle/File handle text/question 2.py +++ b/1 File handle/File handle text/question 2.py @@ -3,33 +3,32 @@ using read function and display those words, which are less than 4 characters. """ +print("Hey!! You can print the word which are less then 4 characters") -print("Hey!! You can print the word which are less then 4 characters") def display_words(file_path): try: with open(file_path) as F: words = F.read().split() - words_less_than_40 = list( filter(lambda word: len(word) < 4, words) ) + words_less_than_40 = list(filter(lambda word: len(word) < 4, words)) for word in words_less_than_40: print(word) - - return "The total number of the word's count which has less than 4 characters", (len(words_less_than_40)) - + + return ( + "The total number of the word's count which has less than 4 characters", + (len(words_less_than_40)), + ) + except FileNotFoundError: print("File not found") + print("Just need to pass the path of your file..") file_path = input("Please, Enter file path: ") if __name__ == "__main__": - - print(display_words(file_path)) - - - - + print(display_words(file_path)) diff --git a/1 File handle/File handle text/question 5.py b/1 File handle/File handle text/question 5.py index 864520df4cd..99ab54dcebf 100644 --- a/1 File handle/File handle text/question 5.py +++ b/1 File handle/File handle text/question 5.py @@ -4,13 +4,15 @@ import time, os from counter import Counter -print("You will see the count of lowercase, uppercase and total count of alphabets in provided file..") +print( + "You will see the count of lowercase, uppercase and total count of alphabets in provided file.." +) file_path = input("Please, Enter file path: ") if os.path.exists(file_path): - print('The file exists and this is the path:\n',file_path) + print("The file exists and this is the path:\n", file_path) def lowercase(file_path): @@ -18,10 +20,14 @@ def lowercase(file_path): with open(file_path) as F: word_counter = Counter(F.read()) - - print(f"The total number of lower case letters are {word_counter.get_total_lower()}") + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) time.sleep(0.5) - print(f"The total number of upper case letters are {word_counter.get_total_upper()}") + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) time.sleep(0.5) print(f"The total number of letters are {word_counter.get_total()}") time.sleep(0.5) @@ -30,8 +36,6 @@ def lowercase(file_path): print("File is not exist.. Please check AGAIN") - - if __name__ == "__main__": lowercase(file_path) diff --git a/1 File handle/File handle text/question 6.py b/1 File handle/File handle text/question 6.py index a98fe3a7cfb..fe50c0a97e0 100644 --- a/1 File handle/File handle text/question 6.py +++ b/1 File handle/File handle text/question 6.py @@ -3,14 +3,20 @@ from counter import Counter + def lowercase(): with open("happy.txt") as F: word_counter = Counter(F.read()) - - print(f"The total number of lower case letters are {word_counter.get_total_lower()}") - print(f"The total number of upper case letters are {word_counter.get_total_upper()}") + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) print(f"The total number of letters are {word_counter.get_total()}") + if __name__ == "__main__": lowercase() diff --git a/1 File handle/File handle text/question3.py b/1 File handle/File handle text/question3.py index bc05c22561d..f48f900e4d7 100644 --- a/1 File handle/File handle text/question3.py +++ b/1 File handle/File handle text/question3.py @@ -4,13 +4,13 @@ import os import time -file_name= input("Enter the file name to create:- ") + +file_name = input("Enter the file name to create:- ") # step1: print(file_name) - def write_to_file(file_name): if os.path.exists(file_name): @@ -21,11 +21,12 @@ def write_to_file(file_name): while True: text = input("enter any text") - F.write(f"{text}\n") + F.write(f"{text}\n") if input("do you want to enter more, y/n").lower() == "n": break - + + # step2: def check_first_letter(): with open(file_name) as F: @@ -37,10 +38,13 @@ def check_first_letter(): count_i = first_letters.count("i") count_m = first_letters.count("m") - print(f"The total number of sentences starting with I or M are {count_i + count_m}") + print( + f"The total number of sentences starting with I or M are {count_i + count_m}" + ) + if __name__ == "__main__": - + write_to_file(file_name) time.sleep(1) check_first_letter() diff --git a/AI Game/Tic-Tac-Toe-AI/tictactoe.py b/AI Game/Tic-Tac-Toe-AI/tictactoe.py index 6157ff6efb0..3b1973f1aff 100644 --- a/AI Game/Tic-Tac-Toe-AI/tictactoe.py +++ b/AI Game/Tic-Tac-Toe-AI/tictactoe.py @@ -1,70 +1,81 @@ -import tkinter as tk #provides a library of basic elements of GUI widgets -from tkinter import messagebox #provides a different set of dialogues that are used to display message boxes +import tkinter as tk # provides a library of basic elements of GUI widgets +from tkinter import ( + messagebox, +) # provides a different set of dialogues that are used to display message boxes import random + def check_winner(board, player): # Check rows, columns, and diagonals for a win for i in range(3): - if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): + if all(board[i][j] == player for j in range(3)) or all( + board[j][i] == player for j in range(3) + ): return True - if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): + if all(board[i][i] == player for i in range(3)) or all( + board[i][2 - i] == player for i in range(3) + ): return True return False + def is_board_full(board): - return all(all(cell != ' ' for cell in row) for row in board) + return all(all(cell != " " for cell in row) for row in board) + def minimax(board, depth, is_maximizing): - if check_winner(board, 'X'): + if check_winner(board, "X"): return -1 - if check_winner(board, 'O'): + if check_winner(board, "O"): return 1 - if is_board_full(board): #if game is full, terminate + if is_board_full(board): # if game is full, terminate return 0 - if is_maximizing: #recursive approach that fills board with Os - max_eval = float('-inf') + if is_maximizing: # recursive approach that fills board with Os + max_eval = float("-inf") for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'O' - eval = minimax(board, depth + 1, False) #recursion - board[i][j] = ' ' + if board[i][j] == " ": + board[i][j] = "O" + eval = minimax(board, depth + 1, False) # recursion + board[i][j] = " " max_eval = max(max_eval, eval) return max_eval - else: #recursive approach that fills board with Xs - min_eval = float('inf') + else: # recursive approach that fills board with Xs + min_eval = float("inf") for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'X' - eval = minimax(board, depth + 1, True) #recursion - board[i][j] = ' ' + if board[i][j] == " ": + board[i][j] = "X" + eval = minimax(board, depth + 1, True) # recursion + board[i][j] = " " min_eval = min(min_eval, eval) return min_eval -#determines the best move for the current player and returns a tuple representing the position + +# determines the best move for the current player and returns a tuple representing the position def best_move(board): - best_val = float('-inf') + best_val = float("-inf") best_move = None for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'O' + if board[i][j] == " ": + board[i][j] = "O" move_val = minimax(board, 0, False) - board[i][j] = ' ' + board[i][j] = " " if move_val > best_val: best_val = move_val best_move = (i, j) return best_move + def make_move(row, col): - if board[row][col] == ' ': - board[row][col] = 'X' - buttons[row][col].config(text='X') - if check_winner(board, 'X'): + if board[row][col] == " ": + board[row][col] = "X" + buttons[row][col].config(text="X") + if check_winner(board, "X"): messagebox.showinfo("Tic-Tac-Toe", "You win!") root.quit() elif is_board_full(board): @@ -75,28 +86,37 @@ def make_move(row, col): else: messagebox.showerror("Error", "Invalid move") -#AI's turn to play + +# AI's turn to play def ai_move(): row, col = best_move(board) - board[row][col] = 'O' - buttons[row][col].config(text='O') - if check_winner(board, 'O'): + board[row][col] = "O" + buttons[row][col].config(text="O") + if check_winner(board, "O"): messagebox.showinfo("Tic-Tac-Toe", "AI wins!") root.quit() elif is_board_full(board): messagebox.showinfo("Tic-Tac-Toe", "It's a draw!") root.quit() + root = tk.Tk() root.title("Tic-Tac-Toe") -board = [[' ' for _ in range(3)] for _ in range(3)] +board = [[" " for _ in range(3)] for _ in range(3)] buttons = [] for i in range(3): row_buttons = [] for j in range(3): - button = tk.Button(root, text=' ', font=('normal', 30), width=5, height=2, command=lambda row=i, col=j: make_move(row, col)) + button = tk.Button( + root, + text=" ", + font=("normal", 30), + width=5, + height=2, + command=lambda row=i, col=j: make_move(row, col), + ) button.grid(row=i, column=j) row_buttons.append(button) buttons.append(row_buttons) diff --git a/Armstrong_number.py b/Armstrong_number.py index 59732994f81..4dda5f7484f 100644 --- a/Armstrong_number.py +++ b/Armstrong_number.py @@ -6,19 +6,25 @@ this scripts only works for number in base 10 """ -def is_armstrong_number(number:str): - total:int = 0 - exp:int = len(number) #get the number of digits, this will determinate the exponent - digits:list[int] = [] - for digit in number: digits.append(int(digit)) #get the single digits - for x in digits: total += x ** exp #get the power of each digit and sum it to the total - +def is_armstrong_number(number: str): + total: int = 0 + exp: int = len( + number + ) # get the number of digits, this will determinate the exponent + + digits: list[int] = [] + for digit in number: + digits.append(int(digit)) # get the single digits + for x in digits: + total += x**exp # get the power of each digit and sum it to the total + # display the result if int(number) == total: - print(number,"is an Armstrong number") + print(number, "is an Armstrong number") else: - print(number,"is not an Armstrong number") + print(number, "is not an Armstrong number") + number = input("Enter the number : ") is_armstrong_number(number) diff --git a/Assembler/assembler.py b/Assembler/assembler.py index 24a6840c1d4..47c2f01cdb1 100644 --- a/Assembler/assembler.py +++ b/Assembler/assembler.py @@ -73,7 +73,7 @@ def scanner(string): match state: case 0: - + match ch: case "m": # catch mov-command @@ -185,12 +185,12 @@ def scanner(string): state = 47 token += ch - case _:# error case + case _: # error case state = 0 token = "" raise InvalidSyntax() - + case 2: # state 2 match ch: @@ -200,7 +200,7 @@ def scanner(string): state = 3 token += "v" - case _:# error case + case _: # error case state = 0 token = "" @@ -249,7 +249,7 @@ def scanner(string): raise InvalidSyntax() case 6: # state 6 - + if ch.isdigit(): state = 6 @@ -268,7 +268,7 @@ def scanner(string): raise InvalidSyntax() case 7: # state 7 - + match ch: case "d": @@ -276,7 +276,7 @@ def scanner(string): state = 8 token += ch - case _: # error case + case _: # error case state = 0 token = "" @@ -290,7 +290,7 @@ def scanner(string): state = 9 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -318,7 +318,7 @@ def scanner(string): state = 11 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -332,7 +332,7 @@ def scanner(string): state = 12 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -594,7 +594,7 @@ def scanner(string): raise InvalidSyntax() case 29: # state 29 - + match ch: case "m": @@ -806,7 +806,7 @@ def scanner(string): state = 42 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -819,7 +819,7 @@ def scanner(string): state = 43 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -846,7 +846,7 @@ def scanner(string): state = 45 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -859,7 +859,7 @@ def scanner(string): state = 46 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -886,7 +886,7 @@ def scanner(string): state = 48 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -913,7 +913,7 @@ def scanner(string): state = 50 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -1081,7 +1081,7 @@ def parser(): zeroFlag = False if eax == 0: zeroFlag = True - + case "ebx": ebx += token.token @@ -1089,7 +1089,7 @@ def parser(): zeroFlag = False if ebx == 0: zeroFlag = True - + case "ecx": ecx += token.token @@ -1097,7 +1097,7 @@ def parser(): zeroFlag = False if ecx == 0: zeroFlag = True - + case "edx": edx += token.token @@ -1301,7 +1301,6 @@ def parser(): # actual comparing zeroFlag = setZeroFlag(token.token, tmpToken.token) - elif token.token == "je": @@ -1448,7 +1447,7 @@ def parser(): return if token.t == "register": - + match token.token: case "eax": eax /= eax @@ -1470,8 +1469,9 @@ def parser(): # increment pointer for fetching next token. pointer += 1 + def setZeroFlag(token, tmpToken): - """ return bool for zero flag based on the regToken """ + """return bool for zero flag based on the regToken""" global eax, ebx, ecx, edx # Register in string @@ -1507,6 +1507,7 @@ def setZeroFlag(token, tmpToken): return zeroFlag + def registerLabels(): """ This function search for labels / subprogram-labels and registers this in the 'jumps' list. diff --git a/AutoComplete_App/backend.py b/AutoComplete_App/backend.py index 47e1c7906d6..a86e6797742 100644 --- a/AutoComplete_App/backend.py +++ b/AutoComplete_App/backend.py @@ -1,12 +1,13 @@ import sqlite3 import json + class AutoComplete: """ It works by building a `WordMap` that stores words to word-follower-count ---------------------------- e.g. To train the following statement: - + It is not enough to just know how tools work and what they worth, we have got to learn how to use them and to use them well. And with all these new weapons in your arsenal, we would better @@ -46,9 +47,21 @@ def __init__(self): if not tables_exist: self.conn.execute("CREATE TABLE WordMap(name TEXT, value TEXT)") - self.conn.execute('CREATE TABLE WordPrediction (name TEXT, value TEXT)') - cur.execute("INSERT INTO WordMap VALUES (?, ?)", ("wordsmap", "{}",)) - cur.execute("INSERT INTO WordPrediction VALUES (?, ?)", ("predictions", "{}",)) + self.conn.execute("CREATE TABLE WordPrediction (name TEXT, value TEXT)") + cur.execute( + "INSERT INTO WordMap VALUES (?, ?)", + ( + "wordsmap", + "{}", + ), + ) + cur.execute( + "INSERT INTO WordPrediction VALUES (?, ?)", + ( + "predictions", + "{}", + ), + ) def train(self, sentence): """ @@ -66,14 +79,18 @@ def train(self, sentence): cur = self.conn.cursor() words_list = sentence.split(" ") - words_map = cur.execute("SELECT value FROM WordMap WHERE name='wordsmap'").fetchone()[0] + words_map = cur.execute( + "SELECT value FROM WordMap WHERE name='wordsmap'" + ).fetchone()[0] words_map = json.loads(words_map) - predictions = cur.execute("SELECT value FROM WordPrediction WHERE name='predictions'").fetchone()[0] + predictions = cur.execute( + "SELECT value FROM WordPrediction WHERE name='predictions'" + ).fetchone()[0] predictions = json.loads(predictions) - for idx in range(len(words_list)-1): - curr_word, next_word = words_list[idx], words_list[idx+1] + for idx in range(len(words_list) - 1): + curr_word, next_word = words_list[idx], words_list[idx + 1] if curr_word not in words_map: words_map[curr_word] = {} if next_word not in words_map[curr_word]: @@ -84,20 +101,30 @@ def train(self, sentence): # checking the completion word against the next word if curr_word not in predictions: predictions[curr_word] = { - 'completion_word': next_word, - 'completion_count': 1 + "completion_word": next_word, + "completion_count": 1, } else: - if words_map[curr_word][next_word] > predictions[curr_word]['completion_count']: - predictions[curr_word]['completion_word'] = next_word - predictions[curr_word]['completion_count'] = words_map[curr_word][next_word] + if ( + words_map[curr_word][next_word] + > predictions[curr_word]["completion_count"] + ): + predictions[curr_word]["completion_word"] = next_word + predictions[curr_word]["completion_count"] = words_map[curr_word][ + next_word + ] words_map = json.dumps(words_map) predictions = json.dumps(predictions) - cur.execute("UPDATE WordMap SET value = (?) WHERE name='wordsmap'", (words_map,)) - cur.execute("UPDATE WordPrediction SET value = (?) WHERE name='predictions'", (predictions,)) - return("training complete") + cur.execute( + "UPDATE WordMap SET value = (?) WHERE name='wordsmap'", (words_map,) + ) + cur.execute( + "UPDATE WordPrediction SET value = (?) WHERE name='predictions'", + (predictions,), + ) + return "training complete" def predict(self, word): """ @@ -110,17 +137,18 @@ def predict(self, word): - returns the completion word of the input word """ cur = self.conn.cursor() - predictions = cur.execute("SELECT value FROM WordPrediction WHERE name='predictions'").fetchone()[0] + predictions = cur.execute( + "SELECT value FROM WordPrediction WHERE name='predictions'" + ).fetchone()[0] predictions = json.loads(predictions) - completion_word = predictions[word.lower()]['completion_word'] + completion_word = predictions[word.lower()]["completion_word"] return completion_word - if __name__ == "__main__": input_ = "It is not enough to just know how tools work and what they worth,\ we have got to learn how to use them and to use them well. And with\ all these new weapons in your arsenal, we would better get those profits fired up" ac = AutoComplete() ac.train(input_) - print(ac.predict("to")) \ No newline at end of file + print(ac.predict("to")) diff --git a/AutoComplete_App/frontend.py b/AutoComplete_App/frontend.py index 90e576e849e..35d776daeb5 100644 --- a/AutoComplete_App/frontend.py +++ b/AutoComplete_App/frontend.py @@ -8,15 +8,17 @@ def train(): ac = backend.AutoComplete() ac.train(sentence) + def predict_word(): word = predict_word_entry.get() ac = backend.AutoComplete() print(ac.predict(word)) + if __name__ == "__main__": root = Tk() root.title("Input note") - root.geometry('300x300') + root.geometry("300x300") train_label = Label(root, text="Train") train_label.pack() @@ -34,4 +36,4 @@ def predict_word(): predict_button = Button(root, text="predict", command=predict_word) predict_button.pack() - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py index 3082dbb7193..786ac9c6f25 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -23,13 +23,14 @@ # Here the collection name is on_call which has documents with fields phone , from (%H:%M:%S time to call the person),date + # gets data from cloud database and calls 5 min prior the time (from time) alloted in the database def search(): calling_time = datetime.now() one_hours_from_now = (calling_time + timedelta(hours=1)).strftime("%H:%M:%S") current_date = str(strftime("%d-%m-%Y", gmtime())) - docs = db.collection(u"on_call").where(u"date", u"==", current_date).stream() + docs = db.collection("on_call").where("date", "==", current_date).stream() list_of_docs = [] for doc in docs: diff --git a/Battery_notifier.py b/Battery_notifier.py index d871e43d928..2f45301bc1e 100644 --- a/Battery_notifier.py +++ b/Battery_notifier.py @@ -6,9 +6,7 @@ # battery percent will return the current battery prcentage percent = battery.percent -charging = ( - battery.power_plugged -) +charging = battery.power_plugged # Notification(title, description, duration)--to send # notification to desktop diff --git a/Binary_search.py b/Binary_search.py index 0b2211d6a48..3961529fcc8 100644 --- a/Binary_search.py +++ b/Binary_search.py @@ -24,7 +24,10 @@ def binary_search(arr, l, r, x): # Main Function if __name__ == "__main__": # User input array - arr = [int(x) for x in input("Enter the array with elements separated by commas: ").split(",")] + arr = [ + int(x) + for x in input("Enter the array with elements separated by commas: ").split(",") + ] # User input element to search for x = int(input("Enter the element you want to search for: ")) diff --git a/BlackJack_game/blackjack.py b/BlackJack_game/blackjack.py index c1bc919e01c..a241ac94416 100644 --- a/BlackJack_game/blackjack.py +++ b/BlackJack_game/blackjack.py @@ -107,7 +107,7 @@ def dealer_choice(): # to continue the game again and again !! k = input("Want to hit or stay?\n Press 1 for hit and 0 for stay ") - if k == "1": #Ammended 1 to a string + if k == "1": # Ammended 1 to a string random.shuffle(deck) p_cards.append(deck.pop()) print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards) diff --git a/BoardGame-CLI/python.py b/BoardGame-CLI/python.py index 40183159ec1..49929a775ce 100644 --- a/BoardGame-CLI/python.py +++ b/BoardGame-CLI/python.py @@ -2,16 +2,35 @@ # Define the game board with snakes and ladders snakes_and_ladders = { - 2: 38, 7: 14, 8: 31, 15: 26, 16: 6, 21: 42, - 28: 84, 36: 44, 46: 25, 49: 11, 51: 67, 62: 19, - 64: 60, 71: 91, 74: 53, 78: 98, 87: 94, 89: 68, - 92: 88, 95: 75, 99: 80 + 2: 38, + 7: 14, + 8: 31, + 15: 26, + 16: 6, + 21: 42, + 28: 84, + 36: 44, + 46: 25, + 49: 11, + 51: 67, + 62: 19, + 64: 60, + 71: 91, + 74: 53, + 78: 98, + 87: 94, + 89: 68, + 92: 88, + 95: 75, + 99: 80, } + # Function to roll a six-sided die def roll_die(): return random.randint(1, 6) + # Function to simulate a single turn def take_turn(current_position, player_name): # Roll the die @@ -36,6 +55,7 @@ def take_turn(current_position, player_name): return new_position + # Main game loop def play_snakes_and_ladders(): player1_position = 1 @@ -65,5 +85,6 @@ def play_snakes_and_ladders(): elif player2_position == 100: print(f"{player2_name} won!") + # Start the game play_snakes_and_ladders() diff --git a/BoardGame-CLI/snakeLadder.py b/BoardGame-CLI/snakeLadder.py index d8892ed4339..eb10bcbc904 100644 --- a/BoardGame-CLI/snakeLadder.py +++ b/BoardGame-CLI/snakeLadder.py @@ -43,11 +43,11 @@ def play(): global imp while imp: - print("/"*20) + print("/" * 20) print("1 -> roll the dice (or enter)") print("2 -> start new game") print("3 -> exit the game") - print("/"*20) + print("/" * 20) for i in players: n = input("{}'s turn: ".format(i)) or 1 @@ -70,7 +70,7 @@ def play(): looproll = roll() temp1 += looproll print(f"you got {looproll} ") - if counter_6 == 3 : + if counter_6 == 3: temp1 -= 18 print("Three consectutives 6 got cancelled") print("") @@ -116,19 +116,19 @@ def move(a, i): # snake bite code def snake(c, i): - if (c == 32): + if c == 32: players[i] = 10 - elif (c == 36): + elif c == 36: players[i] = 6 - elif (c == 48): + elif c == 48: players[i] = 26 - elif (c == 63): + elif c == 63: players[i] = 18 - elif (c == 88): + elif c == 88: players[i] = 24 - elif (c == 95): + elif c == 95: players[i] = 56 - elif (c == 97): + elif c == 97: players[i] = 78 else: return players[i] @@ -141,21 +141,21 @@ def snake(c, i): def ladder(a, i): global players - if (a == 4): + if a == 4: players[i] = 14 - elif (a == 8): + elif a == 8: players[i] = 30 - elif (a == 20): + elif a == 20: players[i] = 38 - elif (a == 40): + elif a == 40: players[i] = 42 - elif (a == 28): + elif a == 28: players[i] = 76 - elif (a == 50): + elif a == 50: players[i] = 67 - elif (a == 71): + elif a == 71: players[i] = 92 - elif (a == 88): + elif a == 88: players[i] = 99 else: return players[i] @@ -165,9 +165,9 @@ def ladder(a, i): # while run: -print("/"*40) +print("/" * 40) print("Welcome to the snake ladder game !!!!!!!") -print("/"*40) +print("/" * 40) player_input() diff --git a/BoardGame-CLI/uno.py b/BoardGame-CLI/uno.py index 4f36372a5f8..f10f46c4ff8 100644 --- a/BoardGame-CLI/uno.py +++ b/BoardGame-CLI/uno.py @@ -1,6 +1,7 @@ # uno game # import random + """ Generate the UNO deck of 108 cards. Parameters: None @@ -99,9 +100,10 @@ def canPlay(colour, value, playerHand): numPlayers = int(input("How many players?")) while numPlayers < 2 or numPlayers > 4: numPlayers = int( - input("Invalid. Please enter a number between 2-4.\nHow many players?")) + input("Invalid. Please enter a number between 2-4.\nHow many players?") + ) for player in range(numPlayers): - players_name.append(input("Enter player {} name: ".format(player+1))) + players_name.append(input("Enter player {} name: ".format(player + 1))) players.append(drawCards(5)) @@ -121,11 +123,12 @@ def canPlay(colour, value, playerHand): print("Card on top of discard pile: {}".format(discards[-1])) if canPlay(currentColour, cardVal, players[playerTurn]): cardChosen = int(input("Which card do you want to play?")) - while not canPlay(currentColour, cardVal, [players[playerTurn][cardChosen-1]]): - cardChosen = int( - input("Not a valid card. Which card do you want to play?")) - print("You played {}".format(players[playerTurn][cardChosen-1])) - discards.append(players[playerTurn].pop(cardChosen-1)) + while not canPlay( + currentColour, cardVal, [players[playerTurn][cardChosen - 1]] + ): + cardChosen = int(input("Not a valid card. Which card do you want to play?")) + print("You played {}".format(players[playerTurn][cardChosen - 1])) + discards.append(players[playerTurn].pop(cardChosen - 1)) # cheak if player won if len(players[playerTurn]) == 0: @@ -142,13 +145,13 @@ def canPlay(colour, value, playerHand): cardVal = splitCard[1] if currentColour == "Wild": for x in range(len(colours)): - print("{}) {}".format(x+1, colours[x])) - newColour = int( - input("What colour would you like to choose? ")) + print("{}) {}".format(x + 1, colours[x])) + newColour = int(input("What colour would you like to choose? ")) while newColour < 1 or newColour > 4: newColour = int( - input("Invalid option. What colour would you like to choose")) - currentColour = colours[newColour-1] + input("Invalid option. What colour would you like to choose") + ) + currentColour = colours[newColour - 1] if cardVal == "Reverse": playDirection = playDirection * -1 elif cardVal == "Skip": @@ -156,20 +159,20 @@ def canPlay(colour, value, playerHand): if playerTurn >= numPlayers: playerTurn = 0 elif playerTurn < 0: - playerTurn = numPlayers-1 + playerTurn = numPlayers - 1 elif cardVal == "Draw Two": - playerDraw = playerTurn+playDirection + playerDraw = playerTurn + playDirection if playerDraw == numPlayers: playerDraw = 0 elif playerDraw < 0: - playerDraw = numPlayers-1 + playerDraw = numPlayers - 1 players[playerDraw].extend(drawCards(2)) elif cardVal == "Draw Four": - playerDraw = playerTurn+playDirection + playerDraw = playerTurn + playDirection if playerDraw == numPlayers: playerDraw = 0 elif playerDraw < 0: - playerDraw = numPlayers-1 + playerDraw = numPlayers - 1 players[playerDraw].extend(drawCards(4)) print("") else: @@ -180,7 +183,7 @@ def canPlay(colour, value, playerHand): if playerTurn >= numPlayers: playerTurn = 0 elif playerTurn < 0: - playerTurn = numPlayers-1 + playerTurn = numPlayers - 1 print("Game Over") print("{} is the Winner!".format(winner)) diff --git a/Caesar Cipher Encoder & Decoder.py b/Caesar Cipher Encoder & Decoder.py index 63097b39e17..1df020bd03d 100644 --- a/Caesar Cipher Encoder & Decoder.py +++ b/Caesar Cipher Encoder & Decoder.py @@ -6,6 +6,7 @@ # Improved by: OfficialAhmed (https://github.com/OfficialAhmed) + def get_int() -> int: """ Get integer, otherwise redo @@ -19,6 +20,7 @@ def get_int() -> int: return key + def main(): print("[>] CAESAR CIPHER DECODER!!! \n") @@ -42,9 +44,9 @@ def encode(): encoded_cipher = "" text = input("Enter text to encode: ") key = get_int() - + for char in text: - + ascii = ord(char) + key encoded_cipher += chr(ascii) @@ -64,5 +66,5 @@ def decode(): print(decoded_cipher) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Calculate resistance.py b/Calculate resistance.py index 10c7a5ad3e2..605d4390214 100644 --- a/Calculate resistance.py +++ b/Calculate resistance.py @@ -1,12 +1,14 @@ def res(R1, R2): - sum = R1 + R2 - if (option =="series"): - return sum - else: - return (R1 * R2)/(R1 + R2) + sum = R1 + R2 + if option == "series": + return sum + else: + return (R1 * R2) / (R1 + R2) + + Resistance1 = int(input("Enter R1 : ")) Resistance2 = int(input("Enter R2 : ")) option = str(input("Enter series or parallel :")) print("\n") -R = res(Resistance1,Resistance2 ) +R = res(Resistance1, Resistance2) print("The total resistance is", R) diff --git a/Calendar (GUI).py b/Calendar (GUI).py index 1649a78785d..648f60bff9f 100644 --- a/Calendar (GUI).py +++ b/Calendar (GUI).py @@ -7,6 +7,7 @@ # Function + def text(): month_int = int(month.get()) year_int = int(year.get()) diff --git a/Cat/cat.py b/Cat/cat.py index 552ed6c1e7a..0c9ba120255 100644 --- a/Cat/cat.py +++ b/Cat/cat.py @@ -20,8 +20,10 @@ David Costell (DontEatThemCookies on GitHub) v2 - 03/12/2022 """ + import sys + def with_files(files): """Executes when file(s) is/are specified.""" try: @@ -35,6 +37,7 @@ def with_files(files): for contents in file_contents: sys.stdout.write(contents) + def no_files(): """Executes when no file(s) is/are specified.""" try: @@ -47,6 +50,7 @@ def no_files(): except EOFError: exit() + def main(): """Entry point of the cat program.""" # Read the arguments passed to the program @@ -55,5 +59,6 @@ def main(): else: with_files(sys.argv[1:]) + if __name__ == "__main__": main() diff --git a/Checker_game_by_dz/first.py b/Checker_game_by_dz/first.py index 55c572e3629..b809df4a00b 100644 --- a/Checker_game_by_dz/first.py +++ b/Checker_game_by_dz/first.py @@ -16,6 +16,7 @@ WIN = pg.display.set_mode((st.width, st.height)) pg.display.set_caption("Checkers") + # get row and col for mouse def get_row_col_mouse(pos): x, y = pos diff --git a/Checker_game_by_dz/modules/checker_board.py b/Checker_game_by_dz/modules/checker_board.py index b14df11b360..0e8615ee292 100644 --- a/Checker_game_by_dz/modules/checker_board.py +++ b/Checker_game_by_dz/modules/checker_board.py @@ -7,6 +7,7 @@ from .statics import * from .pieces import * + # checker board creation class checker_board: def __init__(self): diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index 3c3c06ea616..a75395515e5 100644 --- a/Colors/pixel_sort.py +++ b/Colors/pixel_sort.py @@ -30,6 +30,7 @@ total = 0 dict, final, img_list = {}, [], [] + # Create dataframe and save it as an excel file def createDataSet(val=0, data=[]): global dict diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py index c1aa7825a19..b9f0b1a93e5 100644 --- a/CountMillionCharacter.py +++ b/CountMillionCharacter.py @@ -6,6 +6,7 @@ Credit to William J. Turkel and Adam Crymble for the word frequency code used below. I just merged the two ideas. """ + import re pattern = re.compile("\W") # re is used to compile the expression more than once diff --git a/Crack_password.py b/Crack_password.py index b32af07afd6..2cae1721b18 100644 --- a/Crack_password.py +++ b/Crack_password.py @@ -1,11 +1,39 @@ from random import * + user_pass = input("Enter your password: ") -password = ['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',] +password = [ + "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", +] guess = "" -while (guess != user_pass): +while guess != user_pass: guess = "" for letter in range(len(user_pass)): guess_letter = password[randint(0, 25)] guess = str(guess_letter) + str(guess) print(guess) -print("Your password is",guess) +print("Your password is", guess) diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py index a8e85097a14..da29312fe73 100644 --- a/Decimal_To_Binary.py +++ b/Decimal_To_Binary.py @@ -47,6 +47,7 @@ def dtbconverter(num): THis program accepts fractional values, the accuracy can be set below: """ + # Function to convert decimal number # to binary using recursion def DecimalToBinary(num): diff --git a/Divide Operator.py b/Divide Operator.py index 3e6468f6daf..7a2c8a2ed65 100644 --- a/Divide Operator.py +++ b/Divide Operator.py @@ -1,5 +1,5 @@ class DivisionOperation: - INT_MAX = float('inf') + INT_MAX = float("inf") def __init__(self, num1, num2): self.num1 = num1 diff --git a/Droplistmenu/GamesCalender.py b/Droplistmenu/GamesCalender.py index 990a164bd93..12a29d110e6 100644 --- a/Droplistmenu/GamesCalender.py +++ b/Droplistmenu/GamesCalender.py @@ -1,4 +1,3 @@ - from tkinter import * from tkcalendar import Calendar import tkinter as tk @@ -9,26 +8,21 @@ # Adjust size window.geometry("600x500") -gameList =["Game List:"] +gameList = ["Game List:"] + + # Change the label text def show(): - game = selected1.get() + " vs " + selected2.get()+" on "+cal.get_date() + game = selected1.get() + " vs " + selected2.get() + " on " + cal.get_date() gameList.append(game) - #print(gameList) + # print(gameList) gameListshow = "\n".join(gameList) - #print(gameList) + # print(gameList) label.config(text=gameListshow) # Dropdown menu options -options = [ - "Team 1", - "Team 2", - "Team 3", - "Team 4", - "Team 5", - "Team 6" -] +options = ["Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6"] # datatype of menu text selected1 = StringVar() @@ -53,19 +47,16 @@ def show(): drop2.place(x=100, y=110) # Add Calendar -cal = Calendar(window, selectmode='day', - year=2022, month=12, - day=1) +cal = Calendar(window, selectmode="day", year=2022, month=12, day=1) cal.place(x=300, y=20) - # Create button, it will change label text -button = Button( window, text="Add to calender", command=show).place(x=100,y=200) +button = Button(window, text="Add to calender", command=show).place(x=100, y=200) # Create Label label = Label(window, text=" ") label.place(x=150, y=250) -window.mainloop() \ No newline at end of file +window.mainloop() diff --git a/Electronics_Algorithms/resistance.py b/Electronics_Algorithms/resistance.py index c088732d90c..07cf335607c 100644 --- a/Electronics_Algorithms/resistance.py +++ b/Electronics_Algorithms/resistance.py @@ -1,69 +1,40 @@ -def resistance_calculator(material:str, lenght:float, section:float, temperature:float): - """ - material is a string indicating the material of the wire - - lenght is a floating value indicating the lenght of the wire in meters - - diameter is a floating value indicating the diameter of the wire in millimeters - - temperature is a floating value indicating the temperature at which the wire is operating in °C - - Available materials: - - silver - - copper - - aluminium - - tungsten - - iron - - steel - - zinc - - solder""" - - materials = { - "silver": { - "rho": 0.0163, - "coefficient": 0.0038 - }, - - "copper": { - "rho": 0.0178, - "coefficient": 0.00381 - }, - - "aluminium": { - "rho": 0.0284, - "coefficient": 0.004 - }, - - "tungsten": { - "rho": 0.055, - "coefficient": 0.0045 - }, - - "iron": { - "rho": 0.098, - "coefficient": 0.006 - }, - - "steel": { - "rho": 0.15, - "coefficient": 0.0047 - }, - - "zinc": { - "rho": 0.06, - "coefficient": 0.0037 - }, - - "solder": { - "rho": 0.12, - "coefficient": 0.0043 - } - } - - rho_20deg = materials[material]["rho"] - temp_coefficient = materials[material]["coefficient"] - - rho = rho_20deg * (1 + temp_coefficient * (temperature - 20)) - resistance = rho * lenght / section - - return f"{resistance}Ω" +def resistance_calculator( + material: str, lenght: float, section: float, temperature: float +): + """ + material is a string indicating the material of the wire + + lenght is a floating value indicating the lenght of the wire in meters + + diameter is a floating value indicating the diameter of the wire in millimeters + + temperature is a floating value indicating the temperature at which the wire is operating in °C + + Available materials: + - silver + - copper + - aluminium + - tungsten + - iron + - steel + - zinc + - solder""" + + materials = { + "silver": {"rho": 0.0163, "coefficient": 0.0038}, + "copper": {"rho": 0.0178, "coefficient": 0.00381}, + "aluminium": {"rho": 0.0284, "coefficient": 0.004}, + "tungsten": {"rho": 0.055, "coefficient": 0.0045}, + "iron": {"rho": 0.098, "coefficient": 0.006}, + "steel": {"rho": 0.15, "coefficient": 0.0047}, + "zinc": {"rho": 0.06, "coefficient": 0.0037}, + "solder": {"rho": 0.12, "coefficient": 0.0043}, + } + + rho_20deg = materials[material]["rho"] + temp_coefficient = materials[material]["coefficient"] + + rho = rho_20deg * (1 + temp_coefficient * (temperature - 20)) + resistance = rho * lenght / section + + return f"{resistance}Ω" diff --git a/Emoji Dictionary/emoji_dictionary.py b/Emoji Dictionary/emoji_dictionary.py index 04949946c9c..171efc98b31 100644 --- a/Emoji Dictionary/emoji_dictionary.py +++ b/Emoji Dictionary/emoji_dictionary.py @@ -314,6 +314,7 @@ def on_inputentry_click(event): ) outputtxt.place(x=120, y=400) + # function for exiting def exit_win(): if mbox.askokcancel("Exit", "Do you want to exit?"): diff --git a/Encryption using base64.py b/Encryption using base64.py index a5d874e00e2..6e2bc924f1f 100644 --- a/Encryption using base64.py +++ b/Encryption using base64.py @@ -1,14 +1,15 @@ import base64 -#Encryption + +# Encryption message = input() -message_bytes = message.encode('ascii') +message_bytes = message.encode("ascii") base64_bytes = base64.b64encode(message_bytes) -base64_message = base64_bytes.decode('ascii') +base64_message = base64_bytes.decode("ascii") print(base64_message) -#Decryption -base64_bytes = base64_message.encode('ascii') +# Decryption +base64_bytes = base64_message.encode("ascii") message_bytes = base64.b64decode(base64_bytes) -message = message_bytes.decode('ascii') +message = message_bytes.decode("ascii") print(message) diff --git a/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py index 76ca3b43eb7..c7ecd32ef75 100644 --- a/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py +++ b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py @@ -1,6 +1,7 @@ import cv2 import os + def extract_thumbnail(video_path, frame_size): """ Extracts a thumbnail frame from a video and saves it as an image file. @@ -18,22 +19,30 @@ def extract_thumbnail(video_path, frame_size): Example: extract_thumbnail('my_video.mp4', (320, 240)) - + Required Packages: cv2 (pip install cv2) - + This function is useful for generating thumbnail images from videos. """ video_capture = cv2.VideoCapture(video_path) # Open the video file for reading - total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Get the total number of frames in the video + total_frames = int( + video_capture.get(cv2.CAP_PROP_FRAME_COUNT) + ) # Get the total number of frames in the video middle_frame_index = total_frames // 2 # Calculate the index of the middle frame - video_capture.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_index) # Seek to the middle frame + video_capture.set( + cv2.CAP_PROP_POS_FRAMES, middle_frame_index + ) # Seek to the middle frame success, frame = video_capture.read() # Read the middle frame video_capture.release() # Release the video capture object if success: - frame = cv2.resize(frame, frame_size) # Resize the frame to the specified dimensions + frame = cv2.resize( + frame, frame_size + ) # Resize the frame to the specified dimensions thumbnail_filename = f"{os.path.basename(video_path)}_thumbnail.jpg" # Create a filename for the thumbnail cv2.imwrite(thumbnail_filename, frame) # Save the thumbnail frame as an image else: - raise Exception("Could not extract frame") # Raise an exception if frame extraction fails + raise Exception( + "Could not extract frame" + ) # Raise an exception if frame extraction fails diff --git a/FIND FACTORIAL OF A NUMBER.py b/FIND FACTORIAL OF A NUMBER.py index 37bc7cd8c01..2ad83891877 100644 --- a/FIND FACTORIAL OF A NUMBER.py +++ b/FIND FACTORIAL OF A NUMBER.py @@ -1,13 +1,18 @@ # Python program to find the factorial of a number provided by the user. + def factorial(n): - if n < 0: # factorial of number less than 0 is not possible - return "Oops!Factorial Not Possible" - elif n == 0: # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. - return 1 - else: - return n*factorial(n-1) -#Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0. - -n = int(input("Enter a number: ")) # asks the user for input -print(factorial(n)) # function call + if n < 0: # factorial of number less than 0 is not possible + return "Oops!Factorial Not Possible" + elif ( + n == 0 + ): # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. + return 1 + else: + return n * factorial(n - 1) + + +# Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0. + +n = int(input("Enter a number: ")) # asks the user for input +print(factorial(n)) # function call diff --git a/Face and eye Recognition/face_recofnation_first.py b/Face and eye Recognition/face_recofnation_first.py index c60faba84db..e50e6fa24f3 100644 --- a/Face and eye Recognition/face_recofnation_first.py +++ b/Face and eye Recognition/face_recofnation_first.py @@ -49,4 +49,4 @@ def detect_faces_and_eyes(): if __name__ == "__main__": # Call the main function - detect_faces_and_eyes() \ No newline at end of file + detect_faces_and_eyes() diff --git a/Face_Mask_detection (haarcascade)/mask_detection.py b/Face_Mask_detection (haarcascade)/mask_detection.py index 9ba4c34734b..619c27bae9f 100644 --- a/Face_Mask_detection (haarcascade)/mask_detection.py +++ b/Face_Mask_detection (haarcascade)/mask_detection.py @@ -22,7 +22,7 @@ cv2.imshow("webcam", img) faces = faceCascade.detectMultiScale(img, 1.1, 4) - for (x, y, w, h) in faces: + for x, y, w, h in faces: crop_img = img[y : y + h, x : x + w] crop_img = cv2.resize(crop_img, (224, 224)) normalized_image_array = (crop_img.astype(np.float32) / 127.0) - 1 diff --git a/FibonacciNumbersWithGenerators.py b/FibonacciNumbersWithGenerators.py index 5d090a0a7ea..15771630222 100644 --- a/FibonacciNumbersWithGenerators.py +++ b/FibonacciNumbersWithGenerators.py @@ -1,10 +1,10 @@ -def fibonacci_generator(n = None): +def fibonacci_generator(n=None): """ - Generating function up to n fibonacci numbers iteratively - Params: - n: int - Return: - int + Generating function up to n fibonacci numbers iteratively + Params: + n: int + Return: + int """ f0, f1 = 0, 1 yield f1 @@ -14,5 +14,6 @@ def fibonacci_generator(n = None): f0, f1 = f1, fn n -= 1 + for n_fibo in fibonacci_generator(7): print(n_fibo) diff --git a/Find current weather of any city using openweathermap API.py b/Find current weather of any city using openweathermap API.py index cb2659c122f..794cca88f9b 100644 --- a/Find current weather of any city using openweathermap API.py +++ b/Find current weather of any city using openweathermap API.py @@ -1,72 +1,74 @@ -# Python program to find current -# weather details of any city -# using openweathermap api +# Python program to find current +# weather details of any city +# using openweathermap api -# import required modules -import requests, json +# import required modules +import requests, json -# Enter your API key here +# Enter your API key here api_key = "Your_API_Key" -# base_url variable to store url +# base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" -# Give city name -city_name = input("Enter city name : ") - -# complete_url variable to store -# complete url address -complete_url = base_url + "appid=" + api_key + "&q=" + city_name - -# get method of requests module -# return response object -response = requests.get(complete_url) - -# json method of response object -# convert json format data into -# python format data -x = response.json() - -# Now x contains list of nested dictionaries -# Check the value of "cod" key is equal to -# "404", means city is found otherwise, -# city is not found -if x["cod"] != "404": - - # store the value of "main" - # key in variable y - y = x["main"] - - # store the value corresponding - # to the "temp" key of y - current_temperature = y["temp"] - - # store the value corresponding - # to the "pressure" key of y - current_pressure = y["pressure"] - - # store the value corresponding - # to the "humidity" key of y - current_humidiy = y["humidity"] - - # store the value of "weather" - # key in variable z - z = x["weather"] - - # store the value corresponding - # to the "description" key at - # the 0th index of z - weather_description = z[0]["description"] - - # print following values - print(" Temperature (in kelvin unit) = " + - str(current_temperature) + - "\n atmospheric pressure (in hPa unit) = " + - str(current_pressure) + - "\n humidity (in percentage) = " + - str(current_humidiy) + - "\n description = " + - str(weather_description)) - -else: - print(" City Not Found ") +# Give city name +city_name = input("Enter city name : ") + +# complete_url variable to store +# complete url address +complete_url = base_url + "appid=" + api_key + "&q=" + city_name + +# get method of requests module +# return response object +response = requests.get(complete_url) + +# json method of response object +# convert json format data into +# python format data +x = response.json() + +# Now x contains list of nested dictionaries +# Check the value of "cod" key is equal to +# "404", means city is found otherwise, +# city is not found +if x["cod"] != "404": + + # store the value of "main" + # key in variable y + y = x["main"] + + # store the value corresponding + # to the "temp" key of y + current_temperature = y["temp"] + + # store the value corresponding + # to the "pressure" key of y + current_pressure = y["pressure"] + + # store the value corresponding + # to the "humidity" key of y + current_humidiy = y["humidity"] + + # store the value of "weather" + # key in variable z + z = x["weather"] + + # store the value corresponding + # to the "description" key at + # the 0th index of z + weather_description = z[0]["description"] + + # print following values + print( + " Temperature (in kelvin unit) = " + + str(current_temperature) + + "\n atmospheric pressure (in hPa unit) = " + + str(current_pressure) + + "\n humidity (in percentage) = " + + str(current_humidiy) + + "\n description = " + + str(weather_description) + ) + +else: + print(" City Not Found ") diff --git a/FindingResolutionOfAnImage.py b/FindingResolutionOfAnImage.py index 9c6336d8d1d..333a1effb2a 100644 --- a/FindingResolutionOfAnImage.py +++ b/FindingResolutionOfAnImage.py @@ -1,24 +1,25 @@ def jpeg_res(filename): - """"This function prints the resolution of the jpeg image file passed into it""" + """ "This function prints the resolution of the jpeg image file passed into it""" - # open image for reading in binary mode - with open(filename,'rb') as img_file: + # open image for reading in binary mode + with open(filename, "rb") as img_file: - # height of image (in 2 bytes) is at 164th position - img_file.seek(163) + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) - # read the 2 bytes - a = img_file.read(2) + # read the 2 bytes + a = img_file.read(2) - # calculate height - height = (a[0] << 8) + a[1] + # calculate height + height = (a[0] << 8) + a[1] - # next 2 bytes is width - a = img_file.read(2) + # next 2 bytes is width + a = img_file.read(2) - # calculate width - width = (a[0] << 8) + a[1] + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is", width, "x", height) - print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") diff --git a/FizzBuzz.py b/FizzBuzz.py index 59c78fad2a9..cf8caba4c4e 100644 --- a/FizzBuzz.py +++ b/FizzBuzz.py @@ -18,5 +18,4 @@ def FizzBuzz(num): print(i) - FizzBuzz(20) # prints FizzBuzz up to 20 diff --git a/Generate a random number between 0 to 9.py b/Generate a random number between 0 to 9.py index a035d9f8502..c304fa85b1d 100644 --- a/Generate a random number between 0 to 9.py +++ b/Generate a random number between 0 to 9.py @@ -3,4 +3,4 @@ # importing the random module import random -print(random.randint(0,9)) +print(random.randint(0, 9)) diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index a922894a8d0..d42f4a3ac86 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -113,7 +113,7 @@ def download_wallpapers_1080p(): ################### def view_images_directory(): - for (folders, subfolder, files) in walk(curdir): + for folders, subfolder, files in walk(curdir): for folder in subfolder: print(folder) return True diff --git a/Grocery calculator.py b/Grocery calculator.py index eedb5c7ea15..6ab49fc1b8b 100644 --- a/Grocery calculator.py +++ b/Grocery calculator.py @@ -1,45 +1,47 @@ -'''This will be a Python script that functions as a grocery calculator. It will take in key-value pairs for items +"""This will be a Python script that functions as a grocery calculator. It will take in key-value pairs for items and their prices, and return the subtotal and total, and can print out the list for you for when you're ready to -take it to the store!''' +take it to the store!""" -'''Algorithm: +"""Algorithm: 1. User enters key-value pairs that are added into a dict. -2. Users tells script to return total, subtotal, and key-value pairs in a nicely formatted list.''' +2. Users tells script to return total, subtotal, and key-value pairs in a nicely formatted list.""" -#Object = GroceryList -#Methods = addToList, Total, Subtotal, returnList + +# Object = GroceryList +# Methods = addToList, Total, Subtotal, returnList class GroceryList(dict): - def __init__(self): - self = {} + def __init__(self): + self = {} + + def addToList(self, item, price): + + self.update({item: price}) - def addToList(self, item, price): - - self.update({item:price}) + def Total(self): + total = 0 + for items in self: + total += (self[items]) * 0.07 + (self[items]) + return total - def Total(self): - total = 0 - for items in self: - total += (self[items])*.07 + (self[items]) - return total + def Subtotal(self): + subtotal = 0 + for items in self: + subtotal += self[items] + return subtotal - def Subtotal(self): - subtotal = 0 - for items in self: - subtotal += self[items] - return subtotal + def returnList(self): + return self - def returnList(self): - return self -'''Test list should return: +"""Test list should return: Total = 10.70 Subtotal = 10 returnList = {"milk":4, "eggs":3, "kombucha":3} -''' +""" List1 = GroceryList() -List1.addToList("milk",4) +List1.addToList("milk", 4) List1.addToList("eggs", 3) List1.addToList("kombucha", 3) @@ -48,16 +50,16 @@ def returnList(self): print(List1.Subtotal()) print(List1.returnList()) -#***************************************************** +# ***************************************************** print() -#***************************************************** +# ***************************************************** List2 = GroceryList() -List2.addToList('cheese', 7.49) -List2.addToList('wine', 25.36) -List2.addToList('steak', 17.64) +List2.addToList("cheese", 7.49) +List2.addToList("wine", 25.36) +List2.addToList("steak", 17.64) print(List2.Total()) print(List2.Subtotal()) diff --git a/Hand-Motion-Detection/hand_motion_recognizer.py b/Hand-Motion-Detection/hand_motion_recognizer.py index 59efb53c8ef..4b4fd588dba 100644 --- a/Hand-Motion-Detection/hand_motion_recognizer.py +++ b/Hand-Motion-Detection/hand_motion_recognizer.py @@ -6,43 +6,49 @@ cap = cv2.VideoCapture(0) -with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands: +with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands: while cap.isOpened(): ret, frame = cap.read() - + # BGR 2 RGB image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - + # Flip on horizontal image = cv2.flip(image, 1) - + # Set flag image.flags.writeable = False - + # Detections results = hands.process(image) - + # Set flag to true image.flags.writeable = True - + # RGB 2 BGR image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) - + # Detections print(results) - + # Rendering results if results.multi_hand_landmarks: for num, hand in enumerate(results.multi_hand_landmarks): - mp_drawing.draw_landmarks(image, hand, mp_hands.HAND_CONNECTIONS, - mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), - mp_drawing.DrawingSpec(color=(250, 44, 250), thickness=2, circle_radius=2), - ) - - - cv2.imshow('Hand Tracking', image) - - if cv2.waitKey(10) & 0xFF == ord('q'): + mp_drawing.draw_landmarks( + image, + hand, + mp_hands.HAND_CONNECTIONS, + mp_drawing.DrawingSpec( + color=(121, 22, 76), thickness=2, circle_radius=4 + ), + mp_drawing.DrawingSpec( + color=(250, 44, 250), thickness=2, circle_radius=2 + ), + ) + + cv2.imshow("Hand Tracking", image) + + if cv2.waitKey(10) & 0xFF == ord("q"): break cap.release() diff --git a/Hotel-Management.py b/Hotel-Management.py index edfdec0934a..021daba2110 100644 --- a/Hotel-Management.py +++ b/Hotel-Management.py @@ -1,36 +1,15 @@ - def menu(): options = { - 1 : { - "title" : "Add new customer details", - "method": lambda : add() - }, - - 2 : { - "title" : "Modify already existing customer details", - "method": lambda : modify() - }, - - 3 : { - "title" : "Search customer details", - "method": lambda : search() - }, - - 4 : { - "title" : "View all customer details", - "method": lambda : view() - }, - - 5 : { - "title" : "Delete customer details", - "method": lambda : remove() - }, - - 6 : { - "title" : "Exit the program", - "method": lambda : exit() - } + 1: {"title": "Add new customer details", "method": lambda: add()}, + 2: { + "title": "Modify already existing customer details", + "method": lambda: modify(), + }, + 3: {"title": "Search customer details", "method": lambda: search()}, + 4: {"title": "View all customer details", "method": lambda: view()}, + 5: {"title": "Delete customer details", "method": lambda: remove()}, + 6: {"title": "Exit the program", "method": lambda: exit()}, } print(f"\n\n{' '*25}Welcome to Hotel Database Management Software\n\n") @@ -39,7 +18,7 @@ def menu(): print(f"{num}: {option.get('title')}") print() - options.get( int(input("Enter your choice(1-6): ")) ).get("method")() + options.get(int(input("Enter your choice(1-6): "))).get("method")() def add(): @@ -167,7 +146,7 @@ def modify(): print() with open("Management.txt", "w", encoding="utf-8") as File: - + match choice: case 1: category = "First_Name" diff --git a/ImageDownloader/img_downloader.py b/ImageDownloader/img_downloader.py index 9844635cdaf..f12f940e920 100644 --- a/ImageDownloader/img_downloader.py +++ b/ImageDownloader/img_downloader.py @@ -18,7 +18,7 @@ def ImageDownloader(url): # USAGE print("Hey!! Welcome to the Image downloader...") -link=input("Please enter the url from where you want to download the image..") +link = input("Please enter the url from where you want to download the image..") # now you can give the input at run time and get download the images. # https://www.123rf.com/stock-photo/spring_color.html?oriSearch=spring&ch=spring&sti=oazo8ueuz074cdpc48 ImageDownloader(link) diff --git a/Image_resize.py b/Image_resize.py index 9c6336d8d1d..333a1effb2a 100644 --- a/Image_resize.py +++ b/Image_resize.py @@ -1,24 +1,25 @@ def jpeg_res(filename): - """"This function prints the resolution of the jpeg image file passed into it""" + """ "This function prints the resolution of the jpeg image file passed into it""" - # open image for reading in binary mode - with open(filename,'rb') as img_file: + # open image for reading in binary mode + with open(filename, "rb") as img_file: - # height of image (in 2 bytes) is at 164th position - img_file.seek(163) + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) - # read the 2 bytes - a = img_file.read(2) + # read the 2 bytes + a = img_file.read(2) - # calculate height - height = (a[0] << 8) + a[1] + # calculate height + height = (a[0] << 8) + a[1] - # next 2 bytes is width - a = img_file.read(2) + # next 2 bytes is width + a = img_file.read(2) - # calculate width - width = (a[0] << 8) + a[1] + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is", width, "x", height) - print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") diff --git a/Industrial_developed_hangman/src/hangman/main.py b/Industrial_developed_hangman/src/hangman/main.py index b2a7e780ac3..4124040d556 100644 --- a/Industrial_developed_hangman/src/hangman/main.py +++ b/Industrial_developed_hangman/src/hangman/main.py @@ -11,7 +11,7 @@ DEBUG = False success_code = 200 request_timeout = 1000 -data_path = Path(__file__).parent.parent.parent / 'Data' +data_path = Path(__file__).parent.parent.parent / "Data" year = 4800566455 @@ -43,7 +43,9 @@ def print_right(text: str, print_function: Callable[[str], None]) -> None: print_function(Style.RESET_ALL + Fore.GREEN + text) -def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.choice) -> str: +def parse_word_from_local( + choice_function: Callable[[List[str]], str] = random.choice +) -> str: # noqa: DAR201 """ Parse word from local file. @@ -53,13 +55,15 @@ def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.c :raises FileNotFoundError: file to read words not found. """ try: - with open(data_path / 'local_words.txt', encoding='utf8') as words_file: - return choice_function(words_file.read().split('\n')) + with open(data_path / "local_words.txt", encoding="utf8") as words_file: + return choice_function(words_file.read().split("\n")) except FileNotFoundError: - raise FileNotFoundError('File local_words.txt was not found') + raise FileNotFoundError("File local_words.txt was not found") -def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word') -> str: +def parse_word_from_site( + url: str = "https://random-word-api.herokuapp.com/word", +) -> str: # noqa: DAR201 """ Parse word from website. @@ -72,16 +76,18 @@ def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word' try: response: requests.Response = requests.get(url, timeout=request_timeout) except ConnectionError: - raise ConnectionError('There is no connection to the internet') + raise ConnectionError("There is no connection to the internet") if response.status_code == success_code: return json.loads(response.content.decode())[0] - raise RuntimeError('Something go wrong with getting the word from site') + raise RuntimeError("Something go wrong with getting the word from site") class MainProcess(object): """Manages game process.""" - def __init__(self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: Callable) -> None: + def __init__( + self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: Callable + ) -> None: """ Init MainProcess object. @@ -91,8 +97,8 @@ def __init__(self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: :parameter ch_func: Function that will be used to choice word. """ self._source = source - self._answer_word = '' - self._word_string_to_show = '' + self._answer_word = "" + self._word_string_to_show = "" self._guess_attempts_coefficient = 2 self._print_function = pr_func self._input_function = in_func @@ -110,15 +116,19 @@ def get_word(self) -> str: return parse_word_from_site() elif self._source == Source.FROM_FILE: return parse_word_from_local(self._choice_function) - raise AttributeError('Non existing enum') + raise AttributeError("Non existing enum") def user_lose(self) -> None: """Print text for end of game and exits.""" - print_wrong(f"YOU LOST(the word was '{self._answer_word}')", self._print_function) # noqa:WPS305 + print_wrong( + f"YOU LOST(the word was '{self._answer_word}')", self._print_function + ) # noqa:WPS305 def user_win(self) -> None: """Print text for end of game and exits.""" - print_wrong(f'{self._word_string_to_show} YOU WON', self._print_function) # noqa:WPS305 + print_wrong( + f"{self._word_string_to_show} YOU WON", self._print_function + ) # noqa:WPS305 def game_process(self, user_character: str) -> bool: # noqa: DAR201 @@ -133,9 +143,9 @@ def game_process(self, user_character: str) -> bool: for index, character in enumerate(self._answer_word): if character == user_character: word_list_to_show[index] = user_character - self._word_string_to_show = ''.join(word_list_to_show) + self._word_string_to_show = "".join(word_list_to_show) else: - print_wrong('There is no such character in word', self._print_function) + print_wrong("There is no such character in word", self._print_function) if self._answer_word == self._word_string_to_show: self.user_win() return True @@ -144,26 +154,32 @@ def game_process(self, user_character: str) -> bool: def start_game(self) -> None: """Start main process of the game.""" if time.time() > year: - print_right('this program is more then 100years age', self._print_function) - with open(data_path / 'text_images.txt', encoding='utf8') as text_images_file: + print_right("this program is more then 100years age", self._print_function) + with open(data_path / "text_images.txt", encoding="utf8") as text_images_file: print_wrong(text_images_file.read(), self._print_function) - print_wrong('Start guessing...', self._print_function) + print_wrong("Start guessing...", self._print_function) self._answer_word = self.get_word() - self._word_string_to_show = '_' * len(self._answer_word) + self._word_string_to_show = "_" * len(self._answer_word) attempts_amount = int(self._guess_attempts_coefficient * len(self._answer_word)) if DEBUG: print_right(self._answer_word, self._print_function) for attempts in range(attempts_amount): user_remaining_attempts = attempts_amount - attempts - print_right(f'You have {user_remaining_attempts} more attempts', self._print_function) # noqa:WPS305 - print_right(f'{self._word_string_to_show} enter character to guess: ', self._print_function) # noqa:WPS305 + print_right( + f"You have {user_remaining_attempts} more attempts", + self._print_function, + ) # noqa:WPS305 + print_right( + f"{self._word_string_to_show} enter character to guess: ", + self._print_function, + ) # noqa:WPS305 user_character = self._input_function().lower() if self.game_process(user_character): break - if '_' in self._word_string_to_show: + if "_" in self._word_string_to_show: self.user_lose() -if __name__ == '__main__': +if __name__ == "__main__": main_process = MainProcess(Source(1), print, input, random.choice) main_process.start_game() diff --git a/Industrial_developed_hangman/tests/test_hangman/test_main.py b/Industrial_developed_hangman/tests/test_hangman/test_main.py index 46d0b1d6f0e..34f03c02885 100644 --- a/Industrial_developed_hangman/tests/test_hangman/test_main.py +++ b/Industrial_developed_hangman/tests/test_hangman/test_main.py @@ -39,9 +39,9 @@ def test_parse_word_from_local() -> None: def test_parse_word_from_local_error() -> None: - data_path = Path(os.path.abspath('')) / 'Data' - real_name = 'local_words.txt' - time_name = 'local_words_not_exist.txt' + data_path = Path(os.path.abspath("")) / "Data" + real_name = "local_words.txt" + time_name = "local_words_not_exist.txt" os.rename(data_path / real_name, data_path / time_name) with pytest.raises(FileNotFoundError): @@ -56,50 +56,60 @@ def test_parse_word_from_site() -> None: def test_parse_word_from_site_no_internet() -> None: with requests_mock.Mocker() as mock: - mock.get('https://random-word-api.herokuapp.com/word', text='["some text"]') - assert parse_word_from_site() == 'some text' + mock.get("https://random-word-api.herokuapp.com/word", text='["some text"]') + assert parse_word_from_site() == "some text" def test_parse_word_from_site_err() -> None: with pytest.raises(RuntimeError): - parse_word_from_site(url='https://www.google.com/dsfsdfds/sdfsdf/sdfds') + parse_word_from_site(url="https://www.google.com/dsfsdfds/sdfsdf/sdfds") def test_get_word(choice_fn: Callable) -> None: fk_print = FkPrint() - fk_input = FkInput(['none']) - main_process = MainProcess(Source(1), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["none"]) + main_process = MainProcess( + Source(1), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) assert isinstance(main_process.get_word(), str) def test_start_game_win(choice_fn: Callable) -> None: fk_print = FkPrint() - fk_input = FkInput(['j', 'a', 'm']) - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["j", "a", "m"]) + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'YOU WON' in fk_print.container[-1] + assert "YOU WON" in fk_print.container[-1] -@pytest.mark.parametrize('input_str', [[letter] * 10 for letter in 'qwertyuiopasdfghjklzxcvbnm']) # noqa: WPS435 +@pytest.mark.parametrize( + "input_str", [[letter] * 10 for letter in "qwertyuiopasdfghjklzxcvbnm"] +) # noqa: WPS435 def test_start_game_loose(input_str: List[str], choice_fn: Callable) -> None: fk_print = FkPrint() fk_input = FkInput(input_str) - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'YOU LOST' in fk_print.container[-1] + assert "YOU LOST" in fk_print.container[-1] def test_wow_year(freezer, choice_fn: Callable) -> None: - freezer.move_to('2135-10-17') + freezer.move_to("2135-10-17") fk_print = FkPrint() - fk_input = FkInput(['none'] * 100) # noqa: WPS435 - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["none"] * 100) # noqa: WPS435 + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'this program' in fk_print.container[0] + assert "this program" in fk_print.container[0] diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index bdffa82e63c..0cf02861599 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,5 +1,6 @@ # Python program to convert infix expression to postfix + # Class to convert the expression class Conversion: diff --git a/JARVIS/JARVIS_2.0.py b/JARVIS/JARVIS_2.0.py index 6a4b738e8fa..5386fc9b8e8 100644 --- a/JARVIS/JARVIS_2.0.py +++ b/JARVIS/JARVIS_2.0.py @@ -13,7 +13,7 @@ import subprocess # subprocess module allows you to spawn new processes # master -import pyjokes # for generating random jokes +import pyjokes # for generating random jokes import requests import json from PIL import Image, ImageGrab @@ -30,17 +30,18 @@ # master # auto install for pyttsx3 and speechRecognition import os + try: - import pyttsx3 #Check if already installed -except:# If not installed give exception - os.system('pip install pyttsx3')#install at run time - import pyttsx3 #import again for speak function + import pyttsx3 # Check if already installed +except: # If not installed give exception + os.system("pip install pyttsx3") # install at run time + import pyttsx3 # import again for speak function -try : +try: import speech_recognition as sr except: - os.system('pip install speechRecognition') - import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc.. + os.system("pip install speechRecognition") + import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc.. # importing the pyttsx3 library import webbrowser @@ -82,25 +83,32 @@ def sendEmail(to, content): server.sendmail("youremail@gmail.com", to, content) server.close() + import openai -import base64 -stab=(base64.b64decode(b'c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx').decode("utf-8")) +import base64 + +stab = base64.b64decode( + b"c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx" +).decode("utf-8") api_key = stab + + def ask_gpt3(que): openai.api_key = api_key response = openai.Completion.create( - engine="text-davinci-002", + engine="text-davinci-002", prompt=f"Answer the following question: {question}\n", - max_tokens=150, - n = 1, - stop=None, - temperature=0.7 + max_tokens=150, + n=1, + stop=None, + temperature=0.7, ) answer = response.choices[0].text.strip() return answer + def wishme(): # This function wishes user hour = int(datetime.datetime.now().hour) @@ -249,9 +257,9 @@ def get_app(Q): elif Q == "open github": webbrowser.open("https://github.com/") elif Q == "search for": - que=Q.lstrip("search for") + que = Q.lstrip("search for") answer = ask_gpt3(que) - + elif ( Q == "email to other" ): # here you want to change and input your mail and password whenver you implement @@ -312,7 +320,7 @@ def get_app(Q): "paint": "mspaint.exe", "cmd": "cmd.exe", "browser": "C:\\Program Files\Internet Explorer\iexplore.exe", - "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code" + "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code", } # master diff --git a/Key_Binding/key_binding.py b/Key_Binding/key_binding.py index dfd448497b1..3cedfe512d7 100644 --- a/Key_Binding/key_binding.py +++ b/Key_Binding/key_binding.py @@ -3,8 +3,10 @@ session = Prompt() + @bind.add("ctrl-h") def _(event): print("Hello, World") + session.prompt("") diff --git a/Kilometerstomile.py b/Kilometerstomile.py index 2a4d33c8ff2..fc7b32304c8 100644 --- a/Kilometerstomile.py +++ b/Kilometerstomile.py @@ -6,4 +6,4 @@ # calculate miles miles = kilometers * conv_fac -print(f'{kilometers:.2f} kilometers is equal to {miles:.2f} miles') +print(f"{kilometers:.2f} kilometers is equal to {miles:.2f} miles") diff --git a/Laundary System/code.py b/Laundary System/code.py index 1c71e5a365b..96817e49f7b 100644 --- a/Laundary System/code.py +++ b/Laundary System/code.py @@ -1,75 +1,83 @@ -id=1 -class LaundryService: - def __init__(self,Name_of_customer,Contact_of_customer,Email,Type_of_cloth,Branded,Season,id): - self.Name_of_customer=Name_of_customer - self.Contact_of_customer=Contact_of_customer - self.Email=Email - self.Type_of_cloth=Type_of_cloth - self.Branded=Branded - self.Season=Season - self.id=id +id = 1 - def customerDetails(self): - print("The Specific Details of customer:") - print("customer ID: ",self.id) - print("customer name:", self.Name_of_customer) - print("customer contact no. :", self.Contact_of_customer) - print("customer email:", self.Email) - print("type of cloth", self.Type_of_cloth) - if self.Branded == 1: - a=True - else: - a=False - print("Branded", a) - def calculateCharge(self): - a=0 - if self.Type_of_cloth=="Cotton": - a=50.0 - elif self.Type_of_cloth=="Silk": - a=30.0 - elif self.Type_of_cloth=="Woolen": - a=90.0 - elif self.Type_of_cloth=="Polyester": - a=20.0 - if self.Branded==1: - a=1.5*(a) - else: - pass - if self.Season=="Winter": - a=0.5*a - else: - a=2*a - print(a) - return a - def finalDetails(self): - self.customerDetails() - print("Final charge:",end="") - if self.calculateCharge() >200: - print("to be return in 4 days") - else: - print("to be return in 7 days") -while True: - name=input("Enter the name: ") - contact=int(input("Enter the contact: ")) - email=input("Enter the email: ") - cloth=input("Enter the type of cloth: ") - brand=bool(input("Branded ? ")) - season=input("Enter the season: ") - obj=LaundryService(name,contact,email,cloth,brand,season,id) - obj.finalDetails() - id=id+1 - z=input("Do you want to continue(Y/N):") - if z=="Y": - continue - elif z =="N": - print("Thanks for visiting!") - break - else: - print("Select valid option") +class LaundryService: + def __init__( + self, + Name_of_customer, + Contact_of_customer, + Email, + Type_of_cloth, + Branded, + Season, + id, + ): + self.Name_of_customer = Name_of_customer + self.Contact_of_customer = Contact_of_customer + self.Email = Email + self.Type_of_cloth = Type_of_cloth + self.Branded = Branded + self.Season = Season + self.id = id + def customerDetails(self): + print("The Specific Details of customer:") + print("customer ID: ", self.id) + print("customer name:", self.Name_of_customer) + print("customer contact no. :", self.Contact_of_customer) + print("customer email:", self.Email) + print("type of cloth", self.Type_of_cloth) + if self.Branded == 1: + a = True + else: + a = False + print("Branded", a) + def calculateCharge(self): + a = 0 + if self.Type_of_cloth == "Cotton": + a = 50.0 + elif self.Type_of_cloth == "Silk": + a = 30.0 + elif self.Type_of_cloth == "Woolen": + a = 90.0 + elif self.Type_of_cloth == "Polyester": + a = 20.0 + if self.Branded == 1: + a = 1.5 * (a) + else: + pass + if self.Season == "Winter": + a = 0.5 * a + else: + a = 2 * a + print(a) + return a + def finalDetails(self): + self.customerDetails() + print("Final charge:", end="") + if self.calculateCharge() > 200: + print("to be return in 4 days") + else: + print("to be return in 7 days") - \ No newline at end of file +while True: + name = input("Enter the name: ") + contact = int(input("Enter the contact: ")) + email = input("Enter the email: ") + cloth = input("Enter the type of cloth: ") + brand = bool(input("Branded ? ")) + season = input("Enter the season: ") + obj = LaundryService(name, contact, email, cloth, brand, season, id) + obj.finalDetails() + id = id + 1 + z = input("Do you want to continue(Y/N):") + if z == "Y": + continue + elif z == "N": + print("Thanks for visiting!") + break + else: + print("Select valid option") diff --git a/List.py b/List.py index bfc9b223f26..4f93052338c 100644 --- a/List.py +++ b/List.py @@ -1,14 +1,14 @@ List = [] # List is Muteable # means value can be change -List.insert(0, 5) #insertion takes place at mentioned index -List.insert(1, 10) +List.insert(0, 5) # insertion takes place at mentioned index +List.insert(1, 10) List.insert(0, 6) print(List) -List.remove(6) -List.append(9) #insertion takes place at last +List.remove(6) +List.append(9) # insertion takes place at last List.append(1) -List.sort() #arranges element in ascending order +List.sort() # arranges element in ascending order print(List) List.pop() List.reverse() diff --git a/Mad Libs Generator.py b/Mad Libs Generator.py index e8bd53b3a93..652716a2ae6 100644 --- a/Mad Libs Generator.py +++ b/Mad Libs Generator.py @@ -1,22 +1,22 @@ -#Loop back to this point once code finishes +# Loop back to this point once code finishes loop = 1 -while (loop < 10): -# All the questions that the program asks the user +while loop < 10: + # All the questions that the program asks the user noun = input("Choose a noun: ") p_noun = input("Choose a plural noun: ") noun2 = input("Choose a noun: ") place = input("Name a place: ") adjective = input("Choose an adjective (Describing word): ") noun3 = input("Choose a noun: ") -# Displays the story based on the users input - print ("------------------------------------------") - print ("Be kind to your",noun,"- footed", p_noun) - print ("For a duck may be somebody's", noun2,",") - print ("Be kind to your",p_noun,"in",place) - print ("Where the weather is always",adjective,".") - print () - print ("You may think that is this the",noun3,",") - print ("Well it is.") - print ("------------------------------------------") -# Loop back to "loop = 1" + # Displays the story based on the users input + print("------------------------------------------") + print("Be kind to your", noun, "- footed", p_noun) + print("For a duck may be somebody's", noun2, ",") + print("Be kind to your", p_noun, "in", place) + print("Where the weather is always", adjective, ".") + print() + print("You may think that is this the", noun3, ",") + print("Well it is.") + print("------------------------------------------") + # Loop back to "loop = 1" loop = loop + 1 diff --git a/Merge_linked_list.py b/Merge_linked_list.py index 5c1f61e1bcc..521b7b0f3b3 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -1,6 +1,7 @@ # Python3 program merge two sorted linked # in third linked list using recursive. + # Node class class Node: def __init__(self, data): diff --git a/Multiply.py b/Multiply.py index ab37d64d0d2..c8e1b52228f 100644 --- a/Multiply.py +++ b/Multiply.py @@ -1,11 +1,12 @@ -def product(a,b): - if(a0): - dig=n%10 - rev=rev*10+dig - n=n//10 -print("Reverse of the number:",rev) +n = int(input("Enter number: ")) +rev = 0 +while n > 0: + dig = n % 10 + rev = rev * 10 + dig + n = n // 10 +print("Reverse of the number:", rev) diff --git a/PDF/demerge_pdfs.py b/PDF/demerge_pdfs.py index 12fcf081428..ddb984170e0 100644 --- a/PDF/demerge_pdfs.py +++ b/PDF/demerge_pdfs.py @@ -3,16 +3,16 @@ to enhance the experience of reading and feasibility to study only specific parts from the large original textbook """ - import PyPDF2 + path = input() -merged_pdf = open(path, mode='rb') +merged_pdf = open(path, mode="rb") pdf = PyPDF2.PdfFileReader(merged_pdf) -(u, ctr, x) = tuple([0]*3) -for i in range(1, pdf.numPages+1): +(u, ctr, x) = tuple([0] * 3) +for i in range(1, pdf.numPages + 1): if u >= pdf.numPages: print("Successfully done!") @@ -21,15 +21,15 @@ ctr = int(input(f"Enter the number of pages for {name}: ")) u += ctr if u > pdf.numPages: - print('Limit exceeded! ') + print("Limit exceeded! ") break - base_path = '/Users/darpan/Desktop/{}.pdf' + base_path = "/Users/darpan/Desktop/{}.pdf" path = base_path.format(name) - f = open(path, mode='wb') + f = open(path, mode="wb") pdf_writer = PyPDF2.PdfFileWriter() - for j in range(x, x+ctr): + for j in range(x, x + ctr): page = pdf.getPage(j) pdf_writer.addPage(page) diff --git a/PDFtoAudiobook.py b/PDFtoAudiobook.py index 8a679000e66..648eaa23fcf 100644 --- a/PDFtoAudiobook.py +++ b/PDFtoAudiobook.py @@ -1,11 +1,12 @@ import pyttsx3 import pyPDF2 -book = open('book.pdf','rb') + +book = open("book.pdf", "rb") pdfreader = pyPDF2.PdfFileReader(book) pages = pdfreader.numPages print(pages) speaker = pyttsx3.init() -page= pdfreader.getpage(7) +page = pdfreader.getpage(7) text = page.extractText() speaker.say(text) speaker.runAndWait() diff --git a/Palindrome_Checker.py b/Palindrome_Checker.py index 598c16d940d..86b9e4b6e6a 100644 --- a/Palindrome_Checker.py +++ b/Palindrome_Checker.py @@ -3,6 +3,7 @@ A simple method is , to reverse the string and and compare with original string. If both are same that's means string is palindrome otherwise else. """ + phrase = input() if phrase == phrase[::-1]: # slicing technique """phrase[::-1] this code is for reverse a string very smartly""" diff --git a/Password Generator/pass_gen.py b/Password Generator/pass_gen.py index f92b9badad2..298f5931192 100644 --- a/Password Generator/pass_gen.py +++ b/Password Generator/pass_gen.py @@ -39,11 +39,15 @@ class Interface: @classmethod def change_has_characters(cls, change): try: - cls.has_characters[change] # to check if the specified key exists in the dicitonary + cls.has_characters[ + change + ] # to check if the specified key exists in the dicitonary except Exception as err: print(f"Invalid \nan Exception: {err}") else: - cls.has_characters[change] = not cls.has_characters[change] #automaticly changres to the oppesite value already there + cls.has_characters[change] = not cls.has_characters[ + change + ] # automaticly changres to the oppesite value already there print(f"{change} is now set to {cls.has_characters[change]}") @classmethod diff --git a/Patterns/half triangle pattern.py b/Patterns/half triangle pattern.py index 982ae8efda6..10bf4f0d2a8 100644 --- a/Patterns/half triangle pattern.py +++ b/Patterns/half triangle pattern.py @@ -1,22 +1,23 @@ - # (upper half - repeat) - #1 - #22 - #333 - - # (upper half - incremental) - #1 - #12 - #123 - - # (lower half - incremental) - #123 - #12 - #1 - - # (lower half - repeat) - #333 - #22 - #1 +# (upper half - repeat) +# 1 +# 22 +# 333 + +# (upper half - incremental) +# 1 +# 12 +# 123 + +# (lower half - incremental) +# 123 +# 12 +# 1 + +# (lower half - repeat) +# 333 +# 22 +# 1 + def main(): lines = int(input("Enter no.of lines: ")) @@ -40,21 +41,23 @@ def main(): print("Invalid input") exit(0) + def upper_half_repeat_pattern(lines): t = 1 - for column in range(1, (lines +1)): + for column in range(1, (lines + 1)): print(f"{str(t) * column}") t += 1 + def upper_half_incremental_pattern(lines): - for column in range(1, (lines +1)): + for column in range(1, (lines + 1)): row = "" - for ii in range(1, column +1): + for ii in range(1, column + 1): row += str(ii) print(row) - + def lower_half_incremental_pattern(lines): @@ -69,14 +72,16 @@ def lower_half_incremental_pattern(lines): print(row) + def lower_half_repeat_pattern(lines): for row_length in range(lines, 0, -1): - + row = "" - for _ in range(1, row_length+1): + for _ in range(1, row_length + 1): row += str(row_length) print(row) + if __name__ == "__main__": main() diff --git a/Patterns/pattern2.py b/Patterns/pattern2.py index 5e8650e3860..9feebc556b4 100644 --- a/Patterns/pattern2.py +++ b/Patterns/pattern2.py @@ -1,5 +1,5 @@ -#pattern -#$$$$$$$$$$$ +# pattern +# $$$$$$$$$$$ # $$$$$$$$$ # $$$$$$$ # $$$$$ @@ -7,21 +7,20 @@ # $ - def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): - for i in range(lines,0,-1): - for j in range(lines-i): - print(' ', end='') - - for j in range(2*i-1): - print('$',end='') - print() + for i in range(lines, 0, -1): + for j in range(lines - i): + print(" ", end="") + + for j in range(2 * i - 1): + print("$", end="") + print() if __name__ == "__main__": main() - diff --git a/Patterns/pattern5.py b/Patterns/pattern5.py index 58f75df847b..acb37992d29 100644 --- a/Patterns/pattern5.py +++ b/Patterns/pattern5.py @@ -1,19 +1,22 @@ -#pattern Reverse piramid of numbers -#1 -#21 -#321 -#4321 -#54321 +# pattern Reverse piramid of numbers +# 1 +# 21 +# 321 +# 4321 +# 54321 + def main(): lines = int(input("Enter the number of lines: ")) pattern(lines) + def pattern(rows): - for i in range(1, rows+1): + for i in range(1, rows + 1): for j in range(i, 0, -1): print(j, end="") print() + if __name__ == "__main__": main() diff --git a/Patterns/pattern6.py b/Patterns/pattern6.py index 1f02d6ce55a..1384619b0ad 100644 --- a/Patterns/pattern6.py +++ b/Patterns/pattern6.py @@ -1,17 +1,18 @@ # Python code to print the following alphabet pattern -#A -#B B -#C C C -#D D D D -#E E E E E +# A +# B B +# C C C +# D D D D +# E E E E E def alphabetpattern(n): num = 65 for i in range(0, n): - for j in range(0, i+1): + for j in range(0, i + 1): ch = chr(num) print(ch, end=" ") num = num + 1 print("\r") + a = 5 alphabetpattern(a) diff --git a/Patterns/patterns.py b/Patterns/patterns.py index a23b463df12..fa8f47c5b49 100644 --- a/Patterns/patterns.py +++ b/Patterns/patterns.py @@ -14,26 +14,29 @@ # * * # * + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): for i in range(lines): - for j in range(i+1): + for j in range(i + 1): print("* ", end="") print("") print(" ") - for i in range(0,lines): - + for i in range(0, lines): + for j in range(0, (2 * (i - 1)) + 1): print(" ", end="") - + for j in range(0, lines - i): print("*", end=" ") - - print("") + + print("") + if __name__ == "__main__": - main() + main() diff --git a/PingPong/Ball.py b/PingPong/Ball.py index ec1a4a6768f..bd0591733ac 100644 --- a/PingPong/Ball.py +++ b/PingPong/Ball.py @@ -1,6 +1,8 @@ import pygame + pygame.init() + class Ball: def __init__(self, pos, vel, win, rad, minCoord, maxCoord): @@ -12,22 +14,18 @@ def __init__(self, pos, vel, win, rad, minCoord, maxCoord): self.minCoord = minCoord self.maxCoord = maxCoord - def drawBall(self): - pygame.draw.circle(self.win, (255,)*3, self.pos, self.rad, 0) - + pygame.draw.circle(self.win, (255,) * 3, self.pos, self.rad, 0) def doHorizontalFlip(self): self.vel[0] *= -1 - def doVerticalFlip(self): self.vel[1] *= -1 - def borderCollisionCheck(self): if (self.pos[0] <= self.minCoord[0]) or (self.pos[0] >= self.maxCoord[0]): @@ -38,13 +36,11 @@ def borderCollisionCheck(self): self.doVerticalFlip() - def updatePos(self): - self.pos = [self.pos[0]+self.vel[0], self.pos[1]+self.vel[1]] - + self.pos = [self.pos[0] + self.vel[0], self.pos[1] + self.vel[1]] - def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] + def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] if ( self.pos[0] + self.rad > slabPos[0] and self.pos[0] - self.rad < slabPos[2] @@ -55,4 +51,4 @@ def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] if self.pos[0] < slabPos[0] or self.pos[0] > slabPos[2]: self.vel[0] *= -1 if self.pos[1] < slabPos[1] or self.pos[1] > slabPos[3]: - self.vel[1] *= -1 \ No newline at end of file + self.vel[1] *= -1 diff --git a/PingPong/Slab.py b/PingPong/Slab.py index c5fb5d70bec..17b5bbac724 100644 --- a/PingPong/Slab.py +++ b/PingPong/Slab.py @@ -1,31 +1,41 @@ import pygame + pygame.init() + class Slab: def __init__(self, win, size, pos, player, minPos, maxPos): self.win = win self.size = size self.pos = pos - self.player = player #player = 1 or 2 + self.player = player # player = 1 or 2 self.minPos = minPos self.maxPos = maxPos - def draw(self): - pygame.draw.rect(self.win, (255, 255, 255), (self.pos[0], self.pos[1], self.size[0], self.size[1])) - + pygame.draw.rect( + self.win, + (255, 255, 255), + (self.pos[0], self.pos[1], self.size[0], self.size[1]), + ) + def getCoords(self): - return [self.pos[0], self.pos[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]] - + return [ + self.pos[0], + self.pos[1], + self.pos[0] + self.size[0], + self.pos[1] + self.size[1], + ] + def updatePos(self): keys = pygame.key.get_pressed() if self.player == 1: - if keys[pygame.K_UP] and self.getCoords()[1]> self.minPos[1]: + if keys[pygame.K_UP] and self.getCoords()[1] > self.minPos[1]: self.pos[1] -= 0.3 - if keys[pygame.K_DOWN] and self.getCoords()[3]< self.maxPos[1]: + if keys[pygame.K_DOWN] and self.getCoords()[3] < self.maxPos[1]: self.pos[1] += 0.3 else: - if keys[pygame.K_w] and self.getCoords()[1]> self.minPos[1]: + if keys[pygame.K_w] and self.getCoords()[1] > self.minPos[1]: self.pos[1] -= 0.3 - if keys[pygame.K_s] and self.getCoords()[3]< self.maxPos[1]: - self.pos[1] += 0.3 \ No newline at end of file + if keys[pygame.K_s] and self.getCoords()[3] < self.maxPos[1]: + self.pos[1] += 0.3 diff --git a/PingPong/main.py b/PingPong/main.py index 2892f8c9305..b98773e8c08 100644 --- a/PingPong/main.py +++ b/PingPong/main.py @@ -4,17 +4,17 @@ WIDTH = 600 HEIGHT = 600 -BLACK = (0,0,0) -WHITE = (255,)*3 +BLACK = (0, 0, 0) +WHITE = (255,) * 3 pygame.init() -win = pygame.display.set_mode((WIDTH, HEIGHT )) +win = pygame.display.set_mode((WIDTH, HEIGHT)) print("Controls: W&S for player 1 and arrow up and down for player 2") -ball = Ball([300,300 ], [0.3,0.1], win, 10, (0,0), (600,600)) -slab = Slab(win, [10,100], [500, 300], 1, (0, 0), (600, 600)) -slab2 = Slab(win, [10,100], [100, 300], 2, (0, 0), (600, 600)) +ball = Ball([300, 300], [0.3, 0.1], win, 10, (0, 0), (600, 600)) +slab = Slab(win, [10, 100], [500, 300], 1, (0, 0), (600, 600)) +slab2 = Slab(win, [10, 100], [100, 300], 2, (0, 0), (600, 600)) run = True while run: for event in pygame.event.get(): @@ -37,4 +37,4 @@ slab2.draw() pygame.display.update() -pygame.quit() \ No newline at end of file +pygame.quit() diff --git a/Program to reverse Linked List( Recursive solution).py b/Program to reverse Linked List( Recursive solution).py index 96263c6a276..9a97e53acbf 100644 --- a/Program to reverse Linked List( Recursive solution).py +++ b/Program to reverse Linked List( Recursive solution).py @@ -1,6 +1,7 @@ from sys import stdin, setrecursionlimit -setrecursionlimit(10 ** 6) +setrecursionlimit(10**6) + # Following is the Node class already written for the Linked List class Node: diff --git a/Python Distance.py b/Python Distance.py index 5ac0e09fc36..919f1e1528f 100644 --- a/Python Distance.py +++ b/Python Distance.py @@ -6,8 +6,8 @@ # terms = int(input("How many terms? ")) # use anonymous function -result = list(map(lambda x: 2 ** x, range(terms))) +result = list(map(lambda x: 2**x, range(terms))) -print("The total terms are:",terms) +print("The total terms are:", terms) for i in range(terms): - print("2 raised to power",i,"is",result[i]) + print("2 raised to power", i, "is", result[i]) diff --git a/Python Program for Product of unique prime factors of a number.py b/Python Program for Product of unique prime factors of a number.py index 594f032750e..1018f51be56 100644 --- a/Python Program for Product of unique prime factors of a number.py +++ b/Python Program for Product of unique prime factors of a number.py @@ -1,29 +1,29 @@ -# Python program to find sum of given -# series. - -def productPrimeFactors(n): - product = 1 - - for i in range(2, n+1): - if (n % i == 0): - isPrime = 1 - - for j in range(2, int(i/2 + 1)): - if (i % j == 0): - isPrime = 0 - break - - # condition if \'i\' is Prime number - # as well as factor of num - if (isPrime): - product = product * i - - return product - - - -# main() +# Python program to find sum of given +# series. + + +def productPrimeFactors(n): + product = 1 + + for i in range(2, n + 1): + if n % i == 0: + isPrime = 1 + + for j in range(2, int(i / 2 + 1)): + if i % j == 0: + isPrime = 0 + break + + # condition if \'i\' is Prime number + # as well as factor of num + if isPrime: + product = product * i + + return product + + +# main() n = 44 -print (productPrimeFactors(n)) +print(productPrimeFactors(n)) -# Contributed by _omg +# Contributed by _omg diff --git a/Python Program for Tower of Hanoi.py b/Python Program for Tower of Hanoi.py index 7efb1b56363..00c8eb96ce0 100644 --- a/Python Program for Tower of Hanoi.py +++ b/Python Program for Tower of Hanoi.py @@ -1,10 +1,12 @@ -# Recursive Python function to solve the tower of hanoi -def TowerOfHanoi(n , source, destination, auxiliary): - if n==1: - print("Move disk 1 from source ",source," to destination ",destination) - return - TowerOfHanoi(n-1, source, auxiliary, destination) - print("Move disk ",n," from source ",source," to destination ",destination) - TowerOfHanoi(n-1, auxiliary, destination, source) +# Recursive Python function to solve the tower of hanoi +def TowerOfHanoi(n, source, destination, auxiliary): + if n == 1: + print("Move disk 1 from source ", source, " to destination ", destination) + return + TowerOfHanoi(n - 1, source, auxiliary, destination) + print("Move disk ", n, " from source ", source, " to destination ", destination) + TowerOfHanoi(n - 1, auxiliary, destination, source) + + n = 4 -TowerOfHanoi(n,'A','B','C') +TowerOfHanoi(n, "A", "B", "C") diff --git a/Python Program to Count the Number of Each Vowel.py b/Python Program to Count the Number of Each Vowel.py index 297e2488590..eb66d0967d6 100644 --- a/Python Program to Count the Number of Each Vowel.py +++ b/Python Program to Count the Number of Each Vowel.py @@ -1,19 +1,19 @@ # Program to count the number of each vowels # string of vowels -vowels = 'aeiou' +vowels = "aeiou" -ip_str = 'Hello, have you tried our tutorial section yet?' +ip_str = "Hello, have you tried our tutorial section yet?" # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 -count = {}.fromkeys(vowels,0) +count = {}.fromkeys(vowels, 0) # count the vowels for char in ip_str: - if char in count: - count[char] += 1 + if char in count: + count[char] += 1 print(count) diff --git a/Python Program to Display Fibonacci Sequence Using Recursion.py b/Python Program to Display Fibonacci Sequence Using Recursion.py index 5a70deb0e28..7bfb6b7a03a 100644 --- a/Python Program to Display Fibonacci Sequence Using Recursion.py +++ b/Python Program to Display Fibonacci Sequence Using Recursion.py @@ -1,15 +1,16 @@ def recur_fibo(n): - if n <= 1: - return n - else: - return(recur_fibo(n-1) + recur_fibo(n-2)) + if n <= 1: + return n + else: + return recur_fibo(n - 1) + recur_fibo(n - 2) + nterms = 10 # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") else: - print("Fibonacci sequence:") - for i in range(nterms): - print(recur_fibo(i)) + print("Fibonacci sequence:") + for i in range(nterms): + print(recur_fibo(i)) diff --git a/Python Program to Find LCM.py b/Python Program to Find LCM.py index 6e9cf1cc8a1..573ae0557d9 100644 --- a/Python Program to Find LCM.py +++ b/Python Program to Find LCM.py @@ -1,20 +1,22 @@ # Python Program to find the L.C.M. of two input number + def compute_lcm(x, y): - # choose the greater number - if x > y: - greater = x - else: - greater = y + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while True: + if (greater % x == 0) and (greater % y == 0): + lcm = greater + break + greater += 1 - while(True): - if((greater % x == 0) and (greater % y == 0)): - lcm = greater - break - greater += 1 + return lcm - return lcm num1 = 54 num2 = 24 diff --git a/Python Program to Merge Mails.py b/Python Program to Merge Mails.py index 2d18c6dbaee..988fc30a979 100644 --- a/Python Program to Merge Mails.py +++ b/Python Program to Merge Mails.py @@ -3,10 +3,10 @@ # Body of the mail is in body.txt # open names.txt for reading -with open("names.txt", 'r', encoding='utf-8') as names_file: +with open("names.txt", "r", encoding="utf-8") as names_file: # open body.txt for reading - with open("body.txt", 'r', encoding='utf-8') as body_file: + with open("body.txt", "r", encoding="utf-8") as body_file: # read entire content of the body body = body_file.read() @@ -16,6 +16,5 @@ mail = "Hello " + name.strip() + "\n" + body # write the mails to individual files - with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file: + with open(name.strip() + ".txt", "w", encoding="utf-8") as mail_file: mail_file.write(mail) - diff --git a/Python Program to Print the Fibonacci sequence.py b/Python Program to Print the Fibonacci sequence.py index 9f6b1b3d7ce..d6a70a574cd 100644 --- a/Python Program to Print the Fibonacci sequence.py +++ b/Python Program to Print the Fibonacci sequence.py @@ -8,16 +8,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/Python Program to Remove Punctuations from a String.py b/Python Program to Remove Punctuations from a String.py index a1e750a3a4b..003a2a12ee8 100644 --- a/Python Program to Remove Punctuations from a String.py +++ b/Python Program to Remove Punctuations from a String.py @@ -1,5 +1,5 @@ # define punctuation -punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' +punctuations = """!()-[]{};:'"\,<>./?@#$%^&*_~""" my_str = "Hello!!!, he said ---and went." @@ -9,8 +9,8 @@ # remove punctuation from the string no_punct = "" for char in my_str: - if char not in punctuations: - no_punct = no_punct + char + if char not in punctuations: + no_punct = no_punct + char # display the unpunctuated string print(no_punct) diff --git a/Python Program to Reverse a linked list.py b/Python Program to Reverse a linked list.py index c3eff50ebab..fb081b2fb59 100644 --- a/Python Program to Reverse a linked list.py +++ b/Python Program to Reverse a linked list.py @@ -1,57 +1,59 @@ -# Python program to reverse a linked list -# Time Complexity : O(n) -# Space Complexity : O(1) - -# Node class -class Node: - - # Constructor to initialize the node object - def __init__(self, data): - self.data = data - self.next = None - -class LinkedList: - - # Function to initialize head - def __init__(self): - self.head = None - - # Function to reverse the linked list - def reverse(self): - prev = None - current = self.head - while(current is not None): - next = current.next - current.next = prev - prev = current - current = next - self.head = prev - - # Function to insert a new node at the beginning - def push(self, new_data): - new_node = Node(new_data) - new_node.next = self.head - self.head = new_node - - # Utility function to print the linked LinkedList - def printList(self): - temp = self.head - while(temp): - print(temp.data) - temp = temp.next - - -# Driver program to test above functions -llist = LinkedList() -llist.push(20) -llist.push(4) -llist.push(15) -llist.push(85) +# Python program to reverse a linked list +# Time Complexity : O(n) +# Space Complexity : O(1) + + +# Node class +class Node: + + # Constructor to initialize the node object + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to reverse the linked list + def reverse(self): + prev = None + current = self.head + while current is not None: + next = current.next + current.next = prev + prev = current + current = next + self.head = prev + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Utility function to print the linked LinkedList + def printList(self): + temp = self.head + while temp: + print(temp.data) + temp = temp.next + + +# Driver program to test above functions +llist = LinkedList() +llist.push(20) +llist.push(4) +llist.push(15) +llist.push(85) print("Given Linked List") -llist.printList() -llist.reverse() +llist.printList() +llist.reverse() print("\nReversed Linked List") -llist.printList() +llist.printList() -# This code is contributed by Nikhil Kumar Singh(nickzuck_007) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007) diff --git a/Python Program to Sort Words in Alphabetic Order.py b/Python Program to Sort Words in Alphabetic Order.py index 3e4bd3564e5..737f88c5a8e 100644 --- a/Python Program to Sort Words in Alphabetic Order.py +++ b/Python Program to Sort Words in Alphabetic Order.py @@ -1,23 +1,23 @@ # Program to sort words alphabetically and put them in a dictionary with corresponding numbered keys -# We are also removing punctuation to ensure the desired output, without importing a library for assistance. +# We are also removing punctuation to ensure the desired output, without importing a library for assistance. # Declare base variables word_Dict = {} count = 0 my_str = "Hello this Is an Example With cased letters. Hello, this is a good string" -#Initialize punctuation -punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~''' +# Initialize punctuation +punctuations = """!()-[]{};:'",<>./?@#$%^&*_~""" # To take input from the user -#my_str = input("Enter a string: ") +# my_str = input("Enter a string: ") # remove punctuation from the string and use an empty variable to put the alphabetic characters into no_punct = "" for char in my_str: - if char not in punctuations: - no_punct = no_punct + char + if char not in punctuations: + no_punct = no_punct + char -# Make all words in string lowercase. my_str now equals the original string without the punctuation +# Make all words in string lowercase. my_str now equals the original string without the punctuation my_str = no_punct.lower() # breakdown the string into a list of words @@ -36,7 +36,7 @@ # insert sorted words into dictionary with key for word in new_Word_List: - count+=1 + count += 1 word_Dict[count] = word print(word_Dict) diff --git a/Python Program to Transpose a Matrix.py b/Python Program to Transpose a Matrix.py index 98f6dcba024..d636ebcfa6a 100644 --- a/Python Program to Transpose a Matrix.py +++ b/Python Program to Transpose a Matrix.py @@ -1,15 +1,12 @@ -X = [[12,7], - [4 ,5], - [3 ,8]] +X = [[12, 7], [4, 5], [3, 8]] -result = [[0,0,0], - [0,0,0]] +result = [[0, 0, 0], [0, 0, 0]] # iterate through rows for i in range(len(X)): - # iterate through columns - for j in range(len(X[0])): - result[j][i] = X[i][j] + # iterate through columns + for j in range(len(X[0])): + result[j][i] = X[i][j] for r in result: - print(r) + print(r) diff --git a/Python-Array-Equilibrium-Index.py b/Python-Array-Equilibrium-Index.py index 0aac8fbf995..50a7d07f11a 100644 --- a/Python-Array-Equilibrium-Index.py +++ b/Python-Array-Equilibrium-Index.py @@ -14,24 +14,28 @@ -7 1 5 2 -4 3 0 Sample Output : 3 """ -def equilibrium(arr): - - # finding the sum of whole array - total_sum = sum(arr) + + +def equilibrium(arr): + + # finding the sum of whole array + total_sum = sum(arr) leftsum = 0 - for i, num in enumerate(arr): - - # total_sum is now right sum - # for index i - total_sum -= num - - if leftsum == total_sum: - return i - leftsum += num - - # If no equilibrium index found, - # then return -1 + for i, num in enumerate(arr): + + # total_sum is now right sum + # for index i + total_sum -= num + + if leftsum == total_sum: + return i + leftsum += num + + # If no equilibrium index found, + # then return -1 return -1 + + n = int(input()) arr = [int(i) for i in input().strip().split()] print(equilibrium(arr)) diff --git a/Python_swapping.py b/Python_swapping.py index 02b9411bca9..a740662acf0 100644 --- a/Python_swapping.py +++ b/Python_swapping.py @@ -1,18 +1,20 @@ -# Python3 program to swap first -# and last element of a list - -# Swap function -def swapList(newList): - size = len(newList) - - # Swapping - temp = newList[0] - newList[0] = newList[size - 1] - newList[size - 1] = temp - - return newList - -# Driver code -newList = [12, 35, 9, 56, 24] - -print(swapList(newList)) +# Python3 program to swap first +# and last element of a list + + +# Swap function +def swapList(newList): + size = len(newList) + + # Swapping + temp = newList[0] + newList[0] = newList[size - 1] + newList[size - 1] = temp + + return newList + + +# Driver code +newList = [12, 35, 9, 56, 24] + +print(swapList(newList)) diff --git a/Random Password Generator.py b/Random Password Generator.py index b13262dadf8..f420421d14b 100644 --- a/Random Password Generator.py +++ b/Random Password Generator.py @@ -1,12 +1,11 @@ import random -low="abcdefghijklmnopqrstuvwxyz" -upp="ABCDEFGHIJKLMNOPQRSTUVWXYZ" -num="0123456789" -sym="!@#$%^&*" +low = "abcdefghijklmnopqrstuvwxyz" +upp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +num = "0123456789" +sym = "!@#$%^&*" -all=low+upp+num+sym -length=8 -password="".join(random.sample(all,length)) +all = low + upp + num + sym +length = 8 +password = "".join(random.sample(all, length)) print(password) - diff --git a/RandomDice.py b/RandomDice.py index 404c4b30a72..682aaa47613 100644 --- a/RandomDice.py +++ b/RandomDice.py @@ -5,6 +5,7 @@ from random import randint from tkinter import * + # Function to rool the dice def roll(): text.delete(0.0, END) diff --git a/Randomnumber.py b/Randomnumber.py index 45d08b4499b..6cd29746f7c 100644 --- a/Randomnumber.py +++ b/Randomnumber.py @@ -3,4 +3,4 @@ # importing the random module from random import randint -print(randint(0,9)) +print(randint(0, 9)) diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py index f716f5fa16d..409b39102b9 100644 --- a/Search_Engine/backend.py +++ b/Search_Engine/backend.py @@ -3,6 +3,7 @@ import ast import json + class SearchEngine: """ It works by building a reverse index store that maps @@ -27,9 +28,17 @@ def __init__(self): tables_exist = res.fetchone() if not tables_exist: - self.conn.execute("CREATE TABLE IdToDoc(id INTEGER PRIMARY KEY, document TEXT)") - self.conn.execute('CREATE TABLE WordToId (name TEXT, value TEXT)') - cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}",)) + self.conn.execute( + "CREATE TABLE IdToDoc(id INTEGER PRIMARY KEY, document TEXT)" + ) + self.conn.execute("CREATE TABLE WordToId (name TEXT, value TEXT)") + cur.execute( + "INSERT INTO WordToId VALUES (?, ?)", + ( + "index", + "{}", + ), + ) def index_document(self, document): """ @@ -43,13 +52,15 @@ def index_document(self, document): - passes the document to a method to add the document to IdToDoc - retrieves the id of the inserted document - - uses the id to call the method that adds the words of + - uses the id to call the method that adds the words of the document to the reverse index WordToId if the word has not already been indexed """ row_id = self._add_to_IdToDoc(document) cur = self.conn.cursor() - reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0] + reverse_idx = cur.execute( + "SELECT value FROM WordToId WHERE name='index'" + ).fetchone()[0] reverse_idx = json.loads(reverse_idx) document = document.split() for word in document: @@ -60,8 +71,10 @@ def index_document(self, document): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute("UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,)) - return("index successful") + result = cur.execute( + "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) + ) + return "index successful" def _add_to_IdToDoc(self, document): """ @@ -88,7 +101,9 @@ def find_documents(self, search_term): - return the result of the called method """ cur = self.conn.cursor() - reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0] + reverse_idx = cur.execute( + "SELECT value FROM WordToId WHERE name='index'" + ).fetchone()[0] reverse_idx = json.loads(reverse_idx) search_term = search_term.split(" ") all_docs_with_search_term = [] @@ -96,18 +111,18 @@ def find_documents(self, search_term): if term in reverse_idx: all_docs_with_search_term.append(reverse_idx[term]) - if not all_docs_with_search_term: # the search term does not exist + if not all_docs_with_search_term: # the search term does not exist return [] common_idx_of_docs = set(all_docs_with_search_term[0]) for idx in all_docs_with_search_term[1:]: common_idx_of_docs.intersection_update(idx) - if not common_idx_of_docs: # the search term does not exist + if not common_idx_of_docs: # the search term does not exist return [] return self._find_documents_with_idx(common_idx_of_docs) - + def _find_documents_with_idx(self, idxs): """ Returns - list[str]: the list of documents with the idxs @@ -119,11 +134,11 @@ def _find_documents_with_idx(self, idxs): """ idxs = list(idxs) cur = self.conn.cursor() - sql="SELECT document FROM IdToDoc WHERE id in ({seq})".format( - seq=','.join(['?']*len(idxs)) - ) + sql = "SELECT document FROM IdToDoc WHERE id in ({seq})".format( + seq=",".join(["?"] * len(idxs)) + ) result = cur.execute(sql, idxs).fetchall() - return(result) + return result if __name__ == "__main__": @@ -132,4 +147,4 @@ def _find_documents_with_idx(self, idxs): print(se.index_document("happiness is all you need")) se.index_document("no way should we be sad") se.index_document("a cheerful heart is a happy one even in Nigeria") - print(se.find_documents("happy")) \ No newline at end of file + print(se.find_documents("happy")) diff --git a/Search_Engine/frontend.py b/Search_Engine/frontend.py index 93dd7636f19..12f92d58148 100644 --- a/Search_Engine/frontend.py +++ b/Search_Engine/frontend.py @@ -8,15 +8,17 @@ def add_document(): se = backend.SearchEngine() print(se.index_document(document)) + def find_term(): term = find_term_entry.get() se = backend.SearchEngine() print(se.find_documents(term)) + if __name__ == "__main__": root = Tk() root.title("Registration Form") - root.geometry('300x300') + root.geometry("300x300") add_documents_label = Label(root, text="Add Document:") add_documents_label.pack() @@ -34,4 +36,4 @@ def find_term(): search_term_button = Button(root, text="search", command=find_term) search_term_button.pack() - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Search_Engine/test_data.py b/Search_Engine/test_data.py index d58f43e7d17..1c6c7b043ed 100644 --- a/Search_Engine/test_data.py +++ b/Search_Engine/test_data.py @@ -2,7 +2,7 @@ "we should all strive to be happy", "happiness is all you need", "a cheerful heart is a happy one", - "no way should we be sad" + "no way should we be sad", ] -search = "happy" \ No newline at end of file +search = "happy" diff --git a/Sorting Algorithims/heapsort_linkedlist.py b/Sorting Algorithims/heapsort_linkedlist.py index 7e9584077e6..9f535d20ade 100644 --- a/Sorting Algorithims/heapsort_linkedlist.py +++ b/Sorting Algorithims/heapsort_linkedlist.py @@ -3,6 +3,7 @@ def __init__(self, data): self.data = data self.next = None + class LinkedList: def __init__(self): self.head = None @@ -64,6 +65,7 @@ def heap_sort(self): self.swap(0, i) self.heapify(i, 0) + # Example usage: linked_list = LinkedList() linked_list.push(12) diff --git a/Sorting Algorithims/mergesort_linkedlist.py b/Sorting Algorithims/mergesort_linkedlist.py index 429684b6c0c..4e833dc2e29 100644 --- a/Sorting Algorithims/mergesort_linkedlist.py +++ b/Sorting Algorithims/mergesort_linkedlist.py @@ -1,10 +1,12 @@ from __future__ import annotations + class Node: def __init__(self, data: int) -> None: self.data = data self.next = None + class LinkedList: def __init__(self): self.head = None @@ -17,13 +19,14 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head if temp == None: - return 'Linked List is empty' + return "Linked List is empty" while temp.next: - print(temp.data, '->', end='') + print(temp.data, "->", end="") temp = temp.next print(temp.data) return + # Merge two sorted linked lists def merge(left, right): if not left: @@ -40,6 +43,7 @@ def merge(left, right): return result + # Merge sort for linked list def merge_sort(head): if not head or not head.next: @@ -61,9 +65,12 @@ def merge_sort(head): return merge(left, right) + if __name__ == "__main__": ll = LinkedList() - print("Enter the space-separated values of numbers to be inserted in the linked list prompted below:") + print( + "Enter the space-separated values of numbers to be inserted in the linked list prompted below:" + ) arr = list(map(int, input().split())) for num in arr: ll.insert(num) @@ -73,5 +80,5 @@ def merge_sort(head): ll.head = merge_sort(ll.head) - print('Linked list after sorting:') + print("Linked list after sorting:") ll.printLL() diff --git a/Sorting Algorithims/quicksort_linkedlist.py b/Sorting Algorithims/quicksort_linkedlist.py index 97de82e2bc2..0d4f5f58de1 100644 --- a/Sorting Algorithims/quicksort_linkedlist.py +++ b/Sorting Algorithims/quicksort_linkedlist.py @@ -3,6 +3,7 @@ sort the linked list using quicksort technique without using any extra space Time complexity: O(NlogN), Space complexity: O(1) """ + from __future__ import annotations @@ -26,13 +27,14 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head if temp == None: - return 'Linked List is empty' + return "Linked List is empty" while temp.next: - print(temp.data, '->', end='') + print(temp.data, "->", end="") temp = temp.next print(temp.data) return + # Partition algorithm with pivot as first element @@ -65,12 +67,14 @@ def quicksort_LL(start, end): if __name__ == "__main__": ll = LinkedList() - print("Enter the space seperated values of numbers to be inserted in linkedlist prompted below:") + print( + "Enter the space seperated values of numbers to be inserted in linkedlist prompted below:" + ) arr = list(map(int, input().split())) for num in arr: ll.insert(num) print("Linkedlist before sorting:") ll.printLL() quicksort_LL(ll.head, None) - print('Linkedlist after sorting: ') + print("Linkedlist after sorting: ") ll.printLL() diff --git a/Sorting Algorithms/Counting-sort.py b/Sorting Algorithms/Counting-sort.py index 34b1667762d..0b3326b563a 100644 --- a/Sorting Algorithms/Counting-sort.py +++ b/Sorting Algorithms/Counting-sort.py @@ -7,7 +7,6 @@ def counting_sort(tlist, k, n): - """Counting sort algo with sort in place. Args: tlist: target list to sort diff --git a/Sorting Algorithms/Heap sort.py b/Sorting Algorithms/Heap sort.py index 69aa753c283..523668698a0 100644 --- a/Sorting Algorithms/Heap sort.py +++ b/Sorting Algorithms/Heap sort.py @@ -1,5 +1,6 @@ # Python program for implementation of heap Sort + # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): diff --git a/Sorting Algorithms/Iterative Merge Sort.py b/Sorting Algorithms/Iterative Merge Sort.py index 63173b6bf5c..0b518478449 100644 --- a/Sorting Algorithms/Iterative Merge Sort.py +++ b/Sorting Algorithms/Iterative Merge Sort.py @@ -1,5 +1,6 @@ # Iterative Merge sort (Bottom Up) + # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(a): diff --git a/Sorting Algorithms/Tim_sort.py b/Sorting Algorithms/Tim_sort.py index 9cbbb313e5d..307223a438e 100644 --- a/Sorting Algorithms/Tim_sort.py +++ b/Sorting Algorithms/Tim_sort.py @@ -9,6 +9,7 @@ # Python3 program to perform TimSort. RUN = 32 + # This function sorts array from left index to # to right index which is of size atmost RUN def insertionSort(arr, left, right): diff --git a/String_Palindrome.py b/String_Palindrome.py index 6b8302b6477..073ab5b47e4 100644 --- a/String_Palindrome.py +++ b/String_Palindrome.py @@ -1,6 +1,6 @@ # Program to check if a string is palindrome or not -my_str = 'aIbohPhoBiA' +my_str = "aIbohPhoBiA" # make it suitable for caseless comparison my_str = my_str.casefold() @@ -10,6 +10,6 @@ # check if the string is equal to its reverse if list(my_str) == list(rev_str): - print("The string is a palindrome.") + print("The string is a palindrome.") else: - print("The string is not a palindrome.") + print("The string is not a palindrome.") diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index c000547c7bc..4d017d57606 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -2,32 +2,42 @@ import sys + def get_integer(): - for i in range(3,0,-1): # executes the loop 3 times. Giving 3 chances to the user. + for i in range( + 3, 0, -1 + ): # executes the loop 3 times. Giving 3 chances to the user. num = input("enter a number:") - if num.isnumeric(): # checks if entered input is an integer string or not. - num = int(num) # converting integer string to integer. And returns it to where function is called. + if num.isnumeric(): # checks if entered input is an integer string or not. + num = int( + num + ) # converting integer string to integer. And returns it to where function is called. return num else: - print("enter integer only") - print(f'{i-1} chances are left' if (i-1)>1 else f'{i-1} chance is left') # prints if user entered wrong input and chances left. - continue - + print("enter integer only") + print( + f"{i-1} chances are left" if (i - 1) > 1 else f"{i-1} chance is left" + ) # prints if user entered wrong input and chances left. + continue + def addition(num): - Sum=0 - if type(num) is type(None): # Checks if number type is none or not. If type is none program exits. + Sum = 0 + if type(num) is type( + None + ): # Checks if number type is none or not. If type is none program exits. print("Try again!") sys.exit() - while num > 0: # Addition- adding the digits in the number. + while num > 0: # Addition- adding the digits in the number. digit = int(num % 10) Sum += digit num /= 10 - return Sum # Returns sum to where the function is called. - + return Sum # Returns sum to where the function is called. -if __name__ == '__main__': # this is used to overcome the problems while importing this file. +if ( + __name__ == "__main__" +): # this is used to overcome the problems while importing this file. number = get_integer() Sum = addition(number) - print(f'Sum of digits of {number} is {Sum}') # Prints the sum + print(f"Sum of digits of {number} is {Sum}") # Prints the sum diff --git a/TIC_TAC_TOE/index.py b/TIC_TAC_TOE/index.py index 7e494d0e700..5b621eae4db 100644 --- a/TIC_TAC_TOE/index.py +++ b/TIC_TAC_TOE/index.py @@ -3,19 +3,26 @@ def print_board(board): print(" | ".join(row)) print("-" * 9) + def check_winner(board, player): for i in range(3): # Check rows and columns - if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): + if all(board[i][j] == player for j in range(3)) or all( + board[j][i] == player for j in range(3) + ): return True # Check diagonals - if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): + if all(board[i][i] == player for i in range(3)) or all( + board[i][2 - i] == player for i in range(3) + ): return True return False + def is_full(board): return all(cell != " " for row in board for cell in row) + def main(): board = [[" " for _ in range(3)] for _ in range(3)] player = "X" @@ -42,5 +49,6 @@ def main(): else: print("Invalid move. Try again.") + if __name__ == "__main__": main() diff --git a/TaskManager.py b/TaskManager.py index 250eb05323b..7ea37595c4f 100644 --- a/TaskManager.py +++ b/TaskManager.py @@ -1,31 +1,38 @@ import datetime import csv -def load_tasks(filename='tasks.csv'): + +def load_tasks(filename="tasks.csv"): tasks = [] - with open(filename, 'r', newline='') as file: + with open(filename, "r", newline="") as file: reader = csv.reader(file) for row in reader: - tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]}) + tasks.append({"task": row[0], "deadline": row[1], "completed": row[2]}) return tasks -def save_tasks(tasks, filename='tasks.csv'): - with open(filename, 'w', newline='') as file: + +def save_tasks(tasks, filename="tasks.csv"): + with open(filename, "w", newline="") as file: writer = csv.writer(file) for task in tasks: - writer.writerow([task['task'], task['deadline'], task['completed']]) + writer.writerow([task["task"], task["deadline"], task["completed"]]) + def add_task(task, deadline): tasks = load_tasks() - tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'}) + tasks.append({"task": task, "deadline": deadline, "completed": "No"}) save_tasks(tasks) print("Task added successfully!") + def show_tasks(): tasks = load_tasks() for task in tasks: - print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}") + print( + f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}" + ) + # Example usage -add_task('Write daily report', '2024-04-20') +add_task("Write daily report", "2024-04-20") show_tasks() diff --git a/TaskPlanner.py b/TaskPlanner.py index 250eb05323b..7ea37595c4f 100644 --- a/TaskPlanner.py +++ b/TaskPlanner.py @@ -1,31 +1,38 @@ import datetime import csv -def load_tasks(filename='tasks.csv'): + +def load_tasks(filename="tasks.csv"): tasks = [] - with open(filename, 'r', newline='') as file: + with open(filename, "r", newline="") as file: reader = csv.reader(file) for row in reader: - tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]}) + tasks.append({"task": row[0], "deadline": row[1], "completed": row[2]}) return tasks -def save_tasks(tasks, filename='tasks.csv'): - with open(filename, 'w', newline='') as file: + +def save_tasks(tasks, filename="tasks.csv"): + with open(filename, "w", newline="") as file: writer = csv.writer(file) for task in tasks: - writer.writerow([task['task'], task['deadline'], task['completed']]) + writer.writerow([task["task"], task["deadline"], task["completed"]]) + def add_task(task, deadline): tasks = load_tasks() - tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'}) + tasks.append({"task": task, "deadline": deadline, "completed": "No"}) save_tasks(tasks) print("Task added successfully!") + def show_tasks(): tasks = load_tasks() for task in tasks: - print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}") + print( + f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}" + ) + # Example usage -add_task('Write daily report', '2024-04-20') +add_task("Write daily report", "2024-04-20") show_tasks() diff --git a/ThirdAI/Terms and Conditions/ThirdAI.py b/ThirdAI/Terms and Conditions/ThirdAI.py index 67d3928ec4b..046b6998c9a 100644 --- a/ThirdAI/Terms and Conditions/ThirdAI.py +++ b/ThirdAI/Terms and Conditions/ThirdAI.py @@ -26,11 +26,11 @@ def query(self, question): search_results = self.db.search( query=question, top_k=2, - on_error=lambda error_msg: print(f"Error! {error_msg}")) + on_error=lambda error_msg: print(f"Error! {error_msg}"), + ) output = "" for result in search_results: output += result.text + "\n\n" return output - diff --git a/ThirdAI/Terms and Conditions/TkinterUI.py b/ThirdAI/Terms and Conditions/TkinterUI.py index 47317636a23..dd7d0172e74 100644 --- a/ThirdAI/Terms and Conditions/TkinterUI.py +++ b/ThirdAI/Terms and Conditions/TkinterUI.py @@ -9,6 +9,7 @@ class ThirdAIApp: """ A GUI application for using the ThirdAI neural database client to train and query data. """ + def __init__(self, root): """ Initialize the user interface window. @@ -19,7 +20,7 @@ def __init__(self, root): # Initialize the main window self.root = root self.root.geometry("600x500") - self.root.title('ThirdAI - T&C') + self.root.title("ThirdAI - T&C") # Initialize variables self.path = [] @@ -28,33 +29,69 @@ def __init__(self, root): # GUI elements # Labels and buttons - self.menu = tk.Label(self.root, text="Terms & Conditions", font=self.custom_font(30), fg='black', - highlightthickness=2, highlightbackground="red") + self.menu = tk.Label( + self.root, + text="Terms & Conditions", + font=self.custom_font(30), + fg="black", + highlightthickness=2, + highlightbackground="red", + ) self.menu.place(x=125, y=10) - self.insert_button = tk.Button(self.root, text="Insert File!", font=self.custom_font(15), fg='black', bg="grey", - width=10, command=self.file_input) + self.insert_button = tk.Button( + self.root, + text="Insert File!", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.file_input, + ) self.insert_button.place(x=245, y=100) self.text_box = tk.Text(self.root, wrap=tk.WORD, width=30, height=1) self.text_box.place(x=165, y=150) - self.training_button = tk.Button(self.root, text="Training", font=self.custom_font(15), fg='black', bg="grey", - width=10, command=self.training) + self.training_button = tk.Button( + self.root, + text="Training", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.training, + ) self.training_button.place(x=245, y=195) - self.query_label = tk.Label(self.root, text="Query", font=self.custom_font(20), fg='black') + self.query_label = tk.Label( + self.root, text="Query", font=self.custom_font(20), fg="black" + ) self.query_label.place(x=255, y=255) self.query_entry = tk.Entry(self.root, font=self.custom_font(20), width=30) self.query_entry.place(x=70, y=300) - self.processing_button = tk.Button(self.root, text="Processing", font=self.custom_font(15), fg='black', - bg="grey", width=10, command=self.processing) + self.processing_button = tk.Button( + self.root, + text="Processing", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.processing, + ) self.processing_button.place(x=245, y=355) - self.clear_button = tk.Button(self.root, text="Clear", font=15, fg='black', bg="grey", width=10, - command=self.clear_all) + self.clear_button = tk.Button( + self.root, + text="Clear", + font=15, + fg="black", + bg="grey", + width=10, + command=self.clear_all, + ) self.clear_button.place(x=245, y=405) @staticmethod @@ -96,7 +133,9 @@ def training(self): Train the neural database client with the selected PDF file. """ if not self.path: - messagebox.showwarning("No File Selected", "Please select a PDF file before training.") + messagebox.showwarning( + "No File Selected", "Please select a PDF file before training." + ) return self.client.train(self.path[0]) diff --git a/TicTacToe.py b/TicTacToe.py index f1b61b80df9..9a817cf7a8e 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -2,182 +2,195 @@ def print_tic_tac_toe(values): print("\n") print("\t | |") print("\t {} | {} | {}".format(values[0], values[1], values[2])) - print('\t_____|_____|_____') - + print("\t_____|_____|_____") + print("\t | |") print("\t {} | {} | {}".format(values[3], values[4], values[5])) - print('\t_____|_____|_____') - + print("\t_____|_____|_____") + print("\t | |") - + print("\t {} | {} | {}".format(values[6], values[7], values[8])) print("\t | |") print("\n") - - + + # Function to print the score-board def print_scoreboard(score_board): print("\t--------------------------------") print("\t SCOREBOARD ") print("\t--------------------------------") - + players = list(score_board.keys()) print("\t ", players[0], "\t ", score_board[players[0]]) print("\t ", players[1], "\t ", score_board[players[1]]) - + print("\t--------------------------------\n") - + + # Function to check if any player has won def check_win(player_pos, cur_player): - + # All possible winning combinations - soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] - + soln = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [1, 4, 7], + [2, 5, 8], + [3, 6, 9], + [1, 5, 9], + [3, 5, 7], + ] + # Loop to check if any winning combination is satisfied for x in soln: if all(y in player_pos[cur_player] for y in x): - + # Return True if any winning combination satisfies return True - # Return False if no combination is satisfied - return False - + # Return False if no combination is satisfied + return False + + # Function to check if the game is drawn def check_draw(player_pos): - if len(player_pos['X']) + len(player_pos['O']) == 9: + if len(player_pos["X"]) + len(player_pos["O"]) == 9: return True - return False - + return False + + # Function for a single game of Tic Tac Toe def single_game(cur_player): - + # Represents the Tic Tac Toe - values = [' ' for x in range(9)] - + values = [" " for x in range(9)] + # Stores the positions occupied by X and O - player_pos = {'X':[], 'O':[]} - + player_pos = {"X": [], "O": []} + # Game Loop for a single game of Tic Tac Toe while True: print_tic_tac_toe(values) - + # Try exception block for MOVE input try: print("Player ", cur_player, " turn. Which box? : ", end="") - move = int(input()) + move = int(input()) except ValueError: print("Wrong Input!!! Try Again") continue - + # Sanity check for MOVE inout if move < 1 or move > 9: print("Wrong Input!!! Try Again") continue - + # Check if the box is not occupied already - if values[move-1] != ' ': + if values[move - 1] != " ": print("Place already filled. Try again!!") continue - + # Update game information - - # Updating grid status - values[move-1] = cur_player - + + # Updating grid status + values[move - 1] = cur_player + # Updating player positions player_pos[cur_player].append(move) - + # Function call for checking win if check_win(player_pos, cur_player): print_tic_tac_toe(values) - print("Player ", cur_player, " has won the game!!") + print("Player ", cur_player, " has won the game!!") print("\n") return cur_player - + # Function call for checking draw game if check_draw(player_pos): print_tic_tac_toe(values) print("Game Drawn") print("\n") - return 'D' - + return "D" + # Switch player moves - if cur_player == 'X': - cur_player = 'O' + if cur_player == "X": + cur_player = "O" else: - cur_player = 'X' - + cur_player = "X" + + if __name__ == "__main__": - + print("Player 1") player1 = input("Enter the name : ") print("\n") - + print("Player 2") player2 = input("Enter the name : ") print("\n") - + # Stores the player who chooses X and O cur_player = player1 - + # Stores the choice of players - player_choice = {'X' : "", 'O' : ""} - + player_choice = {"X": "", "O": ""} + # Stores the options - options = ['X', 'O'] - + options = ["X", "O"] + # Stores the scoreboard score_board = {player1: 0, player2: 0} print_scoreboard(score_board) - + # Game Loop for a series of Tic Tac Toe - # The loop runs until the players quit + # The loop runs until the players quit while True: - + # Player choice Menu print("Turn to choose for", cur_player) print("Enter 1 for X") print("Enter 2 for O") print("Enter 3 to Quit") - + # Try exception for CHOICE input try: - choice = int(input()) + choice = int(input()) except ValueError: print("Wrong Input!!! Try Again\n") continue - - # Conditions for player choice + + # Conditions for player choice if choice == 1: - player_choice['X'] = cur_player + player_choice["X"] = cur_player if cur_player == player1: - player_choice['O'] = player2 + player_choice["O"] = player2 else: - player_choice['O'] = player1 - + player_choice["O"] = player1 + elif choice == 2: - player_choice['O'] = cur_player + player_choice["O"] = cur_player if cur_player == player1: - player_choice['X'] = player2 + player_choice["X"] = player2 else: - player_choice['X'] = player1 - + player_choice["X"] = player1 + elif choice == 3: print("Final Scores") print_scoreboard(score_board) - break - + break + else: print("Wrong Choice!!!! Try Again\n") - + # Stores the winner in a single game of Tic Tac Toe - winner = single_game(options[choice-1]) - + winner = single_game(options[choice - 1]) + # Edits the scoreboard according to the winner - if winner != 'D' : + if winner != "D": player_won = player_choice[winner] score_board[player_won] = score_board[player_won] + 1 - + print_scoreboard(score_board) # Switch player who chooses X or O if cur_player == player1: diff --git a/To find the largest number between 3 numbers.py b/To find the largest number between 3 numbers.py index 5e7e1575292..1c8e99e8f22 100644 --- a/To find the largest number between 3 numbers.py +++ b/To find the largest number between 3 numbers.py @@ -1,7 +1,6 @@ # Python program to find the largest number among the three input numbers -a=[] +a = [] for i in range(3): a.append(int(input())) -print("The largest among three numbers is:",max(a)) - +print("The largest among three numbers is:", max(a)) diff --git a/Translator/translator.py b/Translator/translator.py index 509be9e6410..2987c91af74 100644 --- a/Translator/translator.py +++ b/Translator/translator.py @@ -1,6 +1,7 @@ from tkinter import * from translate import Translator + # Translator function def translate(): translator = Translator(from_lang=lan1.get(), to_lang=lan2.get()) diff --git a/Triplets with zero sum/find_Triplets_with_zero_sum.py b/Triplets with zero sum/find_Triplets_with_zero_sum.py index 2a2d2b7688d..7fda3f2e2e3 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -4,9 +4,9 @@ Python program to find triplets in a given array whose sum is zero """ + # function to print triplets with 0 sum def find_Triplets_with_zero_sum(arr, num): - """find triplets in a given array whose sum is zero Parameteres : diff --git a/Turtle_Star.py b/Turtle_Star.py index 49ce64cb949..d9b1a3b06ef 100644 --- a/Turtle_Star.py +++ b/Turtle_Star.py @@ -1,29 +1,29 @@ import turtle - + board = turtle.Turtle() - + # first triangle for star -board.forward(100) # draw base - +board.forward(100) # draw base + board.left(120) board.forward(100) - + board.left(120) board.forward(100) - + board.penup() board.right(150) board.forward(50) - + # second triangle for star board.pendown() board.right(90) board.forward(100) - + board.right(120) board.forward(100) - + board.right(120) board.forward(100) - + turtle.done() diff --git a/Voice Command Calculator.py b/Voice Command Calculator.py index ccc6e6c6496..8c220092a38 100644 --- a/Voice Command Calculator.py +++ b/Voice Command Calculator.py @@ -1,32 +1,37 @@ import operator import speech_recognition as s_r -print("Your speech_recognition version is: "+s_r.__version__) + +print("Your speech_recognition version is: " + s_r.__version__) r = s_r.Recognizer() my_mic_device = s_r.Microphone(device_index=1) with my_mic_device as source: print("Say what you want to calculate, example: 3 plus 3") r.adjust_for_ambient_noise(source) audio = r.listen(source) -my_string=r.recognize_google(audio) +my_string = r.recognize_google(audio) print(my_string) + + def get_operator_fn(op): return { - '+' : operator.add, - '-' : operator.sub, - 'x' : operator.mul, - 'divided' :operator.__truediv__, - 'divided by' :operator.__truediv__, - 'divide' :operator.__truediv__, - 'Divided' :operator.__truediv__, - 'Divided by' :operator.__truediv__, - 'Divide' :operator.__truediv__, - 'Mod' : operator.mod, - 'mod' : operator.mod, - '^' : operator.xor, - }[op] + "+": operator.add, + "-": operator.sub, + "x": operator.mul, + "divided": operator.__truediv__, + "divided by": operator.__truediv__, + "divide": operator.__truediv__, + "Divided": operator.__truediv__, + "Divided by": operator.__truediv__, + "Divide": operator.__truediv__, + "Mod": operator.mod, + "mod": operator.mod, + "^": operator.xor, + }[op] + def eval_binary_expr(op1, oper, op2): - op1,op2 = int(op1), int(op2) + op1, op2 = int(op1), int(op2) return get_operator_fn(oper)(op1, op2) + print(eval_binary_expr(*(my_string.split()))) diff --git a/VoiceAssistant/Project_Basic_struct/TextTospeech.py b/VoiceAssistant/Project_Basic_struct/TextTospeech.py index 5c23af072e6..ae0bc6d351c 100644 --- a/VoiceAssistant/Project_Basic_struct/TextTospeech.py +++ b/VoiceAssistant/Project_Basic_struct/TextTospeech.py @@ -4,12 +4,11 @@ from win32com import client import os + def tts(): - audio = 'speech.mp3' - language = 'en' + audio = "speech.mp3" + language = "en" sentence = input("Enter the text to be spoken :- ") - + speaker = win32com.client.Dispatch("SAPI.SpVoice") sp = speaker.Speak(sentence) - - diff --git a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py index 1c2baf70897..8ebde2c4784 100644 --- a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py +++ b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py @@ -11,10 +11,10 @@ def main(): start = 0 end = 0 if start == 0: - print("\nSay \"Hello Python\" to activate the Voice Assistant!") + print('\nSay "Hello Python" to activate the Voice Assistant!') start += 1 while True: - + q = short_hear().lower() if "close" in q: greet("end") @@ -23,7 +23,7 @@ def main(): greet("start") print_menu() while True: - + query = hear().lower() if "close" in query: greet("end") @@ -32,34 +32,51 @@ def main(): elif "text to speech" in query: tts() time.sleep(4) - - elif "search on google" in query or "search google" in query or "google" in query: + elif ( + "search on google" in query + or "search google" in query + or "google" in query + ): google_search() time.sleep(10) - - elif "search on wikipedia" in query or "search wikipedia" in query or "wikipedia" in query: + + elif ( + "search on wikipedia" in query + or "search wikipedia" in query + or "wikipedia" in query + ): wiki_search() time.sleep(10) - + elif "word" in query: ms_word() time.sleep(5) - + elif "book" in query: pdf_read() time.sleep(10) - + elif "speech to text" in query: big_text() time.sleep(5) - + else: print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") - - print("\nDo you want to continue? if yes then say " + Fore.YELLOW + "\"YES\"" + Fore.WHITE + " else say " + Fore.YELLOW + "\"CLOSE PYTHON\"") - speak("Do you want to continue? if yes then say YES else say CLOSE PYTHON") + + print( + "\nDo you want to continue? if yes then say " + + Fore.YELLOW + + '"YES"' + + Fore.WHITE + + " else say " + + Fore.YELLOW + + '"CLOSE PYTHON"' + ) + speak( + "Do you want to continue? if yes then say YES else say CLOSE PYTHON" + ) qry = hear().lower() if "yes" in qry: print_menu() @@ -75,4 +92,5 @@ def main(): else: continue + main() diff --git a/VoiceAssistant/Project_Basic_struct/dictator.py b/VoiceAssistant/Project_Basic_struct/dictator.py index f5cb71fb014..b357633f78b 100644 --- a/VoiceAssistant/Project_Basic_struct/dictator.py +++ b/VoiceAssistant/Project_Basic_struct/dictator.py @@ -4,17 +4,25 @@ from colorama import Fore, Back, Style + def big_text(): - print("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?") - speak("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?") + print( + "By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?" + ) + speak( + "By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?" + ) print(Fore.YELLOW + "Yes or No") query = hear().lower() duration_time = 0 - if "yes" in query or "es" in query or "ye" in query or "s" in query: + if "yes" in query or "es" in query or "ye" in query or "s" in query: - print("Please enter the time(in seconds) for which I shall record your speech - ", end = '') + print( + "Please enter the time(in seconds) for which I shall record your speech - ", + end="", + ) duration_time = int(input().strip()) print("\n") @@ -24,6 +32,7 @@ def big_text(): text = long_hear(duration_time) print("\n" + Fore.LIGHTCYAN_EX + text) + def colours(): text = "Colour" print(Fore.BLACK + text) @@ -43,5 +52,6 @@ def colours(): print(Fore.LIGHTCYAN_EX + text) print(Fore.LIGHTWHITE_EX + text) -#big_text() -#colours() \ No newline at end of file + +# big_text() +# colours() diff --git a/VoiceAssistant/Project_Basic_struct/menu.py b/VoiceAssistant/Project_Basic_struct/menu.py index 8512271c0d2..4261a3cf025 100644 --- a/VoiceAssistant/Project_Basic_struct/menu.py +++ b/VoiceAssistant/Project_Basic_struct/menu.py @@ -1,13 +1,12 @@ -from rich.console import Console # pip3 install Rich +from rich.console import Console # pip3 install Rich from rich.table import Table from speakListen import * def print_menu(): - """Display a table with list of tasks and their associated commands. - """ + """Display a table with list of tasks and their associated commands.""" speak("I can do the following") - table = Table(title="\nI can do the following :- ", show_lines = True) + table = Table(title="\nI can do the following :- ", show_lines=True) table.add_column("Sr. No.", style="cyan", no_wrap=True) table.add_column("Task", style="yellow") @@ -24,4 +23,5 @@ def print_menu(): console = Console() console.print(table) -#print_menu() \ No newline at end of file + +# print_menu() diff --git a/VoiceAssistant/Project_Basic_struct/speakListen.py b/VoiceAssistant/Project_Basic_struct/speakListen.py index e16db721abb..b64ad7d56b8 100644 --- a/VoiceAssistant/Project_Basic_struct/speakListen.py +++ b/VoiceAssistant/Project_Basic_struct/speakListen.py @@ -7,9 +7,9 @@ from rich.progress import Progress -python = pyttsx3.init("sapi5") # name of the engine is set as Python +python = pyttsx3.init("sapi5") # name of the engine is set as Python voices = python.getProperty("voices") -#print(voices) +# print(voices) python.setProperty("voice", voices[1].id) python.setProperty("rate", 140) @@ -19,151 +19,165 @@ def speak(text): Args: text ([str]): [It is the speech to be spoken] - """ + """ python.say(text) python.runAndWait() + def greet(g): """Uses the datetime library to generate current time and then greets accordingly. - + Args: g (str): To decide whether to say hello or good bye """ if g == "start" or g == "s": h = datetime.datetime.now().hour - text = '' + text = "" if h > 12 and h < 17: text = "Hello ! Good Afternoon " elif h < 12 and h > 0: text = "Hello! Good Morning " - elif h >= 17 : + elif h >= 17: text = "Hello! Good Evening " text += " I am Python, How may i help you ?" - speak(text) - + speak(text) + elif g == "quit" or g == "end" or g == "over" or g == "e": - text = 'Thank you!. Good Bye ! ' + text = "Thank you!. Good Bye ! " speak(text) + def hear(): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = 9) # option - #speech = r.listen(source) + speech = r.record(source, duration=9) # option + # speech = r.listen(source) # convert speech to text try: - #print("Recognizing...") + # print("Recognizing...") recognizing() speech = r.recognize_google(speech) print(speech + "\n") - + except Exception as exception: print(exception) return "None" return speech + def recognizing(): - """Uses the Rich library to print a simulates version of "recognizing" by printing a loading bar. - """ + """Uses the Rich library to print a simulates version of "recognizing" by printing a loading bar.""" with Progress() as pr: - rec = pr.add_task("[red]Recognizing...", total = 100) + rec = pr.add_task("[red]Recognizing...", total=100) while not pr.finished: - pr.update(rec, advance = 1.0) + pr.update(rec, advance=1.0) time.sleep(0.01) -def long_hear(duration_time = 60): + +def long_hear(duration_time=60): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear() - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = duration_time) # option - #speech = r.listen(source) + speech = r.record(source, duration=duration_time) # option + # speech = r.listen(source) # convert speech to text try: - print(Fore.RED +"Recognizing...") - #recognizing() + print(Fore.RED + "Recognizing...") + # recognizing() speech = r.recognize_google(speech) - #print(speech + "\n") - + # print(speech + "\n") + except Exception as exception: - print(exception) + print(exception) return "None" return speech -def short_hear(duration_time = 5): + +def short_hear(duration_time=5): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = duration_time) # option - #speech = r.listen(source) + speech = r.record(source, duration=duration_time) # option + # speech = r.listen(source) # convert speech to text try: - print(Fore.RED +"Recognizing...") - #recognizing() + print(Fore.RED + "Recognizing...") + # recognizing() speech = r.recognize_google(speech) - #print(speech + "\n") - + # print(speech + "\n") + except Exception as exception: - print(exception) + print(exception) return "None" return speech - -if __name__ == '__main__': +if __name__ == "__main__": # print("Enter your name") # name = hear() # speak("Hello " + name) # greet("s") # greet("e") pass - #hear() - #recognizing() - + # hear() + # recognizing() diff --git a/VoiceAssistant/Project_Basic_struct/speechtotext.py b/VoiceAssistant/Project_Basic_struct/speechtotext.py index 1b1974c8b79..e73a55eaf32 100644 --- a/VoiceAssistant/Project_Basic_struct/speechtotext.py +++ b/VoiceAssistant/Project_Basic_struct/speechtotext.py @@ -1,6 +1,9 @@ import speech_recognition as sr + # initialize the recognizer r = sr.Recognizer() + + def stt(): with sr.Microphone() as source: # read the audio data from the default microphone @@ -8,4 +11,4 @@ def stt(): print("Recognizing...") # convert speech to text text = r.recognize_google(audio_data) - print(text) \ No newline at end of file + print(text) diff --git a/VoiceAssistant/Project_Basic_struct/websiteWork.py b/VoiceAssistant/Project_Basic_struct/websiteWork.py index c20a2792791..af8c51d3de7 100644 --- a/VoiceAssistant/Project_Basic_struct/websiteWork.py +++ b/VoiceAssistant/Project_Basic_struct/websiteWork.py @@ -11,27 +11,26 @@ def google_search(): - """[Goes to google and searches the website asked by the user] - """ + """[Goes to google and searches the website asked by the user]""" google_search_link = "https://www.google.co.in/search?q=" google_search = "What do you want me to search on Google? " print(google_search) speak(google_search) - + query = hear() if query != "None": - webbrowser.open(google_search_link+query) + webbrowser.open(google_search_link + query) elif query == "None": print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") + def wiki_search(): - """[Speak out the summary in wikipedia and going to the website according to user's choice.] - """ + """[Speak out the summary in wikipedia and going to the website according to user's choice.]""" wiki_search = "What do you want me to search on Wikipedia? Please tell me the exact sentence or word to Search." wiki_search_link = "https://en.wikipedia.org/wiki/" - + print(wiki_search) speak(wiki_search) @@ -39,7 +38,7 @@ def wiki_search(): try: if query != "None": - results = wikipedia.summary(query, sentences = 2) + results = wikipedia.summary(query, sentences=2) print(results) speak(results) @@ -47,7 +46,16 @@ def wiki_search(): speak("Do you want me to open the Wikipedia page?") q = hear().lower() - if "yes" in q or "okay" in q or "ok" in q or "opun" in q or "opan" in q or "vopen" in q or "es" in q or "s" in q: + if ( + "yes" in q + or "okay" in q + or "ok" in q + or "opun" in q + or "opan" in q + or "vopen" in q + or "es" in q + or "s" in q + ): print(wiki_search_link + query) webbrowser.open(wiki_search_link + query) @@ -58,5 +66,6 @@ def wiki_search(): except Exception as e: print("Couldn't find") -#wiki_search() -#google_search() + +# wiki_search() +# google_search() diff --git a/Weather Scrapper/weather.py b/Weather Scrapper/weather.py index 3980d958bd6..788424522ac 100644 --- a/Weather Scrapper/weather.py +++ b/Weather Scrapper/weather.py @@ -1,4 +1,4 @@ -#TODO - refactor & clean code +# TODO - refactor & clean code import csv import time from datetime import datetime @@ -11,22 +11,22 @@ from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By -#TODO - Add input checking +# TODO - Add input checking city = input("City >") state = input("State >") -url = 'https://www.wunderground.com' +url = "https://www.wunderground.com" -#Supresses warnings and specifies the webdriver to run w/o a GUI +# Supresses warnings and specifies the webdriver to run w/o a GUI options = Options() options.headless = True -options.add_argument('log-level=3') +options.add_argument("log-level=3") driver = webdriver.Chrome(options=options) driver.get(url) -#----------------------------------------------------- +# ----------------------------------------------------- # Connected successfully to the site -#Passes the city and state input to the weather sites search box +# Passes the city and state input to the weather sites search box searchBox = driver.find_element(By.XPATH, '//*[@id="wuSearch"]') location = city + " " + state @@ -34,27 +34,40 @@ action = ActionChains(driver) searchBox.send_keys(location) element = WebDriverWait(driver, 10).until( - EC.presence_of_element_located((By.XPATH, '//*[@id="wuForm"]/search-autocomplete/ul/li[2]/a/span[1]')) + EC.presence_of_element_located( + (By.XPATH, '//*[@id="wuForm"]/search-autocomplete/ul/li[2]/a/span[1]') + ) ) searchBox.send_keys(Keys.RETURN) -#----------------------------------------------------- -#Gather weather data -#City - Time - Date - Temperature - Precipitation - Sky - Wind +# ----------------------------------------------------- +# Gather weather data +# City - Time - Date - Temperature - Precipitation - Sky - Wind -#waits till the page loads to begin gathering data +# waits till the page loads to begin gathering data precipitationElem = WebDriverWait(driver, 10).until( - EC.presence_of_element_located((By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]')) + EC.presence_of_element_located( + ( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]', + ) + ) +) +precipitationElem = driver.find_element( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]', ) -precipitationElem = driver.find_element(By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]') precip = "Precipitation:" + precipitationElem.text.split()[0] -windAndSkyElem = driver.find_element(By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[2]') +windAndSkyElem = driver.find_element( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[2]', +) description = windAndSkyElem.text.split(". ") sky = description[0] temp = description[1] wind = description[2] -#Format the date and time +# Format the date and time time = datetime.now().strftime("%H:%M") today = date.today() date = today.strftime("%b-%d-%Y") diff --git a/Web Socket.py b/Web Socket.py index efb44bbbc21..8da7e224c00 100644 --- a/Web Socket.py +++ b/Web Socket.py @@ -1,13 +1,14 @@ # Program to print a data & it's Metadata of online uploaded file using "socket". import socket -skt_c=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -skt_c.connect(('data.pr4e.org',80)) -link='GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() + +skt_c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +skt_c.connect(("data.pr4e.org", 80)) +link = "GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n".encode() skt_c.send(link) while True: - data=skt_c.recv(512) - if len(data)<1: - break - print(data.decode()) + data = skt_c.recv(512) + if len(data) < 1: + break + print(data.decode()) skt_c.close() diff --git a/Webbrowser/tk-browser.py b/Webbrowser/tk-browser.py index cbbfd01bb3e..fc8b6ddebac 100644 --- a/Webbrowser/tk-browser.py +++ b/Webbrowser/tk-browser.py @@ -3,26 +3,28 @@ # Written by Sina Meysami # -from tkinter import * # pip install tk-tools -import tkinterweb # pip install tkinterweb +from tkinter import * # pip install tk-tools +import tkinterweb # pip install tkinterweb import sys + class Browser(Tk): def __init__(self): - super(Browser,self).__init__() + super(Browser, self).__init__() self.title("Tk Browser") try: browser = tkinterweb.HtmlFrame(self) browser.load_website("https://google.com") - browser.pack(fill="both",expand=True) + browser.pack(fill="both", expand=True) except Exception: sys.exit() - - + + def main(): browser = Browser() browser.mainloop() - + + if __name__ == "__main__": # Webbrowser v1.0 main() diff --git a/Wikipdedia/flask_rendering.py b/Wikipdedia/flask_rendering.py index 05c6d7494bf..4dc0432dc22 100644 --- a/Wikipdedia/flask_rendering.py +++ b/Wikipdedia/flask_rendering.py @@ -1,13 +1,13 @@ from flask import Flask, render_template, request import practice_beautifulsoap as data -app = Flask(__name__, template_folder='template') +app = Flask(__name__, template_folder="template") -@app.route('/', methods=["GET", "POST"]) +@app.route("/", methods=["GET", "POST"]) def index(): languages = data.lang() - return render_template('index.html', languages=languages) + return render_template("index.html", languages=languages) @app.route("/display", methods=["POST"]) @@ -19,8 +19,13 @@ def output(): soup_data = data.data(entered_topic, selected_language) soup_image = data.get_image_urls(entered_topic) - return render_template('output.html', heading=entered_topic.upper(), data=soup_data, - url=soup_image, language=selected_language) + return render_template( + "output.html", + heading=entered_topic.upper(), + data=soup_data, + url=soup_image, + language=selected_language, + ) if __name__ == "__main__": diff --git a/Wikipdedia/main.py b/Wikipdedia/main.py index 5596b44786f..c937c7cff1b 100644 --- a/Wikipdedia/main.py +++ b/Wikipdedia/main.py @@ -6,11 +6,11 @@ def print_hi(name): # Use a breakpoint in the code line below to debug your script. - print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. + print(f"Hi, {name}") # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. -if __name__ == '__main__': - print_hi('PyCharm') +if __name__ == "__main__": + print_hi("PyCharm") # See PyCharm help at https://www.jetbrains.com/help/pycharm/ diff --git a/Wikipdedia/practice_beautifulsoap.py b/Wikipdedia/practice_beautifulsoap.py index 00beb87fc44..01938c24139 100644 --- a/Wikipdedia/practice_beautifulsoap.py +++ b/Wikipdedia/practice_beautifulsoap.py @@ -8,11 +8,11 @@ def lang(): try: response = requests.get("https://www.wikipedia.org/") response.raise_for_status() - soup = BeautifulSoup(response.content, 'html.parser') + soup = BeautifulSoup(response.content, "html.parser") - for option in soup.find_all('option'): + for option in soup.find_all("option"): language = option.text - symbol = option['lang'] + symbol = option["lang"] language_symbols[language] = symbol return list(language_symbols.keys()) @@ -29,17 +29,19 @@ def data(selected_topic, selected_language): url = f"https://{symbol}.wikipedia.org/wiki/{selected_topic}" data_response = requests.get(url) data_response.raise_for_status() - data_soup = BeautifulSoup(data_response.content, 'html.parser') + data_soup = BeautifulSoup(data_response.content, "html.parser") - main_content = data_soup.find('div', {'id': 'mw-content-text'}) + main_content = data_soup.find("div", {"id": "mw-content-text"}) filtered_content = "" if main_content: for element in main_content.descendants: - if element.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']: - filtered_content += "\n" + element.get_text(strip=True).upper() + "\n" + if element.name in ["h1", "h2", "h3", "h4", "h5", "h6"]: + filtered_content += ( + "\n" + element.get_text(strip=True).upper() + "\n" + ) - elif element.name == 'p': + elif element.name == "p": filtered_content += element.get_text(strip=True) + "\n" return filtered_content @@ -54,11 +56,11 @@ def get_image_urls(query): search_url = f"https://www.google.com/search?q={query}&tbm=isch" image_response = requests.get(search_url) image_response.raise_for_status() - image_soup = BeautifulSoup(image_response.content, 'html.parser') + image_soup = BeautifulSoup(image_response.content, "html.parser") image_urls = [] - for img in image_soup.find_all('img'): - image_url = img.get('src') + for img in image_soup.find_all("img"): + image_url = img.get("src") if image_url and image_url.startswith("http"): image_urls.append(image_url) diff --git a/WikipediaModule.py b/WikipediaModule.py index dec5e2a5c0b..ca28501fa41 100644 --- a/WikipediaModule.py +++ b/WikipediaModule.py @@ -3,6 +3,7 @@ @author: Albert """ + from __future__ import print_function import wikipedia as wk diff --git a/Wordle/wordle.py b/Wordle/wordle.py index ffed27a1838..9b5e18d033c 100644 --- a/Wordle/wordle.py +++ b/Wordle/wordle.py @@ -26,9 +26,11 @@ import random # Load 5 letter word dictionary -with open("5 letter word dictionary.txt", 'r') as dictionary: +with open("5 letter word dictionary.txt", "r") as dictionary: # Read content of dictionary - dictionary = dictionary.read().split('\n') # This returns a list of all the words in the dictionary + dictionary = dictionary.read().split( + "\n" + ) # This returns a list of all the words in the dictionary # Choose a random word from the dictionary word = random.choice(dictionary) @@ -95,7 +97,6 @@ letter += 1 continue - answer_given = False do_not_add = False # Check if letter is in word @@ -105,7 +106,10 @@ if user_inp[letter] == i: return_answer += "G" else: - if not user_inp[word.index(user_inp[letter])] == word[word.index(user_inp[letter])]: + if ( + not user_inp[word.index(user_inp[letter])] + == word[word.index(user_inp[letter])] + ): return_answer += "Y" else: answer_given = False @@ -117,7 +121,7 @@ # Append checked letter to the list letters_checked if not do_not_add: - letters_checked.append(user_inp[letter]) + letters_checked.append(user_inp[letter]) letter += 1 diff --git a/Youtube Downloader With GUI/main.py b/Youtube Downloader With GUI/main.py index 21d5c534ad5..b21e4495a99 100644 --- a/Youtube Downloader With GUI/main.py +++ b/Youtube Downloader With GUI/main.py @@ -12,6 +12,8 @@ q = input("") if q == "shutdown": os.system("shutdown -s") + + # function progress to keep check of progress of function. def progress(stream=None, chunk=None, remaining=None): file_downloaded = file_size - remaining diff --git a/add_two_nums.py b/add_two_nums.py index f68631f2ea1..f6deff6e67e 100644 --- a/add_two_nums.py +++ b/add_two_nums.py @@ -1,9 +1,10 @@ +import typing + __author__ = "Nitkarsh Chourasia" __version__ = "1.0" -def addition( - num1: typing.Union[int, float], - num2: typing.Union[int, float] -) -> str: + + +def addition(num1: typing.Union[int, float], num2: typing.Union[int, float]) -> str: """A function to add two given numbers.""" # Checking if the given parameters are numerical or not. @@ -17,7 +18,7 @@ def addition( # returning the result. return f"The sum of {num1} and {num2} is: {sum_result}" -) + print(addition(5, 10)) # This will use the provided parameters print(addition(2, 2)) diff --git a/agecalculator.py b/agecalculator.py index 094aa88ca46..86813e30f9f 100644 --- a/agecalculator.py +++ b/agecalculator.py @@ -4,52 +4,51 @@ from _datetime import * win = tk.Tk() -win.title('Age Calculate') -win.geometry('310x400') -# win.iconbitmap('pic.png') this is use extention ico then show pic +win.title("Age Calculate") +win.geometry("310x400") +# win.iconbitmap('pic.png') this is use extention ico then show pic ############################################ Frame ############################################ pic = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png") -win.tk.call('wm','iconphoto',win._w,pic) +win.tk.call("wm", "iconphoto", win._w, pic) -canvas=tk.Canvas(win,width=310,height=190) +canvas = tk.Canvas(win, width=310, height=190) canvas.grid() image = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png") -canvas.create_image(0,0,anchor='nw',image=image) +canvas.create_image(0, 0, anchor="nw", image=image) frame = ttk.Frame(win) -frame.place(x=40,y=220) - +frame.place(x=40, y=220) ############################################ Label on Frame ############################################ -name = ttk.Label(frame,text = 'Name : ',font = ('',12,'bold')) -name.grid(row=0,column=0,sticky = tk.W) +name = ttk.Label(frame, text="Name : ", font=("", 12, "bold")) +name.grid(row=0, column=0, sticky=tk.W) -year = ttk.Label(frame,text = 'Year : ',font = ('',12,'bold')) -year.grid(row=1,column=0,sticky = tk.W) +year = ttk.Label(frame, text="Year : ", font=("", 12, "bold")) +year.grid(row=1, column=0, sticky=tk.W) -month = ttk.Label(frame,text = 'Month : ',font = ('',12,'bold')) -month.grid(row=2,column=0,sticky = tk.W) +month = ttk.Label(frame, text="Month : ", font=("", 12, "bold")) +month.grid(row=2, column=0, sticky=tk.W) -date = ttk.Label(frame,text = 'Date : ',font = ('',12,'bold')) -date.grid(row=3,column=0,sticky = tk.W) +date = ttk.Label(frame, text="Date : ", font=("", 12, "bold")) +date.grid(row=3, column=0, sticky=tk.W) ############################################ Entry Box ############################################ -name_entry = ttk.Entry(frame,width=25) -name_entry.grid(row=0,column=1) +name_entry = ttk.Entry(frame, width=25) +name_entry.grid(row=0, column=1) name_entry.focus() -year_entry = ttk.Entry(frame,width=25) -year_entry.grid(row=1,column=1,pady=5) +year_entry = ttk.Entry(frame, width=25) +year_entry.grid(row=1, column=1, pady=5) -month_entry = ttk.Entry(frame,width=25) -month_entry.grid(row=2,column=1) +month_entry = ttk.Entry(frame, width=25) +month_entry.grid(row=2, column=1) -date_entry = ttk.Entry(frame,width=25) -date_entry.grid(row=3,column=1,pady=5) +date_entry = ttk.Entry(frame, width=25) +date_entry.grid(row=3, column=1, pady=5) def age_cal(): @@ -57,13 +56,12 @@ def age_cal(): year_entry.get() month_entry.get() date_entry.get() - cal = datetime.today()-(int(year_entry)) + cal = datetime.today() - (int(year_entry)) print(cal) -btn = ttk.Button(frame,text='Age calculate',command=age_cal) -btn.grid(row=4,column=1) - +btn = ttk.Button(frame, text="Age calculate", command=age_cal) +btn.grid(row=4, column=1) win.mainloop() diff --git a/armstrongnumber.py b/armstrongnumber.py index 2e714fa9db4..f4def08d440 100644 --- a/armstrongnumber.py +++ b/armstrongnumber.py @@ -10,7 +10,7 @@ temp = num while temp > 0: digit = temp % 10 - sum += digit ** 3 + sum += digit**3 temp //= 10 # display the result diff --git a/automail.py b/automail.py index 84b67424408..6267a9794de 100644 --- a/automail.py +++ b/automail.py @@ -1,25 +1,27 @@ -#find documentation for ezgmail module at https://pypi.org/project/EZGmail/ -#simple simon says module that interacts with google API to read the subject line of an email and respond to "Simon says:" -#DO NOT FORGET TO ADD CREDENTIALS.JSON AND TOKEN.JSON TO .GITIGNORE!!! +# find documentation for ezgmail module at https://pypi.org/project/EZGmail/ +# simple simon says module that interacts with google API to read the subject line of an email and respond to "Simon says:" +# DO NOT FORGET TO ADD CREDENTIALS.JSON AND TOKEN.JSON TO .GITIGNORE!!! import ezgmail, re, time check = True while check: recThreads = ezgmail.recent() - findEmail = re.compile(r'<(.*)@(.*)>') + findEmail = re.compile(r"<(.*)@(.*)>") i = 0 for msg in recThreads: - subEval = recThreads[i].messages[0].subject.split(' ') + subEval = recThreads[i].messages[0].subject.split(" ") sender = recThreads[i].messages[0].sender - if subEval[0] == 'Simon' and subEval[1] == 'says:': - subEval.remove('Simon') - subEval.remove('says:') - replyAddress = findEmail.search(sender).group(0).replace('<','').replace('>','') - replyContent = 'I am now doing ' + ' '.join(subEval) + if subEval[0] == "Simon" and subEval[1] == "says:": + subEval.remove("Simon") + subEval.remove("says:") + replyAddress = ( + findEmail.search(sender).group(0).replace("<", "").replace(">", "") + ) + replyContent = "I am now doing " + " ".join(subEval) ezgmail.send(replyAddress, replyContent, replyContent) ezgmail._trash(recThreads[i]) - if subEval[0] == 'ENDTASK': #remote kill command + if subEval[0] == "ENDTASK": # remote kill command check = False i += 1 - time.sleep(60) #change check frquency; default every minute \ No newline at end of file + time.sleep(60) # change check frquency; default every minute diff --git a/binary search.py b/binary search.py index cfad85df817..2cf464c8f20 100644 --- a/binary search.py +++ b/binary search.py @@ -1,23 +1,25 @@ -def binarySearchAppr (arr, start, end, x): -# check condition - if end >= start: - mid = start + (end- start)//2 - # If element is present at the middle - if arr[mid] == x: - return mid - # If element is smaller than mid - elif arr[mid] > x: - return binarySearchAppr(arr, start, mid-1, x) - # Else the element greator than mid - else: - return binarySearchAppr(arr, mid+1, end, x) - else: - # Element is not found in the array - return -1 -arr = sorted(['t','u','t','o','r','i','a','l']) -x ='r' -result = binarySearchAppr(arr, 0, len(arr)-1, x) +def binarySearchAppr(arr, start, end, x): + # check condition + if end >= start: + mid = start + (end - start) // 2 + # If element is present at the middle + if arr[mid] == x: + return mid + # If element is smaller than mid + elif arr[mid] > x: + return binarySearchAppr(arr, start, mid - 1, x) + # Else the element greator than mid + else: + return binarySearchAppr(arr, mid + 1, end, x) + else: + # Element is not found in the array + return -1 + + +arr = sorted(["t", "u", "t", "o", "r", "i", "a", "l"]) +x = "r" +result = binarySearchAppr(arr, 0, len(arr) - 1, x) if result != -1: - print ("Element is present at index "+str(result)) + print("Element is present at index " + str(result)) else: - print ("Element is not present in array") + print("Element is not present in array") diff --git a/binary_search_trees/delete_a_node_in_bst.py b/binary_search_trees/delete_a_node_in_bst.py index bfb6a0708ac..c600a9f9fd4 100644 --- a/binary_search_trees/delete_a_node_in_bst.py +++ b/binary_search_trees/delete_a_node_in_bst.py @@ -1,35 +1,36 @@ from inorder_successor import inorder_successor + + # The above line imports the inorder_successor function from the inorder_successor.py file -def delete_node(root,val): - """ This function deletes a node with value val from the BST""" - - # search in the left subtree - if root.data < val: - root.right = delete_node(root.right,val) - - # search in the right subtree - elif root.data>val: - root.left=delete_node(root.left,val) - - # node to be deleted is found - else: - # case 1: no child leaf node - if root.left is None and root.right is None: - return None - - # case 2: one child - if root.left is None: - return root.right - - # case 2: one child - elif root.right is None: - return root.left - - # case 3: two children - - # find the inorder successor - IS=inorder_successor(root.right) - root.data=IS.data - root.right=delete_node(root.right,IS.data) - return root - \ No newline at end of file +def delete_node(root, val): + """This function deletes a node with value val from the BST""" + + # search in the left subtree + if root.data < val: + root.right = delete_node(root.right, val) + + # search in the right subtree + elif root.data > val: + root.left = delete_node(root.left, val) + + # node to be deleted is found + else: + # case 1: no child leaf node + if root.left is None and root.right is None: + return None + + # case 2: one child + if root.left is None: + return root.right + + # case 2: one child + elif root.right is None: + return root.left + + # case 3: two children + + # find the inorder successor + IS = inorder_successor(root.right) + root.data = IS.data + root.right = delete_node(root.right, IS.data) + return root diff --git a/binary_search_trees/inorder_successor.py b/binary_search_trees/inorder_successor.py index b9b15666eea..36b26a51119 100644 --- a/binary_search_trees/inorder_successor.py +++ b/binary_search_trees/inorder_successor.py @@ -1,10 +1,10 @@ def inorder_successor(root): - # This function returns the inorder successor of a node in a BST - - # The inorder successor of a node is the node with the smallest value greater than the value of the node - current=root - - # The inorder successor is the leftmost node in the right subtree - while current.left is not None: - current=current.left - return current \ No newline at end of file + # This function returns the inorder successor of a node in a BST + + # The inorder successor of a node is the node with the smallest value greater than the value of the node + current = root + + # The inorder successor is the leftmost node in the right subtree + while current.left is not None: + current = current.left + return current diff --git a/binary_search_trees/inorder_traversal.py b/binary_search_trees/inorder_traversal.py index 3bb4c4101ed..1a98ebcf903 100644 --- a/binary_search_trees/inorder_traversal.py +++ b/binary_search_trees/inorder_traversal.py @@ -1,15 +1,15 @@ def inorder(root): - """ This function performs an inorder traversal of a BST""" - + """This function performs an inorder traversal of a BST""" + # The inorder traversal of a BST is the nodes in increasing order if root is None: return - + # Traverse the left subtree inorder(root.left) - + # Print the root node print(root.data) - + # Traverse the right subtree - inorder(root.right) \ No newline at end of file + inorder(root.right) diff --git a/binary_search_trees/insert_in_bst.py b/binary_search_trees/insert_in_bst.py index dd726d06596..9264cf61723 100644 --- a/binary_search_trees/insert_in_bst.py +++ b/binary_search_trees/insert_in_bst.py @@ -1,17 +1,18 @@ from tree_node import Node -def insert(root,val): - - """ This function inserts a node with value val into the BST""" - + + +def insert(root, val): + """This function inserts a node with value val into the BST""" + # If the tree is empty, create a new node if root is None: return Node(val) - + # If the value to be inserted is less than the root value, insert in the left subtree if val < root.data: - root.left = insert(root.left,val) - + root.left = insert(root.left, val) + # If the value to be inserted is greater than the root value, insert in the right subtree else: - root.right = insert(root.right,val) - return root \ No newline at end of file + root.right = insert(root.right, val) + return root diff --git a/binary_search_trees/main.py b/binary_search_trees/main.py index 96ebb6ae8eb..6986eead3c6 100644 --- a/binary_search_trees/main.py +++ b/binary_search_trees/main.py @@ -10,7 +10,7 @@ def main(): - + # Create a BST root = None root = insert(root, 50) @@ -20,54 +20,51 @@ def main(): root = insert(root, 70) root = insert(root, 60) root = insert(root, 80) - + # Print the inorder traversal of the BST print("Inorder traversal of the original BST:") print_in_range(root, 10, 90) - + # Print the root to leaf paths print("Root to leaf paths:") print_root_to_leaf_paths(root, []) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 20 from the BST:") root = delete_node(root, 20) - + # Print the inorder traversal of the BST print("Inorder traversal of the BST after deleting 20:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 30 from the BST:") root = delete_node(root, 30) - + # Print the inorder traversal of the BST after deleting 30 print("Inorder traversal of the BST after deleting 30:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 50 from the BST:") root = delete_node(root, 50) - + # Print the inorder traversal of the BST after deleting 50 print("Inorder traversal of the BST after deleting 50:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + print("Searching for 70 in the BST:", search(root, 70)) print("Searching for 100 in the BST:", search(root, 100)) print("Inorder traversal of the BST:") @@ -77,9 +74,6 @@ def main(): print("Inorder traversal of the mirror BST:") print_in_range(mirror_root, 10, 90) + if __name__ == "__main__": main() - - - - diff --git a/binary_search_trees/mirror_a_bst.py b/binary_search_trees/mirror_a_bst.py index 73f080f85c2..284809217d5 100644 --- a/binary_search_trees/mirror_a_bst.py +++ b/binary_search_trees/mirror_a_bst.py @@ -1,16 +1,18 @@ from tree_node import Node + + def create_mirror_bst(root): - """ Function to create a mirror of a binary search tree""" - + """Function to create a mirror of a binary search tree""" + # If the tree is empty, return None if root is None: return None - + # Create a new node with the root value - + # Recursively create the mirror of the left and right subtrees left_mirror = create_mirror_bst(root.left) right_mirror = create_mirror_bst(root.right) root.left = right_mirror root.right = left_mirror - return root \ No newline at end of file + return root diff --git a/binary_search_trees/print_in_range.py b/binary_search_trees/print_in_range.py index fecca23ba24..5df1d8aefa2 100644 --- a/binary_search_trees/print_in_range.py +++ b/binary_search_trees/print_in_range.py @@ -1,21 +1,20 @@ -def print_in_range(root,k1,k2): - - """ This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" - - # If the tree is empty, return - if root is None: - return - - # If the root value is in the range, print the root value - if root.data >= k1 and root.data <= k2: - print_in_range(root.left,k1,k2) - print(root.data) - print_in_range(root.right,k1,k2) - - # If the root value is less than k1, the nodes in the range will be in the right subtree - elif root.data < k1: - print_in_range(root.left,k1,k2) - - # If the root value is greater than k2, the nodes in the range will be in the left subtree - else: - print_in_range(root.right,k1,k2) \ No newline at end of file +def print_in_range(root, k1, k2): + """This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" + + # If the tree is empty, return + if root is None: + return + + # If the root value is in the range, print the root value + if root.data >= k1 and root.data <= k2: + print_in_range(root.left, k1, k2) + print(root.data) + print_in_range(root.right, k1, k2) + + # If the root value is less than k1, the nodes in the range will be in the right subtree + elif root.data < k1: + print_in_range(root.left, k1, k2) + + # If the root value is greater than k2, the nodes in the range will be in the left subtree + else: + print_in_range(root.right, k1, k2) diff --git a/binary_search_trees/root_to_leaf_paths.py b/binary_search_trees/root_to_leaf_paths.py index 22867a713ec..5638d1afb97 100644 --- a/binary_search_trees/root_to_leaf_paths.py +++ b/binary_search_trees/root_to_leaf_paths.py @@ -1,17 +1,17 @@ def print_root_to_leaf_paths(root, path): - """ This function prints all the root to leaf paths in a BST""" - + """This function prints all the root to leaf paths in a BST""" + # If the tree is empty, return if root is None: return - + # Add the root value to the path path.append(root.data) if root.left is None and root.right is None: print(path) - + # Recursively print the root to leaf paths in the left and right subtrees else: print_root_to_leaf_paths(root.left, path) print_root_to_leaf_paths(root.right, path) - path.pop() \ No newline at end of file + path.pop() diff --git a/binary_search_trees/search_in_bst.py b/binary_search_trees/search_in_bst.py index 4a95780e43a..08a3449eb2c 100644 --- a/binary_search_trees/search_in_bst.py +++ b/binary_search_trees/search_in_bst.py @@ -1,15 +1,15 @@ def search(root, val): - """ This function searches for a node with value val in the BST and returns True if found, False otherwise""" - + """This function searches for a node with value val in the BST and returns True if found, False otherwise""" + # If the tree is empty, return False if root == None: return False - + # If the root value is equal to the value to be searched, return True if root.data == val: return True - + # If the value to be searched is less than the root value, search in the left subtree if root.data > val: return search(root.left, val) - return search(root.right, val) \ No newline at end of file + return search(root.right, val) diff --git a/binary_search_trees/tree_node.py b/binary_search_trees/tree_node.py index 1d35656da08..1f03b8595ba 100644 --- a/binary_search_trees/tree_node.py +++ b/binary_search_trees/tree_node.py @@ -1,6 +1,6 @@ - # Node class for binary tree + class Node: def __init__(self, data): self.data = data diff --git a/binary_search_trees/validate_bst.py b/binary_search_trees/validate_bst.py index 3569c833005..cbb1a32dd9f 100644 --- a/binary_search_trees/validate_bst.py +++ b/binary_search_trees/validate_bst.py @@ -1,17 +1,17 @@ -def is_valid_bst(root,min,max): - """ Function to check if a binary tree is a binary search tree""" - +def is_valid_bst(root, min, max): + """Function to check if a binary tree is a binary search tree""" + # If the tree is empty, return True if root is None: return True - + # If the root value is less than the minimum value or greater than the maximum value, return False if min is not None and root.data <= min.data: return False - + # If the root value is greater than the maximum value or less than the minimum value, return False elif max is not None and root.data >= max.data: return False - + # Recursively check if the left and right subtrees are BSTs - return is_valid_bst(root.left,min,root) and is_valid_bst(root.right,root,max) \ No newline at end of file + return is_valid_bst(root.left, min, root) and is_valid_bst(root.right, root, max) diff --git a/birthdays.py b/birthdays.py index 19ad2b001a2..a85610e6ded 100644 --- a/birthdays.py +++ b/birthdays.py @@ -1,15 +1,15 @@ -birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} +birthdays = {"Alice": "Apr 1", "Bob": "Dec 12", "Carol": "Mar 4"} while True: - - print('Enter a name: (blank to quit)') - name = input() - if name == '': - break - if name in birthdays: - print(birthdays[name] + ' is the birthday of ' + name) - else: - print('I do not have birthday information for ' + name) - print('What is their birthday?') - bday = input() - birthdays[name] = bday - print('Birthday database updated.') + + print("Enter a name: (blank to quit)") + name = input() + if name == "": + break + if name in birthdays: + print(birthdays[name] + " is the birthday of " + name) + else: + print("I do not have birthday information for " + name) + print("What is their birthday?") + bday = input() + birthdays[name] = bday + print("Birthday database updated.") diff --git a/bodymass.py b/bodymass.py index be37d0db0ef..bfc2c01e1ee 100644 --- a/bodymass.py +++ b/bodymass.py @@ -1,19 +1,19 @@ -kilo = float (input("kilonuzu giriniz(örnek: 84.9): ")) -boy = float (input("Boyunuzu m cinsinden giriniz: ")) +kilo = float(input("kilonuzu giriniz(örnek: 84.9): ")) +boy = float(input("Boyunuzu m cinsinden giriniz: ")) -vki = (kilo / (boy**2)) +vki = kilo / (boy**2) if vki < 18.5: print(f"vucut kitle indeksiniz: {vki} zayıfsınız.") elif vki < 25: - print (f"vucut kitle indeksiniz: {vki} normalsiniz.") + print(f"vucut kitle indeksiniz: {vki} normalsiniz.") elif vki < 30: - print (f"vucut kitle indeksiniz: {vki} fazla kilolusunuz.") + print(f"vucut kitle indeksiniz: {vki} fazla kilolusunuz.") elif vki < 35: - print (f"vucut kitle indeksiniz: {vki} 1. derece obezsiniz") + print(f"vucut kitle indeksiniz: {vki} 1. derece obezsiniz") elif vki < 40: - print (f"vucut kitle indeksiniz: {vki} 2.derece obezsiniz.") -elif vki >40: - print (f"vucut kitle indeksiniz: {vki} 3.derece obezsiniz.") + print(f"vucut kitle indeksiniz: {vki} 2.derece obezsiniz.") +elif vki > 40: + print(f"vucut kitle indeksiniz: {vki} 3.derece obezsiniz.") else: print("Yanlış değer girdiniz.") diff --git a/calc_area.py b/calc_area.py index 7f35917c746..cf7f259e046 100644 --- a/calc_area.py +++ b/calc_area.py @@ -11,7 +11,7 @@ def main(): ) if shape == 1: side = float(input("Enter length of side: ")) - print("Area of square = " + str(side ** 2)) + print("Area of square = " + str(side**2)) elif shape == 2: l = float(input("Enter length: ")) b = float(input("Enter breadth: ")) diff --git a/cartesian_product.py b/cartesian_product.py index 7ed49aae295..dd1926b6e80 100644 --- a/cartesian_product.py +++ b/cartesian_product.py @@ -9,11 +9,11 @@ def cartesian_product(list1, list2): """Cartesian Product of Two Lists.""" for _i in list1: for _j in list2: - print((_i, _j), end=' ') + print((_i, _j), end=" ") # Main -if __name__ == '__main__': +if __name__ == "__main__": list1 = input().split() list2 = input().split() @@ -22,4 +22,3 @@ def cartesian_product(list1, list2): list2 = [int(i) for i in list2] cartesian_product(list1, list2) - diff --git a/check whether the string is Symmetrical or Palindrome.py b/check whether the string is Symmetrical or Palindrome.py index d29772e721a..3747bdc2c47 100644 --- a/check whether the string is Symmetrical or Palindrome.py +++ b/check whether the string is Symmetrical or Palindrome.py @@ -1,53 +1,55 @@ -def palindrome(a): - - mid = (len(a)-1)//2 +def palindrome(a): + + mid = (len(a) - 1) // 2 start = 0 - last = len(a)-1 + last = len(a) - 1 flag = 0 - - while(start= 8 and any(char.isdigit() for char in password) + # Example usage: password_input = input("Enter password: ") if password_validation(password_input): @@ -39,7 +44,8 @@ def password_validation(password): def username_validation(username): # Allow only alphanumeric characters and underscores - return bool(re.match('^[a-zA-Z0-9_]+$', username)) + return bool(re.match("^[a-zA-Z0-9_]+$", username)) + # Example usage: username_input = input("Enter username: ") @@ -51,7 +57,8 @@ def username_validation(username): def country_validation(country): # Example: Allow only alphabetical characters and spaces - return bool(re.match('^[a-zA-Z ]+$', country)) + return bool(re.match("^[a-zA-Z ]+$", country)) + # Example usage: country_input = input("Enter country name: ") @@ -59,4 +66,3 @@ def country_validation(country): print("Country name is valid.") else: print("Invalid country name.") - diff --git a/cloning_a_list.py b/cloning_a_list.py index ceaebef16e7..524225b734f 100644 --- a/cloning_a_list.py +++ b/cloning_a_list.py @@ -1,17 +1,11 @@ -# Python program to copy or clone a list -# Using the Slice Operator -def Cloning(li1): +# Python program to copy or clone a list +# Using the Slice Operator +def Cloning(li1): return li1[:] - -# Driver Code -li1 = [ - 4, - 8, - 2, - 10, - 15, - 18 -] -li2 = Cloning(li1) -print("Original List:", li1) -print("After Cloning:", li2) + + +# Driver Code +li1 = [4, 8, 2, 10, 15, 18] +li2 = Cloning(li1) +print("Original List:", li1) +print("After Cloning:", li2) diff --git a/colorma_as_color.py b/colorma_as_color.py index 9bf2338ebbb..d72029b67f1 100644 --- a/colorma_as_color.py +++ b/colorma_as_color.py @@ -19,4 +19,4 @@ print("back to normal now") -# …or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor the fabulous Blessings, or the incredible _Rich. \ No newline at end of file +# …or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor the fabulous Blessings, or the incredible _Rich. diff --git a/colour spiral.py b/colour spiral.py index 86385ada09d..83c2785828a 100644 --- a/colour spiral.py +++ b/colour spiral.py @@ -1,52 +1,52 @@ # import turtle import turtle - + # defining colors -colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] - +colors = ["red", "yellow", "green", "purple", "blue", "orange"] + # setup turtle pen -t= turtle.Pen() - +t = turtle.Pen() + # changes the speed of the turtle t.speed(10) - + # changes the background color turtle.bgcolor("black") - + # make spiral_web for x in range(200): - t.pencolor(colors[x%6]) # setting color + t.pencolor(colors[x % 6]) # setting color - t.width(x/100 + 1) # setting width + t.width(x / 100 + 1) # setting width - t.forward(x) # moving forward + t.forward(x) # moving forward + + t.left(59) # moving left - t.left(59) # moving left - turtle.done() t.speed(10) - -turtle.bgcolor("black") # changes the background color - + +turtle.bgcolor("black") # changes the background color + # make spiral_web for x in range(200): - t.pencolor(colors[x%6]) # setting color + t.pencolor(colors[x % 6]) # setting color - t.width(x/100 + 1) # setting width + t.width(x / 100 + 1) # setting width - t.forward(x) # moving forward + t.forward(x) # moving forward - t.left(59) # moving left - -turtle.done() \ No newline at end of file + t.left(59) # moving left + +turtle.done() diff --git a/convert celsius into fahrenheit.py b/convert celsius into fahrenheit.py index df58fcda9de..0f3bf8e9838 100644 --- a/convert celsius into fahrenheit.py +++ b/convert celsius into fahrenheit.py @@ -1,4 +1,4 @@ -cels= float(input("enter temp in celsius")) -print("temprature in celsius is :",cels) -fahr = cels*9/5+32 -print("temprature in fahrenhite is :",fahr) +cels = float(input("enter temp in celsius")) +print("temprature in celsius is :", cels) +fahr = cels * 9 / 5 + 32 +print("temprature in fahrenhite is :", fahr) diff --git a/count the numbers of two vovels.py b/count the numbers of two vovels.py index 297e2488590..eb66d0967d6 100644 --- a/count the numbers of two vovels.py +++ b/count the numbers of two vovels.py @@ -1,19 +1,19 @@ # Program to count the number of each vowels # string of vowels -vowels = 'aeiou' +vowels = "aeiou" -ip_str = 'Hello, have you tried our tutorial section yet?' +ip_str = "Hello, have you tried our tutorial section yet?" # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 -count = {}.fromkeys(vowels,0) +count = {}.fromkeys(vowels, 0) # count the vowels for char in ip_str: - if char in count: - count[char] += 1 + if char in count: + count[char] += 1 print(count) diff --git a/create password validity in python.py b/create password validity in python.py index 46793e91061..c69a826e89e 100644 --- a/create password validity in python.py +++ b/create password validity in python.py @@ -1,24 +1,27 @@ import time -pwd=input("Enter your password: ") #any password u want to set + +pwd = input("Enter your password: ") # any password u want to set + def IInd_func(): - count1=0 - for j in range(5): - a=0 - count=0 - user_pwd = input("Enter remember password: ") #password you remember - for i in range(len(pwd)): - if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd - a +=1 - count+=1 - if count==len(pwd): - print("correct pwd") - break - else: - count1 += 1 - print("not correct") - if count1==5: - time.sleep(30) - IInd_func() + count1 = 0 + for j in range(5): + a = 0 + count = 0 + user_pwd = input("Enter remember password: ") # password you remember + for i in range(len(pwd)): + if user_pwd[i] == pwd[a]: # comparing remembered pwd with fixed pwd + a += 1 + count += 1 + if count == len(pwd): + print("correct pwd") + break + else: + count1 += 1 + print("not correct") + if count1 == 5: + time.sleep(30) + IInd_func() + -IInd_func() \ No newline at end of file +IInd_func() diff --git a/decimal to binary.py b/decimal to binary.py index 566f83be43c..03619b074c2 100644 --- a/decimal to binary.py +++ b/decimal to binary.py @@ -3,7 +3,7 @@ def decimalToBinary(num): to binary and prints it""" if num > 1: decimalToBinary(num // 2) - print(num % 2, end='') + print(num % 2, end="") # decimal number diff --git a/depreciated_programs/corona_cases.py b/depreciated_programs/corona_cases.py index e93e7cd99f9..14a7a644f76 100644 --- a/depreciated_programs/corona_cases.py +++ b/depreciated_programs/corona_cases.py @@ -53,7 +53,7 @@ def india(): ╚═╝╚═╝░░╚══╝╚═════╝░╚═╝╚═╝░░╚═╝ Country Name :- {name} -New Confirmed Cases :- {indiaonfirmed} +New Confirmed Cases :- {indiaconfirmed} Total Confirmed Cases :- {indiatotal} New Deaths :- {indiaDeaths} Total Deaths :- {deathstotal} diff --git a/dialogs/messagebox.py b/dialogs/messagebox.py index 14a88dc185d..2a57cb7d1b4 100644 --- a/dialogs/messagebox.py +++ b/dialogs/messagebox.py @@ -2,6 +2,4 @@ from quo.dialog import MessageBox -MessageBox( - title='Example dialog window', - text='Do you want to continue?') +MessageBox(title="Example dialog window", text="Do you want to continue?") diff --git a/digital_clock.py b/digital_clock.py index f461878917b..357a3bb9c3c 100644 --- a/digital_clock.py +++ b/digital_clock.py @@ -20,6 +20,7 @@ # master + # This function is used to # display time on the label def def_time(): diff --git a/divisors_of_a_number.py b/divisors_of_a_number.py index 326378b177f..55ffd18a753 100644 --- a/divisors_of_a_number.py +++ b/divisors_of_a_number.py @@ -1,20 +1,20 @@ a = 0 -while a<= 0 : +while a <= 0: number_to_divide = input("choose the number to divide -->") - try : + try: a = int(number_to_divide) - except ValueError : + except ValueError: a = 0 - if a <= 0 : - print('choose a number grether than 0') + if a <= 0: + print("choose a number grether than 0") list_number_divided = [] -for number in range(1,a + 1) : +for number in range(1, a + 1): b = a % number - if b == 0 : + if b == 0: list_number_divided.append(number) -print('\nthe number ' + number_to_divide + ' can be divided by:') -for item in list_number_divided : - print(f'{item}') -if len(list_number_divided) <= 2 : - print(number_to_divide + ' is a prime number') \ No newline at end of file +print("\nthe number " + number_to_divide + " can be divided by:") +for item in list_number_divided: + print(f"{item}") +if len(list_number_divided) <= 2: + print(number_to_divide + " is a prime number") diff --git a/equations.py b/equations.py index 1fc4b9159d7..464f1d58b67 100644 --- a/equations.py +++ b/equations.py @@ -25,7 +25,7 @@ b = int(input("What is value of b?")) c = int(input("What is value of c?")) - D = b ** 2 - 4 * a * c + D = b**2 - 4 * a * c if D < 0: print("No real values of x satisfies your equation.") diff --git a/fastapi.py b/fastapi.py index 37aa3aa3ce0..8689d7c5b65 100644 --- a/fastapi.py +++ b/fastapi.py @@ -7,6 +7,7 @@ # temp database fakedb = [] + # course model to store courses class Course(BaseModel): id: int diff --git a/fibonici series.py b/fibonici series.py index 17e24228f94..85483ee8ab7 100644 --- a/fibonici series.py +++ b/fibonici series.py @@ -6,16 +6,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/file_ext_changer.py b/file_ext_changer.py index 4d80261b052..407e46f991c 100644 --- a/file_ext_changer.py +++ b/file_ext_changer.py @@ -1,4 +1,5 @@ -'''' Multiple extension changer''' +"""' Multiple extension changer""" + import time from pathlib import Path as p import random as rand @@ -8,7 +9,7 @@ def chxten_(files, xten): chfile = [] for file in files: - ch_file = file.split('.') + ch_file = file.split(".") ch_file = ch_file[0] chfile.append(ch_file) if len(xten) == len(chfile): @@ -22,7 +23,7 @@ def chxten_(files, xten): ch_xten = chfile[i] + xten[i] chxten.append(ch_xten) for i in range(1, (len(chfile) + 1) - len(xten)): - ch_xten = chfile[- + i] + xten[-1] + ch_xten = chfile[-+i] + xten[-1] chxten.append(ch_xten) elif len(xten) == 1: chxten = [] @@ -40,61 +41,64 @@ def chxten_(files, xten): ch_xten = chfile[i] + xten[i] chxten.append(ch_xten) else: - return 'an error occured' + return "an error occured" return chxten # End of function definitions # Beggining of execution of code -#password -password = input('Enter password:') +# password +password = input("Enter password:") password = password.encode() password = hashlib.sha512(password).hexdigest() -if password == 'c99d3d8f321ff63c2f4aaec6f96f8df740efa2dc5f98fccdbbb503627fd69a9084073574ee4df2b888f9fe2ed90e29002c318be476bb62dabf8386a607db06c4': +if ( + password + == "c99d3d8f321ff63c2f4aaec6f96f8df740efa2dc5f98fccdbbb503627fd69a9084073574ee4df2b888f9fe2ed90e29002c318be476bb62dabf8386a607db06c4" +): pass else: - print('wrong password!') + print("wrong password!") time.sleep(0.3) exit(404) -files = input('Enter file names and thier extensions (seperated by commas):') -xten = input('Enter Xtensions to change with (seperated by commas):') +files = input("Enter file names and thier extensions (seperated by commas):") +xten = input("Enter Xtensions to change with (seperated by commas):") -if files == '*': +if files == "*": pw = p.cwd() - files = '' + files = "" for i in pw.iterdir(): if not p.is_dir(i): i = str(i) - if not i.endswith('.py'): + if not i.endswith(".py"): # if not i.endswith('exe'): - if not i.endswith('.log'): - files = files + i + ',' -if files == 'r': + if not i.endswith(".log"): + files = files + i + "," +if files == "r": pw = p.cwd() - files = '' + files = "" filer = [] for i in pw.iterdir(): if p.is_file(i): i = str(i) - if not i.endswith('.py'): - if not i.endswith('.exe'): - if not i.endswith('.log'): + if not i.endswith(".py"): + if not i.endswith(".exe"): + if not i.endswith(".log"): filer.append(i) for i in range(5): - pos = rand.randint(0,len(filer)) - files = files + filer[pos] + ',' + pos = rand.randint(0, len(filer)) + files = files + filer[pos] + "," print(files) -files = files.split(',') -xten = xten.split(',') +files = files.split(",") +xten = xten.split(",") # Validation for file in files: check = p(file).exists() if check == False: - print(f'{file} is not found. Paste this file in the directory of {file}') + print(f"{file} is not found. Paste this file in the directory of {file}") files.remove(file) # Ended validation @@ -102,8 +106,8 @@ def chxten_(files, xten): chxten = chxten_(files, xten) # Error Handlings -if chxten == 'an error occured': - print('Check your inputs correctly') +if chxten == "an error occured": + print("Check your inputs correctly") time.sleep(1) exit(404) else: @@ -111,7 +115,7 @@ def chxten_(files, xten): for i in range(len(files)): f = p(files[i]) f.rename(chxten[i]) - print('All files has been changed') + print("All files has been changed") except PermissionError: pass except FileNotFoundError: @@ -119,7 +123,9 @@ def chxten_(files, xten): for file in files: check = p(file).exists() if check == False: - print(f'{file} is not found. Paste this file in the directory of {file}') + print( + f"{file} is not found. Paste this file in the directory of {file}" + ) files.remove(file) # except Exception: # print('An Error Has Occured in exception') diff --git a/find_cube_root.py b/find_cube_root.py index cf315708a25..87e9b4215b7 100644 --- a/find_cube_root.py +++ b/find_cube_root.py @@ -7,9 +7,9 @@ def cubeRoot(): x = int(input("Enter an integer: ")) for ans in range(0, abs(x) + 1): - if ans ** 3 == abs(x): + if ans**3 == abs(x): break - if ans ** 3 != abs(x): + if ans**3 != abs(x): print(x, "is not a perfect cube!") else: if x < 0: diff --git a/find_prime.py b/find_prime.py index d6d5a515bd2..7e24acb9dad 100644 --- a/find_prime.py +++ b/find_prime.py @@ -24,6 +24,7 @@ p now equal this new number (which is the next prime), and repeat from step 3. - When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n. """ + import sys diff --git a/finding LCM.py b/finding LCM.py index e95feb45b47..573ae0557d9 100644 --- a/finding LCM.py +++ b/finding LCM.py @@ -1,21 +1,22 @@ - # Python Program to find the L.C.M. of two input number + def compute_lcm(x, y): - # choose the greater number - if x > y: - greater = x - else: - greater = y + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while True: + if (greater % x == 0) and (greater % y == 0): + lcm = greater + break + greater += 1 - while(True): - if((greater % x == 0) and (greater % y == 0)): - lcm = greater - break - greater += 1 + return lcm - return lcm num1 = 54 num2 = 24 diff --git a/folder_size.py b/folder_size.py index 7410de8da36..d0ad968e12d 100755 --- a/folder_size.py +++ b/folder_size.py @@ -25,7 +25,7 @@ "Megabytes": float(1) / (1024 * 1024), "Gigabytes": float(1) / (1024 * 1024 * 1024), } -for (path, dirs, files) in os.walk( +for path, dirs, files in os.walk( directory ): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. for file in files: # Get all the files diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py index 7d2ee832dcf..6c74e0d11d9 100644 --- a/game_of_life/game_o_life.py +++ b/game_of_life/game_o_life.py @@ -27,6 +27,7 @@ Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ + import random import sys diff --git a/gcd.py b/gcd.py index 0f10da082d7..7d89fe0515b 100644 --- a/gcd.py +++ b/gcd.py @@ -2,6 +2,7 @@ although there is function to find gcd in python but this is the code which takes two inputs and prints gcd of the two. """ + a = int(input("Enter number 1 (a): ")) b = int(input("Enter number 2 (b): ")) diff --git a/generate_permutations.py b/generate_permutations.py index 4623e08d2c3..26d473d1d32 100644 --- a/generate_permutations.py +++ b/generate_permutations.py @@ -1,16 +1,17 @@ -def generate(A,k): - if k ==1: +def generate(A, k): + if k == 1: print(A) return else: for i in range(k): - generate(A,k-1) - if(i80): + sentence = sentence + line.text + ratio = fuzz.token_set_ratio(sentence, checkString) + if ratio > 80: singleLink.append(k) singleRatio.append(ratio) - if(len(singleLink)>=4): - singleLink=np.array(singleLink) - singleRatio=np.array(singleRatio) - inds=singleRatio.argsort() - sortedLink=singleLink[inds] - sortedFinalList=list(sortedLink[::-1]) - sortedFinalList=sortedFinalList[:4] - FinalResult.append(singleWrite+sortedFinalList) - elif(len(singleLink)<4) and len(singleLink)>0: + if len(singleLink) >= 4: + singleLink = np.array(singleLink) + singleRatio = np.array(singleRatio) + inds = singleRatio.argsort() + sortedLink = singleLink[inds] + sortedFinalList = list(sortedLink[::-1]) + sortedFinalList = sortedFinalList[:4] + FinalResult.append(singleWrite + sortedFinalList) + elif (len(singleLink) < 4) and len(singleLink) > 0: singleLink = np.array(singleLink) singleRatio = np.array(singleRatio) inds = singleRatio.argsort() sortedLink = singleLink[inds] sortedFinalList = list(sortedLink[::-1]) - sortedFinalList=sortedFinalList+(4-len(sortedFinalList))*[[" "]] + sortedFinalList = sortedFinalList + (4 - len(sortedFinalList)) * [[" "]] FinalResult.append(singleWrite + sortedFinalList) else: - sortedFinalList=[[" "]]*4 - FinalResult.append(singleWrite+sortedFinalList) + sortedFinalList = [[" "]] * 4 + FinalResult.append(singleWrite + sortedFinalList) SearchResults() -FinalResult=np.array(FinalResult) -FinalResult=pd.DataFrame(FinalResult) -FinalResult.columns=["Input","Link A","Link B","Link C","Link D"] -FinalResult.replace(" ",np.nan) -FinalResult.to_csv("Susma.csv",index=False) +FinalResult = np.array(FinalResult) +FinalResult = pd.DataFrame(FinalResult) +FinalResult.columns = ["Input", "Link A", "Link B", "Link C", "Link D"] +FinalResult.replace(" ", np.nan) +FinalResult.to_csv("Susma.csv", index=False) print(FinalResult) diff --git a/greaterno.py b/greaterno.py index a4fb15c1231..d636d48e307 100644 --- a/greaterno.py +++ b/greaterno.py @@ -7,15 +7,15 @@ num3 = 12 # uncomment following lines to take three numbers from user -#num1 = float(input("Enter first number: ")) -#num2 = float(input("Enter second number: ")) -#num3 = float(input("Enter third number: ")) +# num1 = float(input("Enter first number: ")) +# num2 = float(input("Enter second number: ")) +# num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): - largest = num1 + largest = num1 elif (num2 >= num1) and (num2 >= num3): - largest = num2 + largest = num2 else: - largest = num3 + largest = num3 print("The largest number is", largest) diff --git a/gstin_scraper.py b/gstin_scraper.py index 4f55ca6de30..a043480331e 100644 --- a/gstin_scraper.py +++ b/gstin_scraper.py @@ -17,28 +17,39 @@ """ -# Using a demo list in case of testing the script. +# Using a demo list in case of testing the script. # This list will be used in case user skips "company input" dialogue by pressing enter. -demo_companies = ["Bank of Baroda", "Trident Limited", "Reliance Limited", "The Yummy Treat", "Yes Bank", "Mumbai Mineral Trading Corporation"] +demo_companies = [ + "Bank of Baroda", + "Trident Limited", + "Reliance Limited", + "The Yummy Treat", + "Yes Bank", + "Mumbai Mineral Trading Corporation", +] + def get_company_list(): company_list = [] - + while True: company = input("Enter a company name (or press Enter to finish): ") if not company: break company_list.append(company) - + return company_list + def fetch_gstins(company_name, csrf_token): - third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/" - payload = {'gstnum': company_name, 'csrfmiddlewaretoken': csrf_token} + third_party_gstin_site = ( + "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + ) + payload = {"gstnum": company_name, "csrfmiddlewaretoken": csrf_token} # Getting the HTML content and extracting the GSTIN content using BeautifulSoup. html_content = requests.post(third_party_gstin_site, data=payload) - soup = BeautifulSoup(html_content.text, 'html.parser') + soup = BeautifulSoup(html_content.text, "html.parser") site_results = soup.find_all(id="searchresult") # Extracting GSTIN specific values from child elements. @@ -46,23 +57,28 @@ def fetch_gstins(company_name, csrf_token): return gstins + def main(): temp = get_company_list() companies = temp if temp else demo_companies all_gstin_data = "" - third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + third_party_gstin_site = ( + "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + ) # Getting the CSRF value for further RESTful calls. page_with_csrf = requests.get(third_party_gstin_site) - soup = BeautifulSoup(page_with_csrf.text, 'html.parser') - csrf_token = soup.find('input', {"name": "csrfmiddlewaretoken"})['value'] + soup = BeautifulSoup(page_with_csrf.text, "html.parser") + csrf_token = soup.find("input", {"name": "csrfmiddlewaretoken"})["value"] for company in companies: gstins = fetch_gstins(company, csrf_token) # Only include GSTINs for Bengaluru and Mumbai-based companies - comma_separated_gstins = ', '.join([g for g in gstins if g.startswith(('27', '29'))]) + comma_separated_gstins = ", ".join( + [g for g in gstins if g.startswith(("27", "29"))] + ) all_gstin_data += f"{company} = {comma_separated_gstins}\n\n" @@ -72,5 +88,6 @@ def main(): # Printing the data print(all_gstin_data) + if __name__ == "__main__": main() diff --git a/gui_calculator.py b/gui_calculator.py index 435b38972d1..e0fa630e427 100644 --- a/gui_calculator.py +++ b/gui_calculator.py @@ -6,6 +6,7 @@ w.title("Calculatorax") w.configure(bg="#03befc") + # Functions(Keypad) def calc1(): b = txt1.get() diff --git a/happy_num.py b/happy_num.py index a9740d0703b..4e0d395f96a 100644 --- a/happy_num.py +++ b/happy_num.py @@ -1,45 +1,44 @@ -#Way2 1: - -#isHappyNumber() will determine whether a number is happy or not -def isHappyNumber(num): - rem = sum = 0; - - #Calculates the sum of squares of digits - while(num > 0): - rem = num%10; - sum = sum + (rem*rem); - num = num//10; - return sum; - -num = 82; -result = num; - -while(result != 1 and result != 4): - result = isHappyNumber(result); - -#Happy number always ends with 1 -if(result == 1): - print(str(num) + " is a happy number after apply way 1"); -#Unhappy number ends in a cycle of repeating numbers which contain 4 -elif(result == 4): - print(str(num) + " is not a happy number after apply way 1"); - - - - - -#way 2: - -#Another way to do this and code is also less -n=num -setData=set() #set datastructure for checking a number is repeated or not. +# Way2 1: + + +# isHappyNumber() will determine whether a number is happy or not +def isHappyNumber(num): + rem = sum = 0 + + # Calculates the sum of squares of digits + while num > 0: + rem = num % 10 + sum = sum + (rem * rem) + num = num // 10 + return sum + + +num = 82 +result = num + +while result != 1 and result != 4: + result = isHappyNumber(result) + +# Happy number always ends with 1 +if result == 1: + print(str(num) + " is a happy number after apply way 1") +# Unhappy number ends in a cycle of repeating numbers which contain 4 +elif result == 4: + print(str(num) + " is not a happy number after apply way 1") + + +# way 2: + +# Another way to do this and code is also less +n = num +setData = set() # set datastructure for checking a number is repeated or not. while 1: - if n==1: - print("{} is a happy number after apply way 2".format(num)) - break - if n in setData: - print("{} is Not a happy number after apply way 2".format(num)) - break - else: - setData.add(n) #adding into set if not inside set - n=int(''.join(str(sum([int(i)**2 for i in str(n)])))) #Pythonic way + if n == 1: + print("{} is a happy number after apply way 2".format(num)) + break + if n in setData: + print("{} is Not a happy number after apply way 2".format(num)) + break + else: + setData.add(n) # adding into set if not inside set + n = int("".join(str(sum([int(i) ** 2 for i in str(n)])))) # Pythonic way diff --git a/how to add three numbers and find type in python.py b/how to add three numbers and find type in python.py index bc8ba8cd6d4..dbe4e228d3e 100644 --- a/how to add three numbers and find type in python.py +++ b/how to add three numbers and find type in python.py @@ -1,8 +1,8 @@ -#python program for adding three no. -x=45 -y=75 -z=25 -t=x+y+z +# python program for adding three no. +x = 45 +y = 75 +z = 25 +t = x + y + z print(t) -#type of output +# type of output print(type(t)) diff --git a/how to display the fibonacci sequence up to n-.py b/how to display the fibonacci sequence up to n-.py index 9f6b1b3d7ce..d6a70a574cd 100644 --- a/how to display the fibonacci sequence up to n-.py +++ b/how to display the fibonacci sequence up to n-.py @@ -8,16 +8,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/image2pdf/image2pdf.py b/image2pdf/image2pdf.py index 2c6d4bda27b..a5aa9a75910 100644 --- a/image2pdf/image2pdf.py +++ b/image2pdf/image2pdf.py @@ -6,13 +6,12 @@ class image2pdf: def __init__(self): self.validFormats = (".jpg", ".jpeg", ".png", ".JPG", ".PNG") self.pictures = [] - - self.directory = "" - self.isMergePDF = True + self.directory = "" + self.isMergePDF = True def getUserDir(self): - """ Allow user to choose image directory """ + """Allow user to choose image directory""" msg = "\n1. Current directory\n2. Custom directory\nEnter a number: " user_option = int(input(msg)) @@ -21,8 +20,10 @@ def getUserDir(self): while user_option <= 0 or user_option >= 3: user_option = int(input(f"\n*Invalid input*\n{msg}")) - self.directory = os.getcwd() if user_option == 1 else input("\nEnter custom directory: ") - + self.directory = ( + os.getcwd() if user_option == 1 else input("\nEnter custom directory: ") + ) + def filter(self, item): return item.endswith(self.validFormats) @@ -35,60 +36,71 @@ def getPictures(self): if not pictures: print(f" [Error] there are no pictures in the directory: {self.directory} ") return False - + print(f"Found picture(s) :") return pictures def selectPictures(self, pictures): - """ Allow user to manually pick each picture or merge all """ + """Allow user to manually pick each picture or merge all""" listedPictures = {} for index, pic in enumerate(pictures): - listedPictures[index+1] = pic + listedPictures[index + 1] = pic print(f"{index+1}: {pic}") - - userInput = input("\n Enter the number(s) - (comma seperated/no spaces) or (A or a) to merge All \nChoice: ").strip().lower() - + + userInput = ( + input( + "\n Enter the number(s) - (comma seperated/no spaces) or (A or a) to merge All \nChoice: " + ) + .strip() + .lower() + ) + if userInput != "a": # Convert user input (number) into corresponding (image title) pictures = ( - listedPictures.get(int(number)) for number in userInput.split(',') + listedPictures.get(int(number)) for number in userInput.split(",") ) self.isMergePDF = False return pictures - def convertPictures(self): """ - Convert pictures according the following: - * If pictures = 0 -> Skip - * If pictures = 1 -> use all - * Else -> allow user to pick pictures + Convert pictures according the following: + * If pictures = 0 -> Skip + * If pictures = 1 -> use all + * Else -> allow user to pick pictures - Then determine to merge all or one pdf + Then determine to merge all or one pdf """ pictures = self.getPictures() totalPictures = len(pictures) if pictures else 0 - + if totalPictures == 0: return - + elif totalPictures >= 2: pictures = self.selectPictures(pictures) - + if self.isMergePDF: - # All pics in one pdf. + # All pics in one pdf. for picture in pictures: - self.pictures.append(Image.open(f"{self.directory}\\{picture}").convert("RGB")) + self.pictures.append( + Image.open(f"{self.directory}\\{picture}").convert("RGB") + ) self.save() else: - # Each pic in seperate pdf. + # Each pic in seperate pdf. for picture in pictures: - self.save(Image.open(f"{self.directory}\\{picture}").convert("RGB"), picture, False) + self.save( + Image.open(f"{self.directory}\\{picture}").convert("RGB"), + picture, + False, + ) # Reset to default value for next run self.isMergePDF = True @@ -102,17 +114,17 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): if isMergeAll: self.pictures[0].save( - f"{self.directory}\\{title}.pdf", - save_all=True, - append_images=self.pictures[1:] + f"{self.directory}\\{title}.pdf", + save_all=True, + append_images=self.pictures[1:], ) - + else: image.save(f"{self.directory}\\{title}.pdf") if __name__ == "__main__": - + # Get user directory only once process = image2pdf() process.getUserDir() @@ -120,7 +132,9 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): # Allow user to rerun any process while True: - user = input("Press (R or r) to Run again\nPress (C or c) to change directory\nPress (Any Key) To Exit\nchoice:").lower() + user = input( + "Press (R or r) to Run again\nPress (C or c) to change directory\nPress (Any Key) To Exit\nchoice:" + ).lower() match user: case "r": process.convertPictures() @@ -129,5 +143,3 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): process.convertPictures() case _: break - - diff --git a/largestno.py b/largestno.py index 0edc35dbe01..53934770163 100644 --- a/largestno.py +++ b/largestno.py @@ -1,7 +1,7 @@ # Python Program to find Largest of two Numbers using if-else statements a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) -if(a >= b): - print(a, "is greater") +if a >= b: + print(a, "is greater") else: - print(b, "is greater") + print(b, "is greater") diff --git a/lcm.py b/lcm.py index c2d5b9731cc..2f0bcf14509 100644 --- a/lcm.py +++ b/lcm.py @@ -1,30 +1,30 @@ def lcm(x, y): """ - Find least common multiple of 2 positive integers. - :param x: int - first integer - :param y: int - second integer - :return: int - least common multiple + Find least common multiple of 2 positive integers. + :param x: int - first integer + :param y: int - second integer + :return: int - least common multiple - >>> lcm(8, 4) - 8 - >>> lcm(5, 3) - 15 - >>> lcm(15, 9) - 45 - >>> lcm(124, 23) - 2852 - >>> lcm(3, 6) - 6 - >>> lcm(13, 34) - 442 - >>> lcm(235, 745) - 35015 - >>> lcm(65, 86) - 5590 - >>> lcm(0, 1) - -1 - >>> lcm(-12, 35) - -1 + >>> lcm(8, 4) + 8 + >>> lcm(5, 3) + 15 + >>> lcm(15, 9) + 45 + >>> lcm(124, 23) + 2852 + >>> lcm(3, 6) + 6 + >>> lcm(13, 34) + 442 + >>> lcm(235, 745) + 35015 + >>> lcm(65, 86) + 5590 + >>> lcm(0, 1) + -1 + >>> lcm(-12, 35) + -1 """ if x <= 0 or y <= 0: return -1 diff --git a/leap year.py b/leap year.py index 1e7739189a4..dbced17c6e2 100644 --- a/leap year.py +++ b/leap year.py @@ -6,12 +6,12 @@ # year = int(input("Enter a year: ")) if (year % 4) == 0: - if (year % 100) == 0: - if (year % 400) == 0: - print("{0} is a leap year".format(year)) - else: - print("{0} is not a leap year".format(year)) - else: - print("{0} is a leap year".format(year)) + if (year % 100) == 0: + if (year % 400) == 0: + print("{0} is a leap year".format(year)) + else: + print("{0} is not a leap year".format(year)) + else: + print("{0} is a leap year".format(year)) else: - print("{0} is not a leap year".format(year)) + print("{0} is not a leap year".format(year)) diff --git a/linear search.py b/linear search.py index 781894f7b47..b1bda494a43 100644 --- a/linear search.py +++ b/linear search.py @@ -1,10 +1,13 @@ -#Author : ShankRoy +# Author : ShankRoy + def linearsearch(arr, x): - for i in range(len(arr)): - if arr[i] == x: - return i - return -1 -arr = ['t','u','t','o','r','i','a','l'] -x = 'a' -print("element found at index "+str(linearsearch(arr,x))) + for i in range(len(arr)): + if arr[i] == x: + return i + return -1 + + +arr = ["t", "u", "t", "o", "r", "i", "a", "l"] +x = "a" +print("element found at index " + str(linearsearch(arr, x))) diff --git a/linear-algebra-python/src/lib.py b/linear-algebra-python/src/lib.py index 9719d915bd2..a58651dbc55 100644 --- a/linear-algebra-python/src/lib.py +++ b/linear-algebra-python/src/lib.py @@ -100,7 +100,7 @@ def eulidLength(self): """ summe = 0 for c in self.__components: - summe += c ** 2 + summe += c**2 return math.sqrt(summe) def __add__(self, other): diff --git a/linear_search.py b/linear_search.py index a4cb39f9cdb..0a005cbcfe2 100644 --- a/linear_search.py +++ b/linear_search.py @@ -8,4 +8,4 @@ print(f"\n{x} found at position {position}") else: print(f"list: {list}") - print(f"{x} is not in list") \ No newline at end of file + print(f"{x} is not in list") diff --git a/local_weighted_learning/local_weighted_learning.py b/local_weighted_learning/local_weighted_learning.py index a3a911c4306..193b82da738 100644 --- a/local_weighted_learning/local_weighted_learning.py +++ b/local_weighted_learning/local_weighted_learning.py @@ -20,7 +20,7 @@ def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) -> # calculating weights for all training examples [x(i)'s] for j in range(m): diff = point - training_data[j] - weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth ** 2)) + weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth**2)) return weights diff --git a/login.py b/login.py index 8095f4f4e54..d4844b261f1 100644 --- a/login.py +++ b/login.py @@ -1,6 +1,7 @@ import os from getpass import getpass + # Devloped By Black_angel # This is Logo Function def logo(): diff --git a/multiplication_table.py b/multiplication_table.py index f659f4289d9..70045ed10e7 100644 --- a/multiplication_table.py +++ b/multiplication_table.py @@ -20,15 +20,15 @@ def table(rows, columns): columns = int(columns) rows = int(rows) - for r in range(1, rows+1): + for r in range(1, rows + 1): c = r - print(r, end='\t') + print(r, end="\t") i = 0 - while columns-1 > i: - print(c+r, end='\t') - c = c+r + while columns - 1 > i: + print(c + r, end="\t") + c = c + r i += 1 - print('\n') + print("\n") table(rows, columns) diff --git a/nDigitNumberCombinations.py b/nDigitNumberCombinations.py index caad36e5e8d..5a17739615d 100644 --- a/nDigitNumberCombinations.py +++ b/nDigitNumberCombinations.py @@ -1,7 +1,7 @@ # ALL the combinations of n digit combo def nDigitCombinations(n): try: - npow = 10 ** n + npow = 10**n numbers = [] for code in range(npow): code = str(code).zfill(n) diff --git a/new_pattern.py b/new_pattern.py index e9ebc1c257c..f23c4a3bfc6 100644 --- a/new_pattern.py +++ b/new_pattern.py @@ -1,25 +1,28 @@ -#pattern -#@@@@@@@@ $ -#@@@@@@@ $$ -#@@@@@@ $$$ -#@@@@@ $$$$ -#@@@@ $$$$$ -#@@@ $$$$$$ -#@@ $$$$$$$ -#@ $$$$$$$$ +# pattern +# @@@@@@@@ $ +# @@@@@@@ $$ +# @@@@@@ $$$ +# @@@@@ $$$$ +# @@@@ $$$$$ +# @@@ $$$$$$ +# @@ $$$$$$$ +# @ $$$$$$$$ + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): t = 1 for i in reversed(range(lines)): - nxt_pattern = "$"*t - pattern = "@"*(i+1) + nxt_pattern = "$" * t + pattern = "@" * (i + 1) final_pattern = pattern + " n " + nxt_pattern print(final_pattern) - t = t +1 + t = t + 1 + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py index 931228df1ec..f6453e063be 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py @@ -28,6 +28,7 @@ def index(request): ### Function to remove item, it receives todo item_id as primary key from url ## + def remove(request, item_id): item = Todo.objects.get(id=item_id) item.delete() diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py index 226e326827f..1c0e6458be6 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py @@ -14,6 +14,7 @@ 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ + from django.contrib import admin from django.urls import path from todo import views diff --git a/num-py.py b/num-py.py index af365bd585d..fb992d8c141 100644 --- a/num-py.py +++ b/num-py.py @@ -1,12 +1,13 @@ import numpy as np + # to check if shape are equal and find there power def get_array(x, y): a = np.shape(x) b = np.shape(y) if a == b: - np_pow_array = x ** y + np_pow_array = x**y print("Array of powers without using np.power: ", np_pow_array) print("Array of powers using np.power: ", np.power(x, y)) diff --git a/number guessing.py b/number guessing.py index 25add25a64d..13ac2cf4198 100644 --- a/number guessing.py +++ b/number guessing.py @@ -1,15 +1,24 @@ import random + attempts_list = [] + + def show_score(): if len(attempts_list) <= 0: print("There is currently no high score, it's yours for the taking!") else: print("The current high score is {} attempts".format(min(attempts_list))) + + def start_game(): random_number = int(random.randint(1, 10)) print("Hello traveler! Welcome to the game of guesses!") player_name = input("What is your name? ") - wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) + wanna_play = input( + "Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format( + player_name + ) + ) # Where the show_score function USED to be attempts = 0 show_score() @@ -41,5 +50,7 @@ def start_game(): print("({})".format(err)) else: print("That's cool, have a good one!") -if __name__ == '__main__': + + +if __name__ == "__main__": start_game() diff --git a/numberguessinggame/index.py b/numberguessinggame/index.py index 3116af47dce..ac8648e71e7 100644 --- a/numberguessinggame/index.py +++ b/numberguessinggame/index.py @@ -1,7 +1,8 @@ import random + def number_guessing_game(): - + secret_number = random.randint(1, 100) attempts = 0 @@ -18,11 +19,14 @@ def number_guessing_game(): elif guess > secret_number: print("Too high! Try again.") else: - print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!") + print( + f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!" + ) break except ValueError: print("Please enter a valid number.") + if __name__ == "__main__": number_guessing_game() diff --git a/numeric_password_cracker.py b/numeric_password_cracker.py index aaf48ac144d..2a6215c9a64 100644 --- a/numeric_password_cracker.py +++ b/numeric_password_cracker.py @@ -1,5 +1,6 @@ import itertools + def generate_password_permutations(length): # Generate numeric password permutations of the given length digits = "0123456789" @@ -7,6 +8,7 @@ def generate_password_permutations(length): password = "".join(combination) yield password + def password_cracker(target_password, max_length=8): # Try different password lengths and generate permutations for length in range(1, max_length + 1): @@ -16,6 +18,7 @@ def password_cracker(target_password, max_length=8): return password return None + if __name__ == "__main__": # Target numeric password (change this to the password you want to crack) target_password = "9133278" @@ -26,5 +29,6 @@ def password_cracker(target_password, max_length=8): if cracked_password: print(f"Password successfully cracked! The password is: {cracked_password}") else: - print("Password not found. Try increasing the max_length or target a different password.") - + print( + "Password not found. Try increasing the max_length or target a different password." + ) diff --git a/password_checker.py b/password_checker.py index afc5f7203ba..4fb610d90a8 100644 --- a/password_checker.py +++ b/password_checker.py @@ -1,24 +1,27 @@ import time -pwd="AKS2608" #any password u want to set + +pwd = "AKS2608" # any password u want to set + def IInd_func(): - count1=0 - for j in range(5): - a=0 - count=0 - user_pwd = input("") #password you remember - for i in range(len(pwd)): - if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd - a +=1 - count+=1 - if count==len(pwd): - print("correct pwd") - break - else: - count1 += 1 - print("not correct") - if count1==5: - time.sleep(30) - IInd_func() + count1 = 0 + for j in range(5): + a = 0 + count = 0 + user_pwd = input("") # password you remember + for i in range(len(pwd)): + if user_pwd[i] == pwd[a]: # comparing remembered pwd with fixed pwd + a += 1 + count += 1 + if count == len(pwd): + print("correct pwd") + break + else: + count1 += 1 + print("not correct") + if count1 == 5: + time.sleep(30) + IInd_func() + IInd_func() diff --git a/password_programs_multiple/animal_name_scraiper.py b/password_programs_multiple/animal_name_scraiper.py index 8204e90d794..55198281e4e 100644 --- a/password_programs_multiple/animal_name_scraiper.py +++ b/password_programs_multiple/animal_name_scraiper.py @@ -51,7 +51,6 @@ while next_sibling and next_sibling.name == "br": next_sibling = next_sibling.next_sibling - # Print the text content of the next sibling element if next_sibling: print(next_sibling.text.strip()) diff --git a/personal_translator.py b/personal_translator.py index 6a704d572c2..146d62e7346 100644 --- a/personal_translator.py +++ b/personal_translator.py @@ -12,6 +12,7 @@ from googletrans import Translator + # make a simple function that will translate any language to english def text_translator(Text): translator = Translator() diff --git a/power_of_n.py b/power_of_n.py index 69b8994be94..f0800006682 100644 --- a/power_of_n.py +++ b/power_of_n.py @@ -3,6 +3,7 @@ __version__ = "1.0.0" __date__ = "2023-09-03" + def binaryExponentiation(x: float, n: int) -> float: """ Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value @@ -49,10 +50,9 @@ def binaryExponentiation(x: float, n: int) -> float: print(f"Version: {__version__}") print(f"Function Documentation: {binaryExponentiation.__doc__}") print(f"Date: {__date__}") - - print() # Blank Line + + print() # Blank Line print(binaryExponentiation(2.00000, 10)) print(binaryExponentiation(2.10000, 3)) print(binaryExponentiation(2.00000, -2)) - \ No newline at end of file diff --git a/powers of 2.py b/powers of 2.py index 5ac0e09fc36..919f1e1528f 100644 --- a/powers of 2.py +++ b/powers of 2.py @@ -6,8 +6,8 @@ # terms = int(input("How many terms? ")) # use anonymous function -result = list(map(lambda x: 2 ** x, range(terms))) +result = list(map(lambda x: 2**x, range(terms))) -print("The total terms are:",terms) +print("The total terms are:", terms) for i in range(terms): - print("2 raised to power",i,"is",result[i]) + print("2 raised to power", i, "is", result[i]) diff --git a/primelib/primelib.py b/primelib/primelib.py index 65856679561..97b7938eaee 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -51,7 +51,7 @@ def pi(maxK=70, prec=1008, disp=1007): gc().prec = prec K, M, L, X, S = 6, 1, 13591409, 1, 13591409 for k in range(1, maxK + 1): - M = Dec((K ** 3 - (K << 4)) * M / k ** 3) + M = Dec((K**3 - (K << 4)) * M / k**3) L += 545140134 X *= -262537412640768000 S += Dec(M * L) / X diff --git a/print hello world.py b/print hello world.py index 0e3295e312d..1d6d4214987 100644 --- a/print hello world.py +++ b/print hello world.py @@ -1,3 +1,3 @@ # This program prints Hello, world! -print('Hello, world!') +print("Hello, world!") diff --git a/prison_break_scrapper.py b/prison_break_scrapper.py index ad50636cd6a..5aaf5ca5601 100644 --- a/prison_break_scrapper.py +++ b/prison_break_scrapper.py @@ -2,6 +2,7 @@ Scrapper for downloading prison break series from an open server and putting them in a designated folder. """ + import os import subprocess diff --git a/python Space Invader game.py b/python Space Invader game.py index 2d07677f67e..baebb348808 100644 --- a/python Space Invader game.py +++ b/python Space Invader game.py @@ -12,19 +12,19 @@ # background -background = pygame.image.load('background.png') +background = pygame.image.load("background.png") -#bg sound -mixer.music.load('background.wav') +# bg sound +mixer.music.load("background.wav") mixer.music.play(-1) # title and icon pygame.display.set_caption("Space Invendera") -icon = pygame.image.load('battleship.png') +icon = pygame.image.load("battleship.png") pygame.display.set_icon(icon) # player -playerimg = pygame.image.load('transport.png') +playerimg = pygame.image.load("transport.png") playerx = 370 playery = 480 playerx_change = 0 @@ -38,37 +38,40 @@ number_of_enemies = 6 for i in range(number_of_enemies): - enemyimg.append(pygame.image.load('enemy.png')) + enemyimg.append(pygame.image.load("enemy.png")) enemyx.append(random.randint(0, 800)) enemyy.append(random.randint(50, 150)) enemyx_change.append(2.5) enemyy_change.append(40) # bullet -bulletimg = pygame.image.load('bullet.png') +bulletimg = pygame.image.load("bullet.png") bulletx = 0 bullety = 480 bulletx_change = 0 bullety_change = 10 bullet_state = "ready" -#score +# score score_value = 0 -font = pygame.font.Font('freesansbold.ttf',32) +font = pygame.font.Font("freesansbold.ttf", 32) textx = 10 texty = 10 -#game over txt -over_font = pygame.font.Font('freesansbold.ttf',64) +# game over txt +over_font = pygame.font.Font("freesansbold.ttf", 64) -def show_score(x ,y): - score = font.render("score :"+ str(score_value),True, (255, 255, 255)) + +def show_score(x, y): + score = font.render("score :" + str(score_value), True, (255, 255, 255)) screen.blit(score, (x, y)) + def game_over_text(): over_txt = over_font.render("GAME OVER", True, (255, 255, 255)) screen.blit(over_txt, (200, 250)) + # for display player img def player(x, y): screen.blit(playerimg, (x, y)) @@ -76,7 +79,8 @@ def player(x, y): # foe desplaing enemy img -def enemy(x, y ,i): + +def enemy(x, y, i): screen.blit(enemyimg[i], (x, y)) @@ -87,7 +91,9 @@ def fire_bullet(x, y): def iscollision(enemyx, enemyy, bulletx, bullety): - distance = math.sqrt((math.pow(enemyx - bulletx, 2)) + (math.pow(enemyy - bullety, 2))) + distance = math.sqrt( + (math.pow(enemyx - bulletx, 2)) + (math.pow(enemyy - bullety, 2)) + ) if distance < 27: return True else: @@ -107,20 +113,20 @@ def iscollision(enemyx, enemyy, bulletx, bullety): running = False # if keystroke in pressed whether it is right of left - if (event.type == pygame.KEYDOWN): - if (event.key == pygame.K_LEFT): + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_LEFT: playerx_change = -5 - if (event.key == pygame.K_RIGHT): + if event.key == pygame.K_RIGHT: playerx_change = 5 - if (event.key == pygame.K_SPACE): + if event.key == pygame.K_SPACE: if bullet_state == "ready": - bullet_sound = mixer.Sound('laser.wav') + bullet_sound = mixer.Sound("laser.wav") bullet_sound.play() bulletx = playerx fire_bullet(bulletx, bullety) - if (event.type == pygame.KEYUP): + if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerx_change = 0 @@ -133,7 +139,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety): for i in range(number_of_enemies): - #game over + # game over if enemyy[i] > 440: for j in range(number_of_enemies): enemyy[j] = 2000 @@ -152,7 +158,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety): # collision collision = iscollision(enemyx[i], enemyy[i], bulletx, bullety) if collision: - explossion_sound = mixer.Sound('explosion.wav') + explossion_sound = mixer.Sound("explosion.wav") explossion_sound.play() bullety = 480 bullet_state = "ready" @@ -172,5 +178,5 @@ def iscollision(enemyx, enemyy, bulletx, bullety): bullety -= bullety_change player(playerx, playery) - show_score(textx,texty) + show_score(textx, texty) pygame.display.update() diff --git a/python program for finding square root for positive number.py b/python program for finding square root for positive number.py index dcb8251f839..2a2a2dc79b9 100644 --- a/python program for finding square root for positive number.py +++ b/python program for finding square root for positive number.py @@ -1,10 +1,10 @@ # Python Program to calculate the square root # Note: change this value for a different result -num = 8 +num = 8 # To take the input from the user -#num = float(input('Enter a number: ')) +# num = float(input('Enter a number: ')) -num_sqrt = num ** 0.5 -print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) +num_sqrt = num**0.5 +print("The square root of %0.3f is %0.3f" % (num, num_sqrt)) diff --git a/python_sms.py b/python_sms.py index b5e578b3b86..99cf8f943dc 100644 --- a/python_sms.py +++ b/python_sms.py @@ -35,9 +35,7 @@ sname = row[0] snumber = row[1] - message = ( - f"{sname} There will be NO training tonight on the {tdate}. Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated" - ) + message = f"{sname} There will be NO training tonight on the {tdate}. Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated" username = "YOUR_USERNAME" sender = "WHO_IS_SENDING_THE_MAIL" @@ -67,10 +65,8 @@ postdata = urllib.urlencode(values) req = urllib2.Request(url, postdata) - print( f"Attempting to send SMS to {sname} at {snumber} on {tdate}") - f.write( - f"Attempting to send SMS to {sname} at {snumber} on {tdate}" - ) + print(f"Attempting to send SMS to {sname} at {snumber} on {tdate}") + f.write(f"Attempting to send SMS to {sname} at {snumber} on {tdate}") try: response = urllib2.urlopen(req) diff --git a/python_webscraper.py b/python_webscraper.py index a9322761a1c..fab418247d5 100644 --- a/python_webscraper.py +++ b/python_webscraper.py @@ -1,19 +1,20 @@ import requests from bs4 import BeautifulSoup + # Make a request on to your website page = requests.get("Paste your Website Domain here") -soup = BeautifulSoup(page.content, 'html.parser') +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'): +for element in soup.select("h1"): all_h1_tags.append(element.text) # Create seventh_p_text and set it to 7th p element text of the page -seventh_p_text = soup.select('p')[6].text +seventh_p_text = soup.select("p")[6].text print(all_h1_tags, seventh_p_text) -# print all h1 elements and the text of the website on your console +# print all h1 elements and the text of the website on your console diff --git a/quiz_game.py b/quiz_game.py index c1ffd6696b0..cd2a8aff48c 100644 --- a/quiz_game.py +++ b/quiz_game.py @@ -1,32 +1,37 @@ -print('Welcome to AskPython Quiz') -answer=input('Are you ready to play the Quiz ? (yes/no) :') -score=0 -total_questions=3 - -if answer.lower()=='yes': - answer=input('Question 1: What is your Favourite programming language?') - if answer.lower()=='python': +print("Welcome to AskPython Quiz") +answer = input("Are you ready to play the Quiz ? (yes/no) :") +score = 0 +total_questions = 3 + +if answer.lower() == "yes": + answer = input("Question 1: What is your Favourite programming language?") + if answer.lower() == "python": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - - - answer=input('Question 2: Do you follow any author on AskPython? ') - if answer.lower()=='yes': + print("Wrong Answer :(") + + answer = input("Question 2: Do you follow any author on AskPython? ") + if answer.lower() == "yes": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - - answer=input('Question 3: What is the name of your favourite website for learning Python?') - if answer.lower()=='askpython': + print("Wrong Answer :(") + + answer = input( + "Question 3: What is the name of your favourite website for learning Python?" + ) + if answer.lower() == "askpython": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - -print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!") -mark=(score/total_questions)*100 -print('Marks obtained:',mark) -print('BYE!') \ No newline at end of file + print("Wrong Answer :(") + +print( + "Thankyou for Playing this small quiz game, you attempted", + score, + "questions correctly!", +) +mark = (score / total_questions) * 100 +print("Marks obtained:", mark) +print("BYE!") diff --git a/rangoli.py b/rangoli.py index 75191e08546..0fc7ccccc10 100644 --- a/rangoli.py +++ b/rangoli.py @@ -3,7 +3,7 @@ # Prints a rangoli of size n def print_rangoli(n): - """Prints a rangoli of size n""" + """Prints a rangoli of size n""" # Width of the rangoli width = 4 * n - 3 @@ -40,6 +40,6 @@ def print_rangoli(n): string = "" -if __name__ == '__main__': +if __name__ == "__main__": n = int(input()) print_rangoli(n) diff --git a/recursiveStrings.py b/recursiveStrings.py index 874a1b0a104..d0385baf6b0 100644 --- a/recursiveStrings.py +++ b/recursiveStrings.py @@ -9,19 +9,25 @@ def CheckTwoStrings(str1, str2): # function takes two strings and check if they are similar # returns True if they are identical and False if they are different - if(len(str1) != len(str2)): + if len(str1) != len(str2): return False - if(len(str1) == 1 and len(str2) == 1): + if len(str1) == 1 and len(str2) == 1: return str1[0] == str2[0] return (str1[0] == str2[0]) and CheckTwoStrings(str1[1:], str2[1:]) def main(): - matrix = [["hello", "wow"], ["ABSD", "ABCD"], - ["List", "List"], ["abcspq", "zbcspq"], - ["1263", "1236"], ["lamar", "lamars"], - ["amczs", "amczs"], ["yeet", "sheesh"], ] + matrix = [ + ["hello", "wow"], + ["ABSD", "ABCD"], + ["List", "List"], + ["abcspq", "zbcspq"], + ["1263", "1236"], + ["lamar", "lamars"], + ["amczs", "amczs"], + ["yeet", "sheesh"], + ] for i in matrix: if CheckTwoStrings(i[0], i[1]): diff --git a/remove a character from a file and rewrite.py b/remove a character from a file and rewrite.py index 18029c53db2..d74fcf764e3 100644 --- a/remove a character from a file and rewrite.py +++ b/remove a character from a file and rewrite.py @@ -1,28 +1,28 @@ -#Remove all the lines that contain the character `a' in a file and write it to another file. -f=open("test1.txt","r") #opening file test1.txt -lines = f.readlines() #saved lines +# Remove all the lines that contain the character `a' in a file and write it to another file. +f = open("test1.txt", "r") # opening file test1.txt +lines = f.readlines() # saved lines print("Original file is :") print(lines) f.close() - -# Rewriting lines -e=open("test3.txt","w") # file containing lines with 'a' -f=open("test1.txt","w") # file containing lines without 'a' +# Rewriting lines + +e = open("test3.txt", "w") # file containing lines with 'a' +f = open("test1.txt", "w") # file containing lines without 'a' for line in lines: - if 'a' in line or 'A' in line: - e.write(line) - else: - f.write(line) - + if "a" in line or "A" in line: + e.write(line) + else: + f.write(line) + e.close() -f.close() +f.close() -f=open("test1.txt","r") -lines=f.readlines() +f = open("test1.txt", "r") +lines = f.readlines() -e=open("test3.txt","r") -lines1=e.readlines() +e = open("test3.txt", "r") +lines1 = e.readlines() print("\n") diff --git a/reversed_pattern3.py b/reversed_pattern3.py index f19ef159691..4ee6131ee41 100644 --- a/reversed_pattern3.py +++ b/reversed_pattern3.py @@ -1,20 +1,23 @@ -#Simple inverted number triangle piramid -#11111 -#2222 -#333 -#44 -#5 +# Simple inverted number triangle piramid +# 11111 +# 2222 +# 333 +# 44 +# 5 + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): t = 1 - for i in reversed(range(1, (lines +1))): - format = str(t)*i + for i in reversed(range(1, (lines + 1))): + format = str(t) * i print(format) t = t + 1 + if __name__ == "__main__": main() diff --git a/russian_roulette.py b/russian_roulette.py index 337f8be8a86..ebf82693225 100644 --- a/russian_roulette.py +++ b/russian_roulette.py @@ -2,6 +2,7 @@ the code is just a russian roulette game against the computer """ + from random import randrange import time @@ -38,7 +39,7 @@ def main(): answer = input("please enter again ('m' or 'p'): ") # set turn - if answer == 'm': + if answer == "m": turn = "player" else: turn = "pc" @@ -49,8 +50,10 @@ def main(): time.sleep(1) print("the gun is being loaded") time.sleep(3) - print("the gun is placed on " + ("your head" if turn == - "player" else "the cpu of the pc")) + print( + "the gun is placed on " + + ("your head" if turn == "player" else "the cpu of the pc") + ) time.sleep(3) print("and...") time.sleep(1) diff --git a/sensors_information.py b/sensors_information.py index 694dc302904..0a233f26ab4 100644 --- a/sensors_information.py +++ b/sensors_information.py @@ -35,7 +35,7 @@ def show_sensors(): for address in ip_addresses(): print("IP Addresses: {0[1]} ({0[0]})".format(address)) print("CPU Load: {:.1f}".format(cpu_load())) - print("RAM Available: {} MiB".format(ram_available() / 1024 ** 2)) + print("RAM Available: {} MiB".format(ram_available() / 1024**2)) print("AC Connected: {}".format(ac_connected())) diff --git a/sierpinski_triangle.py b/sierpinski_triangle.py index 966b5648af3..ebb8f02791c 100644 --- a/sierpinski_triangle.py +++ b/sierpinski_triangle.py @@ -21,6 +21,7 @@ Credits: This code was written by editing the code from http://www.lpb-riannetrujillo.com/blog/python-fractal/ """ + import sys import turtle diff --git a/simulate_memory_cpu.py b/simulate_memory_cpu.py index 9a108fb89cc..d7a29b4373a 100644 --- a/simulate_memory_cpu.py +++ b/simulate_memory_cpu.py @@ -11,30 +11,32 @@ def print_help(): - print('Usage: ') - print(' python cpu_memory_simulator.py m 1GB') - print(' python cpu_memory_simulator.py c 1') - print(' python cpu_memory_simulator.py mc 1GB 2') + print("Usage: ") + print(" python cpu_memory_simulator.py m 1GB") + print(" python cpu_memory_simulator.py c 1") + print(" python cpu_memory_simulator.py mc 1GB 2") + # memory usage def mem(): - pattern = re.compile('^(\d*)([M|G]B)$') + pattern = re.compile("^(\d*)([M|G]B)$") size = sys.argv[2].upper() match = pattern.match(size) if match: num = int(match.group(1)) unit = match.group(2) - if unit == 'MB': - s = ' ' * (num * 1024 * 1024) + if unit == "MB": + s = " " * (num * 1024 * 1024) else: - s = ' ' * (num * 1024 * 1024 * 1024) + s = " " * (num * 1024 * 1024 * 1024) time.sleep(24 * 3600) else: print("bad args.....") print_help() + # cpu usage @@ -42,6 +44,7 @@ def deadloop(): while True: pass + # Specify how many cores to occupy according to the parameters @@ -54,7 +57,7 @@ def cpu(): return if cores > cpu_num: - print("Invalid CPU Num(cpu_count="+str(cpu_num)+")") + print("Invalid CPU Num(cpu_count=" + str(cpu_num) + ")") return if cores is None or cores < 1: @@ -71,11 +74,7 @@ def mem_cpu(): if __name__ == "__main__": if len(sys.argv) >= 3: - switcher = { - 'm': mem, - 'c': cpu, - 'mc': mem_cpu - } + switcher = {"m": mem, "c": cpu, "mc": mem_cpu} switcher.get(sys.argv[1], mem)() else: print_help() diff --git a/singly_linked_list.py b/singly_linked_list.py index bd66b5f5d8b..8eca38598fe 100644 --- a/singly_linked_list.py +++ b/singly_linked_list.py @@ -3,7 +3,8 @@ def __init__(self, data): self.data = data self.next = None -class LinkedList(): + +class LinkedList: def __init__(self): self.head = None @@ -38,7 +39,7 @@ def insert(self, pos, data): elif pos == 0: self.insert_at_head(data) return - elif pos == self.length()-1: + elif pos == self.length() - 1: self.add_node(data) return new_node = Node(data) @@ -53,12 +54,12 @@ def insert(self, pos, data): prev = curr curr = curr.next curr_pos += 1 - + def delete_head(self): temp = self.head self.head = temp.next del temp - + def delete_end(self): curr = self.head prev = None @@ -77,7 +78,7 @@ def delete(self, pos): elif pos == 0: self.delete_head() return - elif pos == self.length()-1: + elif pos == self.length() - 1: self.delete_end() return curr = self.head @@ -98,7 +99,7 @@ def display(self): rev = [] curr = self.head while curr != None: - print(f"{curr.data} --> ", end='') + print(f"{curr.data} --> ", end="") rev.append(curr.data) curr = curr.next print() diff --git a/snake_case_renamer_depth_one.py b/snake_case_renamer_depth_one.py index fdedcb54a7f..b00dc40d41a 100644 --- a/snake_case_renamer_depth_one.py +++ b/snake_case_renamer_depth_one.py @@ -2,6 +2,7 @@ import argparse from typing import Union + def generate_unique_name(directory: str, name: str) -> str: """ Generate a unique name for a file or folder in the specified directory. @@ -24,6 +25,7 @@ def generate_unique_name(directory: str, name: str) -> str: index += 1 return f"{base_name}_{index}{extension}" + def rename_files_and_folders(directory: str) -> None: """ Rename files and folders in the specified directory to lowercase with underscores. @@ -54,6 +56,7 @@ def rename_files_and_folders(directory: str) -> None: os.rename(old_path, new_path) + def main() -> None: """ Main function to handle command-line arguments and call the renaming function. @@ -68,12 +71,19 @@ def main() -> None: """ # Create a parser for command-line arguments - parser = argparse.ArgumentParser(description="Rename files and folders to lowercase with underscores.") - parser.add_argument("directory", type=str, help="Path to the directory containing the files and folders to be renamed.") + parser = argparse.ArgumentParser( + description="Rename files and folders to lowercase with underscores." + ) + parser.add_argument( + "directory", + type=str, + help="Path to the directory containing the files and folders to be renamed.", + ) args = parser.parse_args() # Call the rename_files_and_folders function with the provided directory path rename_files_and_folders(args.directory) + if __name__ == "__main__": main() diff --git a/stack.py b/stack.py index d90048ccf62..c6f4ef523d6 100644 --- a/stack.py +++ b/stack.py @@ -1,5 +1,6 @@ # Python program to reverse a string using stack + # Function to create an empty stack. # It initializes size of stack as 0 def createStack(): diff --git a/stackF_Harsh2255.py b/stackF_Harsh2255.py index b28bf9de77a..6c318694e6b 100644 --- a/stackF_Harsh2255.py +++ b/stackF_Harsh2255.py @@ -4,6 +4,7 @@ # Used to return -infinite when stack is empty from sys import maxsize + # Function to create a stack. It initializes size of stack as 0 def createStack(): stack = [] diff --git a/sum_of_digits_of_a_number.py b/sum_of_digits_of_a_number.py index 06bb321441f..b358189d14e 100644 --- a/sum_of_digits_of_a_number.py +++ b/sum_of_digits_of_a_number.py @@ -1,5 +1,6 @@ import sys + def get_integer_input(prompt, attempts): for i in range(attempts, 0, -1): try: @@ -10,6 +11,7 @@ def get_integer_input(prompt, attempts): print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left") return None + def sum_of_digits(n): total = 0 while n > 0: @@ -17,6 +19,7 @@ def sum_of_digits(n): n //= 10 return total + chances = 3 number = get_integer_input("Enter a number: ", chances) diff --git a/swap.py b/swap.py index 00971b94165..47ec594d5bf 100644 --- a/swap.py +++ b/swap.py @@ -6,10 +6,10 @@ class Swapper: ------- swap_tuple_unpacking(self): Swaps the values of x and y using a tuple unpacking method. - + swap_temp_variable(self): Swaps the values of x and y using a temporary variable. - + swap_arithmetic_operations(self): Swaps the values of x and y using arithmetic operations. @@ -29,7 +29,7 @@ def __init__(self, x, y): """ if not isinstance(x, (int, float)) or not isinstance(y, (float, int)): raise ValueError("Both x and y should be integers.") - + self.x = x self.y = y diff --git a/text-to-audio/text-file-to-audio.py b/text-to-audio/text-file-to-audio.py index aa5ce407d6b..5dd9bdd74fd 100644 --- a/text-to-audio/text-file-to-audio.py +++ b/text-to-audio/text-file-to-audio.py @@ -8,7 +8,7 @@ language = "en" # Get the contents of your file -with open(mytextfile, 'r') as f: +with open(mytextfile, "r") as f: mytext = f.read() f.close() diff --git a/text_to_pig_latin.py b/text_to_pig_latin.py index 850b13913e8..b662b08a5f1 100644 --- a/text_to_pig_latin.py +++ b/text_to_pig_latin.py @@ -18,6 +18,7 @@ def pig_latin_word(word): else: return word[1:] + word[0] + "ay" + def pig_latin_sentence(text): words = text.split() pig_latin_words = [] @@ -31,7 +32,8 @@ def pig_latin_sentence(text): else: pig_latin_words.append(pig_latin_word(word)) - return ' '.join(pig_latin_words) + return " ".join(pig_latin_words) + user_input = input("Enter some English text: ") pig_latin_text = pig_latin_sentence(user_input) diff --git a/tf_idf_generator.py b/tf_idf_generator.py index 4e99e96ce64..b5443278f36 100644 --- a/tf_idf_generator.py +++ b/tf_idf_generator.py @@ -31,6 +31,7 @@ have fun, cheers. """ + import math import pickle @@ -135,17 +136,21 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): TAG, "Total number of unique words in corpus", len(idf), - "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" - if prev_file_path - else "", + ( + "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" + if prev_file_path + else "" + ), ) print( TAG, "Total number of docs in corpus:", len(tf_idf), - "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" - if prev_file_path - else "", + ( + "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" + if prev_file_path + else "" + ), ) # dump if a dir-path is given diff --git a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py index 0e30d89d195..9e421583954 100644 --- a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py +++ b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py @@ -18,12 +18,12 @@ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) - for (x, y, w, h) in faces: + for x, y, w, h in faces: roi_gray = gray[y : y + h, x : x + h] # rec roi_color = frame[y : y + h, x : x + h] nose = nose_cascade.detectMultiScale(roi_gray, scaleFactor=1.5, minNeighbors=5) - for (nx, ny, nw, nh) in nose: + for nx, ny, nw, nh in nose: roi_nose = roi_gray[ny : ny + nh, nx : nx + nw] mustache2 = image_resize(mustache.copy(), width=nw) diff --git a/tic-tac-toe.py b/tic-tac-toe.py index 8956be21237..6210ebd9b9a 100644 --- a/tic-tac-toe.py +++ b/tic-tac-toe.py @@ -13,6 +13,7 @@ Game = Running Mark = "X" + # This Function Draws Game Board def DrawBoard(): print(" %c | %c | %c " % (board[1], board[2], board[3])) diff --git a/tic_tak_toe.py b/tic_tak_toe.py index 3138057fea0..cee42b4be3e 100644 --- a/tic_tak_toe.py +++ b/tic_tak_toe.py @@ -6,6 +6,7 @@ import random from time import sleep + # Creates an empty board def create_board(): return np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) diff --git a/time_delta.py b/time_delta.py index 9b153fd9707..6007cd9b925 100644 --- a/time_delta.py +++ b/time_delta.py @@ -1,6 +1,5 @@ """Time Delta Solution """ - # ----------------------------------------------------------------------------- # You are givent two timestams in the format: Day dd Mon yyyy hh:mm:ss +xxxx # where +xxxx represents the timezone. @@ -26,30 +25,30 @@ # Sample Output: # 25200 # 88200 -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ # Imports import math -import os +import os import random import re import sys import datetime + # Complete the time_delta function below. def time_delta(t1, t2): """ Calculate the time delta between two timestamps in seconds. """ # Convert the timestamps to datetime objects - t1 = datetime.datetime.strptime(t1, '%a %d %b %Y %H:%M:%S %z') - t2 = datetime.datetime.strptime(t2, '%a %d %b %Y %H:%M:%S %z') + t1 = datetime.datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z") + t2 = datetime.datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z") - return (t1 - t2) + return t1 - t2 - -if __name__ == '__main__': +if __name__ == "__main__": t = int(input()) @@ -61,7 +60,3 @@ def time_delta(t1, t2): delta = time_delta(t1, t2) # print Delta with 1 Decimal Place print(round(delta.total_seconds(), 1)) - - - - diff --git a/tuple.py b/tuple.py index 69ee3950b9f..3f32d1df9f2 100644 --- a/tuple.py +++ b/tuple.py @@ -1,11 +1,11 @@ -a=(1,2,3,4,5) -print('Individual elements of Tuple are') +a = (1, 2, 3, 4, 5) +print("Individual elements of Tuple are") for i in a: - print(i,end=' ') + print(i, end=" ") print() -print('Value at index number 3 is:',a[3]) -print('Values from index no 2 are',a[2:]) -print('Length of tuple is',len(a)) -print('Maximum value from tuple is ',max(a)) -print('Minimum value from tuple is ',min(a)) -del a #delete the whole tuple +print("Value at index number 3 is:", a[3]) +print("Values from index no 2 are", a[2:]) +print("Length of tuple is", len(a)) +print("Maximum value from tuple is ", max(a)) +print("Minimum value from tuple is ", min(a)) +del a # delete the whole tuple diff --git a/turtle_shapes_made.py b/turtle_shapes_made.py index e82ece728f4..60017048ffc 100644 --- a/turtle_shapes_made.py +++ b/turtle_shapes_made.py @@ -1,5 +1,6 @@ import turtle + class ShapeDrawer: def __init__(self, color, pensize): self.turtle = turtle.Turtle() @@ -18,6 +19,7 @@ def draw_triangle(self, length): self.turtle.forward(length) self.turtle.left(120) + def main(): scrn = turtle.Screen() scrn.bgcolor("lavender") @@ -45,5 +47,6 @@ def main(): scrn.exitonclick() + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/twitter_post_scraper.py b/twitter_post_scraper.py index 06be7896e8a..5e80e0f2fa3 100644 --- a/twitter_post_scraper.py +++ b/twitter_post_scraper.py @@ -28,9 +28,9 @@ def tweeter_scrapper(): for dirty_tweet in list_of_dirty_tweets: dirty_tweet = re.sub(re_text, "", dirty_tweet, flags=re.MULTILINE) dirty_tweet = re.sub(re_text_1, "", dirty_tweet, flags=re.MULTILINE) - dirty_tweet = dirty_tweet.replace(u"\xa0…", u"") - dirty_tweet = dirty_tweet.replace(u"\xa0", u"") - dirty_tweet = dirty_tweet.replace(u"\u200c", u"") + dirty_tweet = dirty_tweet.replace("\xa0…", "") + dirty_tweet = dirty_tweet.replace("\xa0", "") + dirty_tweet = dirty_tweet.replace("\u200c", "") clear_list_of_tweets.append(dirty_tweet) print(clear_list_of_tweets) diff --git a/ultimate-phone-book/contacts.py b/ultimate-phone-book/contacts.py index 7c53bacb28e..c1d70e9bcac 100644 --- a/ultimate-phone-book/contacts.py +++ b/ultimate-phone-book/contacts.py @@ -12,29 +12,33 @@ import os # get array from pickle data -infile = open('data/pickle-main', 'rb') +infile = open("data/pickle-main", "rb") # defining array array = pickle.load(infile) infile.close() # get key if path exists keyacess = False -path = 'data/pickle-key' -if os.path.isfile('data/pickle-key'): - pklekey = open('data/pickle-key', 'rb') +path = "data/pickle-key" +if os.path.isfile("data/pickle-key"): + pklekey = open("data/pickle-key", "rb") key = pickle.load(pklekey) pklekey.close() - if key == 'SKD0DW99SAMXI19#DJI9': + if key == "SKD0DW99SAMXI19#DJI9": keyacess = True print("key found & is correct") print("ALL FEATURES ENABLED") else: print("key is WRONG\nSOME FEATURES ARE DISABLED") - print("check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free") + print( + "check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free" + ) print("key isn't added to this repo check above repo") else: print("key not found\nSOME FEATURES ARE DISABLED") - print("check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free") + print( + "check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free" + ) print("") print("update-22.02 ADDS SAVING YOUR DATA WHEN CLOSED BY SAVING USING OPTION 0\n##") @@ -45,8 +49,8 @@ number = 2 email = 3 # getting some variables -promptvar = 0 # variable for prompt -loopvar = 0 # variable for main loop +promptvar = 0 # variable for prompt +loopvar = 0 # variable for main loop # making loop to run while loopvar < 1: # ask user what to do @@ -77,7 +81,9 @@ i1 = 0 # print all names while i1 < arraylen: - print(f"{array[fname][i1]} {array[lname][i1]}, {array[number][i1]} {array[email][i1]}") + print( + f"{array[fname][i1]} {array[lname][i1]}, {array[number][i1]} {array[email][i1]}" + ) i1 += 1 print("=======================") @@ -95,7 +101,7 @@ print("which contact would you like to delete? (enter first name)") print("enter '\nSTOP' to STOP deleting contact") rmcontact = input("INPUT: ") - if rmcontact != '\nSTOP': + if rmcontact != "\nSTOP": tempvar = 0 rmvar = 0 for i in range(arraylen): @@ -111,7 +117,7 @@ for i in range(4): print(array[i][rmvar]) tempinp = input("y/n? ") - if tempinp == 'y' or tempinp == 'Y': + if tempinp == "y" or tempinp == "Y": for i in range(4): del array[i][rmvar] print("contact REMOVED.") @@ -122,8 +128,6 @@ print("there are more than one contact with same name") # TODO - - # if option 4 is selected elif a == 4: if keyacess == True: @@ -158,7 +162,7 @@ elif a == 9: if keyacess: # change prompt settings - if promptvar == 0: + if promptvar == 0: promptvar += 1 print("you won't get prompt now!") print("ENTER 9 AGAIN TO START GETTING PROMPT AGAIN!!") @@ -167,11 +171,10 @@ else: print("NEED CORRECT KEY TO ENABLE THIS FEATURE") - # if option 0 is selected elif a == 0: print("Saving your Data ...") - outfile = open('data/pickle-main', 'wb') + outfile = open("data/pickle-main", "wb") pickle.dump(array, outfile) outfile.close() print("YOUR DATA HAS BEEN SAVED SUCESSFULLY!") diff --git a/videodownloder.py b/videodownloder.py index 6b91829e293..1db13a66c00 100644 --- a/videodownloder.py +++ b/videodownloder.py @@ -1,24 +1,25 @@ -from pytube import YouTube +from pytube import YouTube -#location where you save. -PATH = "E:/" #to_do +# location where you save. +PATH = "E:/" # to_do -#link of video. -link=["https://www.youtube.com/watch?v=p8FuTenSWPI", - "https://www.youtube.com/watch?v=JWbnEt3xuos" - ]#list of video links. -for i in link: - try: - yt = YouTube(i) - except: - print("Connection Error") #to handle exception - - #check files with "mp4" extension - mp4files = yt.filter('mp4') +# link of video. +link = [ + "https://www.youtube.com/watch?v=p8FuTenSWPI", + "https://www.youtube.com/watch?v=JWbnEt3xuos", +] # list of video links. +for i in link: + try: + yt = YouTube(i) + except: + print("Connection Error") # to handle exception - d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) - try: - d_video.download(PATH) - except: - print("Some Error!") -print('Task Completed!') + # check files with "mp4" extension + mp4files = yt.filter("mp4") + + d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution) + try: + d_video.download(PATH) + except: + print("Some Error!") +print("Task Completed!") diff --git a/vowel remover function.py b/vowel remover function.py index 5af2ff5f01e..8d6467b57dc 100644 --- a/vowel remover function.py +++ b/vowel remover function.py @@ -4,4 +4,6 @@ def vowel_remover(text): if l.lower() not in "aeiou": string += l return string + + print(vowel_remover("hello world!")) diff --git a/whatsapp-schedule.py b/whatsapp-schedule.py index 15fe074e81b..97c40ab12fd 100644 --- a/whatsapp-schedule.py +++ b/whatsapp-schedule.py @@ -6,6 +6,7 @@ install requirements: python -m pip install selenium """ + import pywhatkit diff --git a/wifi hack by brutefore.py b/wifi hack by brutefore.py index efcbe2c9347..bf346e1a7c7 100644 --- a/wifi hack by brutefore.py +++ b/wifi hack by brutefore.py @@ -20,43 +20,38 @@ The following provides a simple 8 purely digital dictionary generation program codes """ - - - import itertools as its # Problems encountered do not understand? Python learning exchange group: 821 460 695 meet your needs, data base files have been uploaded, you can download their own! -if __name__ == '__main__': +if __name__ == "__main__": words_num = "1234567890" words_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" r = its.product(words_num, repeat=8) - dic = open ( "password-8 digits .txt", "w") + dic = open("password-8 digits .txt", "w") for i in r: dic.write("".join(i)) dic.write("".join("\n")) dic.close() - - - - - - - # 2. brute force password when using longer - - + + +# 2. brute force password when using longer + + import pywifi - -from pywifi import const # quote some definitions - + +from pywifi import const # quote some definitions + import time -''' + +""" Problems encountered do not understand? Python learning exchange group: 821 460 695 meet your needs, data base files have been uploaded, you can download their own! -''' - +""" + + def getwifi(wifilist, wificount): - wifi = pywifi.PyWiFi () # crawled network interface cards - ifaces = wifi.interfaces () [0] # Get the card + wifi = pywifi.PyWiFi() # crawled network interface cards + ifaces = wifi.interfaces()[0] # Get the card ifaces.scan() time.sleep(8) bessis = ifaces.scan_results() @@ -64,7 +59,7 @@ def getwifi(wifilist, wificount): namelist = [] ssidlist = [] for data in bessis: - if data.ssid not in namelist: # remove duplicate names WIFI + if data.ssid not in namelist: # remove duplicate names WIFI namelist.append(data.ssid) allwifilist.append((data.ssid, data.signal)) sorted(allwifilist, key=lambda st: st[1], reverse=True) @@ -78,48 +73,48 @@ def getwifi(wifilist, wificount): ssidlist.append(item[0]) print(allwifilist) return ssidlist - - + + def getifaces(): - wifi = pywifi.PyWiFi () # crawled network interface cards - ifaces = wifi.interfaces () [0] # Get the card - ifaces.disconnect () # disconnect unlimited card connection + wifi = pywifi.PyWiFi() # crawled network interface cards + ifaces = wifi.interfaces()[0] # Get the card + ifaces.disconnect() # disconnect unlimited card connection return ifaces - - + + def testwifi(ifaces, ssidname, password): - profile = pywifi.Profile () # create a wifi connection file - profile.ssid = ssidname # define wifissid - profile.auth = open(const.AUTH_ALG_OPEN) # NIC - profile.akm.append (const.AKM_TYPE_WPA2PSK) # wifi encryption algorithm - #encrypting unit - profile.cipher = const.CIPHER_TYPE_CCMP # - profile.key = password # wifi password - ifaces.remove_all_network_profiles () # delete all other configuration files - tmp_profile = ifaces.add_network_profile (profile) # load the configuration file - ifaces.connect (tmp_profile) # wifi connection - #You can connect to the inner (5) # 5 seconds time.sleep + profile = pywifi.Profile() # create a wifi connection file + profile.ssid = ssidname # define wifissid + profile.auth = open(const.AUTH_ALG_OPEN) # NIC + profile.akm.append(const.AKM_TYPE_WPA2PSK) # wifi encryption algorithm + # encrypting unit + profile.cipher = const.CIPHER_TYPE_CCMP # + profile.key = password # wifi password + ifaces.remove_all_network_profiles() # delete all other configuration files + tmp_profile = ifaces.add_network_profile(profile) # load the configuration file + ifaces.connect(tmp_profile) # wifi connection + # You can connect to the inner (5) # 5 seconds time.sleep if ifaces.status() == const.IFACE_CONNECTED: return True else: return False - - + + def beginwork(wifinamelist): ifaces = getifaces() - path = r # password-8 digits .txt + path = r # password-8 digits .txt # Path = r "password- commonly used passwords .txt" - files = open(path, 'r') + files = open(path, "r") while True: try: password = files.readline() - password = password.strip('\n') + password = password.strip("\n") if not password: break for wifiname in wifinamelist: - print ( "are trying to:" + wifiname + "," + password) + print("are trying to:" + wifiname + "," + password) if testwifi(ifaces, wifiname, password): - print ( "Wifi account:" + wifiname + ", Wifi password:" + password) + print("Wifi account:" + wifiname + ", Wifi password:" + password) wifinamelist.remove(wifiname) break if not wifinamelist: @@ -127,16 +122,10 @@ def beginwork(wifinamelist): except: continue files.close() - - -if __name__ == '__main__': - wifinames_e = [ "", "Vrapile"] # exclude wifi name does not crack + + +if __name__ == "__main__": + wifinames_e = ["", "Vrapile"] # exclude wifi name does not crack wifinames = getwifi(wifinames_e, 5) print(wifinames) beginwork(wifinames) - - - - - - diff --git a/wiki/wiki.py b/wiki/wiki.py index 564c7e1bfd0..bf85e66a0ae 100644 --- a/wiki/wiki.py +++ b/wiki/wiki.py @@ -3,12 +3,24 @@ import wikipedia import tkinter as tk -from tkinter import Label, Button, Entry, Text, messagebox, SOLID, GROOVE, StringVar, WORD, END -#import PIL as ImageTK +from tkinter import ( + Label, + Button, + Entry, + Text, + messagebox, + SOLID, + GROOVE, + StringVar, + WORD, + END, +) + +# import PIL as ImageTK from tkinter import messagebox -class main(): +class main: def __init__(self, root): self.root = root @@ -16,13 +28,13 @@ def __init__(self, root): self.root.geometry("1920x1080") self.lbl1 = Label( - root, - text="WIKIPEDIA SUMMARY", - font=("Verdana", 25, "bold"), - width=50, - bg="yellow", - fg="red", - relief=SOLID, + root, + text="WIKIPEDIA SUMMARY", + font=("Verdana", 25, "bold"), + width=50, + bg="yellow", + fg="red", + relief=SOLID, ) self.lbl1.pack(padx=10, pady=15) @@ -47,7 +59,7 @@ def __init__(self, root): relief=GROOVE, bg="#4cd137", bd=3, - command=lambda:self.summary("None"), + command=lambda: self.summary("None"), ) self.searchbtn.pack() @@ -67,8 +79,8 @@ def summary(self, event): self.searchbtn["text"] = "Searching..." try: self.query = wikipedia.page(self.question.get(), auto_suggest=True) - self.quesbox.delete(0, 'end') - self.answer.delete('1.0', END) + self.quesbox.delete(0, "end") + self.answer.delete("1.0", END) self.answer.insert(END, (self.query.summary)) self.answer.pack() @@ -78,9 +90,9 @@ def summary(self, event): self.searchbtn["text"] = "Search" - # Wikipeida page returns to many pages + if __name__ == "__main__": root = tk.Tk() main(root) diff --git a/wiki_random.py b/wiki_random.py index 3782ea60137..24fbacb206d 100644 --- a/wiki_random.py +++ b/wiki_random.py @@ -14,6 +14,7 @@ enter index of article you would like to see, or 'r' for retry and 'n' for exit. """ + import requests import webbrowser diff --git a/wikipedia.py b/wikipedia.py index 18570cb1bcd..dd7a5f05321 100644 --- a/wikipedia.py +++ b/wikipedia.py @@ -6,6 +6,7 @@ win.title("WIKIPEDIA") win.geometry("200x70") # function + # function def search_wiki(): search = entry.get() diff --git a/youtubedownloader.py b/youtubedownloader.py index 55b5bc85990..1fa4fb57f6b 100644 --- a/youtubedownloader.py +++ b/youtubedownloader.py @@ -9,58 +9,49 @@ def threading(): t1 = Thread(target=download) t1.start() + def download(): try: url = YouTube(str(url_box.get())) video = url.streams.first() - filename = filedialog.asksaveasfilename(defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")]) + filename = filedialog.asksaveasfilename( + defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")] + ) if filename: # Check if a filename is selected video.download(filename=filename) - messagebox.showinfo('', 'Download completed!') + messagebox.showinfo("", "Download completed!") else: - messagebox.showwarning('', 'Download cancelled!') + messagebox.showwarning("", "Download cancelled!") except Exception as e: messagebox.showerror("Error", "An error occurred while downloading the video.") - root = Tk() -root.title('YouTube Downloader') -root.geometry('780x500+200+200') -root.configure(bg='olivedrab1') +root.title("YouTube Downloader") +root.geometry("780x500+200+200") +root.configure(bg="olivedrab1") root.resizable(False, False) # Label widgets introlable = Label( root, - text='YouTube Video Downloader', + text="YouTube Video Downloader", width=30, - relief='ridge', + relief="ridge", bd=4, - font=('chiller', 26, 'italic bold'), - fg='red') + font=("chiller", 26, "italic bold"), + fg="red", +) introlable.place(x=35, y=20) -Label( - root, - text='Enter YouTube Link', - font=('sans-serif', 16), - bg='olivedrab1' - ).place(x=40, y=150) +Label(root, text="Enter YouTube Link", font=("sans-serif", 16), bg="olivedrab1").place( + x=40, y=150 +) -url_box = Entry( - root, - font=('arial', 30), - width=30 - ) +url_box = Entry(root, font=("arial", 30), width=30) url_box.place(x=40, y=180) -btn = Button( - root, - text='DOWNLOAD', - font=('sans-serif', 25), - command=threading - ) +btn = Button(root, text="DOWNLOAD", font=("sans-serif", 25), command=threading) btn.place(x=270, y=240) root.mainloop()