├── .gitignore ├── 1.py ├── 15.py ├── 19.py ├── 1code1020868.py ├── 8.py ├── 9.py ├── Alarm clock.py ├── ArithmeticOperator.py ├── Banking_OOPS.py ├── Built_In_DataType ├── CONTRIBUTING.md ├── COSnSIN.ipynb ├── Digit Recognizer.ipynb ├── Functions.py ├── HACTOBERFEST.md ├── If_Statements.py ├── ImportingModule.py ├── IntroToPython.py ├── JumpStatement.py ├── List.py ├── List_concat_repli.py ├── List_elem_del.py ├── List_iteration.py ├── Loops.py ├── Numberguess.py ├── PalindromeNStringReversal.ipynb ├── Pattern.py ├── Pra_fact_fabbo.py ├── Pratheeksha_game ├── Pratheeksha_python ├── PythonDSA ├── BinarySearch.py ├── BogoSort.py ├── Bubblesort.py ├── DNF_Sort.py ├── DijtraksAlgorithm.py ├── InsertionSort.py ├── KadaneAlgo.py ├── MergeSort.py ├── Pythagorean Triplets(DSA PYTHON)) ├── QuickSort.py ├── SelectionSort.py ├── binary_tree.py ├── breadth_first_search.py ├── circularque.py ├── fibonacciSeries.py ├── heap_sort.py ├── insert_binarytree.py ├── linked.py ├── linked_list_advance.py ├── priorityqueue.py ├── stack.py ├── stack_using_linkedList.py └── traversing.py ├── PythonDecorators.py ├── QuickSort.cpp ├── RCNN object detection ├── RCNN demo.ipynb └── mrcnn │ ├── __init__.py │ ├── config.py │ ├── model.py │ ├── parallel_model.py │ ├── utils.py │ └── visualize.py ├── README.md ├── Sets.py ├── Sorting_List.py ├── Sple_Exception.py ├── Standard_Function.py ├── Star.py ├── Starting.py ├── StringManuplation.py ├── StringTemplate.py ├── String_demonstration_1.py ├── String_slicing.py ├── Text repetition N number.py ├── Time_difference.py ├── Tuples.py ├── Type_Casting.py ├── Variable_AssignMulti_val_c3.py ├── Variable_GlobalVariable.py ├── Variable_c1.py ├── Variable_names_c2.py ├── Variables_print_c4.py ├── addvolumfrendfunc.cpp ├── balanced_paranthesis.py ├── basicDoublyLinkedlist.cpp ├── basicStack.cpp ├── bgremover.py ├── binarysearchincpp045680.cpp ├── bucketSort.py ├── buzz num.cpp ├── calculator.ipynb ├── cf mainik and array.bin ├── check prime or not.cpp ├── cocktailSort.py ├── compherension.py ├── compressed_img.jpg ├── cycleSort.py ├── cyclic sort.java ├── deleating_of_node.cpp ├── design.py ├── diamondPattern.py ├── diamond_pattern.py ├── doublyLinkedList.py ├── euclidGCD.py ├── factorial_of _num.py ├── fibonacci_numbers.py ├── findd_Factorial.py ├── findurl.py ├── game.py ├── heap.py ├── img_compress.py ├── inorder_traversal.py ├── lallu.cpp ├── linearSearchincpp00988.cpp ├── linearsearch.py ├── linkedlistinsrt.py ├── loops.py ├── mergeSort.py ├── nparray.py ├── npfunction.py ├── oops.py ├── pairwise000006.cpp ├── pancakeSort.py ├── pattern.py ├── peigonSort.py ├── perfect.cpp ├── pointer_VEDANT.cpp ├── postorder_traversal.py ├── preorder_traversal.py ├── priorityqueue.py ├── python matrix ├── pythonDictionaries.py ├── pythonprogram.py ├── queue.cpp ├── quickSort.py ├── radhakrishn.py ├── redixSort.py ├── reverse_ll.py ├── runner_score.py ├── selectionsort.py ├── sndkfne.c ├── stack.py ├── stack_usingLinkedlist.py ├── stoogeSort.py ├── timSort.py ├── treeSort.py ├── uncompressed_img.jpg ├── weather_notifications_desktop.py └── zeroSum.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ -------------------------------------------------------------------------------- /1.py: -------------------------------------------------------------------------------- 1 | # Python program to split a string and 2 | # join it using different delimiter 3 | 4 | def split_string(string): 5 | 6 | # Split the string based on space delimiter 7 | list_string = string.split(' ') 8 | 9 | return list_string 10 | 11 | 12 | def join_string(list_string): 13 | 14 | # Join the string based on '-' delimiter 15 | string = '-'.join(list_string) 16 | 17 | return string 18 | 19 | 20 | # Driver Function 21 | if __name__ == '__main__': 22 | string = 'hfg yf h uy' 23 | 24 | # Splitting a string 25 | list_string = split_string(string) 26 | print(list_string) 27 | 28 | # Join list of strings into one 29 | new_string = join_string(list_string) 30 | print(new_string) 31 | -------------------------------------------------------------------------------- /15.py: -------------------------------------------------------------------------------- 1 | # Python program to generate and match 2 | # the string from all random strings 3 | # of same length 4 | 5 | # Importing string, random 6 | # and time modules 7 | import string 8 | import random 9 | import time 10 | 11 | # all possible characters including 12 | # lowercase, uppercase and special symbols 13 | possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:' 14 | 15 | # string to be generated 16 | t = "tytgj" 17 | 18 | # To take input from user 19 | # t = input(str("Enter your target text: ")) 20 | 21 | attemptThis = ''.join(random.choice(possibleCharacters) 22 | for i in range(len(t))) 23 | attemptNext = '' 24 | 25 | completed = False 26 | iteration = 0 27 | 28 | # Iterate while completed is false 29 | while completed == False: 30 | print(attemptThis) 31 | 32 | attemptNext = '' 33 | completed = True 34 | 35 | # Fix the index if matches with 36 | # the strings to be generated 37 | for i in range(len(t)): 38 | if attemptThis[i] != t[i]: 39 | completed = False 40 | attemptNext += random.choice(possibleCharacters) 41 | else: 42 | attemptNext += t[i] 43 | 44 | # increment the iteration 45 | iteration += 1 46 | attemptThis = attemptNext 47 | time.sleep(0.1) 48 | 49 | # Driver Code 50 | print("Target matched after " + 51 | str(iteration) + " iterations") 52 | -------------------------------------------------------------------------------- /19.py: -------------------------------------------------------------------------------- 1 | # input list 2 | lst = [10, 11, 12, 13, 14, 15] 3 | # the above input can also be given as 4 | # lst=list(map(int,input().split())) 5 | l = [] # empty list 6 | 7 | # iterate to reverse the list 8 | for i in lst: 9 | # reversing the list 10 | l.insert(0, i) 11 | # printing result 12 | print(l) 13 | -------------------------------------------------------------------------------- /1code1020868.py: -------------------------------------------------------------------------------- 1 | # Python program to check 2 | # if a string is binary or not 3 | 4 | # function for checking the 5 | # string is accepted or not 6 | 7 | 8 | def check(string): 9 | 10 | # set function convert string 11 | # into set of characters . 12 | p = set(string) 13 | 14 | # declare set of '0', '1' . 15 | s = {'0', '1'} 16 | 17 | # check set p is same as set s 18 | # or set p contains only '0' 19 | # or set p contains only '1' 20 | # or not, if any one condition 21 | # is true then string is accepted 22 | # otherwise not . 23 | if s == p or p == {'0'} or p == {'1'}: 24 | print("Yes") 25 | else: 26 | print("No") 27 | 28 | 29 | # driver code 30 | if __name__ == "__main__": 31 | 32 | string = "101010000111" 33 | 34 | # function calling 35 | check(string) 36 | -------------------------------------------------------------------------------- /8.py: -------------------------------------------------------------------------------- 1 | # Python code 2 | # To reverse words in a given string 3 | 4 | # input string 5 | string = "quiz practice code" 6 | # reversing words in a given string 7 | s = string.split()[::-1] 8 | l = [] 9 | for i in s: 10 | # apending reversed words to l 11 | l.append(i) 12 | # printing reverse words 13 | print(" ".join(l)) 14 | -------------------------------------------------------------------------------- /9.py: -------------------------------------------------------------------------------- 1 | # Initializing String 2 | test_str = "xyzabc" 3 | 4 | # Removing char at pos 3 5 | # using replace 6 | new_str = test_str.replace('e', '') 7 | 8 | # Printing string after removal 9 | # removes all occurrences of 'e' 10 | print("The string after removal of i'th character( doesn't work) : " + new_str) 11 | 12 | # Removing 1st occurrence of s, i.e 5th pos. 13 | # if we wish to remove it. 14 | new_str = test_str.replace('s', '', 1) 15 | 16 | # Printing string after removal 17 | # removes first occurrences of s 18 | print("The string after removal of i'th character(works) : " + new_str) 19 | -------------------------------------------------------------------------------- /Alarm clock.py: -------------------------------------------------------------------------------- 1 | select-site 2 | logo 3 | search 4 | 5 | Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission. 6 | 7 | 8 | 9 | Top 10 Fun & Easy Python Projects for Beginners (with Code) 10 | 11 | Posted in Python 12 | Python Projects 13 | 14 | Simran Kaur Arora 15 | Last Updated 15 Sep, 2022 16 | Share: 17 | share-facebook share-twitter share-linkedin share-reddit share-hackrnews share-whatsapp 18 | 5 Comments 19 | Table of Contents 20 | 21 | AI, ML, and Data Science dominate many fields and industries today - all of them make heavy use of the Python programming language in some way or another. 22 | 23 | 24 | Becoming a master in Python can open many doors in your career and land in some of the best opportunities across the planet. No matter wherever you rate yourself in the Python skill, working on Python projects is a surefire way to boost your skills and build up your profile. While Python books and Python tutorials are helpful, nothing beats getting your hands dirty with actual coding. 25 | 26 | We list several Python projects for beginners for you to challenge yourself and get better at Python coding. 27 | 28 | 29 | 30 | Top 10 Python Project Ideas for Beginners 31 | 1. Mad Libs Generator 32 | This Python beginner project is a good start for beginners as it makes use of strings, variables, and concatenation. The Mad Libs Generator manipulates input data, which could be anything: an adjective, a pronoun, or verb. After taking in the input, the program takes the data and arranges it to build a story. This is a very cool Python project to try out if you’re new to coding. 33 | 34 | Sample Code: 35 | 36 | """ Mad Libs Generator 37 | 38 | ---------------------------------------- 39 | 40 | """ 41 | 42 | #Loop back to this point once code finishes 43 | 44 | loop = 1 45 | 46 | while (loop < 10): 47 | 48 | # All the questions that the program asks the user 49 | 50 | noun = input("Choose a noun: ") 51 | 52 | p_noun = input("Choose a plural noun: ") 53 | 54 | noun2 = input("Choose a noun: ") 55 | 56 | place = input("Name a place: ") 57 | 58 | adjective = input("Choose an adjective (Describing word): ") 59 | 60 | noun3 = input("Choose a noun: ") 61 | 62 | #Displays the story based on the users input 63 | 64 | print ("------------------------------------------") 65 | 66 | print ("Be kind to your",noun,"- footed", p_noun) 67 | 68 | print ("For a duck may be somebody's", noun2,",") 69 | 70 | print ("Be kind to your",p_noun,"in",place) 71 | 72 | print ("Where the weather is always",adjective,".") 73 | 74 | print () 75 | 76 | print ("You may think that is this the",noun3,",") 77 | 78 | print ("Well it is.") 79 | 80 | print ("------------------------------------------") 81 | 82 | # Loop back to "loop = 1" 83 | 84 | loop = loop + 1 85 | 86 | 87 | 2. Number Guessing 88 | This project is a fun game that generates a random number in a certain specified range and the user must guess the number after receiving hints. Every time a user’s guess is wrong they are prompted with more hints to make it easier — at the cost of reducing the score. 89 | 90 | 91 | The program also requires functions to check if an actual number is entered by the user, and finds the difference between the two numbers. 92 | 93 | Sample Code: 94 | 95 | """ Number Guessing Game 96 | 97 | ---------------------------------------- 98 | 99 | """ 100 | 101 | import random 102 | 103 | attempts_list = [] 104 | 105 | def show_score(): 106 | 107 | if len(attempts_list) <= 0: 108 | 109 | print("There is currently no high score, it's yours for the taking!") 110 | 111 | else: 112 | 113 | print("The current high score is {} attempts".format(min(attempts_list))) 114 | 115 | def start_game(): 116 | 117 | random_number = int(random.randint(1, 10)) 118 | 119 | print("Hello traveler! Welcome to the game of guesses!") 120 | 121 | player_name = input("What is your name? ") 122 | 123 | wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) 124 | 125 | # Where the show_score function USED to be 126 | 127 | attempts = 0 128 | 129 | show_score() 130 | 131 | while wanna_play.lower() == "yes": 132 | 133 | try: 134 | 135 | guess = input("Pick a number between 1 and 10 ") 136 | 137 | if int(guess) < 1 or int(guess) > 10: 138 | 139 | raise ValueError("Please guess a number within the given range") 140 | 141 | if int(guess) == random_number: 142 | 143 | print("Nice! You got it!") 144 | 145 | attempts += 1 146 | 147 | attempts_list.append(attempts) 148 | 149 | print("It took you {} attempts".format(attempts)) 150 | 151 | play_again = input("Would you like to play again? (Enter Yes/No) ") 152 | 153 | attempts = 0 154 | 155 | show_score() 156 | 157 | random_number = int(random.randint(1, 10)) 158 | 159 | if play_again.lower() == "no": 160 | 161 | print("That's cool, have a good one!") 162 | 163 | break 164 | 165 | elif int(guess) > random_number: 166 | 167 | print("It's lower") 168 | 169 | attempts += 1 170 | 171 | elif int(guess) < random_number: 172 | 173 | print("It's higher") 174 | 175 | attempts += 1 176 | 177 | except ValueError as err: 178 | 179 | print("Oh no!, that is not a valid value. Try again...") 180 | 181 | print("({})".format(err)) 182 | 183 | else: 184 | 185 | print("That's cool, have a good one!") 186 | 187 | if __name__ == '__main__': 188 | 189 | start_game() 190 | 191 | 192 | 3. Rock Paper Scissors 193 | This rock paper scissors program uses a number of functions so this is a good way of getting that critical concept under your belt. 194 | 195 | 196 | Random function: to generate rock, paper, or scissors. 197 | Valid function: to check the validity of the move. 198 | Result function: to declare the winner of the round. 199 | Scorekeeper: to keep track of the score. 200 | The program requires the user to make the first move before it makes a move. The input could be a string or an alphabet representing either rock, paper or scissors. After evaluating the input string, a winner is decided by the result function and the score of the round is updated by the scorekeeper function. 201 | 202 | Sample Code: 203 | 204 | """ Rock Paper Scissors 205 | 206 | ---------------------------------------- 207 | 208 | """ 209 | 210 | import random 211 | 212 | import os 213 | 214 | import re 215 | 216 | os.system('cls' if os.name=='nt' else 'clear') 217 | 218 | while (1 < 2): 219 | 220 | print ("\n") 221 | 222 | print ("Rock, Paper, Scissors - Shoot!") 223 | 224 | userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ") 225 | 226 | if not re.match("[SsRrPp]", userChoice): 227 | 228 | print ("Please choose a letter:") 229 | 230 | print ("[R]ock, [S]cissors or [P]aper.") 231 | 232 | continue 233 | 234 | # Echo the user's choice 235 | 236 | print ("You chose: " + userChoice) 237 | 238 | choices = ['R', 'P', 'S'] 239 | 240 | opponenetChoice = random.choice(choices) 241 | 242 | print ("I chose: " + opponenetChoice) 243 | 244 | if opponenetChoice == str.upper(userChoice): 245 | 246 | print ("Tie! ") 247 | 248 | #if opponenetChoice == str("R") and str.upper(userChoice) == "P" 249 | 250 | elif opponenetChoice == 'R' and userChoice.upper() == 'S': 251 | 252 | print ("Scissors beats rock, I win! ") 253 | 254 | continue 255 | 256 | elif opponenetChoice == 'S' and userChoice.upper() == 'P': 257 | 258 | print ("Scissors beats paper! I win! ") 259 | 260 | continue 261 | 262 | elif opponenetChoice == 'P' and userChoice.upper() == 'R': 263 | 264 | print ("Paper beat rock, I win!") 265 | 266 | continue 267 | 268 | else: 269 | 270 | print ("You win!") 271 | 272 | 273 | 4. Dice Roll Generator 274 | This dice roll generator is a fairly simple program that makes use of the random function to simulate dice rolls. You can change the maximum value to any number, making it possible to simulate polyhedral dice used in many board games and roleplaying games. 275 | 276 | Sample Code: 277 | 278 | import random 279 | 280 | #Enter the minimum and maximum limits of the dice rolls below 281 | 282 | min_val = 1 283 | 284 | max_val = 6 285 | 286 | #the variable that stores the user’s decision 287 | 288 | roll_again = "yes" 289 | 290 | #The dice roll loop if the user wants to continue 291 | 292 | while roll_again == "yes" or roll_again == "y": 293 | 294 | print("Dices rolling...") 295 | 296 | print("The values are :") 297 | 298 | #Printing the randomly generated variable of the first dice 299 | 300 | print(random.randint(min_val, max_val)) 301 | 302 | #Printing the randomly generated variable of the second dice 303 | 304 | print(random.randint(min_val, max_val)) 305 | 306 | #Here the user enters yes or y to continue and any other input ends the program 307 | 308 | roll_again = input("Roll the Dices Again?") 309 | 310 | 311 | 5. Binary Search Algorithm 312 | The binary search algorithm is a very important one, and requires you to create a list of numbers between 0 and an upper limit, with every succeeding number having a difference of 2 between them. 313 | 314 | When the user inputs a random number to be searched the program begins its search by dividing the list into two halves. First, the first half is searched for the required number and if found, the other half is rejected and vice versa. The search continues until the number is found or the subarray size becomes zero. 315 | 316 | Sample Code: 317 | 318 | # Recursive Binary Search algorithm in Python 319 | 320 | def binarySearch(array, x, low, high): 321 | 322 | if high >= low: 323 | 324 | mid = low + (high - low)//2 325 | 326 | # If found at mid, return the value 327 | 328 | if array[mid] == x: 329 | 330 | return mid 331 | 332 | # Search the first half 333 | 334 | elif array[mid] > x: 335 | 336 | return binarySearch(array, x, low, mid-1) 337 | 338 | # Search the second half 339 | 340 | else: 341 | 342 | return binarySearch(array, x, mid + 1, high) 343 | 344 | else: 345 | 346 | return -1 347 | 348 | array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 349 | 350 | x = int(input("Enter a number between 1 and 10:")) 351 | 352 | result = binarySearch(array, x, 0, len(array)-1) 353 | 354 | if result != -1: 355 | 356 | print("Element is present at position" + str(result)) 357 | 358 | else: 359 | 360 | print("Element not found") 361 | 362 | 363 | 364 | 365 | 6. Calculator 366 | This project teaches you to design a graphical interface and is a good way to get familiar with a library like Tkinter. This library lets you create buttons to perform different operations and display results on the screen. 367 | 368 | Sample Code: 369 | 370 | # Calculator 371 | 372 | def addition (): 373 | 374 | print("Addition") 375 | 376 | n = float(input("Enter the number: ")) 377 | 378 | t = 0 #Total number enter 379 | 380 | ans = 0 381 | 382 | while n != 0: 383 | 384 | ans = ans + n 385 | 386 | t+=1 387 | 388 | n = float(input("Enter another number (0 to calculate): ")) 389 | 390 | return [ans,t] 391 | 392 | def subtraction (): 393 | 394 | print("Subtraction"); 395 | 396 | n = float(input("Enter the number: ")) 397 | 398 | t = 0 #Total number enter 399 | 400 | sum = 0 401 | 402 | while n != 0: 403 | 404 | ans = ans - n 405 | 406 | t+=1 407 | 408 | n = float(input("Enter another number (0 to calculate): ")) 409 | 410 | return [ans,t] 411 | 412 | def multiplication (): 413 | 414 | print("Multiplication") 415 | 416 | n = float(input("Enter the number: ")) 417 | 418 | t = 0 #Total number enter 419 | 420 | ans = 1 421 | 422 | while n != 0: 423 | 424 | ans = ans * n 425 | 426 | t+=1 427 | 428 | n = float(input("Enter another number (0 to calculate): ")) 429 | 430 | return [ans,t] 431 | 432 | def average(): 433 | 434 | an = [] 435 | 436 | an = addition() 437 | 438 | t = an[1] 439 | 440 | a = an[0] 441 | 442 | ans = a / t 443 | 444 | return [ans,t] 445 | 446 | # main... 447 | 448 | while True: 449 | 450 | list = [] 451 | 452 | print(" My first python program!") 453 | 454 | print(" Simple Calculator in python by Malik Umer Farooq") 455 | 456 | print(" Enter 'a' for addition") 457 | 458 | print(" Enter 's' for substraction") 459 | 460 | print(" Enter 'm' for multiplication") 461 | 462 | print(" Enter 'v' for average") 463 | 464 | print(" Enter 'q' for quit") 465 | 466 | c = input(" ") 467 | 468 | if c != 'q': 469 | 470 | if c == 'a': 471 | 472 | list = addition() 473 | 474 | print("Ans = ", list[0], " total inputs ",list[1]) 475 | 476 | elif c == 's': 477 | 478 | list = subtraction() 479 | 480 | print("Ans = ", list[0], " total inputs ",list[1]) 481 | 482 | elif c == 'm': 483 | 484 | list = multiplication() 485 | 486 | print("Ans = ", list[0], " total inputs ",list[1]) 487 | 488 | elif c == 'v': 489 | 490 | list = average() 491 | 492 | print("Ans = ", list[0], " total inputs ",list[1]) 493 | 494 | else: 495 | 496 | print ("Sorry, invilid character") 497 | 498 | else: 499 | 500 | break 501 | 502 | 503 | 7. Alarm Clock 504 | This Command Line Interface (CLI) Python application is a good step up for a beginner developer. More than just setting off an alarm, this program allows certain YouTube links to be added to a text file. When a user sets an alarm, the code picks a random video and starts playing it. 505 | 506 | 507 | Sample Code: 508 | 509 | """ Alarm Clock 510 | 511 | ---------------------------------------- 512 | 513 | """ 514 | 515 | import datetime 516 | 517 | import os 518 | 519 | import time 520 | 521 | import random 522 | 523 | import webbrowser 524 | 525 | # If video URL file does not exist, create one 526 | 527 | if not os.path.isfile("youtube_alarm_videos.txt"): 528 | 529 | print('Creating "youtube_alarm_videos.txt"...') 530 | 531 | with open("youtube_alarm_videos.txt", "w") as alarm_file: 532 | 533 | alarm_file.write("https://www.youtube.com/watch?v=anM6uIZvx74") 534 | 535 | def check_alarm_input(alarm_time): 536 | 537 | """Checks to see if the user has entered in a valid alarm time""" 538 | 539 | if len(alarm_time) == 1: # [Hour] Format 540 | 541 | if alarm_time[0] < 24 and alarm_time[0] >= 0: 542 | 543 | return True 544 | 545 | if len(alarm_time) == 2: # [Hour:Minute] Format 546 | 547 | if alarm_time[0] < 24 and alarm_time[0] >= 0 and \ 548 | 549 | alarm_time[1] < 60 and alarm_time[1] >= 0: 550 | 551 | return True 552 | 553 | elif len(alarm_time) == 3: # [Hour:Minute:Second] Format 554 | 555 | if alarm_time[0] < 24 and alarm_time[0] >= 0 and \ 556 | 557 | alarm_time[1] < 60 and alarm_time[1] >= 0 and \ 558 | 559 | alarm_time[2] < 60 and alarm_time[2] >= 0: 560 | 561 | return True 562 | 563 | return False 564 | 565 | # Get user input for the alarm time 566 | 567 | print("Set a time for the alarm (Ex. 06:30 or 18:30:00)") 568 | 569 | while True: 570 | 571 | alarm_input = input(">> ") 572 | 573 | try: 574 | 575 | alarm_time = [int(n) for n in alarm_input.split(":")] 576 | 577 | if check_alarm_input(alarm_time): 578 | 579 | break 580 | 581 | else: 582 | 583 | raise ValueError 584 | 585 | except ValueError: 586 | 587 | print("ERROR: Enter time in HH:MM or HH:MM:SS format") 588 | 589 | # Convert the alarm time from [H:M] or [H:M:S] to seconds 590 | 591 | seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second 592 | 593 | alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)]) 594 | 595 | # Get the current time of day in seconds 596 | 597 | now = datetime.datetime.now() 598 | 599 | current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])]) 600 | 601 | # Calculate the number of seconds until alarm goes off 602 | 603 | time_diff_seconds = alarm_seconds - current_time_seconds 604 | 605 | # If time difference is negative, set alarm for next day 606 | 607 | if time_diff_seconds < 0: 608 | 609 | time_diff_seconds += 86400 # number of seconds in a day 610 | 611 | # Display the amount of time until the alarm goes off 612 | 613 | print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds)) 614 | 615 | # Sleep until the alarm goes off 616 | 617 | time.sleep(time_diff_seconds) 618 | 619 | # Time for the alarm to go off 620 | 621 | print("Wake Up!") 622 | 623 | # Load list of possible video URLs 624 | 625 | with open("youtube_alarm_videos.txt", "r") as alarm_file: 626 | 627 | videos = alarm_file.readlines() 628 | 629 | # Open a random video from the list 630 | 631 | webbrowser.open(random.choice(videos)) 632 | -------------------------------------------------------------------------------- /ArithmeticOperator.py: -------------------------------------------------------------------------------- 1 | print('Arithmetic operator') 2 | #1 Addition - to add two or more numbers 3 | a = 5 4 | b= 5.0 5 | print(a+b) 6 | 7 | #2 Subtraction - to subtract numbers 8 | a = 1 9 | b=3 10 | print(a-b) 11 | 12 | #3Multiplication - to multiply numbers 13 | 14 | a = 4.5 15 | b=8 16 | print(a*b) 17 | 18 | #4Division / - divide the value to equivalent given numbers 19 | 20 | a=16 21 | b=3 22 | print(a/b) 23 | 24 | #5 floored Division // - return the floor of a/b 25 | print(a//b) 26 | #6Remainder % - returns the remainder of a/b 27 | print(a%b) 28 | var = ' this is Arithmetic operators ' 29 | print ( 'thankyou',var) -------------------------------------------------------------------------------- /Banking_OOPS.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,name,age,gender): 3 | self.name = name 4 | self.age = age 5 | self.gender = gender 6 | def show_details(self): 7 | print("Personal Details\n") 8 | print("Name: ",self.name) 9 | print("Age: ",self.age) 10 | print("Gender: ",self.gender) 11 | 12 | class Bank(User): 13 | def __init__(self,name,age,gender): 14 | super().__init__(name,age,gender) 15 | self.balance = 0 16 | def deposit(self,amount): 17 | self.amount = amount 18 | self.balance = self.balance + amount 19 | print("Amount balance updated : ",self.balance) 20 | def withdraw(self,amount): 21 | self.amount = amount 22 | if(self.amount > self.balance): 23 | print("Insufficient Balance.") 24 | else: 25 | self.balance = self.balance - self.amount 26 | print("Current Balance: ", self.balance) 27 | def view_balance(self): 28 | self.show_details() 29 | print("Current Balance: ", self.balance) 30 | 31 | 32 | Customer = Bank("Vatson",20,"Male") 33 | Customer.show_details() 34 | Customer.deposit(1000) 35 | Customer.deposit(500) 36 | Customer.withdraw(2000) 37 | Customer.withdraw(600) 38 | Customer.view_balance() -------------------------------------------------------------------------------- /Built_In_DataType: -------------------------------------------------------------------------------- 1 | Built-in Data Types 2 | In programming, data type is an important concept. 3 | 4 | Variables can store data of different types, and different types can do different things. 5 | 6 | Python has the following data types built-in by default, in these categories: 7 | 8 | Text Type: str 9 | Numeric Types: int, float, complex 10 | Sequence Types: list, tuple, range 11 | Mapping Type: dict 12 | Set Types: set, frozenset 13 | Boolean Type: bool 14 | Binary Types: bytes, bytearray, memoryview -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | this repository is only for algorithms and data structure in which you can upload in python language algorithms which will useful for many other people. happy coding 👨‍💻. 2 | 3 | -------------------------------------------------------------------------------- /Functions.py: -------------------------------------------------------------------------------- 1 | def fabbonacci(i): 2 | if i<=0: 3 | return 0 4 | elif i==1: 5 | return 1 6 | else: 7 | return fabbonacci(i-1)+fabbonacci(i-2) 8 | def getSum(a,b): 9 | return a+b 10 | def printSum(a,b): 11 | print(a+b) 12 | x = float(input()) 13 | y = float(input()) 14 | 15 | print(getSum(x,y)) 16 | printSum(x,y) 17 | for i in range(6): 18 | print(fabbonacci(i)) -------------------------------------------------------------------------------- /HACTOBERFEST.md: -------------------------------------------------------------------------------- 1 | # Rules and resources for Hactoberfest: 2 | 3 | - Registration [here](https://hacktoberfest.com)to participate on Hactoberfest 2022. 4 | - Get [Resources](https://hacktoberfest.digitalocean.com/resources) from official website. 5 | -------------------------------------------------------------------------------- /If_Statements.py: -------------------------------------------------------------------------------- 1 | var = 'good' 2 | var = 'bad' 3 | var = 'n' 4 | var = 'vskdd' 5 | 6 | 7 | if var == 'good' or var == 'n': 8 | print('good') 9 | elif var == 'bad': 10 | print("bad") 11 | else: 12 | print('not same') -------------------------------------------------------------------------------- /ImportingModule.py: -------------------------------------------------------------------------------- 1 | from cmath import pi 2 | import math 3 | print('enter the radius of the circle :') 4 | r=float(input()) 5 | print('Area of Circle : ' , math.pi*r*r) 6 | print(math.pow(5,3))#return the 5 to the power 3 -------------------------------------------------------------------------------- /IntroToPython.py: -------------------------------------------------------------------------------- 1 | #in python "#" is used to comment out any line 2 | # if you space at the beginning at line than indentation is occur 3 | 4 | 5 | 6 | if 5 > 2 : 7 | print("five is greater than two ,") 8 | 9 | 10 | 11 | 12 | """ 13 | this is comment 14 | write in more than 15 | one line 16 | """ -------------------------------------------------------------------------------- /JumpStatement.py: -------------------------------------------------------------------------------- 1 | #break statement - when break statement execute in the loop 2 | #the loop will break , after that out of the loop will execute. 3 | for i in range(5): 4 | if i==3: 5 | break;#here if value of i will 3 then loop will break 6 | else: 7 | print(i) 8 | 9 | 10 | #continue statement- when continue statement execute then that 11 | #skips other part will execute as it is . 12 | print() 13 | for i in range(5): 14 | if i==3: 15 | continue#here skips value 3 16 | else: 17 | print(i) 18 | 19 | """ 20 | pass: The pass statement is basically a null statement, 21 | which is generally used as a placeholder. It is used to 22 | prevent any code from executing in its scope. 23 | """ 24 | print() 25 | for i in range(5): 26 | if i % 2 == 0: 27 | pass 28 | else: 29 | print(i) 30 | 31 | #return - 32 | def myreturn (x): 33 | if x=='hello': 34 | return True 35 | else: 36 | return False 37 | 38 | print(myreturn(input())) -------------------------------------------------------------------------------- /List.py: -------------------------------------------------------------------------------- 1 | 2 | #list is a circular linked list which is used to store the multiple values . 3 | weekdays= ['sunday','monday','tuesday','wednesday'] 4 | print(weekdays) 5 | #positive indexing 6 | print(weekdays[0],weekdays[2]) 7 | #negative indexing 8 | print(weekdays[-1],weekdays[-2]) 9 | 10 | multi_val=['rishavh',34,'rakesh',-34,39.09,'s'] 11 | print(multi_val) 12 | """ 13 | Slicing of list - 14 | if 4 element of data present in list than 15 | positive indexing - 0 1 2 3 16 | negative indexing - -4 -3 -2 -1 17 | 18 | list[ps_iex:ps_iex]==> list_name[3:2] 19 | list[ng_iex:ng_iex]==> list_name[-3:-2] 20 | """ 21 | print(weekdays[1:4]) 22 | print(weekdays[-3:-1]) 23 | 24 | 25 | # changing values in list 26 | #weekdays[0]=45 27 | print(weekdays) 28 | weekdays[0]='holiday' 29 | print(weekdays[0]) 30 | print(weekdays) -------------------------------------------------------------------------------- /List_concat_repli.py: -------------------------------------------------------------------------------- 1 | #List concatenation 2 | from calendar import week 3 | 4 | 5 | weekday=['monday','tuesday','wednesday','thursday','friday'] 6 | print('Before concatenation :',weekday) 7 | weekends=['saturday','sunday'] 8 | weekday=weekday+weekends 9 | print('After concatenation :',weekday) 10 | 11 | #list replication 12 | print('before: ', weekends) 13 | weekends=weekends*3 14 | print('After Replication',weekends) 15 | -------------------------------------------------------------------------------- /List_elem_del.py: -------------------------------------------------------------------------------- 1 | #Delete a elment in a list 2 | week=['saturday','sunday','monday','tuesday','wednesday'] 3 | print('week [0] : ',week[0]) 4 | print('week [-1] : ',week[-1]) 5 | print('week [-2] : ',week[-2]) 6 | print('week [-3] : ',week[-3]) 7 | print('week [-4] : ',week[-4]) 8 | 9 | 10 | print('before Deletion :',week) 11 | del week[-1] 12 | print() 13 | print('After deletion : ',week) 14 | del week[-3] 15 | print() 16 | print('After deletion : ',week) 17 | 18 | #after deletion the indexing of element also change -------------------------------------------------------------------------------- /List_iteration.py: -------------------------------------------------------------------------------- 1 | #Using loops itereation - In a list iterate all elements through loop 2 | week=['saturday','sunday','monday','tuesday','wednesday'] 3 | d=0 4 | 5 | for day in week: 6 | print(day,':',d) 7 | d+=1 8 | 9 | #using IN and NOT Keyword check whether element is present or not 10 | print( "tuesday" in week) 11 | print('hello' not in week) 12 | 13 | #Adding values in list 14 | 15 | #1. insert(position, value)-> This function inserts an element into a particular index of a list. 16 | 17 | week.insert(0,'specialDay') 18 | print(week) 19 | 20 | #2.append(): This function appends an element at the back of a list. 21 | week.append('lastDay') 22 | print(week) -------------------------------------------------------------------------------- /Loops.py: -------------------------------------------------------------------------------- 1 | #1 for loops 2 | #--> for with range - 3 | for i in range(5): 4 | print(i) 5 | #this print 0 1 2 3 4 6 | #--> for with range (start , stop , step) 7 | print() 8 | for i in range(2,11,2): 9 | print(i) 10 | # print - 2 4 6 8 10 11 | print() 12 | #for with in - used to iterate different containers in python 13 | a = [4,6,4 ,3,2] 14 | for ele in a : 15 | print(ele) 16 | 17 | #2.) while loops 18 | cont = 5 19 | print() 20 | while cont>0 : 21 | print(cont) 22 | cont=cont-1 -------------------------------------------------------------------------------- /Numberguess.py: -------------------------------------------------------------------------------- 1 | import random 2 | number = random.randint(1, 100) 3 | 4 | player_name = input("Hello, What's your name: ") 5 | number_of_guesses = 0 6 | print('okay! '+ player_name+ ' I am Guessing a number between 1 and 100:') 7 | 8 | while number_of_guesses < 5: 9 | guess = int(input()) 10 | number_of_guesses += 1 11 | if guess < number: 12 | print('Your guess is too low') 13 | if guess > number: 14 | print('Your guess is too high') 15 | if guess == number: 16 | break 17 | if guess == number: 18 | print('You guessed the number in ' + str(number_of_guesses) + ' tries!') 19 | else: 20 | print('You did not guess the number, The number was ' + str(number)) -------------------------------------------------------------------------------- /PalindromeNStringReversal.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "collapsed_sections": [], 8 | "authorship_tag": "ABX9TyP4CeLuOwuQdzKCsIJxcBFG", 9 | "include_colab_link": true 10 | }, 11 | "kernelspec": { 12 | "name": "python3", 13 | "display_name": "Python 3" 14 | }, 15 | "language_info": { 16 | "name": "python" 17 | } 18 | }, 19 | "cells": [ 20 | { 21 | "cell_type": "markdown", 22 | "metadata": { 23 | "id": "view-in-github", 24 | "colab_type": "text" 25 | }, 26 | "source": [ 27 | "\"Open" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": { 34 | "id": "96n16XU_s8V_", 35 | "colab": { 36 | "base_uri": "https://localhost:8080/" 37 | }, 38 | "outputId": "bfc14516-01b1-42d7-8c73-3263983b00c4" 39 | }, 40 | "outputs": [ 41 | { 42 | "output_type": "stream", 43 | "name": "stdout", 44 | "text": [ 45 | "ENTER THE WORD: malayalam\n", 46 | "malayalam is a palindrome\n" 47 | ] 48 | } 49 | ], 50 | "source": [ 51 | "x= str(input(\"ENTER THE WORD: \"))\n", 52 | "\n", 53 | "if x == x[::-1] :\n", 54 | " print(x, \"is a palindrome\")\n", 55 | "else:\n", 56 | " print(x[::-1], \" is the reverse\")" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": [], 62 | "metadata": { 63 | "id": "WzZOYrhUj1xF" 64 | }, 65 | "execution_count": null, 66 | "outputs": [] 67 | } 68 | ] 69 | } -------------------------------------------------------------------------------- /Pattern.py: -------------------------------------------------------------------------------- 1 | # GitHub Username: ManishGhimire127 2 | # Name: Ekraj Ghimire 3 | 4 | # Function to demonstrate printing pattern in python 5 | def pypart(n): 6 | 7 | # outer loop to handle number of rows 8 | # n in this case 9 | for i in range(0, n): 10 | 11 | # inner loop to handle number of columns 12 | # values changing acc. to outer loop 13 | for j in range(0, i+1): 14 | 15 | # printing stars 16 | print("* ",end="") 17 | 18 | # ending line after each row 19 | print("\r") 20 | 21 | # Driver Code 22 | n = 5 23 | pypart(n) 24 | -------------------------------------------------------------------------------- /Pra_fact_fabbo.py: -------------------------------------------------------------------------------- 1 | def fabonacci( n): 2 | print('fabonacci:') 3 | if n==0 : 4 | print(0) 5 | elif n<2: 6 | print(0) 7 | print(1) 8 | else : 9 | print(0) 10 | print(1) 11 | a = 0 12 | b=1 13 | c=0 14 | while cpaper wins \n" 8 | + "Rock vs scissor->Rock wins \n" 9 | +"paper vs scissor->scissor wins \n") 10 | 11 | while True: 12 | print("Enter choice \n 1 for Rock, \n 2 for paper, and \n 3 for scissor \n") 13 | 14 | # take the input from user 15 | choice = int(input("User turn: ")) 16 | 17 | # OR is the short-circuit operator 18 | # if any one of the condition is true 19 | # then it return True value 20 | 21 | # looping until user enter invalid input 22 | while choice > 3 or choice < 1: 23 | choice = int(input("enter valid input: ")) 24 | 25 | 26 | # initialize value of choice_name variable 27 | # corresponding to the choice value 28 | if choice == 1: 29 | choice_name = 'Rock' 30 | elif choice == 2: 31 | choice_name = 'paper' 32 | else: 33 | choice_name = 'scissor' 34 | 35 | # print user choice 36 | print("user choice is: " + choice_name) 37 | print("\nNow its computer turn.......") 38 | 39 | # Computer chooses randomly any number 40 | # among 1 , 2 and 3. Using randint method 41 | # of random module 42 | comp_choice = random.randint(1, 3) 43 | 44 | # looping until comp_choice value 45 | # is equal to the choice value 46 | while comp_choice == choice: 47 | comp_choice = random.randint(1, 3) 48 | 49 | # initialize value of comp_choice_name 50 | # variable corresponding to the choice value 51 | if comp_choice == 1: 52 | comp_choice_name = 'Rock' 53 | elif comp_choice == 2: 54 | comp_choice_name = 'paper' 55 | else: 56 | comp_choice_name = 'scissor' 57 | 58 | print("Computer choice is: " + comp_choice_name) 59 | 60 | print(choice_name + " V/s " + comp_choice_name) 61 | #we need to check of a draw 62 | if choice == comp_choice: 63 | print("Draw=> ", end = "") 64 | result = Draw 65 | 66 | # condition for winning 67 | if((choice == 1 and comp_choice == 2) or 68 | (choice == 2 and comp_choice ==1 )): 69 | print("paper wins => ", end = "") 70 | result = "paper" 71 | 72 | elif((choice == 1 and comp_choice == 3) or 73 | (choice == 3 and comp_choice == 1)): 74 | print("Rock wins =>", end = "") 75 | result = "Rock" 76 | else: 77 | print("scissor wins =>", end = "") 78 | result = "scissor" 79 | 80 | # Printing either user or computer wins or draw 81 | if result == Draw: 82 | print("<== Its a tie ==>") 83 | if result == choice_name: 84 | print("<== User wins ==>") 85 | else: 86 | print("<== Computer wins ==>") 87 | 88 | print("Do you want to play again? (Y/N)") 89 | ans = input().lower 90 | 91 | 92 | # if user input n or N then condition is True 93 | if ans == 'n': 94 | break 95 | 96 | # after coming out of the while loop 97 | # we print thanks for playing 98 | print("\nThanks for playing") 99 | -------------------------------------------------------------------------------- /Pratheeksha_python: -------------------------------------------------------------------------------- 1 | class PriorityQueue(object): 2 | def __init__(self): 3 | self.queue = [] 4 | 5 | def __str__(self): 6 | return ' '.join([str(i) for i in self.queue]) 7 | def isEmpty(self): 8 | return len(self.queue) == 0 9 | def insert(self, data): 10 | self.queue.append(data) 11 | def delete(self): 12 | try: 13 | max_val = 0 14 | for i in range(len(self.queue)): 15 | if self.queue[i] > self.queue[max_val]: 16 | max_val = i 17 | item = self.queue[max_val] 18 | del self.queue[max_val] 19 | return item 20 | except IndexError: 21 | print() 22 | exit() 23 | 24 | if __name__ == '__main__': 25 | myQueue = PriorityQueue() 26 | myQueue.insert(12) 27 | myQueue.insert(1) 28 | myQueue.insert(14) 29 | myQueue.insert(7) 30 | print(myQueue) 31 | while not myQueue.isEmpty(): 32 | print(myQueue.delete()) 33 | 34 | -------------------------------------------------------------------------------- /PythonDSA/BinarySearch.py: -------------------------------------------------------------------------------- 1 | # Binary search bubble shot program 2 | def binarySearch(nums,val): 3 | low=0 4 | up=len(nums) -1 5 | 6 | while low<=up : 7 | mid = (low + up) //2 8 | 9 | if nums[mid] == val: 10 | 11 | return f'Element {val} found at position {mid}' 12 | 13 | elif nums[mid] < val: 14 | low = mid+1 15 | else: 16 | up=mid-1 17 | 18 | 19 | 20 | inp = [4,7,8,12,45,99,101] 21 | key=int(input("Enter the num to search:\n")) 22 | 23 | out = binarySearch(inp,key) 24 | 25 | if out: 26 | print(out) 27 | else: 28 | print("Element did not found! ") 29 | -------------------------------------------------------------------------------- /PythonDSA/BogoSort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Time complexity: 3 | Worst case: O(∞) 4 | Average case: O(n * n!) 5 | Best case: O(n) 6 | """ 7 | 8 | from random import randint 9 | 10 | def bogosort(arr): 11 | while not is_sorted(arr): 12 | shuffle(arr) 13 | 14 | def shuffle(arr): 15 | for i in range(len(arr)): 16 | j = randint(0, len(arr) - 1) 17 | arr[i], arr[j] = arr[j], arr[i] 18 | 19 | def is_sorted(arr): 20 | for i in range(len(arr) - 1): 21 | if arr[i] > arr[i + 1]: 22 | return False 23 | return True 24 | 25 | def main(): 26 | print("Enter space separated numbers to sort: ", end="") 27 | arr = [int(x) for x in input().split()] 28 | bogosort(arr) 29 | print("Sorted array: ", arr) 30 | 31 | if __name__ == "__main__": 32 | main() -------------------------------------------------------------------------------- /PythonDSA/Bubblesort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | #Working of Bubble sort 3 | -Starting from the first index, compare the first and the second elements. 4 | -If the first element is greater than the second element, they are swapped. 5 | -Now, compare the second and the third elements. Swap them if they are not in order. 6 | -The above process goes on until the last element.''' 7 | # Bubble sort in Python 8 | 9 | def bubbleSort(array): 10 | 11 | # loop to access each array element 12 | for i in range(len(array)): 13 | 14 | # loop to compare array elements 15 | for j in range(0, len(array) - i - 1): 16 | 17 | # compare two adjacent elements 18 | # change > to < to sort in descending order 19 | if array[j] > array[j + 1]: 20 | 21 | # swapping elements if elements 22 | # are not in the intended order 23 | temp = array[j] 24 | array[j] = array[j+1] 25 | array[j+1] = temp 26 | 27 | 28 | data = [-2, 45, 0, 11, -9] 29 | 30 | bubbleSort(data) 31 | 32 | print('Sorted Array in Ascending Order:') 33 | print(data) 34 | -------------------------------------------------------------------------------- /PythonDSA/DNF_Sort.py: -------------------------------------------------------------------------------- 1 | def dnfSort(arr, n): 2 | low = 0 3 | mid = 0 4 | high = n - 1 5 | while mid <= high: 6 | if arr[mid] == 0: 7 | arr[low], arr[mid] = arr[mid], arr[low] 8 | low = low + 1 9 | mid = mid + 1 10 | elif arr[mid] == 1: 11 | mid = mid + 1 12 | else: 13 | arr[mid], arr[high] = arr[high], arr[mid] 14 | high = high - 1 15 | 16 | def main(): 17 | arr = [int(x) for x in input("Enter space separated numbers to sort: ").split()] 18 | dnfSort(arr, len(arr)) 19 | print("Sorted array: ", arr) 20 | 21 | if __name__ == "__main__": 22 | main() -------------------------------------------------------------------------------- /PythonDSA/DijtraksAlgorithm.py: -------------------------------------------------------------------------------- 1 | # Python program for Dijkstra's single 2 | # source shortest path algorithm. The program is 3 | # for adjacency matrix representation of the graph 4 | 5 | # Library for INT_MAX 6 | import sys 7 | 8 | 9 | class Graph(): 10 | 11 | def __init__(self, vertices): 12 | self.V = vertices 13 | self.graph = [[0 for column in range(vertices)] 14 | for row in range(vertices)] 15 | 16 | def printSolution(self, dist): 17 | print("Vertex \tDistance from Source") 18 | for node in range(self.V): 19 | print(node, "\t", dist[node]) 20 | 21 | # A utility function to find the vertex with 22 | # minimum distance value, from the set of vertices 23 | # not yet included in shortest path tree 24 | def minDistance(self, dist, sptSet): 25 | 26 | # Initialize minimum distance for next node 27 | min = sys.maxsize 28 | 29 | # Search not nearest vertex not in the 30 | # shortest path tree 31 | for u in range(self.V): 32 | if dist[u] < min and sptSet[u] == False: 33 | min = dist[u] 34 | min_index = u 35 | 36 | return min_index 37 | 38 | # Function that implements Dijkstra's single source 39 | # shortest path algorithm for a graph represented 40 | # using adjacency matrix representation 41 | def dijkstra(self, src): 42 | 43 | dist = [sys.maxsize] * self.V 44 | dist[src] = 0 45 | sptSet = [False] * self.V 46 | 47 | for cout in range(self.V): 48 | 49 | # Pick the minimum distance vertex from 50 | # the set of vertices not yet processed. 51 | # x is always equal to src in first iteration 52 | x = self.minDistance(dist, sptSet) 53 | 54 | # Put the minimum distance vertex in the 55 | # shortest path tree 56 | sptSet[x] = True 57 | 58 | # Update dist value of the adjacent vertices 59 | # of the picked vertex only if the current 60 | # distance is greater than new distance and 61 | # the vertex in not in the shortest path tree 62 | for y in range(self.V): 63 | if self.graph[x][y] > 0 and sptSet[y] == False and \ 64 | dist[y] > dist[x] + self.graph[x][y]: 65 | dist[y] = dist[x] + self.graph[x][y] 66 | 67 | self.printSolution(dist) 68 | if __name__ == "__main__": 69 | g = Graph(9) 70 | g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], 71 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 72 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 73 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 74 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 75 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 76 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 77 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 78 | [0, 0, 2, 0, 0, 0, 6, 7, 0] 79 | ] 80 | 81 | g.dijkstra(0) 82 | 83 | 84 | -------------------------------------------------------------------------------- /PythonDSA/InsertionSort.py: -------------------------------------------------------------------------------- 1 | # Insertion sort in Python 2 | 3 | 4 | def insertionSort(array): 5 | 6 | for step in range(1, len(array)): 7 | key = array[step] 8 | j = step - 1 9 | 10 | # Compare key with each element on the left of it until an element smaller than it is found 11 | # For descending order, change keyarray[j]. 12 | while j >= 0 and key < array[j]: 13 | array[j + 1] = array[j] 14 | j = j - 1 15 | 16 | # Place key at after the element just smaller than it. 17 | array[j + 1] = key 18 | 19 | 20 | data = [9, 5, 1, 4, 3] 21 | insertionSort(data) 22 | print('Sorted Array in Ascending Order:') 23 | print(data) 24 | -------------------------------------------------------------------------------- /PythonDSA/KadaneAlgo.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | arr = list(map(int, input().split())) 4 | max_so_far = -sys.maxsize 5 | max_ending_here = 0 6 | start = 0 7 | end = 0 8 | s, e = 0, 0 9 | 10 | for i in range(len(arr)): 11 | max_ending_here += arr[i] 12 | if max_ending_here > max_so_far: 13 | max_so_far = max_ending_here 14 | end = i 15 | start = s 16 | if max_ending_here < 0: 17 | max_ending_here = 0 18 | s = i+1 19 | print("Maximum contiguous subarray sum: ", max_so_far) 20 | print("Starting index: ", start) 21 | print("Ending index: ", end) 22 | -------------------------------------------------------------------------------- /PythonDSA/MergeSort.py: -------------------------------------------------------------------------------- 1 | # MergeSort in Python 2 | 3 | 4 | def mergeSort(array): 5 | if len(array) > 1: 6 | 7 | # r is the point where the array is divided into two subarrays 8 | r = len(array)//2 9 | L = array[:r] 10 | M = array[r:] 11 | 12 | # Sort the two halves 13 | mergeSort(L) 14 | mergeSort(M) 15 | 16 | i = j = k = 0 17 | 18 | # Until we reach either end of either L or M, pick larger among 19 | # elements L and M and place them in the correct position at A[p..r] 20 | while i < len(L) and j < len(M): 21 | if L[i] < M[j]: 22 | array[k] = L[i] 23 | i += 1 24 | else: 25 | array[k] = M[j] 26 | j += 1 27 | k += 1 28 | 29 | # When we run out of elements in either L or M, 30 | # pick up the remaining elements and put in A[p..r] 31 | while i < len(L): 32 | array[k] = L[i] 33 | i += 1 34 | k += 1 35 | 36 | while j < len(M): 37 | array[k] = M[j] 38 | j += 1 39 | k += 1 40 | 41 | 42 | # Print the array 43 | def printList(array): 44 | for i in range(len(array)): 45 | print(array[i], end=" ") 46 | print() 47 | 48 | 49 | # Driver program 50 | if __name__ == '__main__': 51 | array = [6, 5, 12, 10, 9, 1] 52 | 53 | mergeSort(array) 54 | 55 | print("Sorted array is: ") 56 | printList(array) 57 | -------------------------------------------------------------------------------- /PythonDSA/Pythagorean Triplets(DSA PYTHON)): -------------------------------------------------------------------------------- 1 | # Python3 program to generate pythagorean 2 | # triplets smaller than a given limit 3 | 4 | # Function to generate pythagorean 5 | # triplets smaller than limit 6 | def pythagoreanTriplets(limits) : 7 | c, m = 0, 2 8 | 9 | # Limiting c would limit 10 | # all a, b and c 11 | while c < limits : 12 | 13 | # Now loop on n from 1 to m-1 14 | for n in range(1, m) : 15 | a = m * m - n * n 16 | b = 2 * m * n 17 | c = m * m + n * n 18 | 19 | # if c is greater than a and b 20 | # limit then break it 21 | if c > limits : 22 | break 23 | 24 | print(a, b, c) 25 | 26 | m = m + 1 27 | 28 | 29 | # Driver Code 30 | if __name__ == '__main__' : 31 | 32 | limit = 20 33 | pythagoreanTriplets(limit) 34 | -------------------------------------------------------------------------------- /PythonDSA/QuickSort.py: -------------------------------------------------------------------------------- 1 | # Quick sort in Python 2 | 3 | # function to find the partition position 4 | def partition(array, low, high): 5 | 6 | # choose the rightmost element as pivot 7 | pivot = array[high] 8 | 9 | # pointer for greater element 10 | i = low - 1 11 | 12 | # traverse through all elements 13 | # compare each element with pivot 14 | for j in range(low, high): 15 | if array[j] <= pivot: 16 | # if element smaller than pivot is found 17 | # swap it with the greater element pointed by i 18 | i = i + 1 19 | 20 | # swapping element at i with element at j 21 | (array[i], array[j]) = (array[j], array[i]) 22 | 23 | # swap the pivot element with the greater element specified by i 24 | (array[i + 1], array[high]) = (array[high], array[i + 1]) 25 | 26 | # return the position from where partition is done 27 | return i + 1 28 | 29 | # function to perform quicksort 30 | def quickSort(array, low, high): 31 | if low < high: 32 | 33 | # find pivot element such that 34 | # element smaller than pivot are on the left 35 | # element greater than pivot are on the right 36 | pi = partition(array, low, high) 37 | 38 | # recursive call on the left of pivot 39 | quickSort(array, low, pi - 1) 40 | 41 | # recursive call on the right of pivot 42 | quickSort(array, pi + 1, high) 43 | 44 | 45 | data = [8, 7, 2, 1, 0, 9, 6] 46 | print("Unsorted Array") 47 | print(data) 48 | 49 | size = len(data) 50 | 51 | quickSort(data, 0, size - 1) 52 | 53 | print('Sorted Array in Ascending Order:') 54 | print(data) 55 | -------------------------------------------------------------------------------- /PythonDSA/SelectionSort.py: -------------------------------------------------------------------------------- 1 | # Selection sort in Python 2 | # time complexity O(n*n) 3 | #sorting by finding min_index 4 | def selectionSort(array, size): 5 | 6 | for ind in range(size): 7 | min_index = ind 8 | for j in range(ind + 1, size): 9 | # select the minimum element in every iteration 10 | if array[j] < array[min_index]: 11 | min_index = j 12 | # swapping the elements to sort the array 13 | (array[ind], array[min_index]) = (array[min_index], array[ind]) 14 | 15 | arr = [-2, 45, 0, 11, -9,88,-97,-202,747] 16 | size = len(arr) 17 | selectionSort(arr, size) 18 | print('The array after sorting in Ascending Order by selection sort is:') 19 | print(arr) 20 | -------------------------------------------------------------------------------- /PythonDSA/binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | implementation of a binary tree. 3 | see: https://en.wikipedia.org/wiki/Binary_tree 4 | """ 5 | from typing import Any 6 | 7 | 8 | class BinaryTreeNode: 9 | def __init__(self, data: Any = None): 10 | self.left = None 11 | self.right = None 12 | self.data = data 13 | -------------------------------------------------------------------------------- /PythonDSA/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | implementation of BFS algorithm. 3 | see: https://en.wikipedia.org/wiki/Breadth-first_search 4 | """ 5 | from typing import Optional, Callable, Any, List 6 | 7 | from binary_tree import BinaryTreeNode 8 | 9 | 10 | def nop(*args, **kwargs): 11 | pass 12 | 13 | 14 | def breadth_first_traversal(root: BinaryTreeNode, action: Optional[Callable] = nop): 15 | queue = [root] 16 | while queue: 17 | current_node = queue.pop(0) 18 | if current_node.left is not None: 19 | queue.append(current_node.left) 20 | if current_node.right is not None: 21 | queue.append(current_node.right) 22 | if action(current_node, queue): 23 | # if `action` returns a truthy value, it means the traversal is done. 24 | return True 25 | 26 | return False 27 | 28 | 29 | def breadth_first_search(root: BinaryTreeNode, value: Any): 30 | def search_action(current_node: BinaryTreeNode, queue: List): 31 | if current_node.data == value: 32 | print(f"{value} was found!") 33 | return True 34 | 35 | if not queue: 36 | print(f"{value} was not found.") 37 | 38 | print(f"searching value: {value}") 39 | return breadth_first_traversal(root=root, action=search_action) 40 | 41 | 42 | def breadth_first_print(root: BinaryTreeNode, is_print_queue=False): 43 | def print_action(current_node: BinaryTreeNode, queue: List): 44 | print(current_node.data) 45 | if is_print_queue: 46 | print("queue is:", [node.data for node in queue]) 47 | 48 | print(f"printing binary tree from {root.data}:") 49 | return breadth_first_traversal(root, action=print_action) 50 | 51 | 52 | def test_stuff(): 53 | # tree looks like this: 54 | # 1 55 | # 2 3 56 | # 4 5 N 6 57 | # 7 8 N N N N 58 | tree = BinaryTreeNode(data=1) 59 | node2 = tree.left = BinaryTreeNode(data=2) 60 | node3 = tree.right = BinaryTreeNode(data=3) 61 | node4 = node2.left = BinaryTreeNode(data=4) 62 | node2.right = BinaryTreeNode(data=5) 63 | node3.right = BinaryTreeNode(data=6) 64 | node4.left = BinaryTreeNode(data=7) 65 | node4.right = BinaryTreeNode(data=8) 66 | 67 | breadth_first_print(tree) 68 | print() 69 | 70 | print("bfs 8:") 71 | assert breadth_first_search(tree, 8) 72 | print() 73 | 74 | print("bfs 3 8:") 75 | assert not breadth_first_search(node3, 8) 76 | print() 77 | 78 | print("bfp queue 4:") 79 | breadth_first_print(node4, is_print_queue=True) 80 | -------------------------------------------------------------------------------- /PythonDSA/circularque.py: -------------------------------------------------------------------------------- 1 | 2 | class MyCircularQueue(): 3 | 4 | def __init__(self, k): 5 | self.k = k 6 | self.queue = [None] * k 7 | self.head = self.tail = -1 8 | 9 | def enqueue(self, data): 10 | 11 | if ((self.tail + 1) % self.k == self.head): 12 | print("The circular queue is full\n") 13 | 14 | elif (self.head == -1): 15 | self.head = 0 16 | self.tail = 0 17 | self.queue[self.tail] = data 18 | else: 19 | self.tail = (self.tail + 1) % self.k 20 | self.queue[self.tail] = data 21 | 22 | 23 | def dequeue(self): 24 | if (self.head == -1): 25 | print("The circular queue is empty\n") 26 | 27 | elif (self.head == self.tail): 28 | temp = self.queue[self.head] 29 | self.head = -1 30 | self.tail = -1 31 | return temp 32 | else: 33 | temp = self.queue[self.head] 34 | self.head = (self.head + 1) % self.k 35 | return temp 36 | 37 | def printCQueue(self): 38 | if(self.head == -1): 39 | print("No element in the circular queue") 40 | 41 | elif (self.tail >= self.head): 42 | for i in range(self.head, self.tail + 1): 43 | print(self.queue[i], end=" ") 44 | print() 45 | else: 46 | for i in range(self.head, self.k): 47 | print(self.queue[i], end=" ") 48 | for i in range(0, self.tail + 1): 49 | print(self.queue[i], end=" ") 50 | print() 51 | 52 | obj = MyCircularQueue(5) 53 | obj.enqueue(1) 54 | obj.enqueue(2) 55 | obj.enqueue(3) 56 | obj.enqueue(4) 57 | obj.enqueue(5) 58 | print("Initial queue") 59 | obj.printCQueue() 60 | 61 | obj.dequeue() 62 | print("After removing an element from the queue") 63 | obj.printCQueue() 64 | -------------------------------------------------------------------------------- /PythonDSA/fibonacciSeries.py: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term 2 | 3 | nterms = int(input("How many terms? ")) 4 | 5 | # first two terms 6 | n1, n2 = 0, 1 7 | count = 0 8 | 9 | # check if the number of terms is valid 10 | if nterms <= 0: 11 | print("Please enter a positive integer") 12 | # if there is only one term, return n1 13 | elif nterms == 1: 14 | print("Fibonacci sequence upto",nterms,":") 15 | print(n1) 16 | # generate fibonacci sequence 17 | else: 18 | print("Fibonacci sequence:") 19 | while count < nterms: 20 | print(n1) 21 | nth = n1 + n2 22 | # update values 23 | n1 = n2 24 | n2 = nth 25 | count += 1 26 | -------------------------------------------------------------------------------- /PythonDSA/heap_sort.py: -------------------------------------------------------------------------------- 1 | import time 2 | import random 3 | 4 | def heapify(arr, n, i): 5 | largest = i 6 | l = 2 * i + 1 7 | r = 2 * i + 2 8 | if l < n and arr[largest] < arr[l]: 9 | largest = l 10 | if r < n and arr[largest] < arr[r]: 11 | largest = r 12 | if largest != i: 13 | arr[i], arr[largest] = arr[largest], arr[i] 14 | heapify(arr, n, largest) 15 | 16 | def heapsort(arr,n): 17 | for i in range(n//2 - 1, -1, -1): 18 | heapify(arr, n, i) 19 | for i in range(n-1, 0, -1): 20 | arr[i], arr[0] = arr[0], arr[i] 21 | heapify(arr, i, 0) 22 | 23 | l = [] 24 | a = int(input("Enter the size of array: ")) 25 | for i in range(a): 26 | n = random.randint(1, 100) 27 | l.append(n) 28 | 29 | start = time.time() 30 | heapsort(l, a) 31 | end = time.time() 32 | t = end-start 33 | print(f"heapsort running time: {t:.4f}") 34 | -------------------------------------------------------------------------------- /PythonDSA/insert_binarytree.py: -------------------------------------------------------------------------------- 1 | # Python program to demonstrate 2 | # insert operation in binary search tree 3 | 4 | # A utility class that represents 5 | # an individual node in a BST 6 | 7 | 8 | class Node: 9 | def __init__(self, key): 10 | self.left = None 11 | self.right = None 12 | self.val = key 13 | 14 | # A utility function to insert 15 | # a new node with the given key 16 | 17 | 18 | def insert(root, key): 19 | if root is None: 20 | return Node(key) 21 | else: 22 | if root.val == key: 23 | return root 24 | elif root.val < key: 25 | root.right = insert(root.right, key) 26 | else: 27 | root.left = insert(root.left, key) 28 | return root 29 | 30 | # A utility function to do inorder tree traversal 31 | 32 | 33 | def inorder(root): 34 | if root: 35 | inorder(root.left) 36 | print(root.val) 37 | inorder(root.right) 38 | 39 | 40 | # Driver program to test the above functions 41 | # Let us create the following BST 42 | # 50 43 | # / \ 44 | # 30 70 45 | # / \ / \ 46 | # 20 40 60 80 47 | 48 | r = Node(50) 49 | r = insert(r, 30) 50 | r = insert(r, 20) 51 | r = insert(r, 40) 52 | r = insert(r, 70) 53 | r = insert(r, 60) 54 | r = insert(r, 80) 55 | 56 | # Print inoder traversal of the BST 57 | inorder(r) 58 | -------------------------------------------------------------------------------- /PythonDSA/linked.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | #Traversing and printing the list 10 | def listprint(self): 11 | printval = self.headval 12 | while printval is not None: 13 | print (printval.dataval) 14 | printval = printval.nextval 15 | 16 | list1 = SLinkedList() 17 | lis=[] 18 | print("Enter 10 elements") 19 | for i in range(10): 20 | a=int(input()) 21 | lis.append(a); 22 | list1.headval = Node(lis[0]) 23 | printval = list1.headval 24 | for i in range(1,10): 25 | e=Node(lis[i]) 26 | printval.nextval=e 27 | printval=printval.nextval 28 | print("printed linked list is:") 29 | list1.listprint() 30 | -------------------------------------------------------------------------------- /PythonDSA/linked_list_advance.py: -------------------------------------------------------------------------------- 1 | """ 2 | Linked List implementation with many features, including, append, push, append at position, delete at position, detect cycle, etc. 3 | """ 4 | 5 | class Node: 6 | def __init__(self, data): 7 | self.data = data 8 | self.next = None 9 | 10 | class LinkedList: 11 | def __init__(self): 12 | self.head = None 13 | 14 | def print_list(self): 15 | temp = self.head 16 | while temp: 17 | print(temp.data, end=" ") 18 | temp = temp.next 19 | print() 20 | 21 | def push(self, data): 22 | new_node = Node(data) 23 | new_node.next = self.head 24 | self.head = new_node 25 | 26 | def append(self, data): 27 | new_node = Node(data) 28 | if self.head is None: 29 | self.head = new_node 30 | return 31 | temp = self.head 32 | while temp.next: 33 | temp = temp.next 34 | temp.next = new_node 35 | 36 | def insert_after(self, prev_node, data): 37 | if prev_node is None: 38 | print("Previous node cannot be None") 39 | return 40 | new_node = Node(data) 41 | new_node.next = prev_node.next 42 | prev_node.next = new_node 43 | 44 | def delete_node(self, key): 45 | temp = self.head 46 | if temp is not None: 47 | if temp.data == key: 48 | self.head = temp.next 49 | temp = None 50 | return 51 | while temp is not None: 52 | if temp.data == key: 53 | break 54 | prev = temp 55 | temp = temp.next 56 | if temp == None: 57 | return 58 | prev.next = temp.next 59 | temp = None 60 | 61 | def delete_node_at_position(self, position): 62 | if self.head is None: 63 | return 64 | temp = self.head 65 | if position == 0: 66 | self.head = temp.next 67 | temp = None 68 | return 69 | for i in range(position - 1): 70 | temp = temp.next 71 | if temp is None: 72 | break 73 | if temp is None: 74 | return 75 | if temp.next is None: 76 | return 77 | next = temp.next.next 78 | temp.next = None 79 | temp.next = next 80 | 81 | def delete_list(self): 82 | current = self.head 83 | while current: 84 | prev = current.next 85 | del current.data 86 | current = prev 87 | self.head = None 88 | 89 | def count(self): 90 | temp = self.head 91 | count = 0 92 | while temp: 93 | count += 1 94 | temp = temp.next 95 | return count 96 | 97 | def search(self, key): 98 | temp = self.head 99 | while temp: 100 | if temp.data == key: 101 | return True 102 | temp = temp.next 103 | return False 104 | 105 | def get_nth(self, index): 106 | temp = self.head 107 | count = 0 108 | while temp: 109 | if count == index: 110 | return temp.data 111 | count += 1 112 | temp = temp.next 113 | assert(False) 114 | return 0 115 | 116 | def get_nth_from_last(self, index): 117 | temp = self.head 118 | length = 0 119 | while temp: 120 | length += 1 121 | temp = temp.next 122 | if length < index: 123 | return 124 | temp = self.head 125 | for i in range(0, length - index): 126 | temp = temp.next 127 | return temp.data 128 | 129 | def get_middle(self): 130 | slow = self.head 131 | fast = self.head 132 | if self.head is not None: 133 | while fast and fast.next: 134 | fast = fast.next.next 135 | slow = slow.next 136 | return slow.data 137 | return None 138 | 139 | def detect_loop(self): 140 | s = set() 141 | temp = self.head 142 | while temp: 143 | if temp in s: 144 | return True 145 | s.add(temp) 146 | temp = temp.next 147 | return False 148 | 149 | def remove_duplicates(self): 150 | prev = None 151 | dup_values = dict() 152 | temp = self.head 153 | while temp: 154 | if temp.data in dup_values: 155 | prev.next = temp.next 156 | temp = None 157 | else: 158 | dup_values[temp.data] = 1 159 | prev = temp 160 | temp = prev.next 161 | 162 | def reverse(self): 163 | prev = None 164 | current = self.head 165 | while current: 166 | next = current.next 167 | current.next = prev 168 | prev = current 169 | current = next 170 | self.head = prev 171 | 172 | def main(): 173 | llist = LinkedList() 174 | llist.append(6) 175 | llist.push(7) 176 | llist.push(1) 177 | llist.append(4) 178 | llist.insert_after(llist.head.next, 8) 179 | print("Created linked list is: ", end="") 180 | llist.print_list() 181 | print("Element at index 3 is: ", llist.get_nth(3)) 182 | print("Element at index 3 from last is: ", llist.get_nth_from_last(3)) 183 | print("Middle element is: ", llist.get_middle()) 184 | print("Count of nodes is: ", llist.count()) 185 | print("List has loop: ", llist.detect_loop()) 186 | llist.remove_duplicates() 187 | print("List after removing duplicates: ", end="") 188 | llist.print_list() 189 | llist.reverse() 190 | print("List after reversing: ", end="") 191 | llist.print_list() 192 | llist.delete_node(1) 193 | print("List after deleting node 1: ", end="") 194 | llist.print_list() 195 | llist.delete_node_at_position(2) 196 | print("List after deleting node at position 2: ", end="") 197 | llist.print_list() 198 | llist.delete_list() 199 | print("List after deleting entire list: ", end="") 200 | llist.print_list() 201 | 202 | if __name__ == "__main__": 203 | main() 204 | -------------------------------------------------------------------------------- /PythonDSA/priorityqueue.py: -------------------------------------------------------------------------------- 1 | # A simple implementation of Priority Queue 2 | class PriorityQueue(object): 3 | def __init__(self): 4 | self.queue = [] 5 | 6 | def __str__(self): 7 | return ' '.join([str(i) for i in self.queue]) 8 | 9 | # for checking if the queue is empty 10 | def isEmpty(self): 11 | return len(self.queue) == 0 12 | 13 | # for inserting an element in the queue 14 | def insert(self, data): 15 | self.queue.append(data) 16 | 17 | # for popping an element based on Priority 18 | def delete(self): 19 | try: 20 | max_val = 0 21 | for i in range(len(self.queue)): 22 | if self.queue[i] > self.queue[max_val]: 23 | max_val = i 24 | item = self.queue[max_val] 25 | del self.queue[max_val] 26 | return item 27 | except IndexError: 28 | print() 29 | exit() 30 | 31 | if __name__ == '__main__': 32 | myQueue = PriorityQueue() 33 | myQueue.insert(12) 34 | myQueue.insert(1) 35 | myQueue.insert(14) 36 | myQueue.insert(7) 37 | print(myQueue) 38 | while not myQueue.isEmpty(): 39 | print(myQueue.delete()) 40 | -------------------------------------------------------------------------------- /PythonDSA/stack.py: -------------------------------------------------------------------------------- 1 | # Python program to 2 | # demonstrate stack implementation 3 | # using list 4 | 5 | stack = [] 6 | 7 | # append() function to push 8 | # element in the stack 9 | stack.append('a') 10 | stack.append('b') 11 | stack.append('c') 12 | 13 | print('Initial stack') 14 | print(stack) 15 | 16 | # pop() function to pop 17 | # element from stack in 18 | # LIFO order 19 | print('\nElements popped from stack:') 20 | print(stack.pop()) 21 | print(stack.pop()) 22 | print(stack.pop()) 23 | 24 | print('\nStack after elements are popped:') 25 | print(stack) 26 | 27 | # uncommenting print(stack.pop()) 28 | # will cause an IndexError 29 | # as the stack is now empty 30 | -------------------------------------------------------------------------------- /PythonDSA/stack_using_linkedList.py: -------------------------------------------------------------------------------- 1 | # python3 program to Implement a stack 2 | # using singly linked list 3 | 4 | class Node: 5 | 6 | # Class to create nodes of linked list 7 | # constructor initializes node automatically 8 | def __init__(self, data): 9 | self.data = data 10 | self.next = None 11 | 12 | 13 | class Stack: 14 | 15 | # head is default NULL 16 | def __init__(self): 17 | self.head = None 18 | 19 | # Checks if stack is empty 20 | def isempty(self): 21 | if self.head == None: 22 | return True 23 | else: 24 | return False 25 | 26 | # Method to add data to the stack 27 | # adds to the start of the stack 28 | def push(self, data): 29 | 30 | if self.head == None: 31 | self.head = Node(data) 32 | 33 | else: 34 | newnode = Node(data) 35 | newnode.next = self.head 36 | self.head = newnode 37 | 38 | # Remove element that is the current head (start of the stack) 39 | def pop(self): 40 | 41 | if self.isempty(): 42 | return None 43 | 44 | else: 45 | # Removes the head node and makes 46 | # the preceding one the new head 47 | poppednode = self.head 48 | self.head = self.head.next 49 | poppednode.next = None 50 | return poppednode.data 51 | 52 | # Returns the head node data 53 | def peek(self): 54 | 55 | if self.isempty(): 56 | return None 57 | 58 | else: 59 | return self.head.data 60 | 61 | # Prints out the stack 62 | def display(self): 63 | 64 | iternode = self.head 65 | if self.isempty(): 66 | print("Stack Underflow") 67 | 68 | else: 69 | 70 | while(iternode != None): 71 | 72 | print(iternode.data, end = "") 73 | iternode = iternode.next 74 | if(iternode != None): 75 | print(" -> ", end = "") 76 | return 77 | 78 | 79 | # Driver code 80 | if __name__ == "__main__": 81 | MyStack = Stack() 82 | 83 | MyStack.push(11) 84 | MyStack.push(22) 85 | MyStack.push(33) 86 | MyStack.push(44) 87 | 88 | # Display stack elements 89 | MyStack.display() 90 | 91 | # Print top element of stack 92 | print("\nTop element is ", MyStack.peek()) 93 | 94 | # Delete top elements of stack 95 | MyStack.pop() 96 | MyStack.pop() 97 | 98 | # Display stack elements 99 | MyStack.display() 100 | 101 | # Print top element of stack 102 | print("\nTop element is ", MyStack.peek()) 103 | -------------------------------------------------------------------------------- /PythonDSA/traversing.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | 10 | def listprint(self): 11 | printval = self.headval 12 | while printval is not None: 13 | print (printval.dataval) 14 | printval = printval.nextval 15 | 16 | list = SLinkedList() 17 | list.headval = Node("Mon") 18 | e2 = Node("Tue") 19 | e3 = Node("Wed") 20 | 21 | # Link first Node to second node 22 | list.headval.nextval = e2 23 | 24 | # Link second Node to third node 25 | e2.nextval = e3 26 | 27 | list.listprint() -------------------------------------------------------------------------------- /PythonDecorators.py: -------------------------------------------------------------------------------- 1 | #Decorators 2 | 3 | #Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more "Pythonic". 4 | 5 | #To properly explain decorators we will slowly build up from functions. Make sure to run every cell in this Notebook for this lecture to look the same on your own computer. 6 | 7 | 8 | #Creating a Decorator 9 | def new_decorator(func): 10 | 11 | def wrap_func(): 12 | print("Code would be here, before executing the func") 13 | 14 | func() 15 | 16 | print("Code here will execute after the func()") 17 | 18 | return wrap_func 19 | 20 | def func_needs_decorator(): 21 | print("This function is in need of a Decorator") 22 | 23 | #func_needs_decorator() 24 | 25 | This function is in need of a Decorator 26 | -------------------------------------------------------------------------------- /QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int *a, int *b) 5 | { 6 | int t = *a; 7 | *a = *b; 8 | *b = t; 9 | } 10 | 11 | int partition(int arr[], int low, int high) 12 | { 13 | int pivot = arr[high]; // pivot 14 | int i = (low - 1); 15 | 16 | for (int j = low; j <= high - 1; j++) 17 | { 18 | if (arr[j] < pivot) 19 | { 20 | i++; 21 | swap(&arr[i], &arr[j]); 22 | } 23 | } 24 | swap(&arr[i + 1], &arr[high]); 25 | return (i + 1); 26 | } 27 | 28 | void quickSort(int arr[], int low, int high) 29 | { 30 | if (low < high) 31 | { 32 | int pi = partition(arr, low, high); 33 | quickSort(arr, low, pi - 1); 34 | quickSort(arr, pi + 1, high); 35 | } 36 | } 37 | 38 | void printArray(int arr[], int size) 39 | { 40 | int i; 41 | for (i = 0; i < size; i++) 42 | cout << arr[i] << " "; 43 | cout << endl; 44 | } 45 | 46 | int main() 47 | { 48 | int arr[] = {10, 7, 8, 9, 1, 5}; 49 | int n = sizeof(arr) / sizeof(arr[0]); 50 | quickSort(arr, 0, n - 1); 51 | cout << "Sorted array: \n"; 52 | printArray(arr, n); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /RCNN object detection/RCNN demo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Mask R-CNN Demo\n", 8 | "\n", 9 | "A quick intro to using the pre-trained model to detect and segment objects." 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import os\n", 19 | "import sys\n", 20 | "import random\n", 21 | "import math\n", 22 | "import numpy as np\n", 23 | "import skimage.io\n", 24 | "import matplotlib\n", 25 | "import matplotlib.pyplot as plt\n", 26 | "\n", 27 | "# Root directory of the project\n", 28 | "ROOT_DIR = os.path.abspath(\"../\")\n", 29 | "\n", 30 | "# Import Mask RCNN\n", 31 | "sys.path.append(ROOT_DIR) # To find local version of the library\n", 32 | "from mrcnn import utils\n", 33 | "import mrcnn.model as modellib\n", 34 | "from mrcnn import visualize\n", 35 | "# Import COCO config\n", 36 | "sys.path.append(os.path.join(ROOT_DIR, \"samples/coco/\")) # To find local version\n", 37 | "import coco\n", 38 | "\n", 39 | "%matplotlib inline \n", 40 | "\n", 41 | "# Directory to save logs and trained model\n", 42 | "MODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n", 43 | "\n", 44 | "# Local path to trained weights file\n", 45 | "COCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n", 46 | "# Download COCO trained weights from Releases if needed\n", 47 | "if not os.path.exists(COCO_MODEL_PATH):\n", 48 | " utils.download_trained_weights(COCO_MODEL_PATH)\n", 49 | "\n", 50 | "# Directory of images to run detection on\n", 51 | "IMAGE_DIR = os.path.join(ROOT_DIR, \"images\")" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "## Configurations" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "class InferenceConfig(coco.CocoConfig):\n", 68 | " # Set batch size to 1 since we'll be running inference on\n", 69 | " # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n", 70 | " GPU_COUNT = 1\n", 71 | " IMAGES_PER_GPU = 1\n", 72 | "\n", 73 | "config = InferenceConfig()\n", 74 | "config.display()" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "metadata": {}, 80 | "source": [ 81 | "## Create Model and Load Trained Weights" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "metadata": { 88 | "collapsed": true, 89 | "scrolled": false 90 | }, 91 | "outputs": [], 92 | "source": [ 93 | "# Create model object in inference mode.\n", 94 | "model = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n", 95 | "\n", 96 | "# Load weights trained on MS-COCO\n", 97 | "model.load_weights(COCO_MODEL_PATH, by_name=True)" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "## Class Names" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "metadata": { 111 | "collapsed": true 112 | }, 113 | "outputs": [], 114 | "source": [ 115 | "# COCO Class names\n", 116 | "# Index of the class in the list is its ID. For example, to get ID of\n", 117 | "# the teddy bear class, use: class_names.index('teddy bear')\n", 118 | "class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n", 119 | " 'bus', 'train', 'truck', 'boat', 'traffic light',\n", 120 | " 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n", 121 | " 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n", 122 | " 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n", 123 | " 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n", 124 | " 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n", 125 | " 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n", 126 | " 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n", 127 | " 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n", 128 | " 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n", 129 | " 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n", 130 | " 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n", 131 | " 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n", 132 | " 'teddy bear', 'hair drier', 'toothbrush']" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "## Run Object Detection" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "scrolled": false 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "# Load a random image from the images folder\n", 151 | "file_names = next(os.walk(IMAGE_DIR))[2]\n", 152 | "image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))\n", 153 | "\n", 154 | "# Run detection\n", 155 | "results = model.detect([image], verbose=1)\n", 156 | "\n", 157 | "# Visualize results\n", 158 | "r = results[0]\n", 159 | "visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n", 160 | " class_names, r['scores'])" 161 | ] 162 | } 163 | ], 164 | "metadata": { 165 | "kernelspec": { 166 | "display_name": "Python 3.9.6 64-bit", 167 | "language": "python", 168 | "name": "python3" 169 | }, 170 | "language_info": { 171 | "codemirror_mode": { 172 | "name": "ipython", 173 | "version": 3 174 | }, 175 | "file_extension": ".py", 176 | "mimetype": "text/x-python", 177 | "name": "python", 178 | "nbconvert_exporter": "python", 179 | "pygments_lexer": "ipython3", 180 | "version": "3.9.6" 181 | }, 182 | "vscode": { 183 | "interpreter": { 184 | "hash": "ecdd6f9454a6b285b6bbad304ddaf73cd5eb009f60cedde024860756b5c5c23b" 185 | } 186 | } 187 | }, 188 | "nbformat": 4, 189 | "nbformat_minor": 2 190 | } 191 | -------------------------------------------------------------------------------- /RCNN object detection/mrcnn/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /RCNN object detection/mrcnn/config.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mask R-CNN 3 | Base Configurations class. 4 | 5 | Copyright (c) 2017 Matterport, Inc. 6 | Licensed under the MIT License (see LICENSE for details) 7 | Written by Waleed Abdulla 8 | """ 9 | 10 | import numpy as np 11 | 12 | 13 | # Base Configuration Class 14 | # Don't use this class directly. Instead, sub-class it and override 15 | # the configurations you need to change. 16 | 17 | class Config(object): 18 | """Base configuration class. For custom configurations, create a 19 | sub-class that inherits from this one and override properties 20 | that need to be changed. 21 | """ 22 | # Name the configurations. For example, 'COCO', 'Experiment 3', ...etc. 23 | # Useful if your code needs to do things differently depending on which 24 | # experiment is running. 25 | NAME = None # Override in sub-classes 26 | 27 | # NUMBER OF GPUs to use. When using only a CPU, this needs to be set to 1. 28 | GPU_COUNT = 1 29 | 30 | # Number of images to train with on each GPU. A 12GB GPU can typically 31 | # handle 2 images of 1024x1024px. 32 | # Adjust based on your GPU memory and image sizes. Use the highest 33 | # number that your GPU can handle for best performance. 34 | IMAGES_PER_GPU = 2 35 | 36 | # Number of training steps per epoch 37 | # This doesn't need to match the size of the training set. Tensorboard 38 | # updates are saved at the end of each epoch, so setting this to a 39 | # smaller number means getting more frequent TensorBoard updates. 40 | # Validation stats are also calculated at each epoch end and they 41 | # might take a while, so don't set this too small to avoid spending 42 | # a lot of time on validation stats. 43 | STEPS_PER_EPOCH = 1000 44 | 45 | # Number of validation steps to run at the end of every training epoch. 46 | # A bigger number improves accuracy of validation stats, but slows 47 | # down the training. 48 | VALIDATION_STEPS = 50 49 | 50 | # Backbone network architecture 51 | # Supported values are: resnet50, resnet101. 52 | # You can also provide a callable that should have the signature 53 | # of model.resnet_graph. If you do so, you need to supply a callable 54 | # to COMPUTE_BACKBONE_SHAPE as well 55 | BACKBONE = "resnet101" 56 | 57 | # Only useful if you supply a callable to BACKBONE. Should compute 58 | # the shape of each layer of the FPN Pyramid. 59 | # See model.compute_backbone_shapes 60 | COMPUTE_BACKBONE_SHAPE = None 61 | 62 | # The strides of each layer of the FPN Pyramid. These values 63 | # are based on a Resnet101 backbone. 64 | BACKBONE_STRIDES = [4, 8, 16, 32, 64] 65 | 66 | # Size of the fully-connected layers in the classification graph 67 | FPN_CLASSIF_FC_LAYERS_SIZE = 1024 68 | 69 | # Size of the top-down layers used to build the feature pyramid 70 | TOP_DOWN_PYRAMID_SIZE = 256 71 | 72 | # Number of classification classes (including background) 73 | NUM_CLASSES = 1 # Override in sub-classes 74 | 75 | # Length of square anchor side in pixels 76 | RPN_ANCHOR_SCALES = (32, 64, 128, 256, 512) 77 | 78 | # Ratios of anchors at each cell (width/height) 79 | # A value of 1 represents a square anchor, and 0.5 is a wide anchor 80 | RPN_ANCHOR_RATIOS = [0.5, 1, 2] 81 | 82 | # Anchor stride 83 | # If 1 then anchors are created for each cell in the backbone feature map. 84 | # If 2, then anchors are created for every other cell, and so on. 85 | RPN_ANCHOR_STRIDE = 1 86 | 87 | # Non-max suppression threshold to filter RPN proposals. 88 | # You can increase this during training to generate more propsals. 89 | RPN_NMS_THRESHOLD = 0.7 90 | 91 | # How many anchors per image to use for RPN training 92 | RPN_TRAIN_ANCHORS_PER_IMAGE = 256 93 | 94 | # ROIs kept after tf.nn.top_k and before non-maximum suppression 95 | PRE_NMS_LIMIT = 6000 96 | 97 | # ROIs kept after non-maximum suppression (training and inference) 98 | POST_NMS_ROIS_TRAINING = 2000 99 | POST_NMS_ROIS_INFERENCE = 1000 100 | 101 | # If enabled, resizes instance masks to a smaller size to reduce 102 | # memory load. Recommended when using high-resolution images. 103 | USE_MINI_MASK = True 104 | MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask 105 | 106 | # Input image resizing 107 | # Generally, use the "square" resizing mode for training and predicting 108 | # and it should work well in most cases. In this mode, images are scaled 109 | # up such that the small side is = IMAGE_MIN_DIM, but ensuring that the 110 | # scaling doesn't make the long side > IMAGE_MAX_DIM. Then the image is 111 | # padded with zeros to make it a square so multiple images can be put 112 | # in one batch. 113 | # Available resizing modes: 114 | # none: No resizing or padding. Return the image unchanged. 115 | # square: Resize and pad with zeros to get a square image 116 | # of size [max_dim, max_dim]. 117 | # pad64: Pads width and height with zeros to make them multiples of 64. 118 | # If IMAGE_MIN_DIM or IMAGE_MIN_SCALE are not None, then it scales 119 | # up before padding. IMAGE_MAX_DIM is ignored in this mode. 120 | # The multiple of 64 is needed to ensure smooth scaling of feature 121 | # maps up and down the 6 levels of the FPN pyramid (2**6=64). 122 | # crop: Picks random crops from the image. First, scales the image based 123 | # on IMAGE_MIN_DIM and IMAGE_MIN_SCALE, then picks a random crop of 124 | # size IMAGE_MIN_DIM x IMAGE_MIN_DIM. Can be used in training only. 125 | # IMAGE_MAX_DIM is not used in this mode. 126 | IMAGE_RESIZE_MODE = "square" 127 | IMAGE_MIN_DIM = 800 128 | IMAGE_MAX_DIM = 1024 129 | # Minimum scaling ratio. Checked after MIN_IMAGE_DIM and can force further 130 | # up scaling. For example, if set to 2 then images are scaled up to double 131 | # the width and height, or more, even if MIN_IMAGE_DIM doesn't require it. 132 | # However, in 'square' mode, it can be overruled by IMAGE_MAX_DIM. 133 | IMAGE_MIN_SCALE = 0 134 | # Number of color channels per image. RGB = 3, grayscale = 1, RGB-D = 4 135 | # Changing this requires other changes in the code. See the WIKI for more 136 | # details: https://github.com/matterport/Mask_RCNN/wiki 137 | IMAGE_CHANNEL_COUNT = 3 138 | 139 | # Image mean (RGB) 140 | MEAN_PIXEL = np.array([123.7, 116.8, 103.9]) 141 | 142 | # Number of ROIs per image to feed to classifier/mask heads 143 | # The Mask RCNN paper uses 512 but often the RPN doesn't generate 144 | # enough positive proposals to fill this and keep a positive:negative 145 | # ratio of 1:3. You can increase the number of proposals by adjusting 146 | # the RPN NMS threshold. 147 | TRAIN_ROIS_PER_IMAGE = 200 148 | 149 | # Percent of positive ROIs used to train classifier/mask heads 150 | ROI_POSITIVE_RATIO = 0.33 151 | 152 | # Pooled ROIs 153 | POOL_SIZE = 7 154 | MASK_POOL_SIZE = 14 155 | 156 | # Shape of output mask 157 | # To change this you also need to change the neural network mask branch 158 | MASK_SHAPE = [28, 28] 159 | 160 | # Maximum number of ground truth instances to use in one image 161 | MAX_GT_INSTANCES = 100 162 | 163 | # Bounding box refinement standard deviation for RPN and final detections. 164 | RPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2]) 165 | BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2]) 166 | 167 | # Max number of final detections 168 | DETECTION_MAX_INSTANCES = 100 169 | 170 | # Minimum probability value to accept a detected instance 171 | # ROIs below this threshold are skipped 172 | DETECTION_MIN_CONFIDENCE = 0.7 173 | 174 | # Non-maximum suppression threshold for detection 175 | DETECTION_NMS_THRESHOLD = 0.3 176 | 177 | # Learning rate and momentum 178 | # The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes 179 | # weights to explode. Likely due to differences in optimizer 180 | # implementation. 181 | LEARNING_RATE = 0.0005 182 | LEARNING_MOMENTUM = 0.9 183 | 184 | # Weight decay regularization 185 | WEIGHT_DECAY = 0.0001 186 | 187 | # Loss weights for more precise optimization. 188 | # Can be used for R-CNN training setup. 189 | LOSS_WEIGHTS = { 190 | "rpn_class_loss": 1., 191 | "rpn_bbox_loss": 1., 192 | "mrcnn_class_loss": 1., 193 | "mrcnn_bbox_loss": 1., 194 | "mrcnn_mask_loss": 1. 195 | } 196 | 197 | # Use RPN ROIs or externally generated ROIs for training 198 | # Keep this True for most situations. Set to False if you want to train 199 | # the head branches on ROI generated by code rather than the ROIs from 200 | # the RPN. For example, to debug the classifier head without having to 201 | # train the RPN. 202 | USE_RPN_ROIS = True 203 | 204 | # Train or freeze batch normalization layers 205 | # None: Train BN layers. This is the normal mode 206 | # False: Freeze BN layers. Good when using a small batch size 207 | # True: (don't use). Set layer in training mode even when predicting 208 | TRAIN_BN = False # Defaulting to False since batch size is often small 209 | 210 | # Gradient norm clipping 211 | GRADIENT_CLIP_NORM = 5.0 212 | 213 | def __init__(self): 214 | """Set values of computed attributes.""" 215 | # Effective batch size 216 | self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT 217 | 218 | # Input image size 219 | if self.IMAGE_RESIZE_MODE == "crop": 220 | self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, 221 | self.IMAGE_CHANNEL_COUNT]) 222 | else: 223 | self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM, 224 | self.IMAGE_CHANNEL_COUNT]) 225 | 226 | # Image meta data length 227 | # See compose_image_meta() for details 228 | self.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSES 229 | 230 | def display(self): 231 | """Display Configuration values.""" 232 | print("\nConfigurations:") 233 | for a in dir(self): 234 | if not a.startswith("__") and not callable(getattr(self, a)): 235 | print("{:30} {}".format(a, getattr(self, a))) 236 | print("\n") 237 | -------------------------------------------------------------------------------- /RCNN object detection/mrcnn/parallel_model.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mask R-CNN 3 | Multi-GPU Support for Keras. 4 | 5 | Copyright (c) 2017 Matterport, Inc. 6 | Licensed under the MIT License (see LICENSE for details) 7 | Written by Waleed Abdulla 8 | 9 | Ideas and a small code snippets from these sources: 10 | https://github.com/fchollet/keras/issues/2436 11 | https://medium.com/@kuza55/transparent-multi-gpu-training-on-tensorflow-with-keras-8b0016fd9012 12 | https://github.com/avolkov1/keras_experiments/blob/master/keras_exp/multigpu/ 13 | https://github.com/fchollet/keras/blob/master/keras/utils/training_utils.py 14 | """ 15 | 16 | import tensorflow as tf 17 | import keras.backend as K 18 | import keras.layers as KL 19 | import keras.models as KM 20 | 21 | 22 | class ParallelModel(KM.Model): 23 | """Subclasses the standard Keras Model and adds multi-GPU support. 24 | It works by creating a copy of the model on each GPU. Then it slices 25 | the inputs and sends a slice to each copy of the model, and then 26 | merges the outputs together and applies the loss on the combined 27 | outputs. 28 | """ 29 | 30 | def __init__(self, keras_model, gpu_count): 31 | """Class constructor. 32 | keras_model: The Keras model to parallelize 33 | gpu_count: Number of GPUs. Must be > 1 34 | """ 35 | self.inner_model = keras_model 36 | self.gpu_count = gpu_count 37 | merged_outputs = self.make_parallel() 38 | super(ParallelModel, self).__init__(inputs=self.inner_model.inputs, 39 | outputs=merged_outputs) 40 | 41 | def __getattribute__(self, attrname): 42 | """Redirect loading and saving methods to the inner model. That's where 43 | the weights are stored.""" 44 | if 'load' in attrname or 'save' in attrname: 45 | return getattr(self.inner_model, attrname) 46 | return super(ParallelModel, self).__getattribute__(attrname) 47 | 48 | def summary(self, *args, **kwargs): 49 | """Override summary() to display summaries of both, the wrapper 50 | and inner models.""" 51 | super(ParallelModel, self).summary(*args, **kwargs) 52 | self.inner_model.summary(*args, **kwargs) 53 | 54 | def make_parallel(self): 55 | """Creates a new wrapper model that consists of multiple replicas of 56 | the original model placed on different GPUs. 57 | """ 58 | # Slice inputs. Slice inputs on the CPU to avoid sending a copy 59 | # of the full inputs to all GPUs. Saves on bandwidth and memory. 60 | input_slices = {name: tf.split(x, self.gpu_count) 61 | for name, x in zip(self.inner_model.input_names, 62 | self.inner_model.inputs)} 63 | 64 | output_names = self.inner_model.output_names 65 | outputs_all = [] 66 | for i in range(len(self.inner_model.outputs)): 67 | outputs_all.append([]) 68 | 69 | # Run the model call() on each GPU to place the ops there 70 | for i in range(self.gpu_count): 71 | with tf.device('/gpu:%d' % i): 72 | with tf.name_scope('tower_%d' % i): 73 | # Run a slice of inputs through this replica 74 | zipped_inputs = zip(self.inner_model.input_names, 75 | self.inner_model.inputs) 76 | inputs = [ 77 | KL.Lambda(lambda s: input_slices[name][i], 78 | output_shape=lambda s: (None,) + s[1:])(tensor) 79 | for name, tensor in zipped_inputs] 80 | # Create the model replica and get the outputs 81 | outputs = self.inner_model(inputs) 82 | if not isinstance(outputs, list): 83 | outputs = [outputs] 84 | # Save the outputs for merging back together later 85 | for l, o in enumerate(outputs): 86 | outputs_all[l].append(o) 87 | 88 | # Merge outputs on CPU 89 | with tf.device('/cpu:0'): 90 | merged = [] 91 | for outputs, name in zip(outputs_all, output_names): 92 | # Concatenate or average outputs? 93 | # Outputs usually have a batch dimension and we concatenate 94 | # across it. If they don't, then the output is likely a loss 95 | # or a metric value that gets averaged across the batch. 96 | # Keras expects losses and metrics to be scalars. 97 | if K.int_shape(outputs[0]) == (): 98 | # Average 99 | m = KL.Lambda(lambda o: tf.add_n(o) / len(outputs), name=name)(outputs) 100 | else: 101 | # Concatenate 102 | m = KL.Concatenate(axis=0, name=name)(outputs) 103 | merged.append(m) 104 | return merged 105 | 106 | 107 | if __name__ == "__main__": 108 | # Testing code below. It creates a simple model to train on MNIST and 109 | # tries to run it on 2 GPUs. It saves the graph so it can be viewed 110 | # in TensorBoard. Run it as: 111 | # 112 | # python3 parallel_model.py 113 | 114 | import os 115 | import numpy as np 116 | import keras.optimizers 117 | from keras.datasets import mnist 118 | from keras.preprocessing.image import ImageDataGenerator 119 | 120 | GPU_COUNT = 2 121 | 122 | # Root directory of the project 123 | ROOT_DIR = os.path.abspath("../") 124 | 125 | # Directory to save logs and trained model 126 | MODEL_DIR = os.path.join(ROOT_DIR, "logs") 127 | 128 | def build_model(x_train, num_classes): 129 | # Reset default graph. Keras leaves old ops in the graph, 130 | # which are ignored for execution but clutter graph 131 | # visualization in TensorBoard. 132 | tf.reset_default_graph() 133 | 134 | inputs = KL.Input(shape=x_train.shape[1:], name="input_image") 135 | x = KL.Conv2D(32, (3, 3), activation='relu', padding="same", 136 | name="conv1")(inputs) 137 | x = KL.Conv2D(64, (3, 3), activation='relu', padding="same", 138 | name="conv2")(x) 139 | x = KL.MaxPooling2D(pool_size=(2, 2), name="pool1")(x) 140 | x = KL.Flatten(name="flat1")(x) 141 | x = KL.Dense(128, activation='relu', name="dense1")(x) 142 | x = KL.Dense(num_classes, activation='softmax', name="dense2")(x) 143 | 144 | return KM.Model(inputs, x, "digit_classifier_model") 145 | 146 | # Load MNIST Data 147 | (x_train, y_train), (x_test, y_test) = mnist.load_data() 148 | x_train = np.expand_dims(x_train, -1).astype('float32') / 255 149 | x_test = np.expand_dims(x_test, -1).astype('float32') / 255 150 | 151 | print('x_train shape:', x_train.shape) 152 | print('x_test shape:', x_test.shape) 153 | 154 | # Build data generator and model 155 | datagen = ImageDataGenerator() 156 | model = build_model(x_train, 10) 157 | 158 | # Add multi-GPU support. 159 | model = ParallelModel(model, GPU_COUNT) 160 | 161 | optimizer = keras.optimizers.SGD(lr=0.01, momentum=0.9, clipnorm=5.0) 162 | 163 | model.compile(loss='sparse_categorical_crossentropy', 164 | optimizer=optimizer, metrics=['accuracy']) 165 | 166 | model.summary() 167 | 168 | # Train 169 | model.fit_generator( 170 | datagen.flow(x_train, y_train, batch_size=64), 171 | steps_per_epoch=50, epochs=10, verbose=1, 172 | validation_data=(x_test, y_test), 173 | callbacks=[keras.callbacks.TensorBoard(log_dir=MODEL_DIR, 174 | write_graph=True)] 175 | ) 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-learning-codes 2 | # data-structure-# Hacktoberfest-2022🔥 3 | ![image](https://user-images.githubusercontent.com/70385488/192114009-0830321a-d227-4a4d-8411-6c03b54d7ce6.png) 4 | 5 |
6 | 7 | 8 | ### This repository aims to help code beginners with their first successful pull request and open-source contribution. :partying_face: 9 | 10 | :star: Feel free to use this project to make your first contribution to an open-source project on GitHub. Practice making your first pull request to a public repository before doing the real thing! 11 | 12 | :star: Make sure to grab some cool swags during Hacktoberfest by getting involved in the open-source community. 13 | 14 | ### This repository is open to all members of the GitHub community. Any member can contribute to this project! The only thing which you need to keep in mind is that it should be genuine PR :grin: 15 | 16 | ## What is Hacktoberfest? :thinking: 17 | A month-long celebration from October 1st to October 31st presented by [Digital Ocean](https://hacktoberfest.digitalocean.com/) and [DEV Community](https://dev.to/) collaborated with [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open-source developer community. 18 | 19 | [https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/) 20 | 21 | ## Rules :fire: 22 | To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repo on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt. 23 | -------------------------------------------------------------------------------- /Sets.py: -------------------------------------------------------------------------------- 1 | #set :- {1,2,3,4}-unique and unordered 2 | ''' 3 | Sets are initialized using curly braces {} or set() in python. 4 | A python set is basically an unordered collection of unique values, i.e. it will 5 | automatically remove duplicate values from the set. 6 | ''' 7 | set1 = {1,2,3} 8 | print('set : ',set1) 9 | set2 = set(['tea','coffee','colddrink','soda','tea','Coffee']) 10 | print('set : ',set2) 11 | dup_set={1,1,1,1,1,2,2,2,4,4,56,5,5,4,6,4,56,4,4,5,4,5} 12 | print(dup_set) 13 | 14 | #using the add() method we can add single element in the set 15 | dup_set.add(456) 16 | print(dup_set) 17 | 18 | #using the update() method we can add multiple elements in the set 19 | dup_set.update(['water','drink','coca']) 20 | print(dup_set) 21 | 22 | #deleting an element within the set 23 | dup_set.remove(1) 24 | # dup_set.remove(1)#IF ELEMETN IS NOT PRESENT IN THE SET THEN remove() method raise an error 25 | print('after deleting : ', dup_set) 26 | 27 | #discard method does not raise an error 28 | dup_set.discard(2) 29 | dup_set.discard(12)#doesn't raise an error 30 | print("after discarding", dup_set) 31 | 32 | 33 | #OPERATORS IN THE SETS 34 | """ 35 | | (Union)->Returns all the unique elements in both the sets. 36 | & (Intersection) -> Returns all the elements common to both the sets. 37 | - (Difference)-> Returns the elements that are unique to the first set 38 | ^(Symmetric Difference) -> Returns all the elements not common to both the sets. 39 | 40 | """ 41 | set_A={1,5,2,84,2,4,5} 42 | print('Set A : ', set_A) 43 | 44 | set_B ={2,5,32,4,2,8,5,6} 45 | print('Set B : ', set_B) 46 | 47 | #intersection of two sets 48 | print('Intersection : ',set_A&set_B) 49 | 50 | #union of two sets 51 | print('Union : ', set_A|set_B) 52 | 53 | #difference of two sets 54 | print('Difference :', set_A-set_B)#consider only unique in first set(not consider common with other sets ) 55 | 56 | #symetric difference of two sets 57 | print("Symetric Difference : ",set_A^set_B)#neglact the common in both sets -------------------------------------------------------------------------------- /Sorting_List.py: -------------------------------------------------------------------------------- 1 | 2 | #Sorting list in lexicographic order 3 | example_list = ['pineapple','banana','vaaabbbcc','apple','grapes','orange'] 4 | print('before Sorting : ',example_list) 5 | example_list.sort() 6 | print('after Sorting : ', example_list) 7 | 8 | #sorting list in ascending order 9 | example=[3,5,7,21,5,6,78,4,1,0,4] 10 | print('before Sorting :',example) 11 | example.sort() 12 | print('Sort in Ascending order : ', example) 13 | 14 | #sorting list in descending order 15 | example2=[3,5,7,21,5,6,78,4,1,0,4] 16 | print('before Sorting :',example2) 17 | example2.sort(reverse=True) 18 | print('Sort in descending order : ', example2) 19 | -------------------------------------------------------------------------------- /Sple_Exception.py: -------------------------------------------------------------------------------- 1 | def divid(a , divisor): 2 | try: 3 | return a/divisor 4 | except ZeroDivisionError as e: 5 | print('Divisor never be Zero !! Error Divide Terminating') 6 | finally: 7 | print('$$$$ divide successful $$$$') 8 | 9 | print(divid(34,1)) 10 | print('program end.') -------------------------------------------------------------------------------- /Standard_Function.py: -------------------------------------------------------------------------------- 1 | #1 print() 2 | var = 'hello learners' 3 | print(var) 4 | print('This is line no.',4 ) 5 | print(123486) 6 | a=[3,5,74,7] 7 | print(a) 8 | a='hello, ' 9 | b='rishabh ' 10 | print(a+b+'yadav') 11 | 12 | #2 input() 13 | a = input() #number input in a 14 | print('this is a = {}'.format(a)) 15 | a=input() 16 | print(a) 17 | myName=input() 18 | print('Hello, {}'.format(myName)) 19 | 20 | #3 len()-The len() function is used find the length(number of elements) 21 | # of any python container like string, list, dictionary, tuple, etc. 22 | a='hello ' 23 | print(len(a)) 24 | b="good boy"#for string 25 | print(len(b)) 26 | a=[4,5,74,3,4]#for list 27 | print(len(a)) 28 | a=('x','y','z')#for tuples 29 | print(a) 30 | print(len(a)) 31 | 32 | 33 | #4 ord() - The ord() function in Python will return an 34 | #integer that represents the Unicode Character passed into it. 35 | #It takes a single character as a parameter. 36 | 37 | print(ord('a')) 38 | print(ord('b')) 39 | print(ord('A')) 40 | print(ord('$')) -------------------------------------------------------------------------------- /Star.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | 3 | drawing_area = Screen() 4 | drawing_area.setup(width=750, height=500) 5 | shape('triangle') 6 | 7 | 8 | def draw_triangle(length=150): 9 | for i in range(3): 10 | forward(length) 11 | left(120) 12 | 13 | 14 | for i in range(40): 15 | draw_triangle() 16 | right(10) 17 | 18 | done() -------------------------------------------------------------------------------- /Starting.py: -------------------------------------------------------------------------------- 1 | print("Starting python .........") -------------------------------------------------------------------------------- /StringManuplation.py: -------------------------------------------------------------------------------- 1 | #Escapes sequences in string 2 | print('this is used to \n new line') 3 | print('this is used to \t tab escape') 4 | print('this is ued to print backslash \\') 5 | print('your\'s is written like this ') 6 | 7 | 8 | 9 | #multiple string 10 | a ='''\nthis hwo 11 | you 12 | can do 13 | this . 14 | using this you can write multiple lines 15 | as ''' 16 | print(a) 17 | 18 | #String indexing 19 | 20 | print('\n') 21 | # p y t h o n 22 | # 0 1 2 3 4 5 23 | # -6 -5 -4 -3 -2 -1 24 | p = 'python' 25 | print(p[0],p[2],p[4],p[5]) 26 | print(p[-1],p[-2],p[-4],p[-6]) 27 | 28 | # String slicing 29 | print(p[-6:-4]) 30 | print(p[2:6]) 31 | print(p[3:-1]) 32 | 33 | # Case Conversion Functions 34 | first_name ='rishabh' 35 | #1 upper 36 | print('upper case - ',first_name.upper()) 37 | last_name = 'YaDav' 38 | #2 lower 39 | print('lower case - ',last_name.lower()) 40 | print('first name is lower or not - ',first_name.islower()) 41 | print('last name is upper or not - ',last_name.isupper()) 42 | print('first name is lower or not - ',first_name.upper().islower()) 43 | print('last name is upper or not - ',last_name.upper().isupper()) 44 | 45 | #string join() and split() function 46 | temp_list = ['hello','how ,are ,you'] 47 | s=' '.join(temp_list) 48 | print(s) 49 | newlist = s.split(',') 50 | print(newlist) 51 | 52 | first = "first" 53 | second = "second" 54 | s = "Sunday is the {} day of the week, whereas Monday is the {} day of the week".format(first, second) 55 | print(s) 56 | -------------------------------------------------------------------------------- /StringTemplate.py: -------------------------------------------------------------------------------- 1 | from string import Template 2 | 3 | nam = "Rishabh yadav" 4 | t = Template('hello ! $w ') 5 | 6 | print(t.substitute(w = nam)) -------------------------------------------------------------------------------- /String_demonstration_1.py: -------------------------------------------------------------------------------- 1 | # IN this we will see how to produce different output with same string 2 | s = "Bamboozled" 3 | # extract B a 4 | print(s[0], s[1]) # using normal indexing 5 | print(s[-10], s[-9]) # using negative indexing 6 | # extract e d 7 | print(s[8], s[9]) # using normal indexing 8 | print(s[-2], s[-1]) # using negative indexing 9 | # extract mboozled 10 | print(s[2:10]) # specifying from start to end 11 | print(s[2:]) # specifying from and not giving end 12 | print(s[-8:]) # using negative indexing 13 | # extract Bamboo 14 | print(s[0:6]) # using normal indexing 15 | print(s[:6]) #not speciying the first caharcter by speciying the last 16 | print(s[-10:-4]) 17 | print(s[:-4]) 18 | #reverse Bamboozled 19 | print(s[::-1])#this will reverse the Bamboozled 20 | print(s[0:10:1]) 21 | print(s[0:10:2])#this will print after 2 character 22 | print(s[0:10:3]) 23 | print(s[0:10:4]) 24 | s=s+"Hype!"#concating the hype 25 | print(s) 26 | s=s[:6]+"Monger"+s[-1] #how to add any word in between 27 | print(s) 28 | -------------------------------------------------------------------------------- /String_slicing.py: -------------------------------------------------------------------------------- 1 | str1 = "Lokesh is learning python" 2 | print(str1) 3 | # print(str1[:6]) print "Lokesh" because it's starting default value is 0 4 | 5 | # print(str1[0:]) print "Lokesh" because it's Last default value is string length 6 | # print(str1[:]) print complete string becuse starting default value is 0 and last value is string length 7 | 8 | # print(str1[1]) print o because index start from 0 9 | 10 | # print(len(str1)) print string length 11 | 12 | # print(str1[0:6]) print Lokesh and in this 0 is included and 6 is exclude it will go from 0 - (n-1), so we have to give 1 extra index 13 | 14 | # print(str1[0:25]) print complete string 15 | 16 | # print(str1[0:6:2]) print "Lks" because first it will go from[0:6] that is lokesh and then[0:6:2] means leave multiple of two or every second character. 17 | -------------------------------------------------------------------------------- /Text repetition N number.py: -------------------------------------------------------------------------------- 1 | import pyautogui as pg 2 | import time 3 | time.sleep(10) 4 | 5 | for i in range(10): #range defines no of times 6 | pg.write('Enter your text') 7 | pg.press('Enter') 8 | -------------------------------------------------------------------------------- /Time_difference.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import process_time 3 | pylist=[i for i in range(100)] 4 | start=process_time() 5 | pylist=[i+5 for i in pylist] 6 | end=process_time() 7 | print("Time taken by python list:",end-start) 8 | pyarray=np.array(pylist) 9 | start1=process_time() 10 | pyarray=pyarray+5 11 | end1=process_time() 12 | print("Time taken by numpy array:",end1-start1) 13 | -------------------------------------------------------------------------------- /Tuples.py: -------------------------------------------------------------------------------- 1 | #Tuples in python 2 | ''' 3 | Tuples are entities in Python that work almost similar to that of lists, but differ in the 4 | main feature from lists, is in that they are inmutable. 5 | They are initialized by writing the elements of the tuple with (), separated by 6 | commas. 7 | ''' 8 | 9 | #Defining and initializing a tuple name - example 10 | example = ('first','second','third','fourth') 11 | # example[1]="pahela" #This is not supported by tuple 12 | print(example) 13 | print(example[0]) 14 | print(example[3]) 15 | print(example[1:3])#print the indexno.-1 , indexno.-2 16 | 17 | 18 | #type converting between tuple ,lists and strings 19 | demo_list = list(example) 20 | print('Tuple converted into list -> ',demo_list) 21 | 22 | demo_tuple = tuple(demo_list) 23 | print('List converted into tuple : ',demo_tuple) 24 | 25 | list_string = list('rishabh') 26 | tuple_string = tuple('rishabh') 27 | print(list_string) 28 | print(tuple_string) -------------------------------------------------------------------------------- /Type_Casting.py: -------------------------------------------------------------------------------- 1 | """ 2 | TYPE CASTING - Two types 3 | 1. Implicit type casting--->: In implicit type casting, the python compiler 4 | internally typecasts one variable into another type without the external 5 | action of the user. 6 | 7 | Example:- 8 | 9 | """ 10 | int_num=4 11 | float_num=7.9 12 | ans = int_num+float_num 13 | print('Int num type =',type(int_num)) 14 | print('ans num type = ',type(ans)) 15 | #ans is automatic typed casted 16 | # into float type for greater precision 17 | print('Float num type = ',type(float_num)) 18 | 19 | 20 | #Explicit Type Casting: In explicit type casting, the user 21 | # explicitly forces the compiler to convert a variable 22 | # from one type to another. The different ways of 23 | # explicit typecasting are given below: 24 | 25 | #1.)Integer to String or Float: 26 | """ 27 | To typecast an integer into a string type, 28 | we use the str() method. Similarly, to typecast 29 | it into a float type, we use the float() method. 30 | For example: 31 | """ 32 | 33 | var = 123 34 | print("this is string-"+str(var)) 35 | var = 23 36 | print(float(var)) 37 | 38 | #2.) Float to integer 39 | 40 | f=56.39 41 | print(int(f)) 42 | 43 | -------------------------------------------------------------------------------- /Variable_AssignMulti_val_c3.py: -------------------------------------------------------------------------------- 1 | #Many value to multiple variable 2 | x , y, z = "mohan","shyam","Hari" 3 | print(x) 4 | print(y) 5 | print(z) 6 | print() 7 | print() 8 | x , y, z = "mohan",5.9,2 9 | print(x) 10 | print(y) 11 | print(z) 12 | print() 13 | print() 14 | #One value to multiple vaiable 15 | x = y =z = "ram" 16 | print(x) 17 | print(y) 18 | print(z) 19 | 20 | 21 | #Unpack a Collection 22 | #If you have a collection of values in a list, tuple etc. 23 | # Python allows you to extract the values into variables. 24 | # This is called unpacking. 25 | 26 | #Example 27 | 28 | fruits = ["mango", 14 , "orange",45 , "apple",1] 29 | m,w,o,ow,a,aw=fruits 30 | print(m) 31 | print(w) 32 | print(o) 33 | print(ow) 34 | print(a) 35 | print(aw) -------------------------------------------------------------------------------- /Variable_GlobalVariable.py: -------------------------------------------------------------------------------- 1 | x = "awesome"#x is global variable 2 | def myfunction(): 3 | print("This is value of Global Variable : "+ x) 4 | print() 5 | 6 | 7 | myfunction() 8 | print() 9 | 10 | g = "awesome"#global variable 11 | def myfun(): 12 | g="fantastic"#Value of g is changed at local level 13 | print("Python is "+ g) 14 | 15 | myfun() 16 | print("Python is : "+ g)#global value printed 17 | print() 18 | print() 19 | 20 | #Global keyword 21 | #To create a global variable inside a function, you can use the global keyword. 22 | 23 | #Example 24 | def fun1(): 25 | global x 26 | x = "fantastic " 27 | 28 | fun1() 29 | print("Python is "+ x ) 30 | print() 31 | 32 | #Example 33 | #To change the value of a global variable inside a function, 34 | # refer to the variable by using the global keyword: 35 | x="fantastic" 36 | def fun1(): 37 | global x 38 | x = "awesome " 39 | 40 | fun1() 41 | print("Python is "+ x ) 42 | -------------------------------------------------------------------------------- /Variable_c1.py: -------------------------------------------------------------------------------- 1 | from tkinter import DoubleVar 2 | from tokenize import Double 3 | 4 | 5 | x = 5 # this is int type value 6 | y= "Rishabh" # this is string type value 7 | z = 5.4 # this float type value 8 | print("INT value - ", x) 9 | print ("String value - ", y) 10 | print ( "Float value - ",z) 11 | 12 | 13 | #Expilict type casting the data types 14 | x = float(5) #float type data - 5.0 15 | y=int(2) #int type data - 2 16 | z = str("yadav")#str type data - yadav 17 | 18 | print("INT value - ", y) 19 | print ("String value - ", z) 20 | print ( "Float value - ",x) 21 | 22 | 23 | 24 | """ 25 | Get the Type 26 | You can get the data type of a variable with the type() function. 27 | """ 28 | 29 | x = 4 30 | y= "str" 31 | # is same as 32 | z='str' 33 | 34 | print(type(x)) 35 | print(type(y)) 36 | print(z) 37 | print (type(z)) 38 | 39 | """ 40 | Case-Sensitive 41 | Variable names are case-sensitive. 42 | """ 43 | 44 | A = 'rishabh yadav' 45 | a = 'rakesh singh' 46 | # a doesn't overwrite A means a and A both are different 47 | print(A) 48 | print(a) 49 | -------------------------------------------------------------------------------- /Variable_names_c2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Variable Names 3 | A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: 4 | A variable name must start with a letter or the underscore character 5 | A variable name cannot start with a number 6 | A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) 7 | Variable names are case-sensitive (age, Age and AGE are three different variables) 8 | """ 9 | #Legal variable names: 10 | 11 | myvar = "Mohan" 12 | my_var = "Mohan" 13 | _my_var = "Mohan" 14 | myVar = "Mohan" 15 | MYVAR = "Mohan" 16 | myvar2 = "Mohan" 17 | 18 | """ 19 | Illegal variable names: 20 | 21 | 2myvar = "John" 22 | my-var = "John" 23 | my var = "John" 24 | 25 | 26 | """ 27 | 28 | """ 29 | 30 | Multi Words Variable Names 31 | Variable names with more than one word can be difficult to read. 32 | 33 | There are several techniques you can use to make them more readable: 34 | """ 35 | #Camel Case 36 | #Each word, except the first, starts with a capital letter: 37 | 38 | myVariableName = "Mohan" 39 | 40 | #Pascal Case 41 | #Each words starts with capital letter ; 42 | 43 | MyVariableName="Mohan" 44 | 45 | #snake case 46 | #Each word is seperated by underscore charchater 47 | 48 | my_variable_name="Mohan" 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Variables_print_c4.py: -------------------------------------------------------------------------------- 1 | #print(x) print is used to variable x 2 | x = "I am Starting learning Python " 3 | print(x) 4 | 5 | a="I " 6 | b='am ' 7 | c='starting ' 8 | d='learning ' 9 | e = 'python ' 10 | print (a+b+c+d+e) 11 | 12 | print("I "+"am "+"Starting "+"learning " +"Python ") 13 | 14 | v1=5 15 | v2 = 'rakesh' 16 | print(v1,v2); 17 | print('mohan', 45) 18 | #You can't print like this - 19 | #print(v1+v2) 20 | 21 | v0,v1=6,8 22 | print(v0+v1) 23 | print (6+8) 24 | -------------------------------------------------------------------------------- /addvolumfrendfunc.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Cuboid; 5 | class Sphere 6 | { 7 | private: 8 | int radius; 9 | double volume; 10 | 11 | public: 12 | void Acceptdata() 13 | { 14 | cout << "Enter the radius:"; 15 | cin >> radius; 16 | } 17 | void CalculateVolume() 18 | { 19 | volume = 4 / 3.0 * 3.14 * radius * radius * radius; 20 | } 21 | void Display() 22 | { 23 | cout << "The volume of Sphere is :" << volume << endl; 24 | } 25 | friend void AddVolume(Sphere sph, Cuboid cbd); 26 | }; 27 | 28 | class Cuboid 29 | { 30 | private: 31 | int length, breadth, height; 32 | double volume; 33 | 34 | public: 35 | void AcceptData() 36 | { 37 | cout << "Enter the length:"; 38 | cin >> length; 39 | cout << "Enter the breadth:"; 40 | cin >> breadth; 41 | cout << "Enter the height:"; 42 | cin >> height; 43 | } 44 | void CalculateVolume() 45 | { 46 | volume = length * breadth * height; 47 | } 48 | void Display() 49 | { 50 | cout << "The volume of Sphere is:" << volume << endl; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /balanced_paranthesis.py: -------------------------------------------------------------------------------- 1 | """ 2 | To check the paranthesis balance. 3 | Example: 4 | 5 | Test: {[]{()}} 6 | Output: Balanced 7 | 8 | Test: ((() 9 | Output: Unbalanced 10 | """ 11 | 12 | def is_paranthesis_balanced(expression): 13 | open_tup = tuple('({[') 14 | close_tup = tuple(')}]') 15 | 16 | map = dict(zip(open_tup, close_tup)) 17 | queue = [] 18 | 19 | for i in expression: 20 | if i in open_tup: 21 | queue.append(map[i]) 22 | elif i in close_tup: 23 | if not queue or i!=queue.pop(): 24 | return "Unbalanced" 25 | if not queue: 26 | return "Balanced" 27 | else: 28 | return "Unbalanced" 29 | 30 | # Driver code 31 | print("{[]{()}}", "->", is_paranthesis_balanced("{[]{()}}")) 32 | print("((()", "->", is_paranthesis_balanced("((()")) -------------------------------------------------------------------------------- /basicDoublyLinkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node{ 4 | public: 5 | int data; 6 | Node* next; 7 | Node* prev; 8 | Node(int data) 9 | { 10 | this->data=data; 11 | this->next=NULL; 12 | this->prev=NULL; 13 | } 14 | 15 | ~Node() 16 | { 17 | int value=this->data; 18 | if(this->next!=NULL) 19 | { 20 | delete next; 21 | // this->next=NULL; 22 | } 23 | cout<<"Memory is free for : "<prev=temp; 36 | temp->next=head; 37 | head=temp; 38 | } 39 | } 40 | void insertAtTail(Node* &tail,Node* &head,int d) 41 | { 42 | if(tail==NULL) 43 | { 44 | Node* temp=new Node(d); 45 | tail=temp; 46 | head=temp; 47 | } 48 | else{ 49 | Node* temp=new Node(d); 50 | tail->next=temp; 51 | temp->prev=tail; 52 | tail=temp; 53 | } 54 | } 55 | void insertAtPosition(Node* & tail,Node* &head,int position,int d) 56 | { 57 | if(position==1) 58 | { 59 | insertAtHead(tail,head,d); 60 | return; 61 | } 62 | int cnt=1; 63 | Node* temp=head; 64 | while(cntnext; 67 | cnt++; 68 | } 69 | if(temp->next==NULL) 70 | { 71 | insertAtTail(tail,head,d); 72 | return; 73 | } 74 | Node* nodeToInsert=new Node(d); 75 | nodeToInsert->next=temp->next; 76 | temp->next->prev=nodeToInsert; 77 | temp->next=nodeToInsert; 78 | nodeToInsert->prev=temp; 79 | } 80 | void deleteAtPosition(Node*& head,int position) 81 | { 82 | if(position==1) 83 | { 84 | Node* temp=head; 85 | temp->next->prev=NULL; 86 | head=head->next; 87 | temp->next=NULL; 88 | delete temp; 89 | } 90 | else{ 91 | Node* previous=NULL; 92 | Node* curr=head; 93 | int cnt=1; 94 | while(cntnext; 98 | cnt++; 99 | } 100 | curr->prev=NULL; 101 | previous->next=curr->next; 102 | curr->next=NULL; 103 | delete curr; 104 | } 105 | } 106 | void print(Node* &head) 107 | { 108 | Node*temp=head; 109 | while(temp!=NULL) 110 | { 111 | cout<data<<" "; 112 | temp=temp->next; 113 | } 114 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | stacks; 6 | s.push(1); 7 | s.push(2); 8 | s.push(3); 9 | s.push(4); 10 | s.push(5); 11 | s.push(6); 12 | while(!s.empty()) 13 | { 14 | cout< 2 | using namespace std; 3 | 4 | int binarysearch(int n, int arr[], int key) 5 | { 6 | int l = 0; 7 | int r = n - 1; 8 | int mid = (l + r) / 2; 9 | while (l <= r) 10 | { 11 | int mid = (l + r) / 2; 12 | if (key == arr[mid]) 13 | { 14 | return mid; 15 | } 16 | else if (key < arr[mid]) 17 | { 18 | r = mid - 1; 19 | } 20 | else if (key > arr[mid]) 21 | { 22 | l = mid + 1; 23 | } 24 | } 25 | return -1; 26 | } 27 | 28 | int main() 29 | { 30 | int n; 31 | cin >> n; 32 | int arr[n]; 33 | for (int i = 0; i < n; i++) 34 | { 35 | cin >> arr[i]; 36 | } 37 | int key; 38 | cin >> key; 39 | cout << binarysearch(n, arr, key); 40 | return 0; 41 | } -------------------------------------------------------------------------------- /bucketSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to sort an array 2 | # using bucket sort 3 | def insertionSort(b): 4 | for i in range(1, len(b)): 5 | up = b[i] 6 | j = i - 1 7 | while j >= 0 and b[j] > up: 8 | b[j + 1] = b[j] 9 | j -= 1 10 | b[j + 1] = up 11 | return b 12 | 13 | def bucketSort(x): 14 | arr = [] 15 | slot_num = 10 # 10 means 10 slots, each 16 | # slot's size is 0.1 17 | for i in range(slot_num): 18 | arr.append([]) 19 | 20 | # Put array elements in different buckets 21 | for j in x: 22 | index_b = int(slot_num * j) 23 | arr[index_b].append(j) 24 | 25 | # Sort individual buckets 26 | for i in range(slot_num): 27 | arr[i] = insertionSort(arr[i]) 28 | 29 | # concatenate the result 30 | k = 0 31 | for i in range(slot_num): 32 | for j in range(len(arr[i])): 33 | x[k] = arr[i][j] 34 | k += 1 35 | return x 36 | 37 | # Driver Code 38 | x = [0.897, 0.565, 0.656, 39 | 0.1234, 0.665, 0.3434] 40 | print("Sorted Array is") 41 | print(bucketSort(x)) 42 | 43 | # This code is contributed by 44 | # Oneil Hsiao 45 | -------------------------------------------------------------------------------- /buzz num.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n=0; 5 | printf("enter a num"); 6 | scanf("%d",&n); 7 | if(n%7==0 or n%10==7) 8 | { 9 | printf("buzz num"); 10 | } 11 | else 12 | { 13 | printf("not buzz"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /calculator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "Select operation.\n", 13 | "1.Add\n", 14 | "2.Subtract\n", 15 | "3.Multiply\n", 16 | "4.Divide\n" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "def add(x, y):\n", 22 | " return x + y\n", 23 | "\n", 24 | "# This function subtracts two numbers\n", 25 | "def subtract(x, y):\n", 26 | " return x - y\n", 27 | "\n", 28 | "# This function multiplies two numbers\n", 29 | "def multiply(x, y):\n", 30 | " return x * y\n", 31 | "\n", 32 | "# This function divides two numbers\n", 33 | "def divide(x, y):\n", 34 | " return x / y\n", 35 | "\n", 36 | "\n", 37 | "print(\"Select operation.\")\n", 38 | "print(\"1.Add\")\n", 39 | "print(\"2.Subtract\")\n", 40 | "print(\"3.Multiply\")\n", 41 | "print(\"4.Divide\")\n", 42 | "\n", 43 | "while True:\n", 44 | " # take input from the user\n", 45 | " choice = input(\"Enter choice(1/2/3/4): \")\n", 46 | "\n", 47 | " # check if choice is one of the four options\n", 48 | " if choice in ('1', '2', '3', '4'):\n", 49 | " num1 = float(input(\"Enter first number: \"))\n", 50 | " num2 = float(input(\"Enter second number: \"))\n", 51 | "\n", 52 | " if choice == '1':\n", 53 | " print(num1, \"+\", num2, \"=\", add(num1, num2))\n", 54 | "\n", 55 | " elif choice == '2':\n", 56 | " print(num1, \"-\", num2, \"=\", subtract(num1, num2))\n", 57 | "\n", 58 | " elif choice == '3':\n", 59 | " print(num1, \"*\", num2, \"=\", multiply(num1, num2))\n", 60 | "\n", 61 | " elif choice == '4':\n", 62 | " print(num1, \"/\", num2, \"=\", divide(num1, num2))\n", 63 | " \n", 64 | " # check if user wants another calculation\n", 65 | " # break the while loop if answer is no\n", 66 | " next_calculation = input(\"Let's do next calculation? (yes/no): \")\n", 67 | " if next_calculation == \"no\":\n", 68 | " break\n", 69 | " \n", 70 | " else:\n", 71 | " print(\"Invalid Input\")\n" 72 | ] 73 | } 74 | ], 75 | "metadata": { 76 | "kernelspec": { 77 | "display_name": "Python 3.9.7 64-bit", 78 | "language": "python", 79 | "name": "python3" 80 | }, 81 | "language_info": { 82 | "codemirror_mode": { 83 | "name": "ipython", 84 | "version": 3 85 | }, 86 | "file_extension": ".py", 87 | "mimetype": "text/x-python", 88 | "name": "python", 89 | "nbconvert_exporter": "python", 90 | "pygments_lexer": "ipython3", 91 | "version": "3.9.7" 92 | }, 93 | "orig_nbformat": 4, 94 | "vscode": { 95 | "interpreter": { 96 | "hash": "be195e74ed175410d6540ba025da5c4406bdff32be56f2bbb5032c9081165736" 97 | } 98 | } 99 | }, 100 | "nbformat": 4, 101 | "nbformat_minor": 2 102 | } 103 | -------------------------------------------------------------------------------- /cf mainik and array.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/cf mainik and array.bin -------------------------------------------------------------------------------- /check prime or not.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cin>>n; 7 | for (int i=2; i<=n; i++){ 8 | if (n%i==0){ 9 | cout<<" it is prime "<< endl; 10 | break; 11 | } 12 | if (n%i!=0){ 13 | cout<<"it is not a prime"< a[i + 1]): 20 | a[i], a[i + 1] = a[i + 1], a[i] 21 | swapped = True 22 | 23 | # if nothing moved, then array is sorted. 24 | if (swapped == False): 25 | break 26 | 27 | # otherwise, reset the swapped flag so that it 28 | # can be used in the next stage 29 | swapped = False 30 | 31 | # move the end point back by one, because 32 | # item at the end is in its rightful spot 33 | end = end-1 34 | 35 | # from right to left, doing the same 36 | # comparison as in the previous stage 37 | for i in range(end-1, start-1, -1): 38 | if (a[i] > a[i + 1]): 39 | a[i], a[i + 1] = a[i + 1], a[i] 40 | swapped = True 41 | 42 | # increase the starting point, because 43 | # the last stage would have moved the next 44 | # smallest number to its rightful spot. 45 | start = start + 1 46 | 47 | 48 | # Driver code 49 | a = [5, 1, 4, 2, 8, 0, 2] 50 | cocktailSort(a) 51 | print("Sorted array is:") 52 | for i in range(len(a)): 53 | print("% d" % a[i]) 54 | -------------------------------------------------------------------------------- /compherension.py: -------------------------------------------------------------------------------- 1 | #List compherension 2 | a = [1,2,3,4,5] 3 | print('List A : ',a) 4 | #b is store the multiply of 2 with a 's list element 5 | b=[i*2 for i in a] 6 | print('List B: ',b) 7 | 8 | #set compherension 9 | set_A = {4,5,2,4,2,5,4,6,8,2} 10 | #set_B is store the square of element in set_A 11 | set_B={i**2 for i in set_A} 12 | print('Set A : ',set_A) 13 | print('Set B : ',set_B) 14 | 15 | 16 | # Dict Comprehension: 17 | # It is a shorter syntax to create a new dictionary using values of an existing 18 | # dictionary. 19 | a = {'Hello':'World', 'First': 1} 20 | # b stores elements of a in value-key pair format 21 | b = {val: k for k , val in a.items()} 22 | print(b) -------------------------------------------------------------------------------- /compressed_img.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/compressed_img.jpg -------------------------------------------------------------------------------- /cycleSort.py: -------------------------------------------------------------------------------- 1 | # Python program to implement cycle sort 2 | 3 | def cycleSort(array): 4 | writes = 0 5 | 6 | # Loop through the array to find cycles to rotate. 7 | for cycleStart in range(0, len(array) - 1): 8 | item = array[cycleStart] 9 | 10 | # Find where to put the item. 11 | pos = cycleStart 12 | for i in range(cycleStart + 1, len(array)): 13 | if array[i] < item: 14 | pos += 1 15 | 16 | # If the item is already there, this is not a cycle. 17 | if pos == cycleStart: 18 | continue 19 | 20 | # Otherwise, put the item there or right after any duplicates. 21 | while item == array[pos]: 22 | pos += 1 23 | array[pos], item = item, array[pos] 24 | writes += 1 25 | 26 | # Rotate the rest of the cycle. 27 | while pos != cycleStart: 28 | 29 | # Find where to put the item. 30 | pos = cycleStart 31 | for i in range(cycleStart + 1, len(array)): 32 | if array[i] < item: 33 | pos += 1 34 | 35 | # Put the item there or right after any duplicates. 36 | while item == array[pos]: 37 | pos += 1 38 | array[pos], item = item, array[pos] 39 | writes += 1 40 | 41 | return writes 42 | 43 | # driver code 44 | arr = [1, 8, 3, 9, 10, 10, 2, 4 ] 45 | n = len(arr) 46 | cycleSort(arr) 47 | 48 | print("After sort : ") 49 | for i in range(0, n) : 50 | print(arr[i], end = ' ') 51 | 52 | -------------------------------------------------------------------------------- /cyclic sort.java: -------------------------------------------------------------------------------- 1 | // java program to check implement cycle sort 2 | import java.util.*; 3 | public class MissingNumber { 4 | public static void main(String[] args) 5 | { 6 | int[] arr = { 3, 2, 4, 5, 1 }; 7 | int n = arr.length; 8 | System.out.println("Before sort :"); 9 | System.out.println(Arrays.toString(arr)); 10 | CycleSort(arr, n); 11 | 12 | } 13 | 14 | static void CycleSort(int[] arr, int n) 15 | { 16 | int i = 0; 17 | while (i < n) { 18 | 19 | int correctpos = arr[i] - 1; 20 | if (arr[i] < n && arr[i] != arr[correctpos]) { 21 | 22 | swap(arr, i, correctpos); 23 | } 24 | else { 25 | 26 | i++; 27 | } 28 | } 29 | System.out.println("After sort : "); 30 | System.out.print(Arrays.toString(arr)); 31 | 32 | 33 | } 34 | 35 | static void swap(int[] arr, int i, int correctpos) 36 | { 37 | 38 | int temp = arr[i]; 39 | arr[i] = arr[correctpos]; 40 | arr[correctpos] = temp; 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /deleating_of_node.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *next; 9 | }; 10 | 11 | void trivarsal(struct node *ptr) 12 | { 13 | while (ptr != NULL) 14 | { 15 | cout << "Element are :- " << ptr->data << endl; 16 | ptr = ptr->next; 17 | } 18 | } 19 | // case 1 --> delete at first 20 | // struct node *Deleteatfirst(struct node *head){ 21 | // struct node *ptr=head; 22 | // head=head->next; 23 | // free(ptr); 24 | // return head; 25 | // } 26 | 27 | // case 2 --> deletion a element at given index 28 | // struct node *DeleteAtIndex(struct node *head,int index){ 29 | // struct node *ptr=head; 30 | // struct node *q = head->next; 31 | // for(int i=0;inext; 33 | // q->next; 34 | // } 35 | // ptr->next = q->next; 36 | // free(q); 37 | // return head; 38 | 39 | 40 | 41 | // case 3 :- delete at last element 42 | struct node *DeleteAtLast(struct node *head){ 43 | struct node *p = head; 44 | struct node *q = head->next; 45 | while(q->next != NULL){ 46 | p= p->next; 47 | q= p->next; 48 | } 49 | p ->next = NULL; 50 | free(q); 51 | return head; 52 | } 53 | 54 | 55 | int main() 56 | { 57 | struct node *head; 58 | struct node *second; 59 | struct node *third; 60 | struct node *fourth; 61 | struct node *fifth; 62 | struct node *six; 63 | struct node *seven; 64 | struct node *eight; 65 | head = (struct node *)malloc(sizeof(struct node)); 66 | second = (struct node *)malloc(sizeof(struct node)); 67 | third = (struct node *)malloc(sizeof(struct node)); 68 | fourth = (struct node *)malloc(sizeof(struct node)); 69 | fifth = (struct node *)malloc(sizeof(struct node)); 70 | six = (struct node *)malloc(sizeof(struct node)); 71 | seven = (struct node *)malloc(sizeof(struct node)); 72 | eight = (struct node *)malloc(sizeof(struct node)); 73 | 74 | head->data = 1; 75 | head->next = second; 76 | 77 | second->data = 2; 78 | second->next = third; 79 | 80 | third->data = 3; 81 | third->next = fourth; 82 | 83 | fourth->data = 4; 84 | fourth->next =fifth; 85 | 86 | fifth->data = 5; 87 | fifth->next =six; 88 | 89 | six->data = 6; 90 | six->next =seven; 91 | 92 | seven->data = 7; 93 | seven->next =eight; 94 | 95 | eight->data = 8; 96 | eight->next = NULL; 97 | 98 | cout<<"before deletion :- "< i: 6 | # display space 7 | print(' ', end=' ') 8 | j -= 1 9 | print('*', end=' ') 10 | k = 1 11 | while k < 2 * (i - 1): 12 | print(' ', end=' ') 13 | k += 1 14 | if i == 1: 15 | print() 16 | else: 17 | print('*') 18 | i += 1 19 | 20 | i = rows - 1 21 | while i >= 1: 22 | j = rows 23 | while j > i: 24 | print(' ', end=' ') 25 | j -= 1 26 | print('*', end=' ') 27 | k = 1 28 | while k <= 2 * (i - 1): 29 | print(' ', end=' ') 30 | k += 1 31 | if i == 1: 32 | print() 33 | else: 34 | print('*') 35 | i -= 1 36 | -------------------------------------------------------------------------------- /diamond_pattern.py: -------------------------------------------------------------------------------- 1 | n=int(input("enter the number of rows")) 2 | 3 | for i in range(n): 4 | 5 | for j in range(1,int((n/2))-i+3): 6 | 7 | print(sep=" ",end=" ") 8 | 9 | for k in range(1,i+2): 10 | 11 | print("*", end=" ") 12 | 13 | 14 | 15 | print() 16 | 17 | for i in range(n): 18 | 19 | for j in range(1,5-(int((n/2))-i+3)+2): 20 | 21 | print(sep=" ",end=" ") 22 | 23 | for k in range(1,5-i): 24 | 25 | print("*", end=" ") 26 | 27 | print() -------------------------------------------------------------------------------- /doublyLinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.item = data 4 | self.next = None 5 | self.prev = None 6 | # Class for doubly Linked List 7 | class doublyLinkedList: 8 | def __init__(self): 9 | self.start_node = None 10 | # Insert Element to Empty list 11 | def InsertToEmptyList(self, data): 12 | if self.start_node is None: 13 | new_node = Node(data) 14 | self.start_node = new_node 15 | else: 16 | print("The list is empty") 17 | # Insert element at the end 18 | def InsertToEnd(self, data): 19 | # Check if the list is empty 20 | if self.start_node is None: 21 | new_node = Node(data) 22 | self.start_node = new_node 23 | return 24 | n = self.start_node 25 | # Iterate till the next reaches NULL 26 | while n.next is not None: 27 | n = n.next 28 | new_node = Node(data) 29 | n.next = new_node 30 | new_node.prev = n 31 | # Delete the elements from the start 32 | def DeleteAtStart(self): 33 | if self.start_node is None: 34 | print("The Linked list is empty, no element to delete") 35 | return 36 | if self.start_node.next is None: 37 | self.start_node = None 38 | return 39 | self.start_node = self.start_node.next 40 | self.start_prev = None; 41 | # Delete the elements from the end 42 | def delete_at_end(self): 43 | # Check if the List is empty 44 | if self.start_node is None: 45 | print("The Linked list is empty, no element to delete") 46 | return 47 | if self.start_node.next is None: 48 | self.start_node = None 49 | return 50 | n = self.start_node 51 | while n.next is not None: 52 | n = n.next 53 | n.prev.next = None 54 | def counting_nodes(self): 55 | n = self.start_node 56 | t=0 57 | while n is not None: 58 | t=t+1 59 | n=n.next 60 | print(f"No of nodes is {t}") 61 | 62 | # Traversing and Displaying each element of the list 63 | def duplicate(self): 64 | lis2=[] 65 | n = self.start_node 66 | while n is not None: 67 | if n.item in lis2: 68 | n.prev.next=n.next 69 | else: 70 | 71 | lis2.append(n.item) 72 | 73 | 74 | n=n.next 75 | # for i in range(len(lis2)): 76 | # print(f"Element is: {lis2[i]}") 77 | self.Display() 78 | 79 | def Display(self): 80 | if self.start_node is None: 81 | print("The list is empty") 82 | return 83 | else: 84 | n = self.start_node 85 | while n is not None: 86 | print("Element is: ", n.item) 87 | n = n.next 88 | print("\n") 89 | # Create a new Doubly Linked List 90 | NewDoublyLinkedList = doublyLinkedList() 91 | # Insert the element to empty list 92 | n=int(input("Enter the no nodes\n")) 93 | lis=[] 94 | print("Enter the element\n") 95 | for i in range(n): 96 | a=int(input()) 97 | lis.append(a) 98 | NewDoublyLinkedList.InsertToEmptyList(lis[0]) 99 | # Insert the element at the end 100 | for i in range(1,n): 101 | 102 | NewDoublyLinkedList.InsertToEnd(lis[i]) 103 | 104 | 105 | NewDoublyLinkedList.Display() 106 | # Counting the nodes 107 | NewDoublyLinkedList.counting_nodes() 108 | # Deleting last two elements 109 | NewDoublyLinkedList.delete_at_end() 110 | NewDoublyLinkedList.delete_at_end() 111 | print("After deleting element\n") 112 | # Counting the nodes 113 | NewDoublyLinkedList.counting_nodes() 114 | # Display Data 115 | NewDoublyLinkedList.Display() 116 | # removing duplicate 117 | print("\nRemoving duplicate\n") 118 | NewDoublyLinkedList.duplicate() 119 | 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /euclidGCD.py: -------------------------------------------------------------------------------- 1 | # Python code to demonstrate naive 2 | # method to compute gcd ( recursion ) 3 | 4 | 5 | def hcf(a, b): 6 | if(b == 0): 7 | return a 8 | else: 9 | return hcf(b, a % b) 10 | 11 | a = 60 12 | b = 48 13 | 14 | # prints 12 15 | print("The gcd of 60 and 48 is : ", end="") 16 | print(hcf(60, 48)) 17 | -------------------------------------------------------------------------------- /factorial_of _num.py: -------------------------------------------------------------------------------- 1 | # Python 3 program to find 2 | # factorial of given number 3 | def factorial(n): 4 | if n < 0: 5 | return 0 6 | elif n == 0 or n == 1: 7 | return 1 8 | else: 9 | fact = 1 10 | while(n > 1): 11 | fact *= n 12 | n -= 1 13 | return fact 14 | 15 | # Driver Code 16 | num = 5 17 | print("Factorial of",num,"is", 18 | factorial(num)) 19 | 20 | 21 | -------------------------------------------------------------------------------- /fibonacci_numbers.py: -------------------------------------------------------------------------------- 1 | # Function for nth Fibonacci number 2 | def Fibonacci(n): 3 | 4 | # Check if input is 0 then it will 5 | # print incorrect input 6 | if n < 0: 7 | print("Incorrect input") 8 | 9 | # Check if n is 0 10 | # then it will return 0 11 | elif n == 0: 12 | return 0 13 | 14 | # Check if n is 1,2 15 | # it will return 1 16 | elif n == 1 or n == 2: 17 | return 1 18 | 19 | else: 20 | return Fibonacci(n-1) + Fibonacci(n-2) 21 | 22 | # Driver Program 23 | print(Fibonacci(9)) 24 | 25 | # This code is contributed by Saket Modi 26 | # then corrected and improved by Himanshu Kanojiya 27 | -------------------------------------------------------------------------------- /findd_Factorial.py: -------------------------------------------------------------------------------- 1 | def print_factors(x): 2 | print("The factors of",x,"are:") 3 | for i in range(1, x + 1): 4 | if x % i == 0: 5 | print(i) 6 | 7 | num = 320 8 | 9 | print_factors(num) -------------------------------------------------------------------------------- /findurl.py: -------------------------------------------------------------------------------- 1 | # Python code to find the URL from an input string 2 | # Using the regular expression 3 | import re 4 | 5 | def Find(string): 6 | 7 | # findall() has been used 8 | # with valid conditions for urls in string 9 | regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" 10 | url = re.findall(regex,string) 11 | return [x[0] for x in url] 12 | 13 | # Driver Code 14 | string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/' 15 | print("Urls: ", Find(string)) 16 | -------------------------------------------------------------------------------- /game.py: -------------------------------------------------------------------------------- 1 | i=input('Wanna play tic tac toe \n yes or no:') 2 | if i=='yes': 3 | print('so lets go!!') 4 | v=input('which character do u want,x or o?') 5 | n=v.lower() 6 | if n=='x': 7 | print('player1=',n) 8 | print('player2=o') 9 | elif n=='o': 10 | print('player1=o') 11 | print('player2=x') 12 | elif i=='no': 13 | print('thank u') 14 | if i=='yes': 15 | 16 | Win = 1 17 | 18 | Draw = -1 19 | 20 | Running = 0 21 | 22 | Stop = 1 23 | board=['-','-','-', 24 | '-','-','-', 25 | '-','-','-'] 26 | print(board[0],'I',board[1],'I',board[2]) 27 | print('-----------') 28 | print(board[3],'I',board[4],'I',board[5]) 29 | print('-----------') 30 | print(board[6],'I',board[7],'I',board[8]) 31 | def CheckPosition(v): 32 | if(board[v] == ' '): 33 | 34 | return True 35 | else: 36 | return False 37 | k=0 38 | while k<9: 39 | i= int(input('player 1:select a spot:')) 40 | if v=='x': 41 | if board[i]!='x' and board[i]!='o': 42 | board[i]=v 43 | print(board[0],'I',board[1],'I',board[2]) 44 | print('-----------') 45 | print(board[3],'I',board[4],'I',board[5]) 46 | print('-----------') 47 | print(board[6],'I',board[7],'I',board[8]) 48 | j=int(input('player2-select a spot:')) 49 | if board[j]!='x' and board[j]!='o': 50 | board[j]='o' 51 | print(board[0],'I',board[1],'I',board[2]) 52 | print('-----------') 53 | print(board[3],'I',board[4],'I',board[5]) 54 | print('-----------') 55 | print(board[6],'I',board[7],'I',board[8]) 56 | k=k+1 57 | else: 58 | if v=='o': 59 | if board[i]!='x' and board[i]!='o': 60 | board[i]=v 61 | print(board[0],'I',board[1],'I',board[2]) 62 | print('-----------') 63 | print(board[3],'I',board[4],'I',board[5]) 64 | print('-----------') 65 | print(board[6],'I',board[7],'I',board[8]) 66 | j=int(input('player2-select a spot')) 67 | if board[j]!='x' and board[j]!='o': 68 | board[j]='x' 69 | print(board[0],'I',board[1],'I',board[2]) 70 | print('-----------') 71 | print(board[3],'I',board[4],'I',board[5]) 72 | print('-----------') 73 | print(board[6],'I',board[7],'I',board[8]) 74 | k=k+1 75 | 76 | -------------------------------------------------------------------------------- /heap.py: -------------------------------------------------------------------------------- 1 | # importing "heapq" to implement heap queue 2 | import heapq 3 | 4 | # initializing list 5 | li = [5, 7, 9, 1, 3] 6 | 7 | # using heapify to convert list into heap 8 | heapq.heapify(li) 9 | 10 | # printing created heap 11 | print ("The created heap is : ",(list(li))) 12 | -------------------------------------------------------------------------------- /img_compress.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | file_path = "python-learning-codes/uncompressed_img.jpg" 3 | img = Image.open(file_path) 4 | height, width = img.size 5 | compressed = img.resize((height, width), Image.ANTIALIAS) 6 | compressed.save("python-learning-codes/compressed_img.jpg", optimize=True,quality=9) -------------------------------------------------------------------------------- /inorder_traversal.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Inorder traversal 34 | # Left -> Root -> Right 35 | def inorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res = self.inorderTraversal(root.left) 39 | res.append(root.data) 40 | res = res + self.inorderTraversal(root.right) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.inorderTraversal(root)) -------------------------------------------------------------------------------- /lallu.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int a=0; 6 | int b=0; 7 | int c=a-b; 8 | cout< 2 | using namespace std; 3 | void linearsearch(int arr[], int n, int key) 4 | { 5 | for (int i = 0; i < n; i++) 6 | { 7 | if (arr[i] == key) 8 | { 9 | cout << "element found at " << i; 10 | } 11 | } 12 | } 13 | 14 | int main() 15 | { 16 | int n; 17 | cout << "enter no. of array you want"; 18 | cin >> n; 19 | int arr[n]; 20 | cout << "enter the array :- "; 21 | for (int i = 0; i < n; i++) 22 | { 23 | 24 | cin >> arr[i]; 25 | } 26 | 27 | int key; 28 | cout << "enter the key :-"; 29 | cin >> key; 30 | linearsearch(arr, n, key); 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /linearsearch.py: -------------------------------------------------------------------------------- 1 | def search(arr, x): 2 | 3 | for i in range(len(arr)): 4 | 5 | if arr[i] == x: 6 | return i+1 7 | 8 | return -1 9 | print("Enter the list of numbers seprated by space") 10 | arr = [int(i) for i in input().split(" ")] 11 | print("Enter the key") 12 | x = int(input()) 13 | 14 | print(search(arr, x)) 15 | -------------------------------------------------------------------------------- /linkedlistinsrt.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | # Print the linked list 10 | def listprint(self): 11 | printval = self.headval 12 | while printval is not None: 13 | print (printval.dataval) 14 | printval = printval.nextval 15 | def AtBegining(self,newdata): 16 | NewNode = Node(newdata) 17 | 18 | # Update the new nodes next val to existing node 19 | NewNode.nextval = self.headval 20 | self.headval = NewNode 21 | 22 | list = SLinkedList() 23 | list.headval = Node("Mon") 24 | e2 = Node("Tue") 25 | e3 = Node("Wed") 26 | 27 | list.headval.nextval = e2 28 | e2.nextval = e3 29 | 30 | list.AtBegining("Sun") 31 | list.listprint() 32 | -------------------------------------------------------------------------------- /loops.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # While loop 4 | x = 0 5 | while(x<5): 6 | print(x) 7 | x = x + 1 8 | 9 | # Foo loop 10 | for i in range(5,10): 11 | print(i) 12 | 13 | -------------------------------------------------------------------------------- /mergeSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i],end=" ") 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i],end=" ") 79 | 80 | -------------------------------------------------------------------------------- /nparray.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | #1 D array 3 | a=np.array([1,2,3,4,5]) 4 | print(a) 5 | #2 D array 6 | b=np.array([[1,2,3],[4,5,6]]) 7 | print(b) 8 | #array of zeroes 9 | c=np.zeros((2,3)) 10 | print(c) 11 | #array of ones 12 | d=np.ones((2,3)) 13 | print(d) 14 | #array of any number 15 | e=np.full((2,3),5) 16 | print(e) 17 | #identity matrix 18 | f=np.eye(3) 19 | print(f) 20 | #random matrix 21 | 22 | g=np.random.random((2,3)) 23 | print(g) 24 | #random arrays in fixed range 25 | h=np.random.randint(1,10,(2,3)) 26 | print(h) 27 | #convert a list to numpy array 28 | list1=[1,2,3,4,5] 29 | np_array=np.asarray(list1) 30 | print(np_array) 31 | #transpose a matrix 32 | print(np.transpose(h)) 33 | -------------------------------------------------------------------------------- /npfunction.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | #arrange function 3 | 4 | print(np.arrange(2,10)) 5 | print(np.arrange(2,10,2)) 6 | print(np.arrange(1,2,0.1)) 7 | 8 | #linspace function 9 | print(np.linspace(1,2,10)) 10 | 11 | #reshape function 12 | a=np.array([1,2,3,4,5,6,7,8,9]) 13 | print(a.reshape(3,3)) 14 | 15 | #dot function 16 | a=np.array([1,2,3]) 17 | b=np.array([4,5,6]) 18 | print(np.dot(a,b)) 19 | vec_a=2+3j 20 | vec_b=4+7j 21 | print(np.dot(vec_a,vec_b)) 22 | 23 | #argmin function 24 | a=np.array([1,2,3,4,5,6,7,8,9]) 25 | print(np.argmin(a)) 26 | #argmax function 27 | print(np.argmax(a)) 28 | 29 | #mean function 30 | print(np.mean(a)) 31 | #median function 32 | print(np.median(a)) 33 | #standard deviation function 34 | print(np.std(a)) 35 | #variance function 36 | print(np.var(a)) 37 | 38 | #concatenate function 39 | a=np.array([1,2,3]) 40 | b=np.array([4,5,6]) 41 | print(np.concatenate((a,b))) 42 | #stack function 43 | print(np.stack((a,b))) 44 | print(np.stack((a,b),axis=1)) 45 | 46 | #split function 47 | a=np.array([1,2,3,4,5,6,7,8,9]) 48 | print(np.split(a,3)) 49 | print(np.split(a,[3,5])) 50 | 51 | #sort function 52 | a=np.array([1,2,3,4,5,6,7,8,9]) 53 | print(np.sort(a)) 54 | #reverse function 55 | print(np.sort(a)[::-1]) 56 | 57 | #unique function 58 | a=np.array([1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]) 59 | print(np.unique(a)) 60 | 61 | 62 | -------------------------------------------------------------------------------- /oops.py: -------------------------------------------------------------------------------- 1 | class Person(object): 2 | 3 | # __init__ is known as the constructor 4 | def __init__(self, name, idnumber): 5 | self.name = name 6 | self.idnumber = idnumber 7 | 8 | def display(self): 9 | print(self.name) 10 | print(self.idnumber) 11 | 12 | def details(self): 13 | print("My name is {}".format(self.name)) 14 | print("IdNumber: {}".format(self.idnumber)) 15 | 16 | # child class 17 | class Employee(Person): 18 | def __init__(self, name, idnumber, salary, post): 19 | self.salary = salary 20 | self.post = post 21 | 22 | # invoking the __init__ of the parent class 23 | Person.__init__(self, name, idnumber) 24 | 25 | def details(self): 26 | print("My name is {}".format(self.name)) 27 | print("IdNumber: {}".format(self.idnumber)) 28 | print("Post: {}".format(self.post)) 29 | 30 | 31 | # creation of an object variable or an instance 32 | a = Employee('Rahul', 886012, 200000, "Intern") 33 | 34 | # calling a function of the class Person using 35 | # its instance 36 | a.display() 37 | a.details() 38 | -------------------------------------------------------------------------------- /pairwise000006.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void maxProduct(int arr[], int n) 6 | { 7 | if (n < 2) 8 | { 9 | cout << "No pairs exists\n"; 10 | return; 11 | } 12 | 13 | 14 | int a = arr[0], b = arr[1]; 15 | 16 | 17 | 18 | for (int i = 0; i < n; i++) 19 | for (int j = i + 1; j < n; j++) 20 | if (arr[i] * arr[j] > a * b) 21 | a = arr[i], b = arr[j]; 22 | 23 | cout << "Max product pair is {" << a << ", " 24 | << b << "}"; 25 | } 26 | 27 | int main() 28 | { 29 | int arr[] = {1, 4, 3, 6, 7, 0}; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | maxProduct(arr, n); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /pancakeSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to 2 | # sort array using 3 | # pancake sort 4 | 5 | # Reverses arr[0..i] */ 6 | def flip(arr, i): 7 | start = 0 8 | while start < i: 9 | temp = arr[start] 10 | arr[start] = arr[i] 11 | arr[i] = temp 12 | start += 1 13 | i -= 1 14 | 15 | # Returns index of the maximum 16 | # element in arr[0..n-1] */ 17 | def findMax(arr, n): 18 | mi = 0 19 | for i in range(0,n): 20 | if arr[i] > arr[mi]: 21 | mi = i 22 | return mi 23 | 24 | # The main function that 25 | # sorts given array 26 | # using flip operations 27 | def pancakeSort(arr, n): 28 | 29 | # Start from the complete 30 | # array and one by one 31 | # reduce current size 32 | # by one 33 | curr_size = n 34 | while curr_size > 1: 35 | # Find index of the maximum 36 | # element in 37 | # arr[0..curr_size-1] 38 | mi = findMax(arr, curr_size) 39 | 40 | # Move the maximum element 41 | # to end of current array 42 | # if it's not already at 43 | # the end 44 | if mi != curr_size-1: 45 | # To move at the end, 46 | # first move maximum 47 | # number to beginning 48 | flip(arr, mi) 49 | 50 | # Now move the maximum 51 | # number to end by 52 | # reversing current array 53 | flip(arr, curr_size-1) 54 | curr_size -= 1 55 | 56 | # A utility function to 57 | # print an array of size n 58 | def printArray(arr, n): 59 | for i in range(0,n): 60 | print ("%d"%( arr[i]),end=" ") 61 | 62 | # Driver program 63 | arr = [23, 10, 20, 11, 12, 6, 7] 64 | n = len(arr) 65 | pancakeSort(arr, n); 66 | print ("Sorted Array ") 67 | printArray(arr,n) 68 | 69 | -------------------------------------------------------------------------------- /pattern.py: -------------------------------------------------------------------------------- 1 | # Function to demonstrate printing pattern of alphabets 2 | 3 | 4 | def contalpha(n): 5 | 6 | # initializing value corresponding to 'A' 7 | # ASCII value 8 | num = 65 9 | 10 | 11 | # outer loop to handle number of rows 12 | - for i in range(0, n): 13 | 14 | # inner loop to handle number of columns 15 | # values changing acc. to outer loop 16 | for j in range(0, i+1): 17 | 18 | # explicitly converting to char 19 | ch = chr(num) 20 | 21 | # printing char value 22 | print(ch, end=" ") 23 | 24 | # incrementing at each column 25 | num = num + 1 26 | 27 | # ending line after each row 28 | print("\r") 29 | 30 | # Driver code 31 | n = 5 32 | contalpha(n) 33 | -------------------------------------------------------------------------------- /peigonSort.py: -------------------------------------------------------------------------------- 1 | # Python program to implement Pigeonhole Sort */ 2 | def pigeonhole_sort(a): 3 | # size of range of values in the list 4 | # (ie, number of pigeonholes we need) 5 | my_min = min(a) 6 | my_max = max(a) 7 | size = my_max - my_min + 1 8 | 9 | # our list of pigeonholes 10 | holes = [0] * size 11 | 12 | # Populate the pigeonholes. 13 | for x in a: 14 | assert type(x) is int, "integers only please" 15 | holes[x - my_min] += 1 16 | 17 | # Put the elements back into the array in order. 18 | i = 0 19 | for count in range(size): 20 | while holes[count] > 0: 21 | holes[count] -= 1 22 | a[i] = count + my_min 23 | i += 1 24 | 25 | 26 | a = [8, 3, 2, 7, 4, 6, 8] 27 | print("Sorted order is : ", end = ' ') 28 | 29 | pigeonhole_sort(a) 30 | 31 | for i in range(0, len(a)): 32 | print(a[i], end = ' ') 33 | 34 | -------------------------------------------------------------------------------- /perfect.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int i,n; 6 | cin>>n; 7 | int sum=0; 8 | for(i=1;i<=n;i++) 9 | { 10 | if(n%i==0) 11 | { 12 | sum+=i; 13 | } 14 | } 15 | if(sum==2*n) 16 | 17 | cout<<"perfect number"; 18 | 19 | else 20 | cout<<"not perfect"; 21 | return 0; 22 | } -------------------------------------------------------------------------------- /pointer_VEDANT.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void update(int *a,int *b) 5 | { 6 | // Complete this function 7 | int x, y; 8 | // Complete this function 9 | x = *a + *b ; 10 | y = *a - *b ; 11 | *a = x; 12 | *b = abs(y); 13 | 14 | } 15 | 16 | int main() 17 | { 18 | int a, b; 19 | int *pa = &a, *pb = &b; 20 | 21 | scanf("%d %d", &a, &b); 22 | update(pa, pb); 23 | printf("%d\n%d", a, b); 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /postorder_traversal.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Postorder traversal 34 | # Left ->Right -> Root 35 | def PostorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res = self.PostorderTraversal(root.left) 39 | res = res + self.PostorderTraversal(root.right) 40 | res.append(root.data) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.PostorderTraversal(root)) -------------------------------------------------------------------------------- /preorder_traversal.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data): 4 | 5 | self.left = None 6 | self.right = None 7 | self.data = data 8 | # Insert Node 9 | def insert(self, data): 10 | 11 | if self.data: 12 | if data < self.data: 13 | if self.left is None: 14 | self.left = Node(data) 15 | else: 16 | self.left.insert(data) 17 | elif data > self.data: 18 | if self.right is None: 19 | self.right = Node(data) 20 | else: 21 | self.right.insert(data) 22 | else: 23 | self.data = data 24 | 25 | # Print the Tree 26 | def PrintTree(self): 27 | if self.left: 28 | self.left.PrintTree() 29 | print( self.data), 30 | if self.right: 31 | self.right.PrintTree() 32 | 33 | # Preorder traversal 34 | # Root -> Left ->Right 35 | def PreorderTraversal(self, root): 36 | res = [] 37 | if root: 38 | res.append(root.data) 39 | res = res + self.PreorderTraversal(root.left) 40 | res = res + self.PreorderTraversal(root.right) 41 | return res 42 | 43 | root = Node(27) 44 | root.insert(14) 45 | root.insert(35) 46 | root.insert(10) 47 | root.insert(19) 48 | root.insert(31) 49 | root.insert(42) 50 | print(root.PreorderTraversal(root)) -------------------------------------------------------------------------------- /priorityqueue.py: -------------------------------------------------------------------------------- 1 | # A simple implementation of Priority Queue 2 | class PriorityQueue(object): 3 | def __init__(self): 4 | self.queue = [] 5 | 6 | def __str__(self): 7 | return ' '.join([str(i) for i in self.queue]) 8 | 9 | # for checking if the queue is empty 10 | def isEmpty(self): 11 | return len(self.queue) == 0 12 | 13 | # for inserting an element in the queue 14 | def insert(self, data): 15 | self.queue.append(data) 16 | 17 | # for popping an element based on Priority 18 | def delete(self): 19 | try: 20 | max_val = 0 21 | for i in range(len(self.queue)): 22 | if self.queue[i] > self.queue[max_val]: 23 | max_val = i 24 | item = self.queue[max_val] 25 | del self.queue[max_val] 26 | return item 27 | except IndexError: 28 | print() 29 | exit() 30 | 31 | if __name__ == '__main__': 32 | myQueue = PriorityQueue() 33 | myQueue.insert(12) 34 | myQueue.insert(1) 35 | myQueue.insert(14) 36 | myQueue.insert(7) 37 | print(myQueue) 38 | while not myQueue.isEmpty(): 39 | print(myQueue.delete()) 40 | 41 | -------------------------------------------------------------------------------- /python matrix: -------------------------------------------------------------------------------- 1 | X = [[12,7], 2 | [4 ,5], 3 | [3 ,8]] 4 | 5 | result = [[0,0,0], 6 | [0,0,0]] 7 | 8 | # iterate through rows 9 | for i in range(len(X)): 10 | # iterate through columns 11 | for j in range(len(X[0])): 12 | result[j][i] = X[i][j] 13 | 14 | for r in result: 15 | print(r) 16 | -------------------------------------------------------------------------------- /pythonDictionaries.py: -------------------------------------------------------------------------------- 1 | dict_demo ={'first':1,'second':2,'third':3} 2 | print("dictionary :",dict_demo) 3 | keylist = list(dict_demo.keys()) 4 | print('keys : ',keylist) 5 | valuelist = list (dict_demo.values()) 6 | print ('values : ', valuelist) 7 | 8 | # .keys() function is used to print keys of dictionary 9 | for k in dict_demo.keys(): 10 | print(k) 11 | 12 | #.values() function is used to print value of dictionary 13 | for v in dict_demo.values(): 14 | print(v) 15 | 16 | 17 | #print the dictionary item 18 | print('value at key[]-first ',dict_demo['first']) 19 | 20 | #update key value which is present in the dictionary 21 | print() 22 | dict = {0 : 'sunday', 1 : 'monday', 2 : 'tuesday'} 23 | # print (dict['first'].items()) 24 | for item in dict.items(): 25 | print(item) 26 | print() 27 | dict[2] = 'wednesday' 28 | for item in dict.items(): 29 | print(item) 30 | 31 | # we can merge two dictionary into 1 dictionary using update() method 32 | 33 | dict.update(dict_demo) 34 | print(dict) 35 | -------------------------------------------------------------------------------- /pythonprogram.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to insert items into a list in sorted order. 2 | import bisect 3 | # Sample list 4 | my_list = [25, 45, 36, 47, 69, 48, 68, 78, 14, 36] 5 | 6 | print("Original List:") 7 | print(my_list) 8 | sorted_list = [] 9 | for i in my_list: 10 | position = bisect.bisect(sorted_list, i) 11 | bisect.insort(sorted_list, i) 12 | print("Sorted List:") 13 | print(sorted_list) 14 | -------------------------------------------------------------------------------- /queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void print(queueque) 6 | { 7 | queuec=que; 8 | while(!c.empty()) 9 | { 10 | cout<q; 17 | q.push('a'); 18 | q.push('b'); 19 | q.push('c'); 20 | print(q); 21 | 22 | cout<= 0: 28 | index = arr[i] // exp1 29 | output[count[index % 10] - 1] = arr[i] 30 | count[index % 10] -= 1 31 | i -= 1 32 | 33 | # Copying the output array to arr[], 34 | # so that arr now contains sorted numbers 35 | i = 0 36 | for i in range(0, len(arr)): 37 | arr[i] = output[i] 38 | 39 | # Method to do Radix Sort 40 | def radixSort(arr): 41 | 42 | # Find the maximum number to know number of digits 43 | max1 = max(arr) 44 | 45 | # Do counting sort for every digit. Note that instead 46 | # of passing digit number, exp is passed. exp is 10^i 47 | # where i is current digit number 48 | exp = 1 49 | while max1 / exp >= 1: 50 | countingSort(arr, exp) 51 | exp *= 10 52 | 53 | 54 | # Driver code 55 | arr = [170, 45, 75, 90, 802, 24, 2, 66] 56 | 57 | # Function Call 58 | radixSort(arr) 59 | 60 | for i in range(len(arr)): 61 | print(arr[i],end=" ") 62 | 63 | -------------------------------------------------------------------------------- /reverse_ll.py: -------------------------------------------------------------------------------- 1 | # A single node of a singly Linked List 2 | class Node: 3 | # constructor 4 | def __init__(self, data = None, next=None): 5 | self.data = data 6 | self.next = next 7 | 8 | # A Linked List class with a single head node 9 | class LinkedList: 10 | def __init__(self): 11 | self.head = None 12 | 13 | # insertion method for the linked list 14 | def insert(self, data): 15 | newNode = Node(data) 16 | if(self.head): 17 | current = self.head 18 | while(current.next): 19 | current = current.next 20 | current.next = newNode 21 | else: 22 | self.head = newNode 23 | 24 | # print method for the linked list 25 | def printLL(self): 26 | current = self.head 27 | while(current): 28 | print(current.data) 29 | current = current.next 30 | 31 | # Singly Linked List with insertion and print methods 32 | LL = LinkedList() 33 | LL.insert(3) 34 | LL.insert(4) 35 | LL.insert(5) 36 | LL.printLL() 37 | -------------------------------------------------------------------------------- /runner_score.py: -------------------------------------------------------------------------------- 1 | score = int(input()) 2 | arr= list(map(int,inpt(.split())) 3 | z=max(arr) 4 | m=-101 5 | for i in arr : 6 | if i==z : 7 | continue 8 | else : 9 | if i>m : 10 | m=i 11 | print(m) 12 | -------------------------------------------------------------------------------- /selectionsort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(input_list): 2 | for idx in range(len(input_list)): 3 | min_idx = idx 4 | for j in range( idx +1, len(input_list)): 5 | if input_list[min_idx] > input_list[j]: 6 | min_idx = j 7 | # Swap the minimum value with the compared value 8 | input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx] 9 | l = [19,2,31,45,30,11,121,27] 10 | selection_sort(l) 11 | print(l) -------------------------------------------------------------------------------- /sndkfne.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | printf("Hello World"); 6 | 7 | return 0 ; 8 | } -------------------------------------------------------------------------------- /stack.py: -------------------------------------------------------------------------------- 1 | # Python program to 2 | # demonstrate stack implementation 3 | # using list 4 | 5 | stack = [] 6 | 7 | # append() function to push 8 | # element in the stack 9 | stack.append('a') 10 | stack.append('b') 11 | stack.append('c') 12 | 13 | print('Initial stack') 14 | print(stack) 15 | 16 | # pop() function to pop 17 | # element from stack in 18 | # LIFO order 19 | print('\nElements popped from stack:') 20 | print(stack.pop()) 21 | print(stack.pop()) 22 | print(stack.pop()) 23 | 24 | print('\nStack after elements are popped:') 25 | print(stack) 26 | 27 | # uncommenting print(stack.pop()) 28 | # will cause an IndexError 29 | # as the stack is now empty 30 | -------------------------------------------------------------------------------- /stack_usingLinkedlist.py: -------------------------------------------------------------------------------- 1 | # python3 program to Implement a stack 2 | # using singly linked list 3 | 4 | class Node: 5 | 6 | # Class to create nodes of linked list 7 | # constructor initializes node automatically 8 | def __init__(self, data): 9 | self.data = data 10 | self.next = None 11 | 12 | 13 | class Stack: 14 | 15 | # head is default NULL 16 | def __init__(self): 17 | self.head = None 18 | 19 | # Checks if stack is empty 20 | def isempty(self): 21 | if self.head == None: 22 | return True 23 | else: 24 | return False 25 | 26 | # Method to add data to the stack 27 | # adds to the start of the stack 28 | def push(self, data): 29 | 30 | if self.head == None: 31 | self.head = Node(data) 32 | 33 | else: 34 | newnode = Node(data) 35 | newnode.next = self.head 36 | self.head = newnode 37 | 38 | # Remove element that is the current head (start of the stack) 39 | def pop(self): 40 | 41 | if self.isempty(): 42 | return None 43 | 44 | else: 45 | # Removes the head node and makes 46 | # the preceding one the new head 47 | poppednode = self.head 48 | self.head = self.head.next 49 | poppednode.next = None 50 | return poppednode.data 51 | 52 | # Returns the head node data 53 | def peek(self): 54 | 55 | if self.isempty(): 56 | return None 57 | 58 | else: 59 | return self.head.data 60 | 61 | # Prints out the stack 62 | def display(self): 63 | 64 | iternode = self.head 65 | if self.isempty(): 66 | print("Stack Underflow") 67 | 68 | else: 69 | 70 | while(iternode != None): 71 | 72 | print(iternode.data, end = "") 73 | iternode = iternode.next 74 | if(iternode != None): 75 | print(" -> ", end = "") 76 | return 77 | 78 | 79 | # Driver code 80 | if __name__ == "__main__": 81 | MyStack = Stack() 82 | 83 | MyStack.push(11) 84 | MyStack.push(22) 85 | MyStack.push(33) 86 | MyStack.push(44) 87 | 88 | # Display stack elements 89 | MyStack.display() 90 | 91 | # Print top element of stack 92 | print("\nTop element is ", MyStack.peek()) 93 | 94 | # Delete top elements of stack 95 | MyStack.pop() 96 | MyStack.pop() 97 | 98 | # Display stack elements 99 | MyStack.display() 100 | 101 | # Print top element of stack 102 | print("\nTop element is ", MyStack.peek()) 103 | 104 | # This code is contributed by Mathew George 105 | -------------------------------------------------------------------------------- /stoogeSort.py: -------------------------------------------------------------------------------- 1 | # Python program to implement stooge sort 2 | 3 | def stoogesort(arr, l, h): 4 | if l >= h: 5 | return 6 | 7 | # If first element is smaller 8 | # than last, swap them 9 | if arr[l]>arr[h]: 10 | t = arr[l] 11 | arr[l] = arr[h] 12 | arr[h] = t 13 | 14 | # If there are more than 2 elements in 15 | # the array 16 | if h-l + 1 > 2: 17 | t = (int)((h-l + 1)/3) 18 | 19 | # Recursively sort first 2 / 3 elements 20 | stoogesort(arr, l, (h-t)) 21 | 22 | # Recursively sort last 2 / 3 elements 23 | stoogesort(arr, l + t, (h)) 24 | 25 | # Recursively sort first 2 / 3 elements 26 | # again to confirm 27 | stoogesort(arr, l, (h-t)) 28 | 29 | 30 | # deriver 31 | arr = [2, 4, 5, 3, 1] 32 | n = len(arr) 33 | 34 | stoogesort(arr, 0, n-1) 35 | 36 | for i in range(0, n): 37 | print(arr[i], end = ' ') 38 | -------------------------------------------------------------------------------- /timSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to perform basic timSort 2 | MIN_MERGE = 32 3 | 4 | 5 | def calcMinRun(n): 6 | """Returns the minimum length of a 7 | run from 23 - 64 so that 8 | the len(array)/minrun is less than or 9 | equal to a power of 2. 10 | 11 | e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33, 12 | ..., 127=>64, 128=>32, ... 13 | """ 14 | r = 0 15 | while n >= MIN_MERGE: 16 | r |= n & 1 17 | n >>= 1 18 | return n + r 19 | 20 | 21 | # This function sorts array from left index to 22 | # to right index which is of size atmost RUN 23 | def insertionSort(arr, left, right): 24 | for i in range(left + 1, right + 1): 25 | j = i 26 | while j > left and arr[j] < arr[j - 1]: 27 | arr[j], arr[j - 1] = arr[j - 1], arr[j] 28 | j -= 1 29 | 30 | 31 | # Merge function merges the sorted runs 32 | def merge(arr, l, m, r): 33 | 34 | # original array is broken in two parts 35 | # left and right array 36 | len1, len2 = m - l + 1, r - m 37 | left, right = [], [] 38 | for i in range(0, len1): 39 | left.append(arr[l + i]) 40 | for i in range(0, len2): 41 | right.append(arr[m + 1 + i]) 42 | 43 | i, j, k = 0, 0, l 44 | 45 | # after comparing, we merge those two array 46 | # in larger sub array 47 | while i < len1 and j < len2: 48 | if left[i] <= right[j]: 49 | arr[k] = left[i] 50 | i += 1 51 | 52 | else: 53 | arr[k] = right[j] 54 | j += 1 55 | 56 | k += 1 57 | 58 | # Copy remaining elements of left, if any 59 | while i < len1: 60 | arr[k] = left[i] 61 | k += 1 62 | i += 1 63 | 64 | # Copy remaining element of right, if any 65 | while j < len2: 66 | arr[k] = right[j] 67 | k += 1 68 | j += 1 69 | 70 | 71 | # Iterative Timsort function to sort the 72 | # array[0...n-1] (similar to merge sort) 73 | def timSort(arr): 74 | n = len(arr) 75 | minRun = calcMinRun(n) 76 | 77 | # Sort individual subarrays of size RUN 78 | for start in range(0, n, minRun): 79 | end = min(start + minRun - 1, n - 1) 80 | insertionSort(arr, start, end) 81 | 82 | # Start merging from size RUN (or 32). It will merge 83 | # to form size 64, then 128, 256 and so on .... 84 | size = minRun 85 | while size < n: 86 | 87 | # Pick starting point of left sub array. We 88 | # are going to merge arr[left..left+size-1] 89 | # and arr[left+size, left+2*size-1] 90 | # After every merge, we increase left by 2*size 91 | for left in range(0, n, 2 * size): 92 | 93 | # Find ending point of left sub array 94 | # mid+1 is starting point of right sub array 95 | mid = min(n - 1, left + size - 1) 96 | right = min((left + 2 * size - 1), (n - 1)) 97 | 98 | # Merge sub array arr[left.....mid] & 99 | # arr[mid+1....right] 100 | if mid < right: 101 | merge(arr, left, mid, right) 102 | 103 | size = 2 * size 104 | 105 | 106 | # Driver program to test above function 107 | if __name__ == "__main__": 108 | 109 | arr = [-2, 7, 15, -14, 0, 15, 0, 110 | 7, -7, -4, -13, 5, 8, -14, 12] 111 | 112 | print("Given Array is") 113 | print(arr) 114 | 115 | # Function Call 116 | timSort(arr) 117 | 118 | print("After Sorting Array is") 119 | print(arr) 120 | 121 | -------------------------------------------------------------------------------- /treeSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to 2 | # implement Tree Sort 3 | 4 | # Class containing left and 5 | # right child of current 6 | # node and key value 7 | class Node: 8 | 9 | def __init__(self,item = 0): 10 | self.key = item 11 | self.left,self.right = None,None 12 | 13 | 14 | # Root of BST 15 | root = Node() 16 | 17 | root = None 18 | 19 | # This method mainly 20 | # calls insertRec() 21 | def insert(key): 22 | global root 23 | root = insertRec(root, key) 24 | 25 | # A recursive function to 26 | # insert a new key in BST 27 | def insertRec(root, key): 28 | 29 | # If the tree is empty, 30 | # return a new node 31 | 32 | if (root == None): 33 | root = Node(key) 34 | return root 35 | 36 | # Otherwise, recur 37 | # down the tree 38 | if (key < root.key): 39 | root.left = insertRec(root.left, key) 40 | elif (key > root.key): 41 | root.right = insertRec(root.right, key) 42 | 43 | # return the root 44 | return root 45 | 46 | # A function to do 47 | # inorder traversal of BST 48 | def inorderRec(root): 49 | if (root != None): 50 | inorderRec(root.left) 51 | print(root.key ,end = " ") 52 | inorderRec(root.right) 53 | 54 | def treeins(arr): 55 | for i in range(len(arr)): 56 | insert(arr[i]) 57 | 58 | # Driver Code 59 | arr = [5, 4, 7, 2, 11] 60 | treeins(arr) 61 | inorderRec(root) 62 | 63 | -------------------------------------------------------------------------------- /uncompressed_img.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/uncompressed_img.jpg -------------------------------------------------------------------------------- /weather_notifications_desktop.py: -------------------------------------------------------------------------------- 1 | import os,requests 2 | from win10toast import ToastNotifier 3 | from dotenv import load_dotenv 4 | load_dotenv() 5 | 6 | n = ToastNotifier() 7 | city = input("Enter city name: ") 8 | 9 | url = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="+os.getenv("API_key")+"&units=metric" 10 | 11 | r = requests.get(url,auth= (os.getenv("user"),os.getenv("password"))) 12 | r_dict = r.json() 13 | 14 | 15 | current_temp = r_dict['main']['temp'] 16 | 17 | weather_desc = r_dict['weather'][0]['description'] 18 | 19 | temp = (str(current_temp)) 20 | 21 | desc = str(weather_desc) 22 | 23 | result = "Current temperature is: " + temp + " Celsius in " + city+ ".\nCurrent weather condition is: " + desc 24 | n.show_toast("Live Weather update: ", 25 | result, duration = 10) 26 | -------------------------------------------------------------------------------- /zeroSum.py: -------------------------------------------------------------------------------- 1 | n=int(input('Enter number of inputs:\n')) 2 | arr=[int(input("Enter single number and press enter: ")) for _ in range(n)] 3 | 4 | zero_sum_count=0 5 | for i in range(len(arr)): 6 | tmp=[] 7 | for j in range(i,len(arr)): 8 | tmp.append(arr[j]) 9 | if sum(tmp)==0: 10 | zero_sum_count+=1 11 | print('Number of Subarrays with zero sum = ',zero_sum_count) --------------------------------------------------------------------------------