├── .gitignore ├── 1)knapsack_recursive.py ├── 2048game.py ├── ATM.py ├── Age Calculator.py ├── Areas.py ├── ArmstrongNumberCheck.py ├── Average.py ├── BMI.py ├── BankGame.py ├── Bifurcation diagram .py ├── Blackjack.py ├── Bubble_Sort.py ├── Count_Number_of_Vowels_in_a_File.py ├── Decomposing_factors.py ├── Designer_door_mat.py ├── DigitalClock.py ├── DjikistraAlgorithm.py ├── Economy_chart.py ├── Emoji_Convertor ├── Extracting_Numbers_from_textString.py ├── GUI_Tic_Tac_Toe_pvp.py ├── GeoMetric_sum.py ├── GrayCodetoBinary.py ├── Guessnumber.py ├── HangmanGame.py ├── Human_Readable_Time.py ├── Indianflag-Turtle.py ├── InsertionSort.py ├── JumpSearch.py ├── Largest of the three numbers.py ├── LeapYear.py ├── Levenshtein_distance.py ├── Linear_Search.py ├── Linkedlist_reverse.py ├── MatrixOperation.py ├── MaximizeProfitStockProblem.py ├── Minesweeper_Game.py ├── Multiplication_Table.py ├── OTP generator.py ├── Palindrome.py ├── PasswordGenerator.py ├── Password_generator.py ├── Player.py ├── Pong_Game.py ├── ProductOfSumAndDifference.py ├── Queue.py ├── Queue_using_LL.py ├── Quick_sort.py ├── README.md ├── Radix_sort.py ├── Random Team Generator.py ├── RockPaperScissors.py ├── RomanToInt.py ├── SI_units.py ├── SankeGame_GUI.py ├── Sell Buy Stocks to Max Profit.py ├── Sieve_of _Eratosthenes.py ├── SpeedTypingTestInPython.py ├── Spy_number.py ├── Story-generator-game.py ├── TicTacToe.py ├── Tic_tac_toe_game_in_python.py ├── TowerOfHanoi.py ├── YoutubeDownloader.py ├── addition.py ├── adventure_game.py ├── alphabet_rangoli.py ├── an4gram.py ├── area-of-circle.py ├── arithmetic_progression.py ├── armstrong.py ├── arrayReverse.py ├── automorphic.py ├── banking_system.py ├── binarySearch.py ├── binary_to_decimal.py ├── calculator.py ├── calendar_program.py ├── camelCase-to-snake_case.py ├── cielingOfNumInList.py ├── clock.py ├── collatz_sequence.py ├── college.csv ├── compound-interest.py ├── csvgen.py ├── decimal_to_binary.py ├── dfs.py ├── dice.py ├── dice_roller.py ├── digital_root.py ├── dirTree.py ├── disarium.py ├── disjoint_set_union.py ├── duplicates.py ├── email_slicer.py ├── emi-calculator.py ├── employee.csv ├── factorial.py ├── fast_recursive_fibonacci.py ├── fibonacci.py ├── get_coordinates.py ├── gradient_descent.py ├── guicalculator.py ├── hangman.py ├── hcf_lcm.py ├── huffmantree.py ├── image_compress.py ├── img_to_pencil.py ├── insertion_sort.py ├── kadanes_algorithm.py ├── madlibs.py ├── mask_email_address.py ├── max.py ├── meal-of-the-day.py ├── medianOf2SortedArray.py ├── menu-based_student_record.py ├── merge_sort.py ├── notification.py ├── novowels.py ├── number_base_converter.py ├── paranthesis_checker.py ├── parse_csv.py ├── perfect_num.py ├── power_of_a_number.py ├── prime factors of a given number.py ├── prime.py ├── print_decreasing_number.py ├── print_incerasing_number.py ├── print_star_using_loops.py ├── python graphics.py ├── qr.py ├── radixSort.py ├── rainbowSpiral.py ├── random_password_generator.py ├── reddit_scraper.py ├── remove-vowels.py ├── reverse32bitsignedint.py ├── reverse_number.py ├── reverse_words_of_string.py ├── rock-paper-scissors.py ├── rupiah_budgeting_plan.py ├── selection_sort.py ├── sha256_hashing.py ├── simple-interest.py ├── simple_custom_hash_map_implementation.py ├── simple_vending_machine.py ├── snakegame.py ├── soundex.py ├── strong.py ├── substring.py ├── subtitle_synchronizer.py ├── sum-of-divisors.py ├── temperature_convertor_gui.py ├── text-audio-generator.py ├── text-to-emoji.py ├── turtle race.py ├── twoSumusingHashMap.py ├── two_sum_using_two_pointers.py ├── university.csv ├── vendingitems.txt ├── video_jpeg_converter.py ├── weather_gui.py ├── webscraper.py └── weightConverterGUI.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 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 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 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /1)knapsack_recursive.py: -------------------------------------------------------------------------------- 1 | def knapsack_recursive(wt,val,W,n): 2 | if n==0 or W==0: 3 | return 0 4 | else: 5 | if wt[n-1]<=W: 6 | return max(val[n-1]+knapsack_recursive(wt,val,W-wt[n-1],n-1),knapsack_recursive(wt,val,W,n-1)) 7 | elif wt[n-1]>W: 8 | return knapsack_recursive(wt,val,W,n-1) 9 | W = 6 10 | wt = [1,2,3,6] 11 | val = [1,2,4,6] 12 | n=4 13 | knapsack_recursive(wt,val,W,n) 14 | 15 | -------------------------------------------------------------------------------- /2048game.py: -------------------------------------------------------------------------------- 1 | # logic.py to be 2 | # imported in the 2048.py file 3 | 4 | # importing random package 5 | # for methods to generate random 6 | # numbers. 7 | import random 8 | 9 | # function to initialize game / grid 10 | # at the start 11 | def start_game(): 12 | 13 | # declaring an empty list then 14 | # appending 4 list each with four 15 | # elements as 0. 16 | mat =[] 17 | for i in range(4): 18 | mat.append([0] * 4) 19 | 20 | # printing controls for user 21 | print("Commands are as follows : ") 22 | print("'W' or 'w' : Move Up") 23 | print("'S' or 's' : Move Down") 24 | print("'A' or 'a' : Move Left") 25 | print("'D' or 'd' : Move Right") 26 | 27 | # calling the function to add 28 | # a new 2 in grid after every step 29 | add_new_2(mat) 30 | return mat 31 | 32 | # function to add a new 2 in 33 | # grid at any random empty cell 34 | def add_new_2(mat): 35 | 36 | # choosing a random index for 37 | # row and column. 38 | r = random.randint(0, 3) 39 | c = random.randint(0, 3) 40 | 41 | # while loop will break as the 42 | # random cell chosen will be empty 43 | # (or contains zero) 44 | while(mat[r] != 0): 45 | r = random.randint(0, 3) 46 | c = random.randint(0, 3) 47 | 48 | # we will place a 2 at that empty 49 | # random cell. 50 | mat[r] = 2 51 | 52 | # function to get the current 53 | # state of game 54 | def get_current_state(mat): 55 | 56 | # if any cell contains 57 | # 2048 we have won 58 | for i in range(4): 59 | for j in range(4): 60 | if(mat[i][j]== 2048): 61 | return 'WON' 62 | 63 | # if we are still left with 64 | # atleast one empty cell 65 | # game is not yet over 66 | for i in range(4): 67 | for j in range(4): 68 | if(mat[i][j]== 0): 69 | return 'GAME NOT OVER' 70 | 71 | # or if no cell is empty now 72 | # but if after any move left, right, 73 | # up or down, if any two cells 74 | # gets merged and create an empty 75 | # cell then also game is not yet over 76 | for i in range(3): 77 | for j in range(3): 78 | if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]): 79 | return 'GAME NOT OVER' 80 | 81 | for j in range(3): 82 | if(mat[3][j]== mat[3][j + 1]): 83 | return 'GAME NOT OVER' 84 | 85 | for i in range(3): 86 | if(mat[i][3]== mat[i + 1][3]): 87 | return 'GAME NOT OVER' 88 | 89 | # else we have lost the game 90 | return 'LOST' 91 | 92 | # all the functions defined below 93 | # are for left swap initially. 94 | 95 | # function to compress the grid 96 | # after every step before and 97 | # after merging cells. 98 | def compress(mat): 99 | 100 | # bool variable to determine 101 | # any change happened or not 102 | changed = False 103 | 104 | # empty grid 105 | new_mat = [] 106 | 107 | # with all cells empty 108 | for i in range(4): 109 | new_mat.append([0] * 4) 110 | 111 | # here we will shift entries 112 | # of each cell to it's extreme 113 | # left row by row 114 | # loop to traverse rows 115 | for i in range(4): 116 | pos = 0 117 | 118 | # loop to traverse each column 119 | # in respective row 120 | for j in range(4): 121 | if(mat[i][j] != 0): 122 | 123 | # if cell is non empty then 124 | # we will shift it's number to 125 | # previous empty cell in that row 126 | # denoted by pos variable 127 | new_mat[i][pos] = mat[i][j] 128 | 129 | if(j != pos): 130 | changed = True 131 | pos += 1 132 | 133 | # returning new compressed matrix 134 | # and the flag variable. 135 | return new_mat, changed 136 | 137 | # function to merge the cells 138 | # in matrix after compressing 139 | def merge(mat): 140 | 141 | changed = False 142 | 143 | for i in range(4): 144 | for j in range(3): 145 | 146 | # if current cell has same value as 147 | # next cell in the row and they 148 | # are non empty then 149 | if(mat[i][j] == mat[i][j + 1] and mat[i][j] != 0): 150 | 151 | # double current cell value and 152 | # empty the next cell 153 | mat[i][j] = mat[i][j] * 2 154 | mat[i][j + 1] = 0 155 | 156 | # make bool variable True indicating 157 | # the new grid after merging is 158 | # different. 159 | changed = True 160 | 161 | return mat, changed 162 | 163 | # function to reverse the matrix 164 | # means reversing the content of 165 | # each row (reversing the sequence) 166 | def reverse(mat): 167 | new_mat =[] 168 | for i in range(4): 169 | new_mat.append([]) 170 | for j in range(4): 171 | new_mat[i].append(mat[i][3 - j]) 172 | return new_mat 173 | 174 | # function to get the transpose 175 | # of matrix means interchanging 176 | # rows and column 177 | def transpose(mat): 178 | new_mat = [] 179 | for i in range(4): 180 | new_mat.append([]) 181 | for j in range(4): 182 | new_mat[i].append(mat[j][i]) 183 | return new_mat 184 | 185 | # function to update the matrix 186 | # if we move / swipe left 187 | def move_left(grid): 188 | 189 | # first compress the grid 190 | new_grid, changed1 = compress(grid) 191 | 192 | # then merge the cells. 193 | new_grid, changed2 = merge(new_grid) 194 | 195 | changed = changed1 or changed2 196 | 197 | # again compress after merging. 198 | new_grid, temp = compress(new_grid) 199 | 200 | # return new matrix and bool changed 201 | # telling whether the grid is same 202 | # or different 203 | return new_grid, changed 204 | 205 | # function to update the matrix 206 | # if we move / swipe right 207 | def move_right(grid): 208 | 209 | # to move right we just reverse 210 | # the matrix 211 | new_grid = reverse(grid) 212 | 213 | # then move left 214 | new_grid, changed = move_left(new_grid) 215 | 216 | # then again reverse matrix will 217 | # give us desired result 218 | new_grid = reverse(new_grid) 219 | return new_grid, changed 220 | 221 | # function to update the matrix 222 | # if we move / swipe up 223 | def move_up(grid): 224 | 225 | # to move up we just take 226 | # transpose of matrix 227 | new_grid = transpose(grid) 228 | 229 | # then move left (calling all 230 | # included functions) then 231 | new_grid, changed = move_left(new_grid) 232 | 233 | # again take transpose will give 234 | # desired results 235 | new_grid = transpose(new_grid) 236 | return new_grid, changed 237 | 238 | # function to update the matrix 239 | # if we move / swipe down 240 | def move_down(grid): 241 | 242 | # to move down we take transpose 243 | new_grid = transpose(grid) 244 | 245 | # move right and then again 246 | new_grid, changed = move_right(new_grid) 247 | 248 | # take transpose will give desired 249 | # results. 250 | new_grid = transpose(new_grid) 251 | return new_grid, changed 252 | 253 | # this file only contains all the logic 254 | # functions to be called in main function 255 | # present in the other file 256 | -------------------------------------------------------------------------------- /ATM.py: -------------------------------------------------------------------------------- 1 | #ATM Machine Using python 2 | 3 | print("="*30, "Welcome to Python Bank ATM", "="*30) 4 | 5 | restart = ("Y") 6 | chances = 3 7 | balance = 999.99 8 | 9 | while chances >= 0: 10 | pin = int(input("\nPlease enter your 4 Digit pin: ")) 11 | if pin == (1234): 12 | print("\nCorrect pin!!") 13 | 14 | while restart not in ("n", "no", "N", "NO"): 15 | print("\nPlease Press 1 For Your Balance.") 16 | print("Please Press 2 To Make a Withdrawl.") 17 | print("Please Press 3 To Pay in.") 18 | print("Please Press 4 To Return Card.") 19 | 20 | option = int(input("\nWhat Would you like to Choose?: ")) 21 | 22 | if option == 1: 23 | print(f"\nYour Balance is: ${balance}") 24 | restart = input("\nWould You like to do something else? ") 25 | 26 | if restart in ("n", "no", "N", "NO"): 27 | print("\nThank You\n") 28 | break 29 | 30 | elif option == 2: 31 | option2 = ("y") 32 | withdrawl = float(input("\nHow Much Would you like to withdraw? 10, 20, 40, 60, 80, 100 for other enter 1: ")) 33 | 34 | if withdrawl in [10, 20, 40, 60, 80, 100]: 35 | balance = balance - withdrawl 36 | print(f"\nYour balance after the withdrawl is ${balance}") 37 | restart = input("\nWould You like to do something else? ") 38 | 39 | if restart in ("n", "no", "N", "NO"): 40 | print("\nThank You\n") 41 | break 42 | 43 | elif withdrawl == 1: 44 | withdrawl = float(input("\nPlease Enter Desired amount: ")) 45 | balance = balance - withdrawl 46 | print(f"\nYour balance after the withdrawl is ${balance}") 47 | restart = input("\nWould You like to do something else? ") 48 | 49 | if restart in ("n", "no", "N", "NO"): 50 | print("\nThank You\n") 51 | break 52 | 53 | elif withdrawl != [10, 20, 40, 60, 80, 100]: 54 | print("\nINVALID AMOUNT, Please try Again\n") 55 | restart = ("y") 56 | 57 | elif option == 3: 58 | pay_in = float(input("\nHow Much Would you like to Pay In? ")) 59 | balance = balance + pay_in 60 | print(f"\nYour balance after the Pay-in is ${balance}") 61 | restart = input("\nWould You like to do something else? ") 62 | 63 | if restart in ("n", "no", "N", "NO"): 64 | print("\nThank You\n") 65 | break 66 | 67 | elif option == 4: 68 | print("\nPlease wait whilst your card is Returned....") 69 | print("\nThank you for your service") 70 | break 71 | 72 | else: 73 | print("\nPlease enter a correct number.\n") 74 | restart = ("y") 75 | 76 | elif pin != (1234): 77 | print("\nINCORRECT PIN!!\n") 78 | chances = chances - 1 79 | 80 | if chances == 0: 81 | print("Calling the Police...\n") 82 | break -------------------------------------------------------------------------------- /Age Calculator.py: -------------------------------------------------------------------------------- 1 | # Calculate the complete age of a person in years, months and days 2 | 3 | import datetime 4 | 5 | def calculate_age(born): 6 | today = datetime.date.today() 7 | return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) 8 | 9 | def main(): 10 | 11 | # Get the date of birth 12 | dob = input("Enter your date of birth (YYYY-MM-DD): ") 13 | 14 | # Split the date into year, month and day 15 | year, month, day = map(int, dob.split('-')) 16 | 17 | # Calculate the age 18 | age = calculate_age(datetime.date(year, month, day)) 19 | 20 | # Print the age 21 | print("Your age is: {}".format(age)) 22 | 23 | if __name__ == '__main__': 24 | main() -------------------------------------------------------------------------------- /Areas.py: -------------------------------------------------------------------------------- 1 | # Program to calculate the areas of 2d shapes 2 | 3 | import math 4 | 5 | def square(side): 6 | area = side * side 7 | return area 8 | 9 | def rectangle(length, breadth): 10 | area = length * breadth 11 | return area 12 | 13 | def triangle(side1, side2, side3): 14 | s = (side1 + side2 + side3)/2 15 | area = math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) 16 | return area 17 | 18 | def circle(radius): 19 | area = 3.14 * radius * radius 20 | return area 21 | 22 | final_area = 0.0 23 | print("Choose the shape you want to calculate area of: ") 24 | 25 | while True: 26 | print("Square, Rectangle, Triangle, Circle") 27 | shape = input('>> ') 28 | print(shape.lower()) 29 | 30 | if shape.lower() == "square": 31 | side = float(input("Enter the value of side: ")) 32 | final_area = square(side) 33 | break 34 | 35 | elif shape.lower() == "rectangle": 36 | length = float(input("Enter value of length: ")) 37 | breadth = float(input("Enter value of breadth: ")) 38 | final_area = rectangle(length, breadth) 39 | break 40 | 41 | elif shape.lower() == "triangle": 42 | side1 = float(input("Enter the value of 1st side: ")) 43 | side2 = float(input("Enter the value of 2nd side: ")) 44 | side3 = float(input("Enter the value of 3rd side: ")) 45 | final_area = triangle(side1, side2, side3) 46 | break 47 | 48 | elif shape.lower() == "circle": 49 | radius = float(input("Enter the value of radius: ")) 50 | final_area = circle(radius) 51 | break 52 | 53 | else: 54 | print("Please choose a shape from the given 4 or check your spelling again") 55 | 56 | print(f"The area of the shape is: {final_area}") -------------------------------------------------------------------------------- /ArmstrongNumberCheck.py: -------------------------------------------------------------------------------- 1 | print("An Armstrong Number is a number which is equal to the sum of the cubes of it's digits.") 2 | inputNumber = input("Enter a number to check if it's an Armstrong Number or not: ") 3 | sumOfCubes=0 4 | 5 | for digit in inputNumber: 6 | sumOfCubes+=int(digit)**3 7 | 8 | if sumOfCubes==int(inputNumber): print(inputNumber,"is an Armstrong Number.") 9 | else: print(inputNumber,"is NOT an Armstrong Number.") 10 | -------------------------------------------------------------------------------- /Average.py: -------------------------------------------------------------------------------- 1 | n=int(input("Enter the number of elements to be inserted: ")) 2 | a=[] 3 | for i in range(0,n): 4 | elem=int(input("Enter element: ")) 5 | a.append(elem) 6 | avg=sum(a)/n 7 | print("Average of elements in the list",round(avg,2)) 8 | -------------------------------------------------------------------------------- /BMI.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import messagebox 3 | 4 | def reset_entry(): 5 | age_tf.delete(0,'end') 6 | height_tf.delete(0,'end') 7 | weight_tf.delete(0,'end') 8 | 9 | def calculate_bmi(): 10 | kg = int(weight_tf.get()) 11 | m = int(height_tf.get())/100 12 | bmi = kg/(m*m) 13 | bmi = round(bmi, 1) 14 | bmi_index(bmi) 15 | 16 | def bmi_index(bmi): 17 | 18 | if bmi < 18.5: 19 | messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Underweight') 20 | elif (bmi > 18.5) and (bmi < 24.9): 21 | messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Normal') 22 | elif (bmi > 24.9) and (bmi < 29.9): 23 | messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Overweight') 24 | elif (bmi > 29.9): 25 | messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Obesity') 26 | else: 27 | messagebox.showerror('bmi-pythonguides', 'something went wrong!') 28 | 29 | ws = Tk() 30 | ws.title('BMI') 31 | ws.geometry('400x300') 32 | ws.config(bg='#686e70') 33 | 34 | var = IntVar() 35 | 36 | frame = Frame( 37 | ws, 38 | padx=10, 39 | pady=10 40 | ) 41 | frame.pack(expand=True) 42 | 43 | 44 | age_lb = Label( 45 | frame, 46 | text="Enter Age (2 - 120)" 47 | ) 48 | age_lb.grid(row=1, column=1) 49 | 50 | age_tf = Entry( 51 | frame, 52 | ) 53 | age_tf.grid(row=1, column=2, pady=5) 54 | 55 | gen_lb = Label( 56 | frame, 57 | text='Select Gender' 58 | ) 59 | gen_lb.grid(row=2, column=1) 60 | 61 | frame2 = Frame( 62 | frame 63 | ) 64 | frame2.grid(row=2, column=2, pady=5) 65 | 66 | male_rb = Radiobutton( 67 | frame2, 68 | text = 'Male', 69 | variable = var, 70 | value = 1 71 | ) 72 | male_rb.pack(side=LEFT) 73 | 74 | female_rb = Radiobutton( 75 | frame2, 76 | text = 'Female', 77 | variable = var, 78 | value = 2 79 | ) 80 | female_rb.pack(side=RIGHT) 81 | 82 | height_lb = Label( 83 | frame, 84 | text="Enter Height (cm) " 85 | ) 86 | height_lb.grid(row=3, column=1) 87 | 88 | weight_lb = Label( 89 | frame, 90 | text="Enter Weight (kg) ", 91 | 92 | ) 93 | weight_lb.grid(row=4, column=1) 94 | 95 | height_tf = Entry( 96 | frame, 97 | ) 98 | height_tf.grid(row=3, column=2, pady=5) 99 | 100 | weight_tf = Entry( 101 | frame, 102 | ) 103 | weight_tf.grid(row=4, column=2, pady=5) 104 | 105 | frame3 = Frame( 106 | frame 107 | ) 108 | frame3.grid(row=5, columnspan=3, pady=10) 109 | 110 | cal_btn = Button( 111 | frame3, 112 | text='Calculate', 113 | command=calculate_bmi 114 | ) 115 | cal_btn.pack(side=LEFT) 116 | 117 | reset_btn = Button( 118 | frame3, 119 | text='Reset', 120 | command=reset_entry 121 | ) 122 | reset_btn.pack(side=LEFT) 123 | 124 | exit_btn = Button( 125 | frame3, 126 | text='Exit', 127 | command=lambda:ws.destroy() 128 | ) 129 | exit_btn.pack(side=RIGHT) 130 | 131 | ws.mainloop() 132 | -------------------------------------------------------------------------------- /BankGame.py: -------------------------------------------------------------------------------- 1 | #default password is 4758 2 | import random 3 | class BankGame : 4 | @staticmethod 5 | def main( args) : 6 | print("---WELCOME TO ELIX BANKING SERVICES---") 7 | print("") 8 | print("________________________") 9 | print("Enter your name: ") 10 | name = input() 11 | # I am inserting do loop to make the program run forever under correct inputs. 12 | print("Hi, " + name + "\bWelcome to my program!") 13 | print("____________________________") 14 | print("Do you want to start/repeat the program?") 15 | print("Enter Y for Yes and N for No: ") 16 | temp = input()[0] 17 | passw = 4758 18 | bal = 10000 19 | leftbal = 0 20 | print("If you don\'t know the password refer the first line of the program") 21 | print("Please enter the password: ") 22 | # Condition when the statement goes true i.e.- temp equals 1 23 | while True : 24 | if (temp == 'Y' or temp == 'y') : 25 | if (passw == 4758) : 26 | print("") 27 | print("Your initial account balance is Rs. 10000") 28 | # Using for statement to perform 5 operation on each login 29 | x = 0 30 | while (x <= 6) : 31 | print("0. Exit") 32 | print("1. Deposit") 33 | print("2. Withdraw") 34 | print("3. Change passcode") 35 | print("4. Check balance") 36 | print("5. Customer care") 37 | print("Enter the serial no. of your choice") 38 | choice = int(input()) 39 | print("Enter captha to verify that you are not a robot.") 40 | captha = random.randrange(10000) 41 | print(captha) 42 | print("Enter the number shown above: ") 43 | verify = int(input()) 44 | if (verify == captha) : 45 | # If captha gets matched, then these switch statements are executed. 46 | if (choice==0): 47 | print("BYE!......" + name + " HAVE A NICE DAY!") 48 | print("__________________________") 49 | print("@author>[@programmer-yash") 50 | print("Please comment here or open an issue if you have any queries or suggestions!") 51 | print("") 52 | print("#hacktoberfest") 53 | return 0 54 | elif(choice==1): 55 | print("You have chosen to deposit.") 56 | print("Enter the amount to deposit : ") 57 | deposit = int(input()) 58 | bal = bal + deposit 59 | print(str(deposit) + " has been deposited to your account.") 60 | print("Left balance is " + str(bal)) 61 | elif(choice==2): 62 | print("You have chosen to withdraw.") 63 | print("Enter the amount to be withdrawn") 64 | withdraw = int(input()) 65 | print(str(+withdraw) + " has been withdrawn from your account.") 66 | bal = bal - withdraw 67 | print("Check the cash printer.") 68 | print("Left balance is " + str(bal)) 69 | elif(choice==3): 70 | print("You have chosen to change passcode.") 71 | print("Enter the current passcode: ") 72 | check = int(input()) 73 | if (check == passw) : 74 | print("Enter the new passcode") 75 | newP = int(input()) 76 | passw = newP 77 | print("Your new password is " + str(newP)) 78 | else : 79 | print("Wrong passcode!") 80 | elif(choice==4): 81 | print("You have chosen to check balanace.") 82 | print("Your current account balance is " + str(bal)) 83 | elif(choice==5): 84 | print("You have chosen for customer care.") 85 | print("Contact us at:") 86 | print(" Email: yash197911@gmail.com") 87 | else: 88 | print("Wrong choice!!! Choose again...!") 89 | else : 90 | print("xCAPTHA NOT CORRECTx") 91 | x += 1 92 | continue 93 | elif(temp == 'N' or temp == 'n') : 94 | print("BYE!......" + name + " HAVE A NICE DAY!") 95 | print("__________________________") 96 | print("@author>[@programmer-offbeat]") 97 | print("Please comment here if you have any queries or suggestions!") 98 | print("--OR--") 99 | print("create an issue") 100 | print("I will rightly see and reply to your messages and suggestions!") 101 | print() 102 | print("HAPPY CODING!:-)") 103 | return 0 104 | else : 105 | print("Err!..... You have entered a wrong choice!") 106 | print("Try again....!") 107 | # Comdition if password mismatches. 108 | if (passw != 4758) : 109 | print("You have entered wrong password.....Try again!") 110 | if((temp < 100) == False) : 111 | break 112 | 113 | 114 | if __name__=="__main__": 115 | BankGame.main([]) 116 | -------------------------------------------------------------------------------- /Bifurcation diagram .py: -------------------------------------------------------------------------------- 1 | # Bifurcation diagram 2 | 3 | 4 | from cmath import inf 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | import math 8 | import csv 9 | import matplotlib as mpl 10 | import time 11 | from numba import njit 12 | import multiprocessing 13 | from multiprocessing import Pool 14 | multiprocessing.cpu_count() 15 | from functools import reduce 16 | 17 | from functools import partial 18 | 19 | 20 | 21 | start_time = time.time() 22 | 23 | 24 | #change these values 25 | x0=0.1 26 | begin_r=0 27 | end_r=4 28 | step=0.0001 29 | 30 | 31 | 32 | r=np.arange(begin_r,end_r,step) 33 | X=[] 34 | Y=[] 35 | 36 | @njit 37 | def bif(x0, r): 38 | N=1000 39 | x = np.zeros(len(range(0, N))) 40 | x[0]=x0 41 | for i in range(1,N): 42 | x[i] = r * x[i-1] * (1 - x[i-1]) #logistic map #logistic with extra parameter 43 | 44 | return (x[-130:]) 45 | 46 | bif1 = partial(bif,x0) 47 | if __name__ == '__main__': 48 | # create and configure the process pool 49 | with Pool(4) as p: 50 | 51 | for i,ch in enumerate(p.map(bif1,r,chunksize=2500)) : 52 | x1=np.ones(len(ch))*r[i] 53 | X.append(x1) 54 | Y.append(ch) 55 | print("--- %s seconds ---" % (time.time() - start_time)) 56 | 57 | plt.style.use('dark_background') 58 | plt.plot(X,Y, ".w", alpha=1, ms=1.2) 59 | figure = plt.gcf() # get current figure 60 | figure.set_size_inches(1920 / 40, 1080 / 40) 61 | # print("--- %s seconds ---" % (time.time() - start_time)) 62 | plt.show() 63 | 64 | -------------------------------------------------------------------------------- /Blackjack.py: -------------------------------------------------------------------------------- 1 | logo=""" 2 | .------. _ _ _ _ _ 3 | |A_ _ |. | | | | | | (_) | | 4 | |( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __ 5 | | \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ / 6 | | \/ | / \ | | |_) | | (_| | (__| <| | (_| | (__| < 7 | `-----| \ / | |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\ 8 | | \/ K| _/ | 9 | `------' |__/ 10 | """ 11 | import random 12 | 13 | print(logo) 14 | cards=[11,2,3,4,5,6,7,8,9,10,10,10,10] 15 | 16 | player=[] 17 | computer=[] 18 | 19 | player_sum=0 20 | computer_sum=0 21 | 22 | player.append(random.choice(cards)) 23 | 24 | 25 | rand = random.choice(cards) 26 | if (rand == 11 and rand + computer_sum > 21): 27 | player.append(1) 28 | else: 29 | player.append(rand) 30 | 31 | 32 | computer.append(random.choice(cards)) 33 | 34 | 35 | randco = random.choice(cards) 36 | if (rand == 11 and rand + computer_sum > 21): 37 | computer.append(1) 38 | else: 39 | computer.append(rand) 40 | 41 | player_sum+=player[0]+player[1] 42 | computer_sum+=computer[0]+computer[1] 43 | 44 | while(player_sum<=21): 45 | print(f"Your cards : {player} ,current score : {player_sum}") 46 | print(f"Computer's first card : {computer[0]}") 47 | 48 | accept=input("Type y to get another card , Type n to pass : ") 49 | if(accept=='y'): 50 | rand=random.choice(cards) 51 | if(rand==11 and rand+player_sum>21): 52 | player_sum+=1 53 | player.append(1) 54 | else: 55 | player_sum+=rand 56 | player.append(rand) 57 | else:break 58 | 59 | if player_sum>21: 60 | print(f"Your cards : {player} ,current score : {player_sum}") 61 | print("You Lost") 62 | exit() 63 | 64 | while computer_sum 21): 67 | computer_sum += 1 68 | computer.append(1) 69 | else: 70 | computer_sum += rand 71 | computer.append(rand) 72 | 73 | if computer_sum>21 or player_sum>computer_sum : 74 | print(f"Your cards : {player} ,Your score : {player_sum}") 75 | print(f"Computer cards : {computer} ,Computer score : {computer_sum}") 76 | 77 | print("You Won") 78 | exit() 79 | if(computer_sum==player_sum): 80 | print(f"Your cards : {player} ,Your score : {player_sum}") 81 | print(f"Computer cards : {computer} ,Computer score : {computer_sum}") 82 | 83 | print("Draw!!") 84 | exit() 85 | 86 | if(computer_sum>player_sum): 87 | print(f"Your cards : {player} ,Your score : {player_sum}") 88 | print(f"Computer cards : {computer} ,Computer score : {computer_sum}") 89 | 90 | print("You Lost") 91 | exit() -------------------------------------------------------------------------------- /Bubble_Sort.py: -------------------------------------------------------------------------------- 1 | # Python Program for implementation of 2 | # Recursive Bubble sort 3 | class bubbleSort: 4 | 5 | def __init__(self, array): 6 | self.array = array 7 | self.length = len(array) 8 | 9 | def __str__(self): 10 | return " ".join([str(x) 11 | for x in self.array]) 12 | 13 | def bubbleSortRecursive(self, n=None): 14 | if n is None: 15 | n = self.length 16 | count = 0 17 | 18 | # Base case 19 | if n == 1: 20 | return 21 | # One pass of bubble sort. After 22 | # this pass, the largest element 23 | # is moved (or bubbled) to end. 24 | for i in range(n - 1): 25 | if self.array[i] > self.array[i + 1]: 26 | self.array[i], self.array[i + 27 | 1] = self.array[i + 1], self.array[i] 28 | count = count + 1 29 | 30 | # Check if any recursion happens or not 31 | # If any recursion is not happen then return 32 | if (count==0): 33 | return 34 | 35 | # Largest element is fixed, 36 | # recur for remaining array 37 | self.bubbleSortRecursive(n - 1) 38 | 39 | # Driver Code 40 | def main(): 41 | array = [64, 34, 25, 12, 22, 11, 90] 42 | 43 | sort = bubbleSort(array) 44 | 45 | sort.bubbleSortRecursive() 46 | print("Sorted array :\n", sort) 47 | 48 | # Tests ('pip install pytest'; run with 'pytest Bubble_Sort.py') 49 | def test_result_in_order(): 50 | array = [64, 34, 25, 12, 22, 11, 90] 51 | sort = bubbleSort(array) 52 | sort.bubbleSortRecursive() 53 | for i in range(sort.length-1): 54 | assert sort.array[i] < sort.array[i+1] 55 | 56 | 57 | if __name__ == "__main__": 58 | main() -------------------------------------------------------------------------------- /Count_Number_of_Vowels_in_a_File.py: -------------------------------------------------------------------------------- 1 | ######## This program counts and returns the number of vowels in a text file. ######## 2 | 3 | # Ask the user for the name of the file. The file should be in the same folder and should be a text file. 4 | print("Enter the Name of File: ") 5 | 6 | # Convert the name to string and open the file in read mode 7 | fileName = str(input()) 8 | fileHandle = open(fileName, "r") 9 | 10 | # Declare a variable to store the number of vowels. Initally it is zero. 11 | count = 0 12 | 13 | # create an array of all the vowels (upper and lower case) that can be used to compare and determine if a character is a vowel 14 | vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] 15 | 16 | # Read each character and compare it to the characters in the array. If found in the vowels array, then increase count. 17 | for char in fileHandle.read(): 18 | if char in vowels: 19 | count = count+1 20 | 21 | # Close the file 22 | fileHandle.close() 23 | 24 | # Print the count to the screen for the user to see. 25 | print("\nThe total number of vowels in the text are:") 26 | print(count) 27 | -------------------------------------------------------------------------------- /Decomposing_factors.py: -------------------------------------------------------------------------------- 1 | def prime_factors(n): 2 | final = [] 3 | rstr = '' 4 | while n != 1: 5 | for x in range(2,n+1): 6 | if n % x == 0: 7 | n //= x 8 | final.append(x) 9 | break 10 | for x in final: 11 | if f'({x}**{final.count(x)})' in rstr: 12 | continue 13 | rstr += f'({x}**{final.count(x)})' if final.count(x) > 1 else f'({x})' 14 | return rstr 15 | 16 | #Function that decomposes number into their base multiplicants. Usefull for simplifications of square roots etc. 17 | #Example: prime_factors(30) outputs (2)(3)(5) because 30 = 2 * 3 * 5 18 | -------------------------------------------------------------------------------- /Designer_door_mat.py: -------------------------------------------------------------------------------- 1 | pattern = '.|.' 2 | a, b = map(int, input().split()) # 5 < a < 101 and 15 < b < 303 3 | 4 | for i in range(1,a,2): 5 | print((pattern*i).center(b, '-')) 6 | 7 | print('WELCOME'.center(b,'-')) 8 | 9 | for i in reversed(range(1,a,2)): 10 | print((pattern*i).center(b, '-')) -------------------------------------------------------------------------------- /DigitalClock.py: -------------------------------------------------------------------------------- 1 | # importing whole module 2 | from tkinter import * 3 | from tkinter.ttk import * 4 | 5 | # importing strftime function to 6 | # retrieve system's time 7 | from time import strftime 8 | 9 | # creating tkinter window 10 | root = Tk() 11 | root.title('Clock') 12 | 13 | # This function is used to 14 | # display time on the label 15 | def time(): 16 | string = strftime('%H:%M:%S %p') 17 | lbl.config(text = string) 18 | lbl.after(1000, time) 19 | 20 | # Styling the label widget so that clock 21 | # will look more attractive 22 | lbl = Label(root, font = ('calibri', 40, 'bold'), 23 | background = 'purple', 24 | foreground = 'white') 25 | 26 | # Placing clock at the centre 27 | # of the tkinter window 28 | lbl.pack(anchor = 'center') 29 | time() 30 | 31 | mainloop() 32 | -------------------------------------------------------------------------------- /DjikistraAlgorithm.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self): 3 | self.nodes = set() 4 | self.edges = defaultdict(list) 5 | self.distances = {} 6 | 7 | def add_node(self, value): 8 | self.nodes.add(value) 9 | 10 | def add_edge(self, from_node, to_node, distance): 11 | self.edges[from_node].append(to_node) 12 | self.edges[to_node].append(from_node) 13 | self.distances[(from_node, to_node)] = distance 14 | 15 | 16 | def dijsktra(graph, initial): 17 | visited = {initial: 0} 18 | path = {} 19 | 20 | nodes = set(graph.nodes) 21 | 22 | while nodes: 23 | min_node = None 24 | for node in nodes: 25 | if node in visited: 26 | if min_node is None: 27 | min_node = node 28 | elif visited[node] < visited[min_node]: 29 | min_node = node 30 | 31 | if min_node is None: 32 | break 33 | 34 | nodes.remove(min_node) 35 | current_weight = visited[min_node] 36 | 37 | for edge in graph.edges[min_node]: 38 | weight = current_weight + graph.distance[(min_node, edge)] 39 | if edge not in visited or weight < visited[edge]: 40 | visited[edge] = weight 41 | path[edge] = min_node 42 | 43 | return visited, path -------------------------------------------------------------------------------- /Economy_chart.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt; plt.rcdefaults() 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | #objects = ('America', 'India', 'Africa', 'UK', 'UAE','Iran') 6 | objects = ('Brazil', 'Italy', 'Canada', 'France', 'UK','India','Germany','Japan','China','USA') 7 | y_pos = np.arange(len(objects)) 8 | performance=[1.80,2.00,2.10,2.80,3.30,3.50,4.10,4.80,19.80,24.10] 9 | 10 | plt.barh(y_pos, performance, align='center', alpha=1) 11 | plt.yticks(y_pos, objects) 12 | plt.xlabel('Usage') 13 | plt.title('Top 10 Economies of the World in 2022') 14 | 15 | plt.show() 16 | -------------------------------------------------------------------------------- /Emoji_Convertor: -------------------------------------------------------------------------------- 1 | message = input("> ") 2 | words = message.split() 3 | emojis = { 4 | ":)" :"😄", 5 | ":(" :"😔", 6 | ":D" :"😁" 7 | 8 | } 9 | output = " " 10 | for word in words: 11 | output+=emojis.get( word,word) + " " 12 | print(output) 13 | -------------------------------------------------------------------------------- /Extracting_Numbers_from_textString.py: -------------------------------------------------------------------------------- 1 | # Given Sentence 2 | sentence="Ramu have 150 Apples and 10 bananas" 3 | sentence2="Ramu Sell 1 Apple at 15.5 Rupees" 4 | 5 | list1=[] 6 | list2=[] 7 | 8 | sum=0 9 | sum2=0 10 | # split is used to split sentence 11 | # This code is not fit for Decimal Nos. 12 | 13 | print("---------------EXTRACTING NUMBER FROM STRING---------------\n") 14 | for word in sentence.split(): 15 | if word.isdigit(): 16 | list1.append(word) 17 | 18 | print("New List",list1) 19 | 20 | 21 | 22 | # Calculating the SUM 23 | for i in list1: 24 | sum=sum+int(i) 25 | 26 | print("No. without Fraction \nsum=",sum,"\n") 27 | 28 | # If Decimal Numbers occured in the Sentence 29 | for word2 in sentence2.split(): 30 | if not word2.isalpha(): 31 | list2.append(word2) 32 | 33 | print("New List",list2) 34 | 35 | # Calculating the SUM 36 | for j in list2: 37 | sum2=sum2+float(j) 38 | 39 | print("No. with Fraction \nsum=",sum2) 40 | print("-----------------------------------------------------------") -------------------------------------------------------------------------------- /GUI_Tic_Tac_Toe_pvp.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from functools import partial 3 | import time 4 | 5 | gui=tk.Tk() 6 | gui.geometry('500x200') 7 | gui.title('Tic Tac Toe') 8 | 9 | movesPlayed=[] 10 | game_over=False 11 | 12 | Xcount=0 13 | Ocount=0 14 | player,turn=1,'x' 15 | 16 | def clicked(obj): 17 | global player,turn,Xcount,Ocount 18 | 19 | button_clicked=''.join(obj.split()) 20 | #row,column=obj.split() 21 | #row=row.split('w')[1] 22 | 23 | 24 | if button_clicked not in movesPlayed: 25 | globals()[button_clicked].configure(text=turn.center(6)) 26 | movesPlayed.append(button_clicked) 27 | globals()[button_clicked]['state']='disabled' 28 | if player==1: 29 | player,turn=2,'0' 30 | Xcount+=1 31 | player_data.configure(text='Player-2(0) chance') 32 | 33 | 34 | else: 35 | player,turn=1,'x' 36 | Ocount+=1 37 | player_data.configure(text='Player-1(x) chance') 38 | 39 | win_check() 40 | else: 41 | print('Move already played') 42 | 43 | def finish(string): 44 | global game_over 45 | game_over=True 46 | player_data.configure(text='') 47 | player_win.configure(text=string) 48 | player_win.pack() 49 | for i in ('row1','row2','row3'): 50 | for j in range(3): 51 | globals()[i+str(j+1)]['state']='disabled' 52 | rtry=tk.Button(gui,text='Retry',command=Retry) 53 | rtry.pack() 54 | finish.rtry=rtry 55 | 56 | def Retry(): 57 | global movesPlayed,player,turn,Xcount,Ocount,rtry 58 | movesPlayed=[] 59 | player,turn=1,'x' 60 | Xcount,Ocount=0,0 61 | for i in ('row1','row2','row3'): 62 | for j in range(3): 63 | 64 | globals()[i+str(j+1)].configure(text=f' ') 65 | globals()[i+str(j+1)]['state']='active' 66 | finish.rtry.pack_forget() 67 | player_win.pack_forget() 68 | player_data.configure(text='Player-1(x) chance') 69 | 70 | def win_check(): 71 | 72 | 73 | 74 | 75 | if (row11['text'] == row12['text'] == row13['text'] != ' ' or 76 | row21['text'] == row22['text'] == row23['text'] != ' ' or 77 | row31['text'] == row32['text'] == row33['text'] != ' ' or 78 | row11['text'] == row21['text'] == row31['text'] != ' ' or 79 | row12['text'] == row22['text'] == row32['text'] != ' ' or 80 | row13['text'] == row23['text'] == row33['text'] != ' ' or 81 | row11['text'] == row22['text'] == row33['text'] != ' ' or 82 | row13['text'] == row22['text'] == row31['text'] != ' ' 83 | ): 84 | 85 | 86 | if Xcount>Ocount: 87 | string='Player 1(X) won' 88 | else: 89 | string='Player 2(O) won' 90 | finish(string) 91 | 92 | if not game_over: 93 | if (Xcount==5 and Ocount==4 or 94 | Xcount==4 and Ocount==5): 95 | finish('Draw match') 96 | tk.Label(gui,text="PLAYER-1=X\nPLAYER-2=0").pack() 97 | player_data=tk.Label(gui,text='Player-1(x) chance') 98 | player_data.pack() 99 | 100 | row1=tk.Frame(gui) 101 | row1.pack() 102 | row2=tk.Frame(gui) 103 | row2.pack() 104 | row3=tk.Frame(gui) 105 | row3.pack() 106 | 107 | player_win=tk.Label(gui,text='') 108 | for i in ('row1','row2','row3'): 109 | for j in range(3): 110 | 111 | vars()[i+str(j+1)]=tk.Button(vars()[i], text=f' ',bd='1',command=partial(clicked,i+' '+str(j+1))) 112 | vars()[i+str(j+1)].pack(side='left') 113 | 114 | 115 | gui.mainloop() 116 | -------------------------------------------------------------------------------- /GeoMetric_sum.py: -------------------------------------------------------------------------------- 1 | # Geometric Sum = 1 + 1/2 + 1/4 + 1/8 + 1/16 + ... + 1/(2^n) 2 | # where n is the input from the user 3 | # Example: 4 | # Input: 3 5 | # Output: 1.875 6 | 7 | def geometricSum(n): 8 | if n == 0: # base case 9 | return 1 # return 1 if n == 0 10 | smallOutput = geometricSum(n - 1) # recursion call 11 | # adding and smallOutput vaule + 1 and divide using 2^n 12 | return smallOutput + 1 / pow(2, n) 13 | 14 | 15 | n = int(input()) # taking input from user 16 | print(geometricSum(n)) # calling the function and printing the result 17 | -------------------------------------------------------------------------------- /GrayCodetoBinary.py: -------------------------------------------------------------------------------- 1 | def flip_num(my_nu): 2 | return '1' if(my_nu == '0') else '0'; 3 | 4 | def gray_to_binary(gray): 5 | binary_code="" 6 | binary_code += gray[0] 7 | for i in range(1,len(gray)): 8 | 9 | if (gray[i]=='0'): 10 | binary_code += binary_code[i-1] 11 | else: 12 | binary_code += flip_num(binary_code[i-1]) 13 | 14 | return binary_code 15 | 16 | # gray_code="01101001" 17 | 18 | 19 | gray_code=input("please enter the gray code\n") 20 | print("the gray code is : ") 21 | print(gray_code) 22 | # x=gray_to_binary(gray_code) 23 | print("binary code of", gray_code, "is",gray_to_binary(gray_code)) 24 | 25 | # for converting binary numb to decimal 26 | value=0 27 | b_num=list(gray_to_binary(gray_code)) 28 | 29 | for i in range(len(b_num)): 30 | digit=b_num.pop() 31 | if digit =='1': 32 | value = value + pow(2,i) 33 | 34 | print("the decimal value of the number is ", value) 35 | 36 | 37 | # print(12//5) 38 | -------------------------------------------------------------------------------- /Guessnumber.py: -------------------------------------------------------------------------------- 1 | import random 2 | number=random.randint(1,100) 3 | 4 | 5 | def guessNUmber(number, num , level): 6 | 7 | while level!=1: 8 | if(num>number): 9 | print("Too High") 10 | else:print("Too Low") 11 | level-=1 12 | print(f"YOU have {level} attemps left") 13 | num = int(input("Guess the number : ")) 14 | 15 | if(num==number):print(f"YOU GUESSED IT CORRECT IT WAS {num}") 16 | else:print(f"YOU GUESSED IT WRONG IT WAS {number}") 17 | 18 | print("choose the level of game 'hard' or 'easy'") 19 | level = input().lower() 20 | 21 | while True: 22 | 23 | 24 | if(level!="hard" and level!="easy"): 25 | print("Invalid Choice") 26 | else:break 27 | 28 | print("choose the level of game 'hard' or 'easy'") 29 | level = input().lower() 30 | 31 | print("I am thinking of a number betwen 1-100. \n ") 32 | num = int(input("Guess the number : ")) 33 | 34 | if level == "hard": 35 | guessNUmber(number, num, 5) 36 | elif level == "easy:": 37 | guessNUmber(number, num, 10) 38 | -------------------------------------------------------------------------------- /HangmanGame.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | stages = [''' 4 | +---+ 5 | | | 6 | O | 7 | /|\ | 8 | / \ | 9 | | 10 | ========= 11 | ''', ''' 12 | +---+ 13 | | | 14 | O | 15 | /|\ | 16 | / | 17 | | 18 | ========= 19 | ''', ''' 20 | +---+ 21 | | | 22 | O | 23 | /|\ | 24 | | 25 | | 26 | ========= 27 | ''', ''' 28 | +---+ 29 | | | 30 | O | 31 | /| | 32 | | 33 | | 34 | =========''', ''' 35 | +---+ 36 | | | 37 | O | 38 | | | 39 | | 40 | | 41 | ========= 42 | ''', ''' 43 | +---+ 44 | | | 45 | O | 46 | | 47 | | 48 | | 49 | ========= 50 | ''', ''' 51 | +---+ 52 | | | 53 | | 54 | | 55 | | 56 | | 57 | ========= 58 | '''] 59 | lives = 6 60 | word_list = ["baboon", "delhi", "adamantium", "dehradun"] 61 | # choosing a random word from the list 62 | word = random.choice(word_list); 63 | print(f"The chosen word is {word}") 64 | blank_list = [] 65 | 66 | for i in range(len(word)): 67 | blank_list += "_" 68 | end_game=False 69 | while end_game == False: 70 | guess = input("Guess a letter\n") 71 | 72 | if guess not in word: 73 | lives=lives-1 74 | else: 75 | for i in range(len(word)): 76 | if word[i]==guess: 77 | blank_list[i]=guess 78 | 79 | if lives==0 or "_" not in blank_list: 80 | end_game=True 81 | 82 | # Clear.clear() 83 | for i in blank_list: 84 | print(i,end=" ") 85 | print(stages[lives]) 86 | 87 | if(lives==0):print("YOU LOSE!!") 88 | else :print("YOU WON!!") -------------------------------------------------------------------------------- /Human_Readable_Time.py: -------------------------------------------------------------------------------- 1 | def make_readable(seconds): #Function converts an amount of seconds into hours:minutes:seconds 2 | 3 | seconds = int(seconds) #converts seconds into integer 4 | 5 | hour = int(seconds/3600) #Gets hours 6 | minute = int(seconds/60) - (hour*60) #Gets remanining minutes 7 | second = seconds - (minute*60) - (hour*3600) #Gets remaining seconds 8 | 9 | hour = str(hour) if len(str(hour)) > 1 else '0' + str(hour) #adds 0 if the hours,minutes or seconds are only one charachter long 10 | second = str(second) if len(str(second)) > 1 else '0' + str(second) 11 | minute = str(minute) if len(str(minute)) > 1 else '0' + str(minute) 12 | 13 | return f"{hour}:{minute}:{second}" #returns the value 14 | 15 | print(make_readable(input(''))) 16 | input('') 17 | -------------------------------------------------------------------------------- /Indianflag-Turtle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | from turtle import* 3 | 4 | #screen for output 5 | screen = turtle.Screen() 6 | 7 | # Defining a turtle Instance 8 | t = turtle.Turtle() 9 | speed(0) 10 | 11 | # initially penup() 12 | t.penup() 13 | t.goto(-400, 250) 14 | t.pendown() 15 | 16 | # Orange Rectangle 17 | #white rectangle 18 | t.color("orange") 19 | t.begin_fill() 20 | t.forward(800) 21 | t.right(90) 22 | t.forward(167) 23 | t.right(90) 24 | t.forward(800) 25 | t.end_fill() 26 | t.left(90) 27 | t.forward(167) 28 | 29 | # Green Rectangle 30 | t.color("green") 31 | t.begin_fill() 32 | t.forward(167) 33 | t.left(90) 34 | t.forward(800) 35 | t.left(90) 36 | t.forward(167) 37 | t.end_fill() 38 | 39 | # Big Blue Circle 40 | t.penup() 41 | t.goto(70, 0) 42 | t.pendown() 43 | t.color("navy") 44 | t.begin_fill() 45 | t.circle(70) 46 | t.end_fill() 47 | 48 | # Big White Circle 49 | t.penup() 50 | t.goto(60, 0) 51 | t.pendown() 52 | t.color("white") 53 | t.begin_fill() 54 | t.circle(60) 55 | t.end_fill() 56 | 57 | # Mini Blue Circles 58 | t.penup() 59 | t.goto(-57, -8) 60 | t.pendown() 61 | t.color("navy") 62 | for i in range(24): 63 | t.begin_fill() 64 | t.circle(3) 65 | t.end_fill() 66 | t.penup() 67 | t.forward(15) 68 | t.right(15) 69 | t.pendown() 70 | 71 | # Small Blue Circle 72 | t.penup() 73 | t.goto(20, 0) 74 | t.pendown() 75 | t.begin_fill() 76 | t.circle(20) 77 | t.end_fill() 78 | # Spokes 79 | t.penup() 80 | t.goto(0, 0) 81 | t.pendown() 82 | t.pensize(2) 83 | for i in range(24): 84 | t.forward(60) 85 | t.backward(60) 86 | t.left(15) 87 | 88 | #to hold the 89 | #output window 90 | turtle.done() -------------------------------------------------------------------------------- /InsertionSort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(arr): 2 | 3 | for i in range(1, len(arr)): 4 | key = arr[i] 5 | j = i - 1 6 | 7 | while j >= 0 and key < arr[j]: 8 | arr[j + 1] = arr[j] 9 | j = j - 1 10 | 11 | 12 | arr[j + 1] = key 13 | 14 | arr = [9, 8, 6, 7, 1] 15 | print("Unsorted Array:", arr) 16 | insertion_sort(arr) 17 | print('Sorted Array: ', arr) 18 | -------------------------------------------------------------------------------- /JumpSearch.py: -------------------------------------------------------------------------------- 1 | 2 | # Python3 code to implement Jump Search 3 | import math 4 | 5 | def jumpSearch( arr , x , n ): 6 | 7 | # Finding block size to be jumped 8 | step = math.sqrt(n) 9 | 10 | # Finding the block where element is 11 | # present (if it is present) 12 | prev = 0 13 | while arr[int(min(step, n)-1)] < x: 14 | prev = step 15 | step += math.sqrt(n) 16 | if prev >= n: 17 | return -1 18 | 19 | # Doing a linear search for x in 20 | # block beginning with prev. 21 | while arr[int(prev)] < x: 22 | prev += 1 23 | 24 | # If we reached next block or end 25 | # of array, element is not present. 26 | if prev == min(step, n): 27 | return -1 28 | 29 | # If element is found 30 | if arr[int(prev)] == x: 31 | return prev 32 | 33 | return -1 34 | 35 | # Driver code to test function 36 | arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 37 | 34, 55, 89, 144, 233, 377, 610 ] 38 | x = 55 39 | n = len(arr) 40 | 41 | # Find the index of 'x' using Jump Search 42 | index = jumpSearch(arr, x, n) 43 | 44 | # Print the index where 'x' is located 45 | print("Number" , x, "is at index" ,"%.0f"%index) 46 | 47 | #contributed by Rover Phoenix -------------------------------------------------------------------------------- /Largest of the three numbers.py: -------------------------------------------------------------------------------- 1 | # Largest number from the given three numbers 2 | 3 | 4 | # Take the input from the user 5 | num1 = float(input("Enter the first number - ")) 6 | num2 = float(input("Enter the second number - ")) 7 | num3 = float(input("Enter the third number - ")) 8 | 9 | if(num1 >= num2) and (num1 >= num3): 10 | largest = num1 11 | elif(num2 >= num3) and (num2 >= num1): 12 | largest = num2 13 | else: 14 | largest = num3 15 | 16 | print("The largest number is", largest) -------------------------------------------------------------------------------- /LeapYear.py: -------------------------------------------------------------------------------- 1 | def CheckLeap(year): 2 | if (year%4==0 and year%100!=0) or (year%400==0): 3 | print(year,"is a Leap Year") 4 | else: 5 | print(year,"is not a Leap Year") 6 | 7 | year = int(input("Enter the year: ")) 8 | CheckLeap(year) -------------------------------------------------------------------------------- /Levenshtein_distance.py: -------------------------------------------------------------------------------- 1 | # The Levenshtein distance (Edit distance) Problem 2 | 3 | # Informally, the Levenshtein distance between two words is 4 | # the minimum number of single-character edits (insertions, deletions or substitutions) 5 | # required to change one word into the other. 6 | 7 | # For example, the Levenshtein distance between kitten and sitting is 3. 8 | # The minimal edit script that transforms the former into the latter is: 9 | 10 | # kitten —> sitten (substitution of s for k) 11 | # sitten —> sittin (substitution of i for e) 12 | # sittin —> sitting (insertion of g at the end) 13 | 14 | def levenshtein_distance(word_1, chars_1, word_2, chars_2): 15 | # base case if the strings are empty 16 | if chars_1 == 0: 17 | return chars_2 18 | if chars_2 == 0: 19 | return chars_1 20 | 21 | # if last characters of the string match, the cost of 22 | # operations is 0, i.e. no changes are made 23 | if word_1[chars_1 - 1] == word_2[chars_2 - 1]: 24 | cost = 0 25 | else: 26 | cost = 1 27 | 28 | # calculating the numbers of operations recursively 29 | deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1 30 | insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1 31 | substitution = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2 - 1) + cost 32 | 33 | return min(deletion, insertion, substitution) 34 | 35 | # driving script 36 | if __name__ == '__main__': 37 | word_1 = input("Enter Word 1 :") 38 | word_2 = input("Enter Word 2 :") 39 | 40 | print('The Levenshtein distance is:') 41 | print(levenshtein_distance(word_1, len(word_1), word_2, len(word_2))) -------------------------------------------------------------------------------- /Linear_Search.py: -------------------------------------------------------------------------------- 1 | # Linear Search in Python 2 | 3 | 4 | def linearSearch(array, n, x): 5 | 6 | 7 | for i in range(0, n): 8 | if (array[i] == x): 9 | return i 10 | return -1 11 | 12 | 13 | array = [2, 4, 0, 1, 9] 14 | x = 1 15 | n = len(array) 16 | result = linearSearch(array, n, x) 17 | if(result == -1): 18 | print("Element not found") 19 | else: 20 | print("Element found at index: ", result) 21 | -------------------------------------------------------------------------------- /Linkedlist_reverse.py: -------------------------------------------------------------------------------- 1 | # Python program to reverse a linked list 2 | 3 | 4 | # Node class 5 | 6 | 7 | class Node: 8 | 9 | # Constructor to initialize the node object 10 | def __init__(self, data): 11 | self.data = data 12 | self.next = None 13 | 14 | 15 | class LinkedList: 16 | 17 | # Function to initialize head 18 | def __init__(self): 19 | self.head = None 20 | 21 | # Function to reverse the linked list 22 | def reverse(self): 23 | prev = None 24 | current = self.head 25 | while(current is not None): 26 | next = current.next 27 | current.next = prev 28 | prev = current 29 | current = next 30 | self.head = prev 31 | 32 | # Function to insert a new node at the beginning 33 | def push(self, new_data): 34 | new_node = Node(new_data) 35 | new_node.next = self.head 36 | self.head = new_node 37 | 38 | # Utility function to print the LinkedList 39 | def printList(self): 40 | temp = self.head 41 | while(temp): 42 | print (temp.data,end=" ") 43 | temp = temp.next 44 | 45 | 46 | # Driver program to test above functions 47 | llist = LinkedList() 48 | llist.push(20) 49 | llist.push(4) 50 | llist.push(15) 51 | llist.push(85) 52 | 53 | print ("Given Linked List") 54 | llist.printList() 55 | llist.reverse() 56 | print ("\nReversed Linked List") 57 | llist.printList() 58 | 59 | 60 | -------------------------------------------------------------------------------- /MatrixOperation.py: -------------------------------------------------------------------------------- 1 | #Prgram Code Created by Shivsagar Mishra 2 | #This is a program to perform basic matrix operarations such as 1. Addition 2.Substraction 3.Multiplication 4.Transpose 3 | 4 | 5 | import numpy as np 6 | 7 | # Initialize matrix 8 | a = np.array([[1,2,1], [6,5,4], [9,5,8]]) 9 | b = np.array([[3,2,1], [8,6,4], [4,0,0]]) 10 | 11 | while True: 12 | print("List of operations:\n1.Display\n2.Addition\n3.Substraction\n4.Multiplication\n5.Transpose") 13 | counter=int(input("Enter the your Choice:")) 14 | 15 | if counter == 1: 16 | #printing 1st matrix 17 | print("First Matrix:") 18 | print (a,"\n") 19 | # printing 2nd Matrix 20 | print("Second Matrix:") 21 | print(b,"\n") 22 | 23 | elif counter == 2: 24 | print ("The addition of matrices is : ") 25 | print(a.__add__(b),"\n") 26 | 27 | elif counter == 3: 28 | print ("The Substraction of matrices is : ") 29 | print ("Substraction is:") 30 | print(a.__sub__(b),"\n") 31 | 32 | elif counter == 4: 33 | print ("The multiplication of matrices is : ") 34 | print(a.__mul__(b),"\n") 35 | 36 | elif counter == 5: 37 | print ("The Transposition of First matrix is: ") 38 | print(np.transpose(a),"\n") 39 | print("The Transposition of Second Matrix is:") 40 | print(np.transpose(b),"\n") 41 | else: 42 | print("Invalid Option!") 43 | 44 | cont=int(input("Do you want to continue?: 1.Yes\t 2.No\t Enter your choice:")) 45 | if cont==1: 46 | continue 47 | else: 48 | break 49 | 50 | -------------------------------------------------------------------------------- /MaximizeProfitStockProblem.py: -------------------------------------------------------------------------------- 1 | # Module to return the maximum profit that can be made after buying and selling the given stocks 2 | 3 | def maxProfit(price, start, end): 4 | 5 | # If the stocks can't be bought 6 | if (end <= start): 7 | return 0 8 | 9 | # Initialise the profit 10 | profit = 0 11 | 12 | # The day at which the stock must be bought 13 | for i in range(start, end, 1): 14 | 15 | # The day at which the stock must be sold 16 | for j in range(i+1, end+1): 17 | 18 | # If buying the stock at ith day and selling it at jth day is profitable 19 | if (price[j] > price[i]): 20 | 21 | # Update the current profit 22 | current_profit = price[j] - price[i] +\ 23 | maxProfit(price, start, i - 1) + \ 24 | maxProfit(price, j + 1, end) 25 | 26 | # Update the maximum profit so far 27 | profit = max(profit, current_profit) 28 | 29 | return profit 30 | 31 | # Example Driver Code 32 | if __name__ == '__main__': 33 | price = [100, 180, 260, 310, 40, 535, 695] 34 | n = len(price) 35 | 36 | print(maxProfit(price, 0, n - 1)) 37 | 38 | # Solution: 865 39 | 40 | # This code is contributed by Laksh Gupta 41 | -------------------------------------------------------------------------------- /Minesweeper_Game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Generate a random map to start the game. 4 | def randomMap(n, k): 5 | 6 | arr = [[0 for row in range(0,n)] for column in range(0,n)] 7 | 8 | for num in range(0,k): 9 | x = random.randint(0,n-1) 10 | y = random.randint(0,n-1) 11 | arr[y][x] = 'X' 12 | 13 | if (x >=0 and x <= n-2) and (y >= 0 and y <= n-1): 14 | if arr[y][x+1] != 'X': 15 | arr[y][x+1] += 1 # center right 16 | 17 | if (x >=1 and x <= n-1) and (y >= 0 and y <= n-1): 18 | if arr[y][x-1] != 'X': 19 | arr[y][x-1] += 1 # center left 20 | 21 | if (x >= 1 and x <= n-1) and (y >= 1 and y <= n-1): 22 | if arr[y-1][x-1] != 'X': 23 | arr[y-1][x-1] += 1 # top left 24 | 25 | if (x >= 0 and x <= n-2) and (y >= 1 and y <= n-1): 26 | if arr[y-1][x+1] != 'X': 27 | arr[y-1][x+1] += 1 # top right 28 | 29 | if (x >= 0 and x <= n-1) and (y >= 1 and y <= n-1): 30 | if arr[y-1][x] != 'X': 31 | arr[y-1][x] += 1 # top center 32 | 33 | if (x >=0 and x <= n-2) and (y >= 0 and y <= n-2): 34 | if arr[y+1][x+1] != 'X': 35 | arr[y+1][x+1] += 1 # bottom right 36 | 37 | if (x >= 1 and x <= n-1) and (y >= 0 and y <= n-2): 38 | if arr[y+1][x-1] != 'X': 39 | arr[y+1][x-1] += 1 # bottom left 40 | 41 | if (x >= 0 and x <= n-1) and (y >= 0 and y <= n-2): 42 | if arr[y+1][x] != 'X': 43 | arr[y+1][x] += 1 # bottom center 44 | return arr 45 | 46 | # Generate the map for the player. 47 | def playerMap(n): 48 | arr = [['-' for row in range(0,n)] for column in range(0,n)] 49 | return arr 50 | 51 | # Display the map on the screen. 52 | def showMap(map): 53 | for row in map: 54 | print(" ".join(str(cell) for cell in row)) 55 | print("") 56 | 57 | # Check if player has won. 58 | def checkWin(map): 59 | for row in map: 60 | for cell in row: 61 | if cell == '-': 62 | return False 63 | return True 64 | 65 | # Check if player is willing to continue the game. 66 | def checkContinue(score): 67 | print("Your score: ", score) 68 | isContinue = input("Do you want to try again? (y/n) :") 69 | if isContinue == 'n': 70 | return False 71 | return True 72 | 73 | # MINESWEEPER GAME 74 | def Game(): 75 | 76 | GameStatus = True 77 | while GameStatus: 78 | difficulty = input("Select your difficulty (0,1,2):") 79 | if difficulty.lower() == '0': 80 | n = 5 81 | k = 3 82 | elif difficulty.lower() == '1': 83 | n = 6 84 | k = 8 85 | else: 86 | n = 8 87 | k = 20 88 | 89 | minesweeper_map = randomMap(n, k) 90 | player_map = playerMap(n) 91 | score = 0 92 | 93 | while True: 94 | 95 | if checkWin(player_map) == False: 96 | print("Enter the cell you want to open :") 97 | x,y = map(int,input().split()) 98 | x -= 1 # 0 based indexing 99 | y -= 1 # 0 based indexing 100 | if (minesweeper_map[y][x] == 'X'): 101 | print("Game Over!") 102 | showMap(minesweeper_map) 103 | GameStatus = checkContinue(score) 104 | break 105 | else: 106 | player_map[y][x] = minesweeper_map[y][x] 107 | showMap(player_map) 108 | score += 1 109 | 110 | else: 111 | showMap(player_map) 112 | print("Congratulation! You Win!") 113 | GameStatus = checkContinue(score) 114 | break 115 | 116 | # Main Program 117 | if __name__ == "__main__": 118 | try: 119 | Game() 120 | except KeyboardInterrupt: 121 | print('\nGoodbye!') -------------------------------------------------------------------------------- /Multiplication_Table.py: -------------------------------------------------------------------------------- 1 | def multiplicationTable(n, i=1): 2 | if i == 11: 3 | return 4 | print(n, 'x', i, '=', n*i) 5 | multiplicationTable(n, i+1) 6 | 7 | n = int(input("Enter the number:")) 8 | multiplicationTable(n) 9 | -------------------------------------------------------------------------------- /OTP generator.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import random 4 | import smtplib 5 | digits = "012456789" 6 | OTP = "" 7 | for i in range(4): 8 | OTP += digits[math.floor(random.random() * 10)] 9 | msg = str(OTP) + "Your OTP is" 10 | 11 | s = smtplib.SMTP('smtp.gmail.com', 587) 12 | s.starttls() 13 | 14 | emailid = "receiver's id" 15 | s.login("sender's id", "google app password") 16 | s.sendmail("sender's id", emailid, msg) 17 | a = input("Enter the OTP >>: ") 18 | if a == OTP: 19 | print("Verified") 20 | else: 21 | print("Incorrect OTP") 22 | s.quit() 23 | -------------------------------------------------------------------------------- /Palindrome.py: -------------------------------------------------------------------------------- 1 | str_1 = input ("Enter the string to check if it is a palindrome: ") 2 | str_1 = str_1.casefold () 3 | rev_str = reversed (str_1) 4 | if list (str_1) == list (rev_str): 5 | print ("The string is a palindrome.") 6 | else: 7 | print ("The string is not a palindrome.") 8 | -------------------------------------------------------------------------------- /PasswordGenerator.py: -------------------------------------------------------------------------------- 1 | #Password Generator Project 2 | import random 3 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 4 | 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 5 | 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 6 | 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 7 | 'W', 'X', 'Y', 'Z'] 8 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 9 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 10 | 11 | print("Welcome to the PyPassword Generator!") 12 | 13 | 14 | no_letters=int(input("How many letters would you like to use in password?\n")) 15 | no_symbols=int(input("How many symbols would you like? \n")) 16 | no_numbers=int(input("How many numbers would you like? \n")) 17 | 18 | 19 | 20 | 21 | def easy_version(): 22 | password = "" 23 | for i in range(no_letters): 24 | ran=random.randint(0,len(letters)) 25 | password+=letters[ran] 26 | for i in range(no_numbers): 27 | ran=random.randint(0,len(numbers)) 28 | password+=str(numbers[ran]) 29 | for i in range(no_symbols): 30 | ran=random.randint(0,len(symbols)) 31 | password+=str(symbols[ran]) 32 | print(password) 33 | 34 | def hard_version(): 35 | password_list=[] 36 | password="" 37 | for i in range(no_letters): 38 | ran=random.randint(0,len(letters)-1) 39 | password_list+=letters[ran] 40 | for i in range(no_numbers): 41 | ran=random.randint(0,len(numbers)-1) 42 | password_list+=str(numbers[ran]) 43 | for i in range(no_symbols): 44 | ran=random.randint(0,len(symbols)-1) 45 | password_list+=str(symbols[ran]) 46 | 47 | random.shuffle(password_list) 48 | for i in password_list: 49 | password+=i 50 | 51 | print(password) 52 | 53 | 54 | hard_version() 55 | 56 | 57 | -------------------------------------------------------------------------------- /Password_generator.py: -------------------------------------------------------------------------------- 1 | #Password Generator Project 2 | import random as r 3 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 4 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 5 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 6 | 7 | 8 | def easy_pass(nr_letters,nr_symbols,nr_numbers): 9 | random_letters = "" 10 | for i in range(0,nr_letters): 11 | random_letter = r.choice(letters) 12 | random_letters += random_letter 13 | 14 | random_symbols = "" 15 | for i in range(0,nr_symbols): 16 | random_symbol = r.choice(symbols) 17 | random_symbols += random_symbol 18 | 19 | random_numbers = "" 20 | for i in range(0,nr_numbers): 21 | random_number = r.choice(numbers) 22 | random_numbers += random_number 23 | 24 | #Easy Level - Order not randomised: 25 | #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 26 | final_password = random_letters + random_symbols + random_numbers 27 | print(f"Here is your easy password : {final_password}") 28 | 29 | def hard_pass(nr_letters,nr_symbols,nr_numbers): 30 | random_letters = [] 31 | for i in range(0,nr_letters): 32 | random_letter = r.choice(letters) 33 | random_letters.append(random_letter) 34 | 35 | random_symbols = [] 36 | for i in range(0,nr_symbols): 37 | random_symbol = r.choice(symbols) 38 | random_symbols.append(random_symbol) 39 | 40 | random_numbers = [] 41 | for i in range(0,nr_numbers): 42 | random_number = r.choice(numbers) 43 | random_numbers.append(random_number) 44 | 45 | final_password_list = random_letters + random_symbols + random_numbers 46 | r.shuffle(final_password_list) 47 | 48 | 49 | #Hard Level - Order of characters randomised: 50 | #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P 51 | final_pass_in_str = "" 52 | for char in final_password_list: 53 | final_pass_in_str += char 54 | print(f"Here is your hard password : {final_pass_in_str}") 55 | 56 | 57 | def password_generator(): 58 | print("Welcome to the PyPassword Generator!") 59 | nr_letters= int(input("How many letters would you like in your password?\n")) 60 | nr_symbols = int(input(f"How many symbols would you like?\n")) 61 | nr_numbers = int(input(f"How many numbers would you like?\n")) 62 | 63 | print() 64 | easy_pass(nr_letters,nr_symbols,nr_numbers) 65 | print() 66 | hard_pass(nr_letters,nr_symbols,nr_numbers) 67 | 68 | 69 | def main(): 70 | password_generator() 71 | 72 | 73 | if __name__ == '__main__': 74 | main() 75 | -------------------------------------------------------------------------------- /Player.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | 5 | class Player(): 6 | def __init__(self, player): 7 | self.player = player 8 | 9 | def get_move(self, game): 10 | pass 11 | 12 | 13 | class Human(Player): 14 | def __init__(self, player): 15 | super().__init__(player) 16 | 17 | def get_move(self, game): 18 | valid_square = False 19 | val = None 20 | while not valid_square: 21 | square = input(self.player + ' turn. Please introduce a move (1-9): ') 22 | try: 23 | val = int(square) - 1 24 | if val not in game.remaining_moves(): 25 | raise ValueError 26 | valid_square = True 27 | except ValueError: 28 | print('Invalid square. Try again.') 29 | return val 30 | 31 | 32 | class RandomComputer(Player): 33 | def __init__(self, player): 34 | super().__init__(player) 35 | 36 | def get_move(self, game): 37 | square = random.choice(game.remaining_moves()) 38 | return square 39 | 40 | 41 | class SmartComputer(Player): 42 | def __init__(self, player): 43 | super().__init__(player) 44 | 45 | def get_move(self, game): 46 | if len(game.remaining_moves()) == 9: 47 | square = random.choice(game.remaining_moves()) 48 | else: 49 | square = self.minimax(game, self.player)['position'] 50 | return square 51 | 52 | def minimax(self, state, player): 53 | max_player = self.player 54 | min_player = '0' if player == 'X' else 'X' 55 | 56 | # checking if the previous move is winner 57 | if state.actual_winner == min_player: 58 | return {'position': None, 59 | 'score': 1 * (state.number_null_squares() + 1) if min_player == max_player 60 | else -1 * (state.number_null_squares() + 1)} 61 | elif not state.null_squares(): 62 | return {'position': None, 'score': 0} 63 | 64 | if player == max_player: 65 | best = {'position': None, 'score': -math.inf} 66 | else: 67 | best = {'position': None, 'score': math.inf} 68 | 69 | for possible_move in state.remaining_moves(): 70 | state.make_a_move(possible_move, player) 71 | sim_score = self.minimax(state, min_player) 72 | 73 | # undo move 74 | state.board[possible_move] = ' ' 75 | state.actual_winner = None 76 | sim_score['position'] = possible_move 77 | 78 | if player == max_player: 79 | if sim_score['score'] > best['score']: 80 | best = sim_score 81 | else: 82 | if sim_score['score'] < best['score']: 83 | best = sim_score 84 | return best 85 | -------------------------------------------------------------------------------- /Pong_Game.py: -------------------------------------------------------------------------------- 1 | import turtle as t 2 | playerAscore=0 3 | playerBscore=0 4 | 5 | #create a window and declare a variable called window and call the screen() 6 | window=t.Screen() 7 | window.title("The Pong Game") 8 | window.bgcolor("green") 9 | window.setup(width=800,height=600) 10 | window.tracer(0) 11 | 12 | #Creating the left paddle 13 | leftpaddle=t.Turtle() 14 | leftpaddle.speed(0) 15 | leftpaddle.shape("square") 16 | leftpaddle.color("white") 17 | leftpaddle.shapesize(stretch_wid=5,stretch_len=1) 18 | leftpaddle.penup() 19 | leftpaddle.goto(-350,0) 20 | 21 | #Creating the right paddle 22 | rightpaddle=t.Turtle() 23 | rightpaddle.speed(0) 24 | rightpaddle.shape("square") 25 | rightpaddle.color("white") 26 | rightpaddle.shapesize(stretch_wid=5,stretch_len=1) 27 | rightpaddle.penup() 28 | rightpaddle.goto(-350,0) 29 | 30 | #Code for creating the ball 31 | ball=t.Turtle() 32 | ball.speed(0) 33 | ball.shape("circle") 34 | ball.color("red") 35 | ball.penup() 36 | ball.goto(5,5) 37 | ballxdirection=0.2 38 | ballydirection=0.2 39 | 40 | #Code for creating pen for scorecard update 41 | pen=t.Turtle() 42 | pen.speed(0) 43 | pen.color("Blue") 44 | pen.penup() 45 | pen.hideturtle() 46 | pen.goto(0,260) 47 | pen.write("score",align="center",font=('Arial',24,'normal')) 48 | 49 | #code for moving the leftpaddle 50 | def leftpaddleup(): 51 | y=leftpaddle.ycor() 52 | y=y+90 53 | leftpaddle.sety(y) 54 | 55 | def leftpaddledown(): 56 | y=leftpaddle.ycor() 57 | y=y+90 58 | leftpaddle.sety(y) 59 | 60 | #code for moving the rightpaddle 61 | def rightpaddleup(): 62 | y=rightpaddle.ycor() 63 | y=y+90 64 | rightpaddle.sety(y) 65 | 66 | def rightpaddledown(): 67 | y=rightpaddle.ycor() 68 | y=y+90 69 | rightpaddle.sety(y) 70 | 71 | #Assign keys to play 72 | window.listen() 73 | window.onkeypress(leftpaddleup,'w') 74 | window.onkeypress(leftpaddledown,'s') 75 | window.onkeypress(rightpaddleup,'Up') 76 | window.onkeypress(rightpaddledown,'Down') 77 | 78 | while True: 79 | window.update() 80 | 81 | #moving the ball 82 | ball.setx(ball.xcor()+ballxdirection) 83 | ball.sety(ball.ycor()+ballxdirection) 84 | 85 | #border set up 86 | if ball.ycor()>290: 87 | ball.sety(290) 88 | ballydirection=ballydirection*-1 89 | if ball.ycor()<-290: 90 | ball.sety(-290) 91 | ballydirection=ballydirection*-1 92 | 93 | if ball.xcor() > 390: 94 | ball.goto(0,0) 95 | ball_dx = ball_dx * -1 96 | player_a_score = player_a_score + 1 97 | pen.clear() 98 | pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) 99 | os.system("afplay wallhit.wav&") 100 | 101 | 102 | 103 | if(ball.xcor()) < -390: # Left width paddle Border 104 | ball.goto(0,0) 105 | ball_dx = ball_dx * -1 106 | player_b_score = player_b_score + 1 107 | pen.clear() 108 | pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) 109 | os.system("afplay wallhit.wav&") 110 | 111 | # Handling the collisions with paddles. 112 | 113 | if(ball.xcor() > 340) and (ball.xcor() < 350) and (ball.ycor() < rightpaddle.ycor() + 40 and ball.ycor() > rightpaddle.ycor() - 40): 114 | ball.setx(340) 115 | ball_dx = ball_dx * -1 116 | os.system("afplay paddle.wav&") 117 | 118 | if(ball.xcor() < -340) and (ball.xcor() > -350) and (ball.ycor() < leftpaddle.ycor() + 40 and ball.ycor() > leftpaddle.ycor() - 40): 119 | ball.setx(-340) 120 | ball_dx = ball_dx * -1 121 | os.system("afplay paddle.wav&") 122 | -------------------------------------------------------------------------------- /ProductOfSumAndDifference.py: -------------------------------------------------------------------------------- 1 | def solve(a, b): 2 | return (a+b)*(a-b) 3 | 4 | if __name__ == '__main__': 5 | a = int(input()) 6 | b = int(input()) 7 | res = solve(a, b) 8 | print(res) 9 | -------------------------------------------------------------------------------- /Queue.py: -------------------------------------------------------------------------------- 1 | class Queue: 2 | arr = [] 3 | def enqueue(self,item): 4 | self.arr.append(item) 5 | 6 | def dequeue(self): 7 | if len(self.arr) > 0: 8 | ditem = self.arr[0] 9 | del self.arr[0] 10 | return ditem 11 | else: 12 | return #queue is empty 13 | 14 | def dispaly(self): 15 | print(self.arr) 16 | 17 | x = Queue() # Creating object of queue class 18 | x.enqueue(1) 19 | x.enqueue(2) 20 | x.dispaly() # arr = [1,2] 21 | x.dequeue() # Deleting the first element of the queue. 22 | x.dispaly() # arr = [2] 23 | print(x.dequeue()) # 2 24 | print(x.dequeue()) # None(because queue is already empty) -------------------------------------------------------------------------------- /Queue_using_LL.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data = None): 3 | self.data = data 4 | self.next = None 5 | 6 | class Queue: 7 | def __init__(self): 8 | self.head = None 9 | self.last = None 10 | 11 | def enqueue(self, data): 12 | if not self.last: 13 | self.head = Node(data) 14 | self.last = self.head 15 | else: 16 | self.last.next = Node(data) 17 | self.last = self.last.next 18 | 19 | def dequeue(self): 20 | if not self.head: 21 | return None 22 | val = self.head.data 23 | self.head = self.head.next 24 | return val 25 | 26 | def display(self): 27 | temp = self.head 28 | while temp != None: 29 | print(temp.data) 30 | temp = temp.next 31 | 32 | x = Queue() # Creating object of queue class 33 | x.enqueue(1) # Add 1 to the queue 34 | x.enqueue(2)# Add 2 to the queue 35 | x.display() # 1 => 2 36 | print(x.dequeue()) # Deleting the first element of the queue. 37 | x.display() # 2 38 | print(x.dequeue()) # 2 39 | print(x.dequeue()) # None(because queue is already empty) -------------------------------------------------------------------------------- /Quick_sort.py: -------------------------------------------------------------------------------- 1 | # Quick sort algorithm 2 | 3 | def quicksort(array): 4 | if len(array) <= 1: 5 | return array 6 | else: 7 | pivot = array.pop() 8 | items_greater = [] 9 | items_lower = [] 10 | for item in array: 11 | if item > pivot: 12 | items_greater.append(item) 13 | else: 14 | items_lower.append(item) 15 | return quicksort(items_lower) + [pivot] + quicksort(items_greater) 16 | 17 | print(quicksort([3, 5, 1, 2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Basic-Python-Programs 2 | This repository will contain basic python programming questions and their solutions. 3 | 4 | # Do give us a Star 5 | 6 | # Contributions 7 | 8 | - Add a new program which don't exist earlier 9 | - It should be in .py extenstion 10 | - Please run the program and check if there are no errors before making the PR 11 | - Review other PR's as well 12 | - No Spamming allowed, make sure to include all programs in one PR. 13 | -------------------------------------------------------------------------------- /Radix_sort.py: -------------------------------------------------------------------------------- 1 | # Radix sort in Python 2 | # Using counting sort to sort the elements in the basis of significant places 3 | def countingSort(array, place): 4 | size = len(array) 5 | output = [0] * size 6 | count = [0] * 10 7 | 8 | # Calculate count of elements 9 | for i in range(0, size): 10 | index = array[i] // place 11 | count[index % 10] += 1 12 | 13 | # Calculate cumulative count 14 | for i in range(1, 10): 15 | count[i] += count[i - 1] 16 | 17 | # Place the elements in sorted order 18 | i = size - 1 19 | while i >= 0: 20 | index = array[i] // place 21 | output[count[index % 10] - 1] = array[i] 22 | count[index % 10] -= 1 23 | i -= 1 24 | 25 | for i in range(0, size): 26 | array[i] = output[i] 27 | 28 | 29 | # Main function to implement radix sort 30 | def radixSort(array): 31 | # Get maximum element 32 | max_element = max(array) 33 | 34 | # Apply counting sort to sort elements based on place value. 35 | place = 1 36 | while max_element // place > 0: 37 | countingSort(array, place) 38 | place *= 10 39 | 40 | 41 | data = [121, 432, 564, 23, 1, 45, 788] 42 | radixSort(data) 43 | print(data) -------------------------------------------------------------------------------- /Random Team Generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | y = list(map(str,input().split())) 3 | t1 = [] 4 | t2 = [] 5 | while (len(y) != 0): 6 | x = random.choice(y) 7 | if (len(t1) == len(t2)): 8 | t1.append(x) 9 | y.remove(x) 10 | elif (len(t1) > len(t2)): 11 | t2.append(x) 12 | y.remove(x) 13 | print("Team A: ", t1) 14 | print("Team B: ", t2) 15 | 16 | -------------------------------------------------------------------------------- /RockPaperScissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | randomInteger=random.randint(0,2) 4 | userInput=int(input("What do you choose ? Type 0 for Rock,1 for Paper or 2 for Scissors\n")) 5 | if(userInput!=0 and userInput!=1 and userInput!=2): 6 | print("Wrong choise") 7 | exit() 8 | 9 | if(userInput==randomInteger): 10 | print("DRAW!!!") 11 | elif (userInput==randomInteger-1 or (userInput==2 and randomInteger==0)): 12 | print("Computer Won") 13 | elif (randomInteger==userInput-1 or (randomInteger==2 and userInput==0)): 14 | print("YOU WON!!!") 15 | print(userInput) 16 | print(f"computer choose {randomInteger}") -------------------------------------------------------------------------------- /RomanToInt.py: -------------------------------------------------------------------------------- 1 | val = input("Enter your value: ") 2 | class Solution(object): 3 | def romanToInt(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900} 9 | i = 0 10 | num = 0 11 | while i < len(s): 12 | if i+1 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: 97 | time.sleep(1) 98 | head.goto(0, 0) 99 | head.direction = "stop" 100 | 101 | #hiding segments of snake 102 | for segment in segments: 103 | segment.goto(1000,1000) 104 | #clearing the segments 105 | segments.clear() 106 | 107 | #reset score 108 | score = 0 109 | 110 | #reset delay 111 | delay = 0.1 112 | 113 | pen.clear() 114 | pen.write("Score : {} High Score : {} ".format( 115 | score, high_score), align="center", font=("Times New Roman", 24, "bold")) 116 | 117 | #checking collision with food 118 | if head.distance(food) < 20: 119 | x = random.randint(-270, 270) 120 | y = random.randint(-270, 270) 121 | food.goto(x, y) 122 | d = ["red","yellow","blue"] 123 | colors = random.choice(d) 124 | food.color(colors) 125 | e = ["circle","square","triangle"] 126 | shapes = random.choice(e) 127 | food.shape(shapes) 128 | 129 | 130 | #adding new segment 131 | new_segment = turtle.Turtle() 132 | new_segment.speed(0) 133 | new_segment.color("green") 134 | new_segment.shape("square") 135 | new_segment.penup() 136 | segments.append(new_segment) 137 | 138 | delay -= 0.001 139 | score += 10 140 | 141 | if score>high_score: 142 | high_score = score 143 | pen.clear() 144 | pen.write("Score : {} High Score : {} ".format( 145 | score, high_score), align="center", font=("Times New Roman", 24, "bold")) 146 | 147 | #moving segments in reverse order 148 | for i in range(len(segments)-1,0,-1): 149 | x = segments[i-1].xcor() 150 | y = segments[i-1].ycor() 151 | segments[i].goto(x,y) 152 | if len(segments) > 0: 153 | x = head.xcor() 154 | y = head.ycor() 155 | segments[0].goto(x, y) 156 | 157 | move() 158 | 159 | #Checking collisions with body 160 | for segment in segments: 161 | if segment.distance(head) < 20: 162 | time.sleep(1) 163 | head.goto(0,0) 164 | head.direction = "stop" 165 | 166 | #hide segments 167 | for segment in segments: 168 | segment.goto(1000,1000) 169 | segment.clear() 170 | 171 | score = 0 172 | delay = 0.1 173 | pen.clear() 174 | pen.write("Score : {} High Score : {} ".format( 175 | score, high_score), align="center", font=("Times New Roman", 24, "bold")) 176 | time.sleep(delay) 177 | 178 | turtle.done() 179 | 180 | -------------------------------------------------------------------------------- /Sell Buy Stocks to Max Profit.py: -------------------------------------------------------------------------------- 1 | p = list(map(int, input().split())) #Enter the prices of each day 2 | 3 | maxProfit = 0 4 | currentMax = 0 5 | 6 | for i in reversed(p): 7 | currentMax = max(currentMax, i) 8 | profit = currentMax - i 9 | maxProfit = max(profit, maxProfit) 10 | 11 | print("Buy stock when price is:", currentMax-maxProfit) #Buying Price 12 | print("Sell stock when price is:", currentMax) #Selling Price 13 | print("Maximum profit earned:", maxProfit) #Profit Earned -------------------------------------------------------------------------------- /Sieve_of _Eratosthenes.py: -------------------------------------------------------------------------------- 1 | def SieveOfEratosthenes(n): 2 | numbers = {i: True for i in range(2, n+1)} 3 | primes = [] 4 | 5 | p = 2 6 | 7 | while p**2 < n : 8 | if numbers[p] : 9 | for i in range(p**2, n+1, p): 10 | numbers[i] = False 11 | p+=1 12 | for i in range(2, n+1) : 13 | if numbers[i] : 14 | primes.append(i) 15 | 16 | return primes 17 | 18 | def main() : 19 | n = int(input("Enter value of n to find primes between 1 and n (inclusive):")) 20 | arr = SieveOfEratosthenes(n) 21 | print("Primes:", *arr) 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /SpeedTypingTestInPython.py: -------------------------------------------------------------------------------- 1 | ### Speed Typing Test in python ### 2 | 3 | # Imported Library 4 | 5 | import time 6 | import threading 7 | 8 | # Created Class 9 | 10 | class tester: 11 | def __init__(self, paragraph): 12 | self.correctWords = [] 13 | self.incorrectWords = {} 14 | self.typedWords = [] 15 | self.totalWords = [] 16 | self.input = None 17 | self.paragraph = paragraph 18 | self.accuracy = 0 19 | self.time = 0 20 | self.wordPermin = 0 21 | self.run() 22 | 23 | #### Defined the Variable ### 24 | 25 | def clock(self): 26 | while len(self.typedWords) == 0: 27 | self.time += 1 28 | time.sleep(1) 29 | 30 | def run(self): 31 | threading.Thread(target=self.clock).start() 32 | threading.Thread(target=self.testSpeed).start() 33 | 34 | def testSpeed(self): 35 | print('\n\n'+self.paragraph+'\n\n') 36 | self.input = str(input('\t\n'+'Type The Word Which You Want To Know the Speed As well as Incorrect \n\n')) 37 | self.totalWords = self.paragraph.split(' ') 38 | self.typedWords = self.input.split(' ') 39 | 40 | try: 41 | for i in range(len(self.typedWords)): 42 | if(self.typedWords[i] == self.totalWords[i]): 43 | self.correctWords.append(self.typedWords[i]) 44 | else: 45 | self.incorrectWords.update({self.totalWords[i] : self.typedWords[i]}) 46 | 47 | except Exception as e: 48 | print(e) 49 | 50 | 51 | self.accuracy = len(self.correctWords)/len(self.typedWords) * 100 52 | self.wordPerMin = len(self.typedWords) / (self.time/60) 53 | 54 | print('\n\nResult :--') 55 | print(f'Accuracy: -- {self.accuracy}') 56 | print(f'Word Per Minute :-- {self.wordPerMin}') 57 | print(f'Incorrect Words :-- {self.incorrectWords}') 58 | 59 | Mytester = tester("You know you're a programmer when you spend a day to find the problem, and then fix it with one line of code.") 60 | 61 | ### The Code is ended, Thank You #### -------------------------------------------------------------------------------- /Spy_number.py: -------------------------------------------------------------------------------- 1 | num=int(input("Enter your number ")) 2 | sum=0 3 | product=1 4 | num1 = num 5 | 6 | while(num>0): 7 | d=num%10 8 | sum=sum+d 9 | product=product*d 10 | num=num//10 11 | 12 | if(sum==product): 13 | print("{} is a Spy number!".format(num1)) 14 | else: 15 | print("{} is not a Spy number!".format(num1)) 16 | -------------------------------------------------------------------------------- /Story-generator-game.py: -------------------------------------------------------------------------------- 1 | import time 2 | import random 3 | from string import ascii_lowercase 4 | 5 | print('This is a game where you guess the randomly chosen word and if you win, you get a randomly generated short story !') 6 | print('Enjoy !!') 7 | print('\n') 8 | 9 | time.sleep(4) 10 | 11 | name=input('Player Name :- ') 12 | print('\n') 13 | print('Welcome ' + name + '. Let''s play Hangman') 14 | print('') 15 | 16 | time.sleep(1) 17 | 18 | friends=['Chandler','Joey','Monica','Rachel','Ross','Phoebe','Gunther','Janice','Ugly Naked Guy','Mr Heckles','Judy','Jack'] 19 | ramaayan=['Shri Ram','Sita maa','Lakshman','Bharat','Raavan','Hanuman','Maarich','Dashrath','Kaikeyi','King Janak','KumbhKarn','Baali'] 20 | Got=['Theon','Danaerys','Jon Snow','Joeffry','Cersie','Tyrion','Drogon','Baratheon','Starks','Greyjoy','Viserys'] 21 | 22 | print('Choose Category :- ') 23 | choose=int(input('1. F.R.I.E.N.D.S 2. Game Of Thrones 3. Ramaayan ')) 24 | if choose==1: 25 | word=random.choice(friends) 26 | elif choose==2: 27 | word=random.choice(Got) 28 | elif choose==3: 29 | word=random.choice(ramaayan) 30 | 31 | print('HINT : Starts with' + word[0]) 32 | print('\n') 33 | print("Start guessing...") 34 | time.sleep(0.5) 35 | guess='' 36 | turn=10 37 | 38 | while turn>0: 39 | fail=0 40 | for c in word: 41 | if c in guess: 42 | print(c) 43 | else: 44 | print('_') 45 | fail+=1 46 | if fail==0: 47 | print('You Won ' + name + ' !') 48 | print('\n') 49 | print('Here is your story - ') 50 | theme=random.choice(["real world","high fantasy","space sci-fi","alt-history","cyberpunk"]) 51 | if theme == "real world": 52 | subsetting=random.choice(["the Ayodhya","Kishkindha","Lanka","Panchvati","Janakpuri"]) 53 | setting=random.choice(["a small town in ","a big city in ","a farm in ","a school in ","the ocean","the entire world"]) 54 | if setting != "the ocean" or "the entire world": 55 | setting=setting+subsetting 56 | age=random.choice(["newborn ","toddler ","child ","teenager ","young adult ","adult ","middle aged ","elder "]) 57 | race=random.choice(["ayodhyan ","janakis ","lankan ","indian "]) 58 | gengender=random.randint(0,100) 59 | if gengender <= 10: 60 | gender = ("transgender ") 61 | if gengender >= 9: 62 | if gengender >= 47: 63 | gender = ("male ") 64 | if gengender <= 46: 65 | gender = ("female ") 66 | protagonist=age+race+gender 67 | antagonist=random.choice(["a female","a male","a king","a government","a tragic event","traffic","religion","a disease","a rival","the law","an old friend","a dog"]) 68 | if theme == "high fantasy": 69 | setting=random.choice(["The Great Empire","a vast desert","a dark corrupted land","a magic swamp","a unending labryinth","floating islands","a mystical forest","a frozen wasteland","a dangerous jungle land"]) 70 | gender=random.choice(["male ","male ","male ","female ","female ","female ","magical transgender ","agender ","third gender "]) 71 | race=random.choice(["human ","human ","elf ","orc ","dwarf ","gnome ","demon ","angel ","kitsune ","dark elf ","troll ","unicorn "]) 72 | classs=random.choice(["marksmen ","warrior ","wizard ","bard ","thief ","merchant","knight ","spellsword ","peasant ","necromancer ","preist ","bandit ","monarch"]) 73 | protagonist = gender+race+classs 74 | antagonist=random.choice(["a female","a male","an entire race","a god","an evil mage","an order of knights","evil itself","a giant","an invading army","a tyrant","magic","a greedy merchant","a monster","a dragon"]) 75 | if theme == "space sci-fi": 76 | setting=random.choice(["the deep void of space","an asteroid belt","an ice planet","a lava planet","a gas giant","an alien home world","future Earth","another galaxy, far far away","the multiverse"]) 77 | protagonist=random.choice(["human","robot","hive mind","alien","alien","blob","human"]) 78 | antagonist=random.choice(["a female","a male","an entire alien race","a starfleet","an alien","an artifical intellgence","a galactic federation","a glitch in space-time","an invading army","a incredibly infectious space fungus","the limits of science","a robot"]) 79 | if theme == "alt-history": 80 | setting=random.choice(["America","Religion","the Classical Era","the Middle Ages","the Renaissance","the Industrial Era","World War I","World War II","the Modern Era"]) 81 | if setting == "America": 82 | figures=["Abraham Lincoln","George W. Bush Jr.","Benjamin Franklin","Donald Trump","Ronald Reagan","John Adams","Hilary Clinton","King George III","King George Washington","Andrew Jackson","Thomas Edison","Steve Jobs"] 83 | figure=random.choice(figures) 84 | antagonist=random.choice(figures) 85 | if setting == "Religion": 86 | figure=random.choice(["Jesus","Muhammad","Buddha","Krishna","Moses","L. Ron Hubbard","Joseph Smith","Zeus","Ra","Thor"]) 87 | antagonist=random.choice(["Christianity","Islam","Hinduism","Buddhism","Greek mythology","Scientology","the Mormons","Paganism","Heresies"]) 88 | if setting == "the Classical Era": 89 | figures=["Alexander The Great","Julius Caesar","Aristotle","King Tut","Qin Shi Huang","Homer","Augustus","Plato","Cleopatra","Ashoka","Attila the Hun","Leonidas"] 90 | figure=random.choice(figures) 91 | antagonist=random.choice(figures) 92 | if setting == "the Middle Ages": 93 | figures=["Charlemagne","Ghenghis Khan","Saladin","William the Conqueror","Ragnar Lodbrok","Oda Nobunaga","King Richard III","William Wallace","El Cid","Eleanor of Aquitaine","Erik the Red","Vlad the Impaler"] 94 | figure=random.choice(figures) 95 | antagonist=random.choice(figures) 96 | if setting == "the Renaissance": 97 | figures=["Marco Polo","Joan of Arc","Christopher Columbus","Blackbeard","Leonardo da Vinci","William Shakespeare","Henry VIII","Michelangelo","Donatello","Galileo","Admiral Yi Sun-sin","Suleiman the Magnificent"] 98 | figure=random.choice(figures) 99 | antagonist=random.choice(figures) 100 | if setting == "the Industrial Era": 101 | figures=["Henry Ford","Karl Marx","Charles Dickens","John D. Rockefeller","Thomas Edison","Nikola Tesla","Amelia Earheart","Frank C. Mars","Albert Einstein","Napoleon","Ghandi","Mark Twain"] 102 | figure=random.choice(figures) 103 | antagonist=random.choice(figures) 104 | if setting == "World War I": 105 | figure=random.choice(["Woodrow Wilson","Winston Churchill","Tsar Nicholas II","Lenin","Paul von Hindenburg","Ataturk"]) 106 | antagonist=random.choice(["the Ottoman Empire","Germany","the United States","Britain","Austria-Hungary","France"]) 107 | if setting == "World War II": 108 | figure=random.choice(["Hitler","Queen Elizabeth","Franklin D. Roosevelt","Joseph Stalin","Harry Truman","General Hideki Tojo"]) 109 | antagonist=random.choice(["the United States","Germany","the Soviet Union","the United Kingdom","Japan","Italy"]) 110 | if setting == "the Modern Era": 111 | figures=["Obama","Putin","Kim Jong-un","Kanye West","Bill Gates","Guido van Rossum","The Beatles","ISIS","Pope Francis","Mike Tyson","Pewdiepie","Hilary Cliton"] 112 | figure=random.choice(figures) 113 | antagonist=random.choice(figures) 114 | afigure=("figure known as ") 115 | protagonist= afigure+figure 116 | if theme == "cyberpunk": 117 | setting=random.choice(["high-tech Tokyo","New New York","a dystopia","a utopia","a computer simulation","the SuperWeb","Mega Silicon Valley","an underwater city","an extensive underground facility"]) 118 | gender=random.choice(["male ","male ","female ","female ","robogender ","unigender ","agender ","mega genderfluid ","third gender "]) 119 | classs=random.choice(["hacker","cyborg","DJ","technopath","engineer","bomber","corporate","street rat","anarchist"]) 120 | protagonist=gender+classs 121 | antagonist=random.choice(["a large corporation","an evil AI","Python","a gang","a secret society","a new technology","robots","internet trolls","the most powerful cyborg"]) 122 | conflict=random.choice(["fell in love with ","fought against ","attempted to stop ","defended against ","tried to befriend ","explored with ","tried to evade ","competed with ","exceeded beyond ","sought revenge against "]) 123 | end=random.choice(["It did not end well.","It ended very well.","Died tragically.","Lived happily ever after.","It ended sadly.","It was glorious.","In the end, nothing changed.","It ended with a twist.","Gave up."]) 124 | print("In the",theme,"setting of",setting,", there was a", protagonist, "who",conflict,antagonist,".",end) 125 | 126 | break 127 | 128 | 129 | 130 | guesses=input('Guess a character :- ') 131 | guess=guess+guesses 132 | if guesses not in word: 133 | turn-=1 134 | print('Wrong. You have ' + str(turn) + ' more guesses.') 135 | if turn==0: 136 | print('You lose ! The word was ' + word + '. Sorry, you don''t get the story.') 137 | print('\n') 138 | print('Write your story on your own.') 139 | #Winstoryhangman 140 | -------------------------------------------------------------------------------- /TicTacToe.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import messagebox 3 | import random as r 4 | import functools 5 | 6 | 7 | def button(f): 8 | button1 = Button(f, text=" ", fg="Black", font="Arial 20 bold", height=1, width=2, padx=25, pady=20, bg="White", borderwidth=0, 9 | activebackground="White", cursor="hand2", state=NORMAL) 10 | return button1 11 | 12 | 13 | def full(): 14 | for row in range(3): 15 | for col in range(3): 16 | if b[row][col]['text'] == " ": 17 | return False 18 | return True 19 | 20 | 21 | def empty(): 22 | for row in range(3): 23 | for col in range(3): 24 | b[row][col].config(text=" ", state=NORMAL) 25 | 26 | 27 | def winner(s): 28 | return b[0][0]['text'] == b[0][1]['text'] == b[0][2]['text'] == s or b[1][0]['text'] == b[1][1]['text'] == b[1][2]['text'] == s\ 29 | or b[2][0]['text'] == b[2][1]['text'] == b[2][2]['text'] == s or b[0][0]['text'] == b[1][0]['text'] == b[2][0]['text'] == s\ 30 | or b[0][1]['text'] == b[1][1]['text'] == b[2][1]['text'] == s or b[0][2]['text'] == b[1][2]['text'] == b[2][2]['text'] == s\ 31 | or b[0][0]['text'] == b[1][1]['text'] == b[2][2]['text'] == s or b[0][2]['text'] == b[1][1]['text'] == b[2][0]['text'] == s 32 | 33 | 34 | user_checked = [] 35 | com_checked = [] 36 | 37 | 38 | def click(event, param1, param2): 39 | sign = 0 40 | if (param1, param2) in user_checked or (param1, param2) in com_checked: 41 | messagebox.showwarning("Warning", "Select Another Box.") 42 | else: 43 | user_checked.append((param1, param2)) 44 | b[param1][param2]['text'] = 'O' 45 | 46 | if winner("O"): 47 | messagebox.showinfo("Winner", "You Won...") 48 | user_score.set(user_score.get() + 1) 49 | empty() 50 | user_checked.clear() 51 | com_checked.clear() 52 | sign = 1 53 | 54 | if full(): 55 | messagebox.showinfo("Tie", "Match Tie...!") 56 | tie_score.set(tie_score.get() + 1) 57 | empty() 58 | user_checked.clear() 59 | com_checked.clear() 60 | sign = 1 61 | 62 | if sign == 0: 63 | unchecked = [] 64 | for row in range(3): 65 | for col in range(3): 66 | if b[row][col]['text'] == " ": 67 | unchecked.append([row, col]) 68 | index = r.sample(unchecked, 1) 69 | b[index[0][0]][index[0][1]].config(text="X", state=DISABLED) 70 | com_checked.append((index[0][0], index[0][1])) 71 | if winner("X"): 72 | messagebox.showinfo("Winner", "Computer Won...") 73 | com_score.set(com_score.get() + 1) 74 | empty() 75 | user_checked.clear() 76 | com_checked.clear() 77 | else: 78 | pass 79 | 80 | 81 | root = Tk() 82 | root.title("Tic Tac Toe") 83 | root.geometry("420x500") 84 | root.resizable(0, 0) 85 | root.configure(bg="Black") 86 | Label(root, text="TIC TAC TOE", fg="White", bg="Black", font="times 25 bold").pack() 87 | 88 | Frame(root, bg="White").pack(fill=X, pady=10) 89 | frame = Frame(root, bg="Black") 90 | Label(frame, text="YOU", fg="Yellow", bg="Black", font="System 10 bold", padx=50, pady=5).pack(side=LEFT) 91 | Label(frame, text="TIE", fg="Yellow", bg="Black", font="System 10 bold", padx=48, pady=5).pack(side=LEFT) 92 | Label(frame, text="COMPUTER", fg="Yellow", bg="Black", font="System 10 bold", padx=30, pady=5).pack(side=LEFT) 93 | frame.pack(pady=5) 94 | 95 | frame = Frame(root, bg="Black") 96 | user_score = IntVar() 97 | tie_score = IntVar() 98 | com_score = IntVar() 99 | user_score.set(0) 100 | tie_score.set(0) 101 | com_score.set(0) 102 | user = Entry(frame, textvariable=user_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, 103 | justify=CENTER) 104 | user.pack(side=LEFT, padx=35) 105 | tie = Entry(frame, textvariable=tie_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, 106 | justify=CENTER) 107 | tie.pack(side=LEFT, padx=15) 108 | com = Entry(frame, textvariable=com_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, 109 | justify=CENTER) 110 | com.pack(side=LEFT, padx=50) 111 | frame.pack(pady=10) 112 | 113 | Frame(root, bg="White").pack(fill=X, pady=15) 114 | 115 | b = [[], [], []] 116 | for i in range(3): 117 | frame = Frame(root, highlightbackground="Black", highlightthickness=3, bg="Black") 118 | for j in range(3): 119 | b[i].append(button(frame)) 120 | b[i][j].bind("", functools.partial(click, param1=i, param2=j)) 121 | b[i][j].pack(side=LEFT, padx=5) 122 | frame.pack() 123 | 124 | root.mainloop() 125 | -------------------------------------------------------------------------------- /Tic_tac_toe_game_in_python.py: -------------------------------------------------------------------------------- 1 | # print("Namste Duniya") 2 | 3 | def sum(a, b, c): 4 | return a + b + c 5 | 6 | 7 | def printBoard(xState, zState): 8 | one = 'X' if xState[1] else ('0' if zState[1] else 1) 9 | two = 'X' if xState[2] else ('0' if zState[2] else 2) 10 | three = 'X' if xState[3] else ('0' if zState[3] else 3) 11 | four = 'X' if xState[4] else ('0' if zState[4] else 4) 12 | five = 'X' if xState[5] else ('0' if zState[5] else 5) 13 | six = 'X' if xState[6] else ('0' if zState[6] else 6) 14 | senven = 'X' if xState[7] else ('0' if zState[7] else 7) 15 | eight = 'X' if xState[8] else ('0' if zState[8] else 8) 16 | nine = 'X' if xState[9] else ('0' if zState[9] else 9) 17 | print(f"{one} | {two} | {three} ") 18 | print(f"--|---|---") 19 | print(f"{four} | {five} | {six} ") 20 | print(f"--|---|---") 21 | print(f"{senven} | {eight} | {nine} ") 22 | 23 | def checkWin(xState, zState): 24 | wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] 25 | for win in wins: 26 | if(sum(xState[win[0]], xState[win[1]], xState[win[2]]) == 3): 27 | print("X's win") 28 | return 1 29 | if(sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3): 30 | print("O's win") 31 | return 0 32 | return -1 33 | 34 | 35 | 36 | if __name__ == "__main__": 37 | xState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 38 | zState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 39 | turn = 1 # 1for X and for 0 40 | print("Welcome to tic tac toe") 41 | while(True): 42 | printBoard(xState, zState) 43 | if(turn == 1): 44 | print("X's Chance") 45 | value = int(input("Please enter a value: ")) 46 | xState[value] = 1 47 | else: 48 | print("0's Chance") 49 | value = int(input("Please enter a value: ")) 50 | zState[value] = 1 51 | cwin = checkWin(xState, zState) 52 | if(cwin != -1): 53 | print("Match Over") 54 | break 55 | 56 | turn = 1 - turn -------------------------------------------------------------------------------- /TowerOfHanoi.py: -------------------------------------------------------------------------------- 1 | def TowerOfHanoi(Disks, source, temp, destination): 2 | if(Disks == 1): 3 | print("Move Disk 1 From {} to {}".format(source, destination)) 4 | return 5 | TowerOfHanoi(Disks - 1, source, destination, temp) 6 | print("Move Disk {} From {} to {}".format(Disks, source, destination)) 7 | TowerOfHanoi(Disks - 1, temp, source, destination) 8 | 9 | Disks = int(input("Enter Number of Disks: ")) 10 | 11 | # Source : A, Intermediate : B, Destination : C 12 | TowerOfHanoi(Disks, 'A', 'B', 'C') -------------------------------------------------------------------------------- /YoutubeDownloader.py: -------------------------------------------------------------------------------- 1 | #pip install pytube to install library 2 | from pytube import YouTube 3 | link = input("Enter youtube url:") 4 | yt = YouTube(link) 5 | 6 | SAVE_PATH = "E:/" 7 | 8 | #Title of Video 9 | print("Title:",yt.title) 10 | 11 | #Number of Views 12 | print("Views:",yt.views) 13 | 14 | #Length of Video 15 | print("Length of Video:",yt.length,"seconds") 16 | 17 | #Rating of Video 18 | print("Rating:",yt.rating) 19 | 20 | x = input("Do you want video or audio(v/a): ") 21 | if x=="v": 22 | print(yt.streams.filter(progressive=True)) 23 | ys = yt.streams.get_by_itag('22') 24 | 25 | else: 26 | print(yt.streams.filter(only_audio=True)) 27 | ys = yt.streams.get_by_itag('251') 28 | 29 | #Downloading 30 | print("***DOWNLOADING***") 31 | ys.download(SAVE_PATH) 32 | print("***DOWNLOADED***") -------------------------------------------------------------------------------- /addition.py: -------------------------------------------------------------------------------- 1 | num1 = int(input("Enter First Number: ") 2 | num2 = int(input("Enter Second Number: ") 3 | 4 | sum = num1+num2 5 | 6 | print(""Sum of {0} and {1} is {2}" .format(num1, num2, sum)) 7 | -------------------------------------------------------------------------------- /adventure_game.py: -------------------------------------------------------------------------------- 1 | from time import * 2 | 3 | print("Hello! Welcome to the game") 4 | choice = input("Do you want to start the game? Y/N: ").upper() 5 | if choice == 'Y': 6 | print("Let's Go!!") 7 | else: 8 | print("Let's play next time ☹") 9 | sleep(20) 10 | print("""In which path you want to go 11 | A- Concrete road 12 | B- Road in middle of forest 13 | C- Swimming through the ocean\n""") 14 | choice = input("Enter your choice: ").upper() 15 | if choice == 'A': 16 | ch = input("\nThere is a building in the front would u want to enter it? Y/N: ").upper() 17 | if ch == 'Y': 18 | print("\nYou entered the building....") 19 | ch1 = input("Would you like to take the lift (type Y) or go from the stairs (type N)? ").upper() 20 | if ch1 == 'Y': 21 | print("\nYou took the lift and the lift stopped working and it crashed, you died") 22 | sleep(20) 23 | elif ch1 == 'N': 24 | ch2 = input("\nYou reached the terrace u saw a parachute would you like to take it? Y/N: ").upper() 25 | if ch2 == 'Y': 26 | print("\nYou took the parachute and landed on a playground.") 27 | print("You went home empty handed. ") 28 | sleep(20) 29 | elif ch2 == 'N': 30 | print("\nYou can't do anything the building security guard caught you and handed you to the police. ") 31 | print("You failed") 32 | sleep(20) 33 | elif ch == 'N': 34 | ch1 = input("\nYou passed the building and now there is a restaurant would you like to go and have lunch? Y/N: ").upper() 35 | if ch1 == 'Y': 36 | print("\nYou entered the restaurant....") 37 | ch2 = input("You had lunch, would you like to pay the bill(type Y) or run away(type N)? ").upper() 38 | if ch2 == 'Y': 39 | print("\nYou paid the bill but you had no money so the manager called the police and you got arrested") 40 | sleep(20) 41 | elif ch2 == 'N': 42 | print("\nYou ran away... but somehow the police found you so u are arrested") 43 | sleep(20) 44 | elif ch1 == 'N': 45 | print("\nYou were just walking randomly and fell into a manhole...U died") 46 | sleep(20) 47 | elif choice == 'B': 48 | print("\nYou are lost in the forest...") 49 | ch = input("There is a cave in front would you like to enter it? Y/N: ").upper() 50 | if ch == 'Y': 51 | print("\nYou entered the cave there was a giant inside...he wants to become your friend") 52 | ch1 = input("Would you like to become is friend? Y/N: ").upper() 53 | if ch1 == 'Y': 54 | print("\nYou both became friends and he took you to his kingdom made you the price of the kingdom...") 55 | print("You both live a happy life...") 56 | sleep(20) 57 | if ch1 == 'N': 58 | print("\nGiant became angry and ate you raw....RIP") 59 | sleep(20) 60 | elif ch =='N': 61 | print("\nYou ignored the cave and continued your journey") 62 | ch1 = input("You see something buried underground would you like to dig and remove it? Y/N: ").upper() 63 | if ch1 == 'Y': 64 | print("\nLucky you! It was a map and it lead to something ") 65 | ch2 = input("Would you like to follow the map? Y/N: ").upper() 66 | if ch2 == 'Y': 67 | print("\nYou are following the map and you ended up under a big tree and theres a \"X\" mark") 68 | ch3 = input("Would you like to dig it? Y/N: ").upper() 69 | if ch3 == 'Y': 70 | print("\nYou found nothing...") 71 | print("And you got lost in the forest and now you died due to starvation") 72 | sleep(20) 73 | elif ch3 == 'N': 74 | print("\nAnd you got lost in the forest and now you died due to starvation") 75 | sleep(20) 76 | elif ch2 == 'N': 77 | print("\nYou didn't follow the map and went ahead...") 78 | ch3 = input("You saw a \"X\" mark in the ground would you like to dig and see whats there? Y/N: ").upper() 79 | if ch3 == 'Y': 80 | print("\nYou found and treasure worth billions...You realised that the map was a distraction") 81 | print("You are now a billionaire and living your life peacefully") 82 | sleep(20) 83 | elif ch3 == 'N': 84 | print("\nYou went too deep in the forest") 85 | print("You got lost and now you died due to starvation") 86 | sleep(20) 87 | elif ch1 == 'N': 88 | print("\nYou continued your journey and came across a river") 89 | ch2 = input("Would you like to swim and cross the river? Y/N: ").upper() 90 | if ch2 == 'Y': 91 | print("\nYou jumped in the river and there was a crocodile...and you know what happened next lol ") 92 | sleep(20) 93 | elif ch2 == 'N': 94 | print("\nYou went ahead and found a bridge and you crossed the river") 95 | ch3 = input("There are two ways would you like to go right or left? R/L: ").upper() 96 | if ch3 == 'R': 97 | print("\nYou chose the right path and you reached the city and safely went back home!") 98 | sleep(20) 99 | elif ch3 == 'L': 100 | print("\nYou went along the left path...") 101 | print("You saw a cave but you realise that it is the same cave you found at beginning...") 102 | print("And now you are in a infinite loop...Bye Have Fun ") 103 | sleep(20) 104 | elif choice == 'C': 105 | print("\nYou are swimming in the ocean") 106 | ch1 = input("You found an island would like to go there? Y/N: ").upper() 107 | if ch1 == 'Y': 108 | print("\nYou are now walking in the island...") 109 | print("You find that the island is full of cannibals 💀") 110 | ch2 = input("Do you want to run away(type Y) or be friends with them(type N)? ").upper() 111 | if ch2 == 'Y': 112 | print("\nYou are running and there was a bear trap and you stepped on it") 113 | print("They found you....") 114 | sleep(20) 115 | elif ch2 == 'N': 116 | print("\nYou tried to be their friend but you forgot that they don't understand your language...") 117 | print("They thought you were teasing them and they had tasty lunch 🍴") 118 | sleep(20) 119 | elif ch1 == 'N': 120 | print("\nYou ignored the island and swam ahead") 121 | print("You found 2 fisherman in a boat") 122 | ch2 = input("Would you like to join them? Y/N: ").upper() 123 | if ch2 == 'Y': 124 | print("\nThey were very good and they took you with them and you safely made to the land") 125 | print("You are now at home chilling 😎") 126 | sleep(20) 127 | elif ch2 == 'N': 128 | print("\nYou told them that you won't come with them") 129 | print("You are now swimming ahead and you are in middle of nowhere...") 130 | print("You died....") 131 | sleep(20) 132 | else: 133 | print("\nSelect correction option!! ") 134 | sleep(20) 135 | 136 | -------------------------------------------------------------------------------- /alphabet_rangoli.py: -------------------------------------------------------------------------------- 1 | def print_rangoli(size): 2 | rangoli = [] 3 | l = (size-1)*4+1 4 | pattern = "" 5 | for i in range(97+size-1, 96, -1): 6 | pattern = f"{pattern}-{chr(i)}" if pattern != "" else chr(i) 7 | leftSide = f"{pattern :->{l//2+1}}" 8 | rightSide = leftSide[-2::-1] 9 | rangoli.append(leftSide + rightSide) 10 | 11 | print('\n'.join(rangoli)) 12 | print('\n'.join(rangoli[-2::-1])) 13 | 14 | if __name__ == '__main__': 15 | n = int(input()) 16 | print_rangoli(n) -------------------------------------------------------------------------------- /an4gram.py: -------------------------------------------------------------------------------- 1 | #anagram is where both the strings have each characters of the same frequency 2 | #danger and garden is an example of an anagram 3 | 4 | def isanagram(s1,s2): 5 | if(len(s1)!=len(s2)): 6 | return False 7 | 8 | # return sorted(s1) == sorted(s2) 9 | freq1 = {} #declaring dictionaries for mapping purpose 10 | freq2 = {} 11 | 12 | #using dictionary(hash table) for assigning the character as key and no of times it repeated as values 13 | # { 14 | # char1:value1 15 | # } 16 | for char in s1: 17 | if char in freq1: 18 | freq1[char] += 1 19 | else: 20 | freq1[char] = 1 21 | 22 | for char in s2: 23 | if char in freq2: 24 | freq2[char] += 1 25 | else: 26 | freq2[char] = 1 27 | 28 | # for every key in dictionary freq1 we are comparing it with the key in dictionary freq2 29 | # if the key is not found then it will return false 30 | # and simillarly the values from both the dictionaries are being compared 31 | # if any one of the condition is false it will return false "or" is being used 32 | for key in freq1: 33 | if key not in freq2 or freq1[key]!=freq2[key]: 34 | return False 35 | return True 36 | 37 | 38 | 39 | s1 = input("Enter a string\n") 40 | s2 = input("Enter second string\n") 41 | 42 | if isanagram(s1,s2): 43 | print(f"\nThe {s1} and {s2} are Anagrams") 44 | else: 45 | print(f"{s1} and {s2} are not anagram") -------------------------------------------------------------------------------- /area-of-circle.py: -------------------------------------------------------------------------------- 1 | 2 | def findArea(r): 3 | PI = 3.142 4 | return PI * (r*r) 5 | 6 | print("Area is %.2f" % findArea(5)) 7 | -------------------------------------------------------------------------------- /arithmetic_progression.py: -------------------------------------------------------------------------------- 1 | ########################################################################### 2 | 3 | # Question - Arithmetic Progression Generator 4 | 5 | # # Develop a program that: 6 | # 1- read the first term and the common difference of a arithmetic progression 7 | # 2- show the first 10 terms of this progression 8 | # 3- ask to user if he wants show some more terms 9 | # 4- finish the program when user says he wants to show 0 terms 10 | 11 | ########################################################################### 12 | 13 | print("Arithmetic Progression Generator") 14 | print("-=" * 50) 15 | first_term = int(input("First term: ")) 16 | common_difference = int(input("Common difference: ")) 17 | term = first_term 18 | cont = 1 19 | more = 10 20 | total = 0 21 | while more != 0: 22 | total += more 23 | while cont <= total: 24 | print(f"{term}", end=" --> ") 25 | term += common_difference 26 | cont += 1 27 | 28 | print("PAUSE.\n") 29 | 30 | more = int(input("How many terms you want to show more? ")) 31 | print(f"\n\nArithmetic Progression was finished with {total} terms shown.\n\n") 32 | -------------------------------------------------------------------------------- /armstrong.py: -------------------------------------------------------------------------------- 1 | def power(x, y): 2 | 3 | if y == 0: 4 | return 1 5 | if y % 2 == 0: 6 | return power(x, y // 2) * power(x, y // 2) 7 | 8 | return x * power(x, y // 2) * power(x, y // 2) 9 | 10 | def order(x): 11 | 12 | n = 0 13 | while (x != 0): 14 | n = n + 1 15 | x = x // 10 16 | 17 | return n 18 | 19 | def isArmstrong(x): 20 | 21 | n = order(x) 22 | temp = x 23 | sum1 = 0 24 | 25 | while (temp != 0): 26 | r = temp % 10 27 | sum1 = sum1 + power(r, n) 28 | temp = temp // 10 29 | 30 | return (sum1 == x) 31 | 32 | x = 153 33 | print(isArmstrong(x)) 34 | 35 | x = 1253 36 | print(isArmstrong(x)) 37 | -------------------------------------------------------------------------------- /arrayReverse.py: -------------------------------------------------------------------------------- 1 | # Simple swapping of array elements using two pointer method 2 | 3 | def reverse(arr): 4 | start = 0 5 | end = len(arr) - 1 6 | temp = 0 7 | 8 | while( start < end ): 9 | temp=arr[start] 10 | arr[start]=arr[end] 11 | arr[end]=temp 12 | start += 1 13 | end -= 1 14 | 15 | # User input starts 16 | def userInput(): 17 | arr = [] 18 | n = int(input("Enter number of elements:")) 19 | print("Enter the elements") 20 | for i in range(0,n): 21 | element = int(input()) 22 | arr.append(element) 23 | 24 | print("Array before reversing:", arr) 25 | reverse(arr) 26 | print("Array after reversing:", arr) 27 | 28 | userInput() 29 | -------------------------------------------------------------------------------- /automorphic.py: -------------------------------------------------------------------------------- 1 | print("Enter the number you want to check:") 2 | num=int(input()) 3 | square=num*num 4 | flag=0 5 | while(num>0): 6 | if(num%10!=square%10): 7 | print("No, it is not an automorphic number.") 8 | flag=1 9 | break 10 | 11 | num=num//10 12 | square=square//10 13 | if(flag==0): 14 | print("Yes, it is an automorphic number.") 15 | -------------------------------------------------------------------------------- /banking_system.py: -------------------------------------------------------------------------------- 1 | # TODO: 2 | # Parent Class : User 3 | # Holds details about an user 4 | # Has function to show user details 5 | # Child Class : Bank 6 | # Stores details about the account balance 7 | # Stores details about the amount 8 | # Allows for deposit, withdraw and view balance 9 | 10 | # Parent Class 11 | class User(): 12 | def __init__(self,name,age,gender): 13 | self.name = name 14 | self.age = age 15 | self.gender = gender 16 | 17 | def show_details(self): 18 | print(f""" 19 | Personal Details 20 | ------------------------- 21 | Name : {self.name} 22 | Age : {self.age} 23 | Gender : {self.gender} 24 | """) 25 | 26 | # arjun = User('Arjun',20,'Male') 27 | # print(arjun) 28 | # arjun.show_details() 29 | 30 | # Child Class 31 | class Bank(User): 32 | def __init__(self, name, age, gender): 33 | super().__init__(name, age, gender) 34 | self.balance = 0 35 | 36 | def deposit(self,amount): 37 | self.amount = amount 38 | self.balance += self.amount 39 | print(f"Successfully Deposited : ${self.amount}") 40 | print(f"Current Balance : ${self.balance}") 41 | print() 42 | 43 | def withdraw(self,amount): 44 | self.amount = amount 45 | if self.amount < self.balance: 46 | self.balance -= self.amount 47 | print(f"Successfully Withdrawn ${self.amount}") 48 | print(f"Current Balance : ${self.balance}") 49 | print() 50 | else: 51 | print("Not Enough Balance!!!") 52 | print(f"Current Balance : ${self.balance}") 53 | print() 54 | 55 | def view_balance(self): 56 | self.show_details() 57 | print(" -------------------------") 58 | print(f" Current Balance : ${self.balance}") 59 | print() 60 | 61 | #-------------------------------------------------- 62 | 63 | sbi = Bank('Akshay',20,'Male') 64 | print(sbi) 65 | # sbi.show_details() 66 | # sbi.view_balance() 67 | # sbi.deposit(100) 68 | sbi.deposit(1000) 69 | sbi.withdraw(100) 70 | # sbi.withdraw(1100) 71 | -------------------------------------------------------------------------------- /binarySearch.py: -------------------------------------------------------------------------------- 1 | def binarySearch(arr,target): 2 | start = 0 3 | end = len(arr) - 1 4 | 5 | while ( start <= end ): 6 | mid = start + ( end - start ) // 2 7 | if (target < arr[mid]): 8 | end = mid - 1 9 | elif (target > arr[mid]): 10 | start = mid + 1 11 | else: 12 | return mid 13 | return -1 14 | 15 | def userInput(): 16 | arr = [] 17 | n = int(input("Enter number of elements: ")) 18 | print("Enter the elements") 19 | for i in range(0,n): 20 | element = int(input()) 21 | arr.append(element) 22 | print(arr) 23 | target = int(input("Enter the target element: ")) 24 | 25 | result = binarySearch(arr,target) 26 | if(result == -1): 27 | print("Element not found") 28 | else: 29 | print("The element was found at index ", result) 30 | 31 | # Tests ('pip install pytest'; run with 'pytest binarySearch.py') 32 | def test_find_element_in_list(): 33 | arr = [11, 12, 22, 25, 34, 64, 90, 91] 34 | result = binarySearch(arr, 25) 35 | assert result == 3 36 | 37 | def test_elem_missing(): 38 | arr = [11, 12, 22, 25, 34, 64, 90, 91] 39 | result = binarySearch(arr, 16) 40 | assert result == -1 41 | 42 | if __name__ == "__main__": 43 | userInput() -------------------------------------------------------------------------------- /binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | def bin_to_dec(n:int)->int: 2 | return int(str(n),2) 3 | 4 | 5 | 6 | num = int(input('Enter a number (base 2): ')) 7 | print("It's value in base 10 is",bin_to_dec(num)) -------------------------------------------------------------------------------- /calculator.py: -------------------------------------------------------------------------------- 1 | num1=int(input("eneter a digit")) 2 | num2=int(input("eneter a another digit")) 3 | # defination for operators 4 | 5 | #addition 6 | def add(num1, num2): 7 | return num1+num2 8 | #substraction 9 | def subtract(num1, num2): 10 | return num1-num2 11 | #multiply 12 | def multiply(num1, num2): 13 | return num1*num2 14 | #division 15 | def divide(num1, num2): 16 | return num1/num2 17 | 18 | #command for operation 19 | print("choose operation") 20 | print("press 1 for add") 21 | print("press 2 for subs") 22 | print("press 3 for multiply") 23 | print("press 4 for devision") 24 | 25 | 26 | 27 | 28 | 29 | while True: 30 | # take input from the user 31 | choice = input("Enter choice(1/2/3/4): ") 32 | 33 | if choice in ('1', '2', '3', '4'): 34 | 35 | if choice == '1': 36 | print(num1, "+", num2, "=", add(num1, num2)) 37 | 38 | 39 | 40 | elif choice == '2': 41 | print(num1, "-", num2, "=", subtract(num1, num2)) 42 | 43 | elif choice == '3': 44 | print(num1, "*", num2, "=", multiply(num1, num2)) 45 | 46 | 47 | 48 | 49 | 50 | elif choice == '4': 51 | print(num1, "/", num2, "=", divide(num1, num2)) 52 | # check if user wants another calculation 53 | # break the while loop if answer is no 54 | next_calculation = input("Let's do next calculation? (yes/no): ") 55 | if next_calculation == "no": 56 | break 57 | 58 | else: 59 | print("Invalid Input") 60 | -------------------------------------------------------------------------------- /calendar_program.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | ''' 3 | Write a Python program that prints the calendar of a given month in a given year after validating the user input. 4 | ''' 5 | 6 | 7 | def validate_user_input(): 8 | is_valid_year = False 9 | is_valid_month = False 10 | '''user should enter a valid year''' 11 | while not is_valid_year: 12 | year = input("Enter the year \n format: YYYY: ") 13 | if len(year) == 4 and year.isdigit(): 14 | is_valid_year = True 15 | else: 16 | print("Kindly Enter a vaild four-digit year number") 17 | '''user should enter a valid month''' 18 | while not is_valid_month: 19 | month = input("Enter month \n format: 1-12: ") 20 | if month.isdigit() and 12 >= int(month) >= 1: 21 | is_valid_month = True 22 | else: 23 | print("Kindly Enter a vaild month number between 1 and 12") 24 | return [int(year), int(month)] 25 | 26 | 27 | def print_given_month(): 28 | year, month = validate_user_input() 29 | print(year, month) 30 | print(calendar.month(year, month)) 31 | 32 | 33 | print_given_month() -------------------------------------------------------------------------------- /camelCase-to-snake_case.py: -------------------------------------------------------------------------------- 1 | name = input("Enter name of variable in camelCase: ") 2 | 3 | j = 0 4 | 5 | for char in name: 6 | if char.isupper(): 7 | print("_" + char.lower(), end = "") 8 | else: 9 | print(char, end = "") -------------------------------------------------------------------------------- /cielingOfNumInList.py: -------------------------------------------------------------------------------- 1 | # In this problem we have to find a number equal to or the smallest greatest number to the given target number. 2 | 3 | # so we use binary search for this 4 | # case 1: mid==target 5 | # so we have found a number equal to the target. problem solved 6 | # case 2 : element is not in the array 7 | # in this case we would reach the start>end and the while loop would stop. 8 | # and the next greater element would be pointed at by the start. 9 | # so the ceiling of the number would be arr[start]. 10 | 11 | arr =[1,2,3,4,8,9,10,15,19,23,27,29,34,39,45,46,55,59,60,63,68,69] 12 | target = int(input("Enter the target element->")) 13 | start = 0 14 | end = len(arr)-1 15 | 16 | while(startarr[mid]: 24 | start=mid+1 25 | else: 26 | print(f"The ceiling of the element is {arr[start]}") 27 | -------------------------------------------------------------------------------- /clock.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.ttk import * 3 | 4 | from time import strftime 5 | 6 | root = Tk() 7 | root.title("Clock") 8 | 9 | def time(): 10 | string = strftime('%I:%M:%S %p') 11 | label.config(text=string) 12 | label.after(1000, time) 13 | 14 | label = Label(root, font=("ds-digital",80), background = "black", foreground = "cyan") 15 | label.pack(anchor = 'center') 16 | time() 17 | 18 | mainloop() -------------------------------------------------------------------------------- /collatz_sequence.py: -------------------------------------------------------------------------------- 1 | # The Collatz Conjecture is a famous math problem. 2 | # The conjecture is that after applying a sequence of one of two transformations, 3 | # every positive integer will eventually transform into 1. 4 | # The transformations are: divide by 2 if the number is even, multiply by 3 and add 1 if its odd. 5 | # You can see more about it here https://en.wikipedia.org/wiki/Collatz_conjecture 6 | 7 | def collatz(initial_number): 8 | num = initial_number 9 | print(f'Initial number is: {initial_number}') 10 | while num != 1: 11 | print(num) 12 | if num % 2 == 0: 13 | num = int(num / 2) 14 | else: 15 | num = int(3 * num + 1) 16 | else: 17 | print(num) 18 | print('Finally!') -------------------------------------------------------------------------------- /college.csv: -------------------------------------------------------------------------------- 1 | branch,cgpa,name,year 2 | COE,9.0,Nikhil,2 3 | COE,9.1,Sanchit,2 4 | IT,9.3,Aditya,2 5 | SE,9.5,Sagar,1 6 | MCE,7.8,Prateek,3 7 | EP,9.1,Sahil,2 8 | -------------------------------------------------------------------------------- /compound-interest.py: -------------------------------------------------------------------------------- 1 | def compound_interest(principle, rate, time): 2 | 3 | Amount = principle * (pow((1 + rate / 100), time)) 4 | CI = Amount - principle 5 | print("Compound interest is", CI) 6 | 7 | compound_interest(10000, 10.25, 5) 8 | -------------------------------------------------------------------------------- /csvgen.py: -------------------------------------------------------------------------------- 1 | #This file generates a CSV file with integer values, 2 | # Use cases: you can use it for eg. input for testing your sroting algorithms and other program inputs when you need to test with large data. 3 | 4 | import random as rd; 5 | 6 | minNum = 0; 7 | maxNum = 1000; #maximum number in array 8 | lengthOfItems= 500; #this will generate 500 random numbers. 9 | 10 | file = open("newFile.csv", "a") # creates a new file named newFile.csv - feel free to edit file name 11 | 12 | for i in range(lengthOfItems): 13 | file.write(str(str(rd.randint(minNum,maxNum)) + ",")) 14 | 15 | file.close() 16 | #note - you will have to split first line at "," and convert to int 17 | -------------------------------------------------------------------------------- /decimal_to_binary.py: -------------------------------------------------------------------------------- 1 | def dec_to_bin(n:int)->int: 2 | return int(str(bin(n))[2:]) 3 | 4 | #bin() is a function that takes in a string and converts it to binary provided the string is purely integer populated 5 | 6 | 7 | 8 | num = int(input('Enter a number (base 10): ')) 9 | print("It's value in binary is",dec_to_bin(num)) -------------------------------------------------------------------------------- /dfs.py: -------------------------------------------------------------------------------- 1 | #DFS 2 | n = int(input("Enter the number of nodes : ")) 3 | graph = {}; 4 | for i in range(n): 5 | temp = list(map(str, input().split())) 6 | if len(temp) > 1: 7 | graph[temp[0]] = temp[1:] 8 | else: 9 | graph[temp[0]] = [] 10 | 11 | visited = set(); 12 | 13 | def dfs(visited, graph, node): 14 | if node not in visited: 15 | print(node, end = ' ') 16 | 17 | visited.add(node) 18 | for neighbour in graph[node]: 19 | dfs(visited, graph, neighbour); 20 | 21 | source = str(input("Enter the source node : ")) 22 | print("Following DFS is : ") 23 | dfs(visited, graph, source) -------------------------------------------------------------------------------- /dice.py: -------------------------------------------------------------------------------- 1 | """Simulate a six-sided dice roll. 2 | 3 | Usage: 4 | 5 | $ python dice.py 6 | How many dice do you want to roll? [1-6] 5 7 | 8 | ~~~~~~~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~~~~~~~ 9 | ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ 10 | │ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ 11 | │ ● │ │ │ │ ● │ │ ● │ │ ● │ 12 | │ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ 13 | └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ 14 | """ 15 | 16 | import random 17 | 18 | DICE_ART = { 19 | 1: ( 20 | "┌─────────┐", 21 | "│ │", 22 | "│ ● │", 23 | "│ │", 24 | "└─────────┘", 25 | ), 26 | 2: ( 27 | "┌─────────┐", 28 | "│ ● │", 29 | "│ │", 30 | "│ ● │", 31 | "└─────────┘", 32 | ), 33 | 3: ( 34 | "┌─────────┐", 35 | "│ ● │", 36 | "│ ● │", 37 | "│ ● │", 38 | "└─────────┘", 39 | ), 40 | 4: ( 41 | "┌─────────┐", 42 | "│ ● ● │", 43 | "│ │", 44 | "│ ● ● │", 45 | "└─────────┘", 46 | ), 47 | 5: ( 48 | "┌─────────┐", 49 | "│ ● ● │", 50 | "│ ● │", 51 | "│ ● ● │", 52 | "└─────────┘", 53 | ), 54 | 6: ( 55 | "┌─────────┐", 56 | "│ ● ● │", 57 | "│ ● ● │", 58 | "│ ● ● │", 59 | "└─────────┘", 60 | ), 61 | } 62 | DIE_HEIGHT = len(DICE_ART[1]) 63 | DIE_WIDTH = len(DICE_ART[1][0]) 64 | DIE_FACE_SEPARATOR = " " 65 | 66 | 67 | def parse_input(input_string): 68 | """Return `input_string` as an integer between 1 and 6. 69 | 70 | Check if `input_string` is an integer number between 1 and 6. 71 | If so, return an integer with the same value. Otherwise, tell 72 | the user to enter a valid number and quit the program. 73 | """ 74 | if input_string.strip() in {"1", "2", "3", "4", "5", "6"}: 75 | return int(input_string) 76 | else: 77 | print("Please enter a number from 1 to 6.") 78 | raise SystemExit(1) 79 | 80 | 81 | def roll_dice(num_dice): 82 | """Return a list of integers with length `num_dice`. 83 | 84 | Each integer in the returned list is a random number between 85 | 1 and 6, inclusive. 86 | """ 87 | roll_results = [] 88 | for _ in range(num_dice): 89 | roll = random.randint(1, 6) 90 | roll_results.append(roll) 91 | return roll_results 92 | 93 | 94 | def generate_dice_faces_diagram(dice_values): 95 | """Return an ASCII diagram of dice faces from `dice_values`. 96 | 97 | The string returned contains an ASCII representation of each die. 98 | For example, if `dice_values = [4, 1, 3, 2]` then the string 99 | returned looks like this: 100 | 101 | ~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~ 102 | ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ 103 | │ ● ● │ │ │ │ ● │ │ ● │ 104 | │ │ │ ● │ │ ● │ │ │ 105 | │ ● ● │ │ │ │ ● │ │ ● │ 106 | └─────────┘ └─────────┘ └─────────┘ └─────────┘ 107 | """ 108 | dice_faces = _get_dice_faces(dice_values) 109 | dice_faces_rows = _generate_dice_faces_rows(dice_faces) 110 | 111 | # Generate header with the word "RESULTS" centered 112 | width = len(dice_faces_rows[0]) 113 | diagram_header = " RESULTS ".center(width, "~") 114 | 115 | dice_faces_diagram = "\n".join([diagram_header] + dice_faces_rows) 116 | return dice_faces_diagram 117 | 118 | 119 | def _get_dice_faces(dice_values): 120 | dice_faces = [] 121 | for value in dice_values: 122 | dice_faces.append(DICE_ART[value]) 123 | return dice_faces 124 | 125 | 126 | def _generate_dice_faces_rows(dice_faces): 127 | dice_faces_rows = [] 128 | for row_idx in range(DIE_HEIGHT): 129 | row_components = [] 130 | for die in dice_faces: 131 | row_components.append(die[row_idx]) 132 | row_string = DIE_FACE_SEPARATOR.join(row_components) 133 | dice_faces_rows.append(row_string) 134 | return dice_faces_rows 135 | 136 | 137 | # ~~~ App's main code block ~~~ 138 | # 1. Get and validate user's input 139 | num_dice_input = input("How many dice do you want to roll? [1-6] ") 140 | num_dice = parse_input(num_dice_input) 141 | # 2. Roll the dice 142 | roll_results = roll_dice(num_dice) 143 | # 3. Generate the ASCII diagram of dice faces 144 | dice_face_diagram = generate_dice_faces_diagram(roll_results) 145 | # 4. Display the diagram 146 | print(f"\n{dice_face_diagram}") 147 | -------------------------------------------------------------------------------- /dice_roller.py: -------------------------------------------------------------------------------- 1 | from random import randint, seed 2 | 3 | # The randint(a,b) function return a pseudorandom number between a and b, including both. 4 | # The seed() function defines a new seed for pseudorandom numbers. 5 | 6 | # This function defines a die roll. If no specific side is defined, it 'rolls' a six-sided die. 7 | 8 | def die(sides=6): 9 | seed() 10 | result = randint(1, sides) 11 | return result 12 | 13 | # This function defines a dice roll. 14 | # If no specific side and number of dies are defined, it 'rolls' a six-sided die. 15 | #Returns a list of ints with the dice rolls. 16 | 17 | def dice(number_of_die=1, sides=6): 18 | rolls = [] 19 | for roll in range(0, number_of_die): 20 | rolls.append(die(sides)) 21 | return rolls -------------------------------------------------------------------------------- /digital_root.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | A digital root of a number can be gitten by adding each of the individual characters until they reach a 1 digit number 4 | 5 | e.g 6 | 7 | the digital root of 45893 is 8 | 9 | 4+5+8+9+3 10 | 11 | that will give us 29 12 | 13 | and adding up digits if 29 14 | 15 | 2+9 16 | 17 | will give us 11 18 | 19 | adding that 20 | 21 | 1+1 22 | 23 | will give us 2 24 | 25 | """ 26 | 27 | def dig_root(n): 28 | 29 | ''' 30 | 31 | I will try to implement this without using type casting in my code 32 | 33 | ''' 34 | 35 | div , res = 10, 0 36 | 37 | while n > 0: 38 | 39 | res+=n%div 40 | 41 | n//=div 42 | 43 | return res if res<10 else dig_root(res) 44 | 45 | #print(dig_root(45893)) 46 | 47 | print(dig_root (int(input()))) 48 | -------------------------------------------------------------------------------- /dirTree.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | from pathlib import Path 4 | 5 | def display(path, level = 0): 6 | try : 7 | path = Path(path) 8 | except: 9 | print("Enter right path") 10 | return 11 | k = os.listdir(path) 12 | for i in k: 13 | if os.path.isfile(os.path.join(path, i)): 14 | print(" "*level, "--F--", i) 15 | elif os.path.isdir(os.path.join(path, i)): 16 | print(" "*level, "+-D--", i) 17 | display(os.path.join(path, i), level = level + 1) 18 | else: 19 | print(i) 20 | return 21 | 22 | 23 | if __name__ == "__main__": 24 | print("Enter a path") 25 | s = input() 26 | if s == "" : 27 | s = os.getcwd() 28 | l = 0 29 | display(s, level = 0) 30 | -------------------------------------------------------------------------------- /disarium.py: -------------------------------------------------------------------------------- 1 | def calculateLength(n): 2 | length = 0; 3 | while(n != 0): 4 | length = length + 1; 5 | n = n//10; 6 | return length; 7 | 8 | num = 175; 9 | rem = sum = 0; 10 | len = calculateLength(num); 11 | n = num; 12 | while(num > 0): 13 | rem = num%10; 14 | sum = sum + int(rem**len); 15 | num = num//10; 16 | len = len - 1; 17 | if(sum == n): 18 | print(str(n) + " is a disarium number"); 19 | else: 20 | print(str(n) + " is not a disarium number"); 21 | -------------------------------------------------------------------------------- /disjoint_set_union.py: -------------------------------------------------------------------------------- 1 | N = 1000 2 | P = [i for i in range(0,N+1)] # parent 3 | S = [1 for i in range(0,N+1)] # size of set 4 | 5 | def find(u): 6 | if u == P[u]: 7 | return u 8 | else: 9 | P[u] = find(P[u]) 10 | return P[u] 11 | 12 | def union(u,v): 13 | u = find(u) 14 | v = find(v) 15 | if u != v: 16 | # merge smaller set into bigger set 17 | if S[u] < S[v]: 18 | P[u] = v 19 | S[v] += S[u] 20 | else: 21 | P[v] = u 22 | S[u] += S[v] 23 | -------------------------------------------------------------------------------- /duplicates.py: -------------------------------------------------------------------------------- 1 | def Remove(duplicate): 2 | final_list = [] 3 | for num in duplicate: 4 | if num not in final_list: 5 | final_list.append(num) 6 | return final_list 7 | duplicate = [2, 4, 10, 20, 5, 2, 20, 4] 8 | print(Remove(duplicate)) 9 | -------------------------------------------------------------------------------- /email_slicer.py: -------------------------------------------------------------------------------- 1 | 2 | email = input("Enter Your Email: ").strip() 3 | username = email[:email.index("@")] 4 | domain_name = email[email.index("@")+1:] 5 | format_ = (f"Your user name is '{username}' and your domain is '{domain_name}'") 6 | print(format_) -------------------------------------------------------------------------------- /emi-calculator.py: -------------------------------------------------------------------------------- 1 | def emi_calculator(p:float, r:float, t:float): 2 | """EMI Calculator for one months 3 | -------------------------------- 4 | Parameters: 5 | p - principal 6 | r - interest rate per month 7 | t - time period (in years) 8 | """ 9 | r = r / (12 * 100) # one month interest 10 | t = t * 12 # one month period 11 | emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) 12 | return emi 13 | 14 | 15 | principal = float(input("Enter principal amount (in ₹):")) 16 | rate = float(input("Enter Interest Rate per month (%):")) 17 | time = float(input("Enter Time period (in years):")) 18 | emi = emi_calculator(principal, rate, time) 19 | print("Your Monthly EMI is ₹", round(emi,2)) 20 | 21 | -------------------------------------------------------------------------------- /employee.csv: -------------------------------------------------------------------------------- 1 | name,department,birthday month 2 | John Smith,Accounting,November 3 | Erica Meyers,IT,March 4 | David Warne,Accounting,April 5 | May Myers,IT,October 6 | Ryan Gosling,HR,November -------------------------------------------------------------------------------- /factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | 3 | return 1 if (n==1 or n==0) else n * factorial(n - 1); 4 | 5 | 6 | num = int(input("Enter a number: ")); 7 | 8 | print("Factorial of",num,"is",factorial(num)) 9 | -------------------------------------------------------------------------------- /fast_recursive_fibonacci.py: -------------------------------------------------------------------------------- 1 | def fast_rec_fib_helper(n): 2 | """returns the last two elements of the fibonacci sequence.""" 3 | if n <= 1: 4 | return (0,1) 5 | m = n//2 6 | hprv, hcur = fast_rec_fib_helper(m) 7 | prev = (hprv ** 2) + (hcur **2) 8 | curr = hcur * (2 * hprv + hcur) 9 | next = prev + curr 10 | if n % 2 == 0: 11 | return (prev, curr) 12 | else: 13 | return (curr, next) 14 | 15 | def fast_rec_fib(n): 16 | if n==0: 17 | return 0 18 | previous, current = fast_rec_fib_helper(n) 19 | return current 20 | 21 | print(fast_rec_fib(2)) -------------------------------------------------------------------------------- /fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci_of(n): 2 | if n in {0, 1}: 3 | return n 4 | return fibonacci_of(n - 1) + fibonacci_of(n - 2) 5 | for i in range(1,100): 6 | print(fibonacci_of(i)) 7 | -------------------------------------------------------------------------------- /get_coordinates.py: -------------------------------------------------------------------------------- 1 | from geopy.geocoders import Nominatim 2 | 3 | your_address = str(input()) 4 | 5 | geolocator = Nominatim(user_agent="basic_app") 6 | location = geolocator.geocode(your_address) 7 | if location: 8 | print((location.latitude, location.longitude)) 9 | else: 10 | print("Can not find your address!") -------------------------------------------------------------------------------- /gradient_descent.py: -------------------------------------------------------------------------------- 1 | from numpy import asarray 2 | from numpy.random import rand 3 | 4 | # objective function 5 | def objective(x): 6 | return x**2.0 7 | 8 | def derivative(x): 9 | return x * 2.0 10 | 11 | def gradient_descent(objective, derivative, bounds, n_iter, step_size): 12 | solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 13 | for i in range(n_iter): 14 | # calculate gradient 15 | gradient = derivative(solution) 16 | # take a step 17 | solution = solution - step_size * gradient 18 | # evaluate candidate point 19 | solution_eval = objective(solution) 20 | # report progress 21 | print('>%d f(%s) = %.5f' % (i, solution, solution_eval)) 22 | return [solution, solution_eval] 23 | 24 | # Driver Code: 25 | 26 | bounds = asarray([[-1.0, 1.0]]) 27 | n_iter = 30 28 | step_size = 0.1 29 | best, score = gradient_descent(objective, derivative, bounds, n_iter, step_size) 30 | print('Done!') 31 | print('f(%s) = %f' % (best, score)) 32 | -------------------------------------------------------------------------------- /guicalculator.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | root = Tk() 4 | root.title("Simple Calculator") 5 | 6 | data = Entry(root, width=35, borderwidth=5) 7 | data.grid(row=0, column=0, columnspan=3, padx=10, pady=10) 8 | 9 | #data.insert(0, "") 10 | 11 | def button_click(number): 12 | #data.delete(0, END) 13 | current = data.get() 14 | data.delete(0, END) 15 | data.insert(0, str(current) + str(number)) 16 | 17 | def button_clear(): 18 | data.delete(0, END) 19 | 20 | def button_add(): 21 | first_number = data.get() 22 | global f_num 23 | global math 24 | math = "addition" 25 | f_num = int(first_number) 26 | data.delete(0, END) 27 | 28 | def button_equal(): 29 | second_number = data.get() 30 | data.delete(0, END) 31 | 32 | if math == "addition": 33 | data.insert(0, f_num + int(second_number)) 34 | 35 | if math == "subtraction": 36 | data.insert(0, f_num - int(second_number)) 37 | 38 | if math == "multiplication": 39 | data.insert(0, f_num * int(second_number)) 40 | 41 | if math == "division": 42 | data.insert(0, f_num / int(second_number)) 43 | 44 | 45 | 46 | def button_subtract(): 47 | first_number = data.get() 48 | global f_num 49 | global math 50 | math = "subtraction" 51 | f_num = int(first_number) 52 | data.delete(0, END) 53 | 54 | def button_multiply(): 55 | first_number = data.get() 56 | global f_num 57 | global math 58 | math = "multiplication" 59 | f_num = int(first_number) 60 | data.delete(0, END) 61 | 62 | def button_divide(): 63 | first_number = data.get() 64 | global f_num 65 | global math 66 | math = "division" 67 | f_num = int(first_number) 68 | data.delete(0, END) 69 | 70 | 71 | # Define Buttons 72 | 73 | button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1)) 74 | button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2)) 75 | button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3)) 76 | button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4)) 77 | button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5)) 78 | button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6)) 79 | button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7)) 80 | button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8)) 81 | button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9)) 82 | button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0)) 83 | button_add = Button(root, text="+", padx=39, pady=20, command=button_add) 84 | button_equal = Button(root, text="=", padx=91, pady=20, command=button_equal) 85 | button_clear = Button(root, text="Clear", padx=79, pady=20, command=button_clear) 86 | 87 | button_subtract = Button(root, text="-", padx=41, pady=20, command=button_subtract) 88 | button_multiply = Button(root, text="*", padx=40, pady=20, command=button_multiply) 89 | button_divide = Button(root, text="/", padx=41, pady=20, command=button_divide) 90 | 91 | # Put the buttons on the screen 92 | 93 | button_1.grid(row=3, column=0) 94 | button_2.grid(row=3, column=1) 95 | button_3.grid(row=3, column=2) 96 | 97 | button_4.grid(row=2, column=0) 98 | button_5.grid(row=2, column=1) 99 | button_6.grid(row=2, column=2) 100 | 101 | button_7.grid(row=1, column=0) 102 | button_8.grid(row=1, column=1) 103 | button_9.grid(row=1, column=2) 104 | 105 | button_0.grid(row=4, column=0) 106 | button_clear.grid(row=4, column=1, columnspan=2) 107 | button_add.grid(row=5, column=0) 108 | button_equal.grid(row=5, column=1, columnspan=2) 109 | 110 | button_subtract.grid(row=6, column=0) 111 | button_multiply.grid(row=6, column=1) 112 | button_divide.grid(row=6, column=2) 113 | 114 | 115 | root.mainloop() -------------------------------------------------------------------------------- /hangman.py: -------------------------------------------------------------------------------- 1 | import random 2 | guess_list = [ 3 | 'samuel', 4 | 'activity', 5 | 'banana', 6 | 'school', 7 | 'python', 8 | 'programming', 9 | 'hangman', 10 | ] 11 | 12 | print('WELCOME TO MY HANGMAN GAME\n') 13 | cc = random.choice(guess_list).upper() 14 | guesses = len(cc)+4 15 | repw = ['_' for i in range(len(cc))] 16 | while guesses > 0: 17 | print(f'WORD: {" ".join(repw)}') 18 | ug = input('Guess a letter:').upper() 19 | for char in range(len(cc)): 20 | if ug==cc[char]: 21 | repw[char]=ug 22 | if repw.count('_')==0: 23 | print(f'WORD: {" ".join(repw)}') 24 | break 25 | print('Tries remain:',guesses-1,'\n') 26 | guesses-=1 27 | 28 | 29 | print('\nYou WIN🎉\n') if repw.count('_')==0 else print('\nYou LOSE💔') -------------------------------------------------------------------------------- /hcf_lcm.py: -------------------------------------------------------------------------------- 1 | #Finding HCF in python 2 | 3 | a = int(input("Enter the first number: ")) 4 | b = int(input("Enter the second number: ")) 5 | 6 | HCF = 1 7 | 8 | for i in range(2,a+1): 9 | if(a%i==0 and b%i==0): 10 | HCF = i 11 | 12 | print("First Number is: ",a) 13 | print("Second Number is: ",b) 14 | print("HCF of the numbers is: ",HCF) 15 | 16 | 17 | #Finding LCM in python 18 | a = int(input("Enter the first number: ")) 19 | b = int(input("Enter the second number: ")) 20 | 21 | HCF = 1 22 | 23 | for i in range(2,a+1): 24 | if(a%i==0 and b%i==0): 25 | HCF = i 26 | 27 | print("First Number is: ",a) 28 | print("Second Number is: ",b) 29 | 30 | LCM = int((a*b)/(HCF)) 31 | print("LCM of the two numbers is: ",LCM) 32 | 33 | -------------------------------------------------------------------------------- /huffmantree.py: -------------------------------------------------------------------------------- 1 | Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | from heapq import heapify as hpf 4 | from heapq import heappop as hpp 5 | from heapq import heappush as hppu 6 | class Node: 7 | def __init(self,ch,freq,left=None,right=None): 8 | self.ch,self.freq=ch,freq 9 | self.left,self.right=left,right 10 | def __lt__(self,other): 11 | return self.freq1: 20 | left,right=hpp(pq),hpp(pq); 21 | newFreq=left.freq+right.freq 22 | hppu(pq,Node(None,newFreq,left,right)) 23 | root=pq[0] 24 | return root 25 | 26 | -------------------------------------------------------------------------------- /image_compress.py: -------------------------------------------------------------------------------- 1 | # For inforation on Pillow visit https://pypi.org/project/Pillow/ 2 | import os, sys 3 | from PIL import Image 4 | 5 | def compressMe(file, verbose = False): 6 | filepath = os.path.join(os.getcwd(), file) 7 | picture = Image.open(filepath) 8 | picture.save("Compressed_"+file, "JPEG", optimize = True, quality = 10) 9 | return 10 | 11 | def main(): 12 | verbose = False 13 | if (len(sys.argv)>1): 14 | if (sys.argv[1].lower()=="-v"): 15 | verbose = True 16 | cwd = os.getcwd() 17 | formats = ('.jpg', '.jpeg') 18 | 19 | for file in os.listdir(cwd): 20 | if os.path.splitext(file)[1].lower() in formats: 21 | print('compressing', file) 22 | compressMe(file, verbose) 23 | print("Done") 24 | 25 | # Driver code 26 | if __name__ == "__main__": 27 | main() -------------------------------------------------------------------------------- /img_to_pencil.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | print("Enter file_name with extension in this folder(image):") 3 | name = input() 4 | print("Enter output file name without extension") 5 | out = input() 6 | out = out+".png" 7 | image = cv2.imread(name) 8 | 9 | grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 10 | invert = cv2.bitwise_not(grey_img) 11 | 12 | blur = cv2.GaussianBlur(invert, (21, 21), 0) 13 | invertedblur = cv2.bitwise_not(blur) 14 | sketch = cv2.divide(grey_img, invertedblur, scale=256.0) 15 | cv2.imwrite(out, sketch) 16 | -------------------------------------------------------------------------------- /insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(InputList): 2 | for i in range(1, len(InputList)): 3 | j = i-1 4 | nxt_element = InputList[i] 5 | # Compare the current element with next one 6 | while (InputList[j] > nxt_element) and (j >= 0): 7 | InputList[j+1] = InputList[j] 8 | j=j-1 9 | InputList[j+1] = nxt_element 10 | list = [19,2,31,45,30,11,121,27] 11 | insertion_sort(list) 12 | print(list) -------------------------------------------------------------------------------- /kadanes_algorithm.py: -------------------------------------------------------------------------------- 1 | """ 2 | This algorithm is used to find the largest sum in the given array in O(n) Time complexity 3 | """ 4 | 5 | arr=[-1,0,3,4,2,6,-10,5,-9] 6 | 7 | max_sum=0 8 | curr_sum=0 9 | 10 | for i in arr: 11 | curr_sum += i 12 | max_sum=max(max_sum,curr_sum) 13 | 14 | if curr_sum<0: 15 | curr_sum=0 16 | 17 | 18 | print(max_sum) -------------------------------------------------------------------------------- /madlibs.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | loop = 1 4 | 5 | while (loop < 10): 6 | 7 | # All the questions that the program asks the user 8 | 9 | noun = input("Choose a noun: ") 10 | 11 | p_noun = input("Choose a plural noun: ") 12 | 13 | noun2 = input("Choose a noun: ") 14 | 15 | place = input("Name a place: ") 16 | 17 | adjective = input("Choose an adjective (Describing word): ") 18 | 19 | noun3 = input("Choose a noun: ") 20 | 21 | #Displays the story based on the users input 22 | 23 | print ("------------------------------------------") 24 | 25 | print ("Be kind to your",noun,"- footed", p_noun) 26 | 27 | print ("For a duck may be somebody's", noun2,",") 28 | 29 | print ("Be kind to your",p_noun,"in",place) 30 | 31 | print ("Where the weather is always",adjective,".") 32 | 33 | print () 34 | 35 | print ("You may think that is this the",noun3,",") 36 | 37 | print ("Well it is.") 38 | 39 | print ("------------------------------------------") 40 | 41 | # Loop back to "loop = 1" 42 | 43 | loop = loop + 1 -------------------------------------------------------------------------------- /mask_email_address.py: -------------------------------------------------------------------------------- 1 | """ Mask an email address 2 | Search for email addresses in a string, extract the email addresses, mask them and re-insert them in the string. 3 | 4 | Author: Musketeer Computing 5 | Created: 10th October 2022 6 | """ 7 | import re 8 | 9 | 10 | def main(): 11 | sentence = input("Enter a sentence") 12 | emails = re.findall(r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', sentence) 13 | if not emails: 14 | print(' No email address to mask') 15 | exit() 16 | d_emails = {} 17 | for email in emails: 18 | m_email = mask_email(email) 19 | if m_email == 'error': 20 | print('There was an error when masking the email. Stopping the program') 21 | exit() 22 | d_emails[email] = m_email 23 | for k_email, v_email in d_emails.items(): 24 | sentence = re.sub(k_email, v_email, sentence) 25 | print(sentence) 26 | 27 | 28 | def mask_email(email): 29 | lo = email.find('@') 30 | domain_extension = email.rfind('.') 31 | word_count = len(email) 32 | if lo > 0: 33 | return "{0}#####{1}@{2}###{3}".format(email[0], 34 | email[lo-1], 35 | email[lo+1], 36 | email[domain_extension:word_count]) 37 | else: 38 | return "error" 39 | 40 | 41 | if __name__ == "__main__": 42 | main() 43 | -------------------------------------------------------------------------------- /max.py: -------------------------------------------------------------------------------- 1 | def maximum(a, b): 2 | 3 | if a >= b: 4 | return a 5 | else: 6 | return b 7 | 8 | n1 = int(input("Enter First Number: ") 9 | n2 = int(input("Enter Second Number: ") 10 | 11 | print(maximum(n1,n2)) 12 | -------------------------------------------------------------------------------- /meal-of-the-day.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = convert(input("Enter time of the day [in hh:mm 24 hour format] : ")) 3 | 4 | if 7 <= x <= 8: 5 | print("breakfast time") 6 | elif 12 <= x <= 13: 7 | print("lunch time") 8 | elif 18 <= x <= 19: 9 | print("dinner time") 10 | 11 | 12 | def convert(time): 13 | hours, minutes = time.split(":") 14 | hours = int(hours) 15 | minutes = float(minutes)/60 16 | return hours + minutes 17 | 18 | 19 | if __name__ == "__main__": 20 | main() -------------------------------------------------------------------------------- /medianOf2SortedArray.py: -------------------------------------------------------------------------------- 1 | # Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 2 | # example 1 3 | # Input: nums1 = [1,3], nums2 = [2] 4 | # Output: 2.00000 5 | # Explanation: merged array = [1,2,3] and median is 2. 6 | 7 | #Input: nums1 = [1,2], nums2 = [3,4] 8 | # Output: 2.50000 9 | # Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. 10 | 11 | #nums1 and nums2 are 2 sorted arrays 12 | def findMedianSortedArrays(A, B): 13 | 14 | med1 = med2 = i = j = 0 15 | n = len(A) + len(B) 16 | 17 | while (i + j) <= n / 2: 18 | if i < len(A) and j < len(B): 19 | med2 = med1 20 | if A[i] < B[j]: 21 | med1 = A[i] 22 | i += 1 23 | else: 24 | med1 = B[j] 25 | j += 1 26 | elif i < len(A): 27 | med2 = med1 28 | med1 = A[i] 29 | i += 1 30 | elif j < len(B): 31 | med2 = med1 32 | med1 = B[j] 33 | j += 1 34 | 35 | if n % 2 == 0: 36 | return (med1 + med2) / 2.0 37 | else: 38 | return med1 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /menu-based_student_record.py: -------------------------------------------------------------------------------- 1 | singlerecord=[] 2 | studList=[] 3 | choice='y' 4 | while choice.lower()!='n': 5 | studName=input('enter your name ') 6 | Rollno=input('enter your Rollno ') 7 | cgpa=int(input('cgpa :')) 8 | singlerecord.append(studName) 9 | singlerecord.append(Rollno) 10 | singlerecord.append(cgpa) 11 | studList.append(singlerecord) 12 | singlerecord=[] 13 | choice=input('enter your choice [y/n]') 14 | 15 | #append 16 | def appendStudent(): 17 | global studList 18 | singlr = [] 19 | studName=input('enter your name') 20 | Rollno=input('enter your Rollno') 21 | cgpa=int(input('cgpa :')) 22 | singlr.append(studName) 23 | singlr.append(Rollno) 24 | singlr.append(cgpa) 25 | studList.append(singlr) 26 | 27 | 28 | # remove existing record by rollno 29 | def removeRecord(): 30 | global studList 31 | rolln=int(input("enter student's rollno:")) 32 | for record in studList: 33 | if rolln in record: 34 | studList.remove(record) 35 | 36 | # view student by name: 37 | def viewRecord(): 38 | name=input("enter student's name:") 39 | for record in studList: 40 | if name in record: 41 | print(record) 42 | 43 | # copy 44 | def copyList(): 45 | print("what to do??") 46 | 47 | #remove all 48 | def removeAll(): 49 | studList.clear() 50 | 51 | flag = 'y' 52 | while (flag == 'y'): 53 | find = int(input("Enter \n option 1 : Append student \n option 2: remove student by Rollno\n option 3: view student by name\n option 4: copy list\n option 5: remove all students option \n 6: exit")) 54 | if (find == 1): 55 | appendStudent() 56 | elif (find == 2): 57 | removeRecord() 58 | elif (find == 3): 59 | viewRecord() 60 | elif (find == 4): 61 | copyList() 62 | elif (find == 5): 63 | removeAll() 64 | elif (find == 6): 65 | exit 66 | else: 67 | print("enter correct option !!") 68 | flag = input("do u want to continue ? say y or n : \n") 69 | -------------------------------------------------------------------------------- /merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(unsorted_list): 2 | if len(unsorted_list) <= 1: 3 | return unsorted_list 4 | # Find the middle point and devide it 5 | middle = len(unsorted_list) // 2 6 | left_list = unsorted_list[:middle] 7 | right_list = unsorted_list[middle:] 8 | 9 | left_list = merge_sort(left_list) 10 | right_list = merge_sort(right_list) 11 | return list(merge(left_list, right_list)) 12 | 13 | # Merge the sorted halves 14 | def merge(left_half,right_half): 15 | res = [] 16 | while len(left_half) != 0 and len(right_half) != 0: 17 | if left_half[0] < right_half[0]: 18 | res.append(left_half[0]) 19 | left_half.remove(left_half[0]) 20 | else: 21 | res.append(right_half[0]) 22 | right_half.remove(right_half[0]) 23 | if len(left_half) == 0: 24 | res = res + right_half 25 | else: 26 | res = res + left_half 27 | return res 28 | unsorted_list = [64, 34, 25, 12, 22, 11, 90] 29 | print(merge_sort(unsorted_list)) 30 | -------------------------------------------------------------------------------- /notification.py: -------------------------------------------------------------------------------- 1 | import time 2 | from plyer import notification 3 | print("Enter the Remainder Message:") 4 | msg = input() 5 | print("Enter the mode of time seconds or minutes or hours") 6 | mode = input() 7 | print("Enter the time left for remainder or time after which remainder should show:") 8 | t = int(input()) 9 | if mode == "seconds": 10 | 11 | time.sleep(t) 12 | notification.notify( 13 | title = "REMAINDER!!!", 14 | message = msg, 15 | timeout = 10 16 | ) 17 | 18 | elif mode == "minutes": 19 | 20 | time.sleep(t*60) 21 | notification.notify( 22 | title = "REMAINDER!!!", 23 | message = msg, 24 | timeout = 10 25 | ) 26 | 27 | elif mode == "hours": 28 | 29 | time.sleep(t*3600) 30 | notification.notify( 31 | title = "REMAINDER!!!", 32 | message = msg, 33 | timeout = 10 34 | ) 35 | -------------------------------------------------------------------------------- /novowels.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | sts = str(input("Input: ")) 3 | without_vowels = shorten(sts) 4 | print("Output: " + without_vowels) 5 | 6 | def shorten(word): 7 | lttr = "" 8 | for letter in word: 9 | if not letter.lower() in ['a', 'e', 'i', 'o', 'u']: 10 | lttr += letter 11 | return lttr 12 | 13 | if __name__ == "__main__": 14 | main() -------------------------------------------------------------------------------- /number_base_converter.py: -------------------------------------------------------------------------------- 1 | #################################################################################################### 2 | 3 | # Question 4 | # Write a Python script that reads any integer and asks the user to choose which option to convert: 5 | # 1 for Binary 6 | # 2 for Octal 7 | # 3 for Hexadecimal 8 | 9 | #################################################################################################### 10 | num = 0 11 | num = int(input("\nDigit an integer positive or -1 to finish: ")) 12 | 13 | while num != -1: 14 | print(""" 15 | Choose one of the bases to convert: 16 | 17 | [ 1 ] convert to BINARY 18 | [ 2 ] convert to OCTAL 19 | [ 3 ] convert to HEXADECIMAL 20 | """) 21 | 22 | option = int(input("Your choose: ")) 23 | 24 | if option == 1: 25 | print(f"\n{num} converted to BINARY is {bin(num)[2:]}") 26 | elif option == 2: 27 | print(f"\n{num} converted to OCTAL is {oct(num)[2:]}") 28 | elif option == 3: 29 | print(f"\n{num} converted to HEXADECIMAL is {hex(num)[2:].upper()}") 30 | else: 31 | print("\n #### Invalid option. Try again. ####") 32 | 33 | num = int(input("\nDigit an integer positive or -1 to finish: ")) 34 | 35 | print("Bye!!!") 36 | #################################################################################################### 37 | -------------------------------------------------------------------------------- /paranthesis_checker.py: -------------------------------------------------------------------------------- 1 | """ 2 | Paranthesis checker checks to see if in a given array all paranthesis 3 | are closed, if so the function returns true otherwise false. 4 | i.e. {}, [], (), and ([]) would return true, }, or ([)] would return 5 | false. A stack is implemented to check only when a }, ], or ) are 6 | present in array. 7 | Note that if nothing is entered the function returns true. 8 | """ 9 | 10 | def parenthesis_check(parenthesis_array): 11 | 12 | stack = [] 13 | for parenthesis in parenthesis_array: 14 | if parenthesis == '}': 15 | if len(stack) == 0: 16 | return False 17 | prev_parenthesis = stack.pop() 18 | if prev_parenthesis != '{': 19 | return False 20 | elif parenthesis == ']': 21 | if len(stack) == 0: 22 | return False 23 | prev_parenthesis = stack.pop() 24 | if prev_parenthesis != '[': 25 | return False 26 | elif parenthesis == ')': 27 | if len(stack) == 0: 28 | return False 29 | prev_parenthesis = stack.pop() 30 | if prev_parenthesis != '(': 31 | return False 32 | else: stack.append(parenthesis) 33 | 34 | if len(stack) > 0: 35 | return False 36 | else: 37 | return True 38 | 39 | str = input("Input: ") 40 | arr = list(str) 41 | print(parenthesis_check(arr)) -------------------------------------------------------------------------------- /parse_csv.py: -------------------------------------------------------------------------------- 1 | import csv 2 | #read from csv 3 | fields=list() 4 | rows=list() 5 | with open('employee.csv','r') as csv_file: 6 | csv_reader=csv.reader(csv_file) 7 | fields=next(csv_reader) #csv reader object 8 | for row in csv_reader: 9 | rows.append(row) 10 | print("Total no. of rows={}".format(csv_reader.line_num)) 11 | print("Field Names are:"+",".join(field for field in fields)) 12 | print("First 5 rows are:\n") 13 | for row in rows[:5]: 14 | for col in row: 15 | print("{}".format(col),end=" "), 16 | print("\n") 17 | #write to csv 18 | flds=['Name','Branch','Year','CGPA'] 19 | rw= [['Nikhil', 'COE', '2', '9.0'], 20 | ['Sanchit', 'COE', '2', '9.1'], 21 | ['Aditya', 'IT', '2', '9.3'], 22 | ['Sagar', 'SE', '1', '9.5'], 23 | ['Prateek', 'MCE', '3', '7.8'], 24 | ['Sahil', 'EP', '2', '9.1']] 25 | with open("university.csv",'w') as csvfile: 26 | csvwriter=csv.writer(csvfile) 27 | csvwriter.writerow(flds) 28 | csvwriter.writerows(rw) 29 | #write dictionary to csv 30 | 31 | mydict =[{'branch': 'COE', 'cgpa': '9.0', 32 | 'name': 'Nikhil', 'year': '2'}, 33 | {'branch': 'COE', 'cgpa': '9.1', 34 | 'name': 'Sanchit', 'year': '2'}, 35 | {'branch': 'IT', 'cgpa': '9.3', 36 | 'name': 'Aditya', 'year': '2'}, 37 | {'branch': 'SE', 'cgpa': '9.5', 38 | 'name': 'Sagar', 'year': '1'}, 39 | {'branch': 'MCE', 'cgpa': '7.8', 40 | 'name': 'Prateek', 'year': '3'}, 41 | {'branch': 'EP', 'cgpa': '9.1', 42 | 'name': 'Sahil', 'year': '2'}] 43 | 44 | with open("college.csv",'w',newline='') as cv: 45 | fieldnames=["branch","cgpa","name","year"] 46 | writer=csv.DictWriter(cv,fieldnames=fieldnames) 47 | writer.writeheader() 48 | writer.writerows(mydict) 49 | with open("college.csv",'r') as cvf: 50 | reader=csv.DictReader(cvf) 51 | for row in reader: 52 | print(row['name'],row['branch']) -------------------------------------------------------------------------------- /perfect_num.py: -------------------------------------------------------------------------------- 1 | #Perfect Number or Not Check 2 | 3 | n = int(input("Enter the number : ")) 4 | sum=0 5 | for i in range(1,n): 6 | if n%i==0: 7 | sum+=i 8 | if sum==n: 9 | print("Perfect !") 10 | else: 11 | print("Nah !") 12 | -------------------------------------------------------------------------------- /power_of_a_number.py: -------------------------------------------------------------------------------- 1 | def power_of_a_linear(x, n): 2 | if n == 0: 3 | return 1 4 | return x * power_of_a_linear(x, n-1) 5 | 6 | x = int(input("Enter the number:")) 7 | n = int(input("Enter the power:")) 8 | print(power_of_a_linear(x, n)) 9 | -------------------------------------------------------------------------------- /prime factors of a given number.py: -------------------------------------------------------------------------------- 1 | # Python program to print prime factors 2 | 3 | import math 4 | 5 | 6 | def primeFactors(n): 7 | 8 | # Print the number of two\'s that divide n 9 | while n % 2 == 0: 10 | print (2), 11 | n = n / 2 12 | 13 | # n must be odd at this point 14 | # so a skip of 2 ( i = i + 2) can be used 15 | for i in range(3,int(math.sqrt(n))+1,2): 16 | 17 | # while i divides n , print i ad divide n 18 | while n % i== 0: 19 | print (i), 20 | n = n / i 21 | 22 | 23 | if n > 2: 24 | print (n) 25 | 26 | 27 | n = 315 28 | primeFactors(n) 29 | 30 | -------------------------------------------------------------------------------- /prime.py: -------------------------------------------------------------------------------- 1 | def prime(x, y): 2 | prime_list = [] 3 | for i in range(x, y): 4 | if i == 0 or i == 1: 5 | continue 6 | else: 7 | for j in range(2, int(i/2)+1): 8 | if i % j == 0: 9 | break 10 | else: 11 | prime_list.append(i) 12 | return prime_list 13 | 14 | starting_range = 2 15 | ending_range = 7 16 | lst = prime(starting_range, ending_range) 17 | if len(lst) == 0: 18 | print("There are no prime numbers in this range") 19 | else: 20 | print("The prime numbers in this range are: ", lst) 21 | -------------------------------------------------------------------------------- /print_decreasing_number.py: -------------------------------------------------------------------------------- 1 | def printDecreasing(n): 2 | if n == 0: 3 | return 4 | print(n) 5 | printDecreasing(n-1) 6 | 7 | n = int(input("Enter the number:")) 8 | printDecreasing(n) 9 | -------------------------------------------------------------------------------- /print_incerasing_number.py: -------------------------------------------------------------------------------- 1 | def printIncreasing(n): 2 | if n == 0: 3 | return 4 | printIncreasing(n-1) 5 | print(n) 6 | 7 | n = int(input("Enter the number:")) 8 | printIncreasing(n) -------------------------------------------------------------------------------- /print_star_using_loops.py: -------------------------------------------------------------------------------- 1 | print("How Many Row You Want To Print") 2 | one= int(input()) 3 | print("Type 1 Or 0") 4 | two = int(input()) 5 | new =bool(two) 6 | if new == True: 7 | for i in range(1,one+1): 8 | for j in range(1,i+1): 9 | print("*",end=" ") 10 | print() 11 | elif new ==False: 12 | for i in range(one,0,-1): 13 | for j in range(1,i+1): 14 | print("*", end="") 15 | print() 16 | -------------------------------------------------------------------------------- /python graphics.py: -------------------------------------------------------------------------------- 1 | import random 2 | import turtle 3 | colors = ['violet','indigo','blue','green','yellow','orange','red'] # Added VIBGYOR 4 | t = turtle.Turtle() 5 | t.speed(10) 6 | turtle.bgcolor("black") 7 | length=100 8 | angle =50 9 | size=5 10 | for i in range(length): 11 | color=random.choice(colors) 12 | t.pencolor(color) 13 | t.fillcolor(color) 14 | t.penup() 15 | t.forward(i+50) 16 | t.pendown() 17 | t.left(angle) 18 | t.begin_fill() 19 | t.circle(size) 20 | t.end_fill() 21 | turtle.exitonclick() 22 | turtle.bgcolor("black") 23 | -------------------------------------------------------------------------------- /qr.py: -------------------------------------------------------------------------------- 1 | import pyqrcode 2 | from pyqrcode import QRCode 3 | 4 | # String which represent the QR code 5 | s = "https://fueler.io/arjun_ms" 6 | 7 | # Generate QR code 8 | url = pyqrcode.create(s) 9 | 10 | # Create and save the png file naming "myqr.png" 11 | url.svg("myyoutube.svg", scale = 8) -------------------------------------------------------------------------------- /radixSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Radix Sort 2 | 3 | # A function to do counting sort of arr[] according to 4 | # the digit represented by exp. 5 | def countingSort(arr, exp1): 6 | 7 | n = len(arr) 8 | 9 | # The output array elements that will have sorted arr 10 | output = [0] * (n) 11 | 12 | # initialize count array as 0 13 | count = [0] * (10) 14 | 15 | # Store count of occurrences in count[] 16 | for i in range(0, n): 17 | index = (arr[i]/exp1) 18 | count[int((index)%10)] += 1 19 | 20 | # Change count[i] so that count[i] now contains actual 21 | # position of this digit in output array 22 | for i in range(1,10): 23 | count[i] += count[i-1] 24 | 25 | # Build the output array 26 | i = n-1 27 | while i>=0: 28 | index = (arr[i]/exp1) 29 | output[ count[ int((index)%10) ] - 1] = arr[i] 30 | count[int((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 > 0: 50 | countingSort(arr,exp) 51 | exp *= 10 52 | 53 | # Driver code to test above 54 | arr = [ 170, 45, 75, 90, 802, 24, 2, 66] 55 | radixSort(arr) 56 | 57 | for i in range(len(arr)): 58 | print(arr[i],end=" ") 59 | 60 | 61 | -------------------------------------------------------------------------------- /rainbowSpiral.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | from turtle import * 3 | 4 | turtle.title("rainbow spiral") 5 | speed(15) 6 | bgcolor("black") 7 | r,g,b=255,0,0 8 | 9 | for i in range(255*2): 10 | colormode(255) 11 | if i<255//3: 12 | g+=3 13 | elif i<255*2//3: 14 | r-=3 15 | elif i<255: 16 | b+=3 17 | elif i<255*4//3: 18 | g-=3 19 | elif i<255*5//3: 20 | r+=3 21 | else: 22 | b-=3 23 | fd(50+i) 24 | rt(91) 25 | pencolor(r,g,b) 26 | 27 | done() 28 | -------------------------------------------------------------------------------- /random_password_generator.py: -------------------------------------------------------------------------------- 1 | import secrets 2 | import string 3 | 4 | letters = string.ascii_letters 5 | digits = string.digits 6 | special_chars = string.punctuation 7 | 8 | alphabet = letters + digits + special_chars 9 | 10 | # fix password length 11 | pwd_length = 12 12 | 13 | # generate password meeting constraints 14 | while True: 15 | pwd = '' 16 | for i in range(pwd_length): 17 | pwd += ''.join(secrets.choice(alphabet)) 18 | 19 | if (any(char in special_chars for char in pwd) and 20 | sum(char in digits for char in pwd) >= 2): 21 | break 22 | print(pwd) 23 | -------------------------------------------------------------------------------- /reddit_scraper.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import csv 3 | import time 4 | from bs4 import BeautifulSoup 5 | 6 | 7 | class HaikuScraper: 8 | """ 9 | This scraper is designed with the purpose of scraping Haikus (Japanese poems) from Reddit. 10 | """ 11 | def __init__(self, url: str, headers: dict): 12 | self.url = url 13 | self.headers = headers 14 | 15 | def make_request(self): 16 | time.sleep(3) 17 | page = requests.get(self.url, headers=self.headers) 18 | soup = BeautifulSoup(page.text, 'html.parser') 19 | return soup 20 | 21 | def get_next_page(self, soup: BeautifulSoup): 22 | time.sleep(3) 23 | next_button = soup.find('span', class_='next-button') 24 | next_page_link = next_button.find("a").attrs['href'] 25 | return next_page_link 26 | 27 | def get_haikus(self, soup: BeautifulSoup): 28 | haikus = [str(title.text) for title in soup.find_all("a", class_="title may-blank ")] 29 | return haikus 30 | 31 | def write_haikus_to_csv(self, haikus: list): 32 | with open('scraped_haikus_v2.txt', 'a') as f: 33 | writer = csv.writer(f) 34 | for haiku in haikus: 35 | writer.writerow([haiku]) 36 | f.close() 37 | 38 | 39 | 40 | url = "https://old.reddit.com/r/haiku/" 41 | # Headers to mimic a browser visit 42 | headers = {'User-Agent': 'Mozilla/5.0'} 43 | 44 | scraper = HaikuScraper(url, headers) 45 | soup = scraper.make_request() 46 | 47 | haikus = scraper.get_haikus(soup) 48 | scraper.write_haikus_to_csv(haikus) 49 | 50 | counter = 1 51 | 52 | while (counter <= 2500): 53 | time.sleep(2) 54 | link = scraper.get_next_page(soup) 55 | print(f"Page {counter + 1}. Link {link}.") 56 | scraper = HaikuScraper(link, headers) 57 | soup = scraper.make_request() 58 | haikus = scraper.get_haikus(soup) 59 | scraper.write_haikus_to_csv(haikus) 60 | counter += 1 -------------------------------------------------------------------------------- /remove-vowels.py: -------------------------------------------------------------------------------- 1 | vowels = ['a', 'e', 'i', 'o', 'u'] 2 | 3 | text = input("Enter some text: ") 4 | 5 | for char in text: 6 | if(char.lower() in vowels): 7 | continue 8 | else: 9 | print(char, end = '') -------------------------------------------------------------------------------- /reverse32bitsignedint.py: -------------------------------------------------------------------------------- 1 | # reverse a 32 bit signed int 2 | # if ans overflows then returns 0 3 | def reverse32bitsignedint(n): 4 | is_negative = 0 5 | if n < 0: 6 | is_negative = 1 7 | n = -n 8 | ans = 0 9 | while n: 10 | quotient = n // 10 11 | remainder = n % 10 12 | n = quotient 13 | ans = ans * 10 + remainder 14 | limit = 1 << 31 15 | if is_negative: 16 | ans = -ans 17 | if (ans <= -limit) or (ans >= limit - 1): 18 | return 0 19 | return ans 20 | -------------------------------------------------------------------------------- /reverse_number.py: -------------------------------------------------------------------------------- 1 | """This file has the function which reverses real integer.""" 2 | 3 | 4 | def reverse_number(number: int) -> int: 5 | """ 6 | This function reverses a number where number can be real integer 7 | """ 8 | if number == 0: 9 | return 0 10 | 11 | sign = 1 if number > 0 else -1 12 | number = abs(number) 13 | reverse = 0 14 | while number > 0: 15 | current_digit = number % 10 16 | reverse = reverse * 10 + current_digit 17 | number //= 10 18 | return reverse if sign == 1 else reverse * -1 19 | 20 | N = 567 21 | print(reverse_number(N)) 22 | 23 | 24 | N = 0 25 | print(reverse_number(N)) 26 | 27 | 28 | N = -35670 29 | print(reverse_number(N)) 30 | -------------------------------------------------------------------------------- /reverse_words_of_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is Leetcode question: https://leetcode.com/problems/reverse-words-in-a-string/ 3 | 4 | """ 5 | 6 | def reverseWords(s: str) -> str: 7 | s = s.split() 8 | s.reverse() 9 | return " ".join(s) 10 | 11 | 12 | assert reverseWords(" Hello World ")=="World Hello" 13 | assert reverseWords("a good example")=="example good a" 14 | assert reverseWords("okay")=="okay" 15 | -------------------------------------------------------------------------------- /rock-paper-scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | while True: 3 | choices = ["rock","paper","scissors"] 4 | computer = random.choice(choices) 5 | player = input("rock, paper, scissors?:") .lower() 6 | 7 | while player not in choices: 8 | player = input("rock, paper, scissors?:") .lower() 9 | print("invalid choice try again!") 10 | if player == computer: 11 | print("computer: ",computer) 12 | print("player: ",player) 13 | print("Tie!") 14 | 15 | elif player == "rock": 16 | if computer == "paper": 17 | print("computer: ", computer) 18 | print("player: ", player) 19 | print("You lose!") 20 | if computer == "scissors": 21 | print("computer: ", computer) 22 | print("player: ", player) 23 | print("You win!") 24 | 25 | elif player == "scissors": 26 | if computer == "rock": 27 | print("computer: ", computer) 28 | print("player: ", player) 29 | print("You lose!") 30 | if computer == "paper": 31 | print("computer: ", computer) 32 | print("player: ", player) 33 | print("You won!") 34 | 35 | elif player == "paper": 36 | if computer == "scissors": 37 | print("computer: ", computer) 38 | print("player: ", player) 39 | print("You lose!") 40 | if computer == "rock": 41 | print("computer: ", computer) 42 | print("player: ", player) 43 | print("You won!") 44 | 45 | play_again = input("Play again? (yes/no): ").lower() 46 | 47 | if play_again != "yes": 48 | break 49 | 50 | print("Bye!") 51 | -------------------------------------------------------------------------------- /rupiah_budgeting_plan.py: -------------------------------------------------------------------------------- 1 | from turtle import delay 2 | from modul import * 3 | import time 4 | 5 | # assume value is a decimal 6 | def transform_to_rupiah_format(value): 7 | str_value = str(value) 8 | separate_decimal = str_value.split(".") 9 | after_decimal = separate_decimal[0] 10 | before_decimal = separate_decimal[1] 11 | 12 | reverse = after_decimal[::-1] 13 | temp_reverse_value = "" 14 | 15 | for index, val in enumerate(reverse): 16 | if (index + 1) % 3 == 0 and index + 1 != len(reverse): 17 | temp_reverse_value = temp_reverse_value + val + "." 18 | else: 19 | temp_reverse_value = temp_reverse_value + val 20 | 21 | temp_result = temp_reverse_value[::-1] 22 | 23 | return "Rp " + temp_result + ",0" + before_decimal 24 | 25 | 26 | def formatrupiah(uang): 27 | y = str(uang) 28 | if len(y) <= 3: 29 | return 'Rp ' + y 30 | else: 31 | p = y[-3:] 32 | q = y[:-3] 33 | return formatrupiah(q) + '.' + p 34 | 35 | 36 | # default budgeting percentage (single) 37 | living = 0.30 38 | playing = 0.20 39 | saving = 0.50 40 | 41 | # # default budgeting percentage (married) 42 | # living = 0.30 43 | # playing = 0.15 44 | # saving = 0.55 45 | 46 | budget = int(input('Masukkan pemasukan anda: ')) 47 | 48 | 49 | # tiap tiap kategorinya 50 | percent_living = living * 100 51 | percent_playing = playing * 100 52 | percent_saving = saving * 100 53 | percentage = [percent_playing, percent_living, percent_saving] 54 | sum = 00.0 55 | percent_budget = (living + playing + saving)*100 56 | 57 | budget_living = budget * living 58 | budget_playing = budget * playing 59 | budgett_saving = budget * saving 60 | 61 | print('========================================================') 62 | for x in percentage: 63 | print('Checking Persen Budgeting '+'{}'.format(sum)+' %'+' (Checking)') 64 | time.sleep(2) 65 | sum += x 66 | 67 | print('Checking Persen Budgeting '+'{}'.format(percent_budget)+'%'+' (Done)') 68 | time.sleep(2) 69 | print('Budgeting anda adalah sebesar {}'.format(formatrupiah(budget))+',00') 70 | print('Pemasukan anda untuk kebutuhan hidup adalah\t: {}'.format( 71 | transform_to_rupiah_format(budget_living))) 72 | 73 | print('Pemasukan anda untuk kegiatan adalah\t\t: {}'.format( 74 | transform_to_rupiah_format(budget_playing))) 75 | print('Pemasukan anda untuk tabungan adalah\t\t: {}'.format( 76 | transform_to_rupiah_format(budgett_saving))) 77 | print('========================================================') 78 | -------------------------------------------------------------------------------- /selection_sort.py: -------------------------------------------------------------------------------- 1 | # The selection sort algorithm sorts an array by repeatedly finding the minimum element. 2 | # Time Complexity : O(n*n) 3 | 4 | """ 5 | Algorithm :- 6 | Step 1 − Set MIN to location 0 7 | Step 2 − Search the minimum element in the list 8 | Step 3 − Swap with value at location MIN 9 | Step 4 − Increment MIN to point to next element 10 | Step 5 − Repeat until list is sorted 11 | Pseudocode Selection Sort :- 12 | list : array of items 13 | n : size of list 14 | for i = 1 to n - 1 15 | /* set current element as minimum*/ 16 | min = i 17 | 18 | /* check the element to be minimum */ 19 | for j = i+1 to n 20 | if list[j] < list[min] then 21 | min = j; 22 | end if 23 | end for 24 | /* swap the minimum element with the current element*/ 25 | if indexMin != i then 26 | swap list[min] and list[i] 27 | end if 28 | end for 29 | 30 | end procedure 31 | """ 32 | 33 | 34 | def selection_sort(alist): 35 | for i in range(0, len(alist) - 1): 36 | smallest = i 37 | for j in range(i + 1, len(alist)): 38 | if alist[j] < alist[smallest]: 39 | smallest = j 40 | alist[i], alist[smallest] = alist[smallest], alist[i] 41 | 42 | 43 | # Created a User-Input Array 44 | alist = input('Enter The Numbers : ').split() 45 | alist = [int(x) for x in alist] 46 | selection_sort(alist) 47 | print('Sorted List: ', end='') 48 | print(alist) -------------------------------------------------------------------------------- /sha256_hashing.py: -------------------------------------------------------------------------------- 1 | from hashlib import sha256 2 | print("Please enter password to be hashed:") 3 | passwd = input() 4 | hashed = sha256(passwd.encode()).hexdigest() 5 | print("Hashed password:\n" + hashed) 6 | -------------------------------------------------------------------------------- /simple-interest.py: -------------------------------------------------------------------------------- 1 | def simple_interest(p,t,r): 2 | print('The principal is', p) 3 | print('The time period is', t) 4 | print('The rate of interest is',r) 5 | 6 | si = (p * t * r)/100 7 | 8 | print('The Simple Interest is', si) 9 | return si 10 | 11 | 12 | pa = int(input("Enter the principle amount: ")) 13 | time= int(input("Enter the time: ")) 14 | roi = int(input("Enter the rate of interest: ")) 15 | 16 | print(simple_interest(pa, time, roi)) 17 | -------------------------------------------------------------------------------- /simple_custom_hash_map_implementation.py: -------------------------------------------------------------------------------- 1 | # This class is to demonstate the how Hashmap generally works 2 | # Feel free to make changes and play with it 3 | 4 | class MyHashMap: 5 | def __init__(self, max_size=10): 6 | self.MAX_SIZE = max_size 7 | self.map = [None] * self.MAX_SIZE 8 | 9 | # function will return index in the array based on the key 10 | def _hash_function(self, key): 11 | if type(key) == str: 12 | hash_val = 0 13 | for i in range(len(key)): 14 | hash_val += ((i+1)*ord(key[i])) 15 | else: 16 | hash_val = int(key) 17 | 18 | return hash_val % self.MAX_SIZE 19 | 20 | # function to add key and value and 21 | # if key already present updates the value 22 | def add(self, key, val): 23 | idx = self._hash_function(key) 24 | if self.map[idx] is None: 25 | self.map[idx] = [[key, val]] 26 | else: 27 | if self.is_present(key): 28 | for i in range(len(self.map[idx])): 29 | if self.map[idx][i][0] == key: 30 | self.map[idx][i][1] = val 31 | else: 32 | self.map[idx].append([key, val]) 33 | 34 | # returns value if key exits 35 | # else raises an error 36 | def get(self, key): 37 | if self.is_present(key): 38 | idx = self._hash_function(key) 39 | for key_val in self.map[idx]: 40 | if key_val[0] == key: 41 | return key_val[1] 42 | else: 43 | raise KeyError("Key: {} doesn't exist".format(key)) 44 | 45 | # deletes a value if key exists 46 | # else raises error 47 | def delete(self, key): 48 | if self.is_present(key): 49 | idx = self._hash_function(key) 50 | for i in range(len(self.map[idx])): 51 | if self.map[idx][i][0] == key: 52 | del self.map[idx][i] 53 | else: 54 | raise KeyError("Key: {} doesn't exist".format(key)) 55 | 56 | # returns True if key exists 57 | # else False 58 | def is_present(self, key): 59 | idx = self._hash_function(key) 60 | 61 | if self.map[idx] is None: 62 | return False 63 | 64 | for key_val in self.map[idx]: 65 | if key_val[0] == key: 66 | return True 67 | 68 | return False 69 | 70 | 71 | if __name__ == '__main__': 72 | h = MyHashMap() 73 | h.add('name', "Hari") 74 | h.add('roll', 202089) 75 | h.add('name', "kiran") 76 | h.add(3.2, 'float') 77 | print(h.get('name')) 78 | print(h.get('roll')) 79 | print(h.get(3.2)) 80 | -------------------------------------------------------------------------------- /simple_vending_machine.py: -------------------------------------------------------------------------------- 1 | a=dict() 2 | key_list=list() 3 | def readFile(): 4 | with open("vendingitems.txt",'r') as f: 5 | for line in f: 6 | (k,v)=line.strip().split('|') 7 | a[k]=int(v) 8 | key_list=a.keys() 9 | print("Items available in vending machine",key_list) 10 | 11 | def vendingMachine(): 12 | readFile() 13 | while True: 14 | item=input("Enter item name\n") 15 | if(item in a.keys()): 16 | print("Valid Item Name") 17 | #break 18 | cash=int(input("Enter money to deposit\n")) 19 | if(isinstance(cash,int)==False): 20 | print("Bad Input {}\n Try Again!".format(str(cash))) 21 | #continue 22 | else: 23 | if(cash>a[item]): 24 | print("Thank you for your purchase.Enjoy\n") 25 | print("Do not forget to collect your change,{} Rs".format(cash-a[item])) 26 | break 27 | else: 28 | print("Not enough Money to but the item\n") 29 | continue 30 | else: 31 | print("Available Items are {} ,\nTry Again!".format(a.keys())) 32 | continue 33 | 34 | 35 | vendingMachine() -------------------------------------------------------------------------------- /snakegame.py: -------------------------------------------------------------------------------- 1 | """Snake, classic arcade game. 2 | Exercises 3 | 1. How do you make the snake faster or slower? 4 | 2. How can you make the snake go around the edges? 5 | 3. How would you move the food? 6 | 4. Change the snake to respond to mouse clicks. 7 | """ 8 | 9 | from random import randrange 10 | from turtle import * 11 | 12 | from freegames import square, vector 13 | 14 | food = vector(0, 0) 15 | snake = [vector(10, 0)] 16 | aim = vector(0, -10) 17 | 18 | 19 | def change(x, y): 20 | """Change snake direction.""" 21 | aim.x = x 22 | aim.y = y 23 | 24 | 25 | def inside(head): 26 | """Return True if head inside boundaries.""" 27 | return -200 < head.x < 190 and -200 < head.y < 190 28 | 29 | 30 | def move(): 31 | """Move snake forward one segment.""" 32 | head = snake[-1].copy() 33 | head.move(aim) 34 | 35 | if not inside(head) or head in snake: 36 | square(head.x, head.y, 9, 'red') 37 | update() 38 | return 39 | 40 | snake.append(head) 41 | 42 | if head == food: 43 | print('Snake:', len(snake)) 44 | food.x = randrange(-15, 15) * 10 45 | food.y = randrange(-15, 15) * 10 46 | else: 47 | snake.pop(0) 48 | 49 | clear() 50 | 51 | for body in snake: 52 | square(body.x, body.y, 9, 'black') 53 | 54 | square(food.x, food.y, 9, 'green') 55 | update() 56 | ontimer(move, 100) 57 | 58 | 59 | setup(420, 420, 370, 0) 60 | hideturtle() 61 | tracer(False) 62 | listen() 63 | onkey(lambda: change(10, 0), 'Right') 64 | onkey(lambda: change(-10, 0), 'Left') 65 | onkey(lambda: change(0, 10), 'Up') 66 | onkey(lambda: change(0, -10), 'Down') 67 | move() 68 | done() 69 | -------------------------------------------------------------------------------- /soundex.py: -------------------------------------------------------------------------------- 1 | ##SOUNDEX ALGORITHM 2 | 3 | text = 'AMANMADHUKAR' ##Enter your text here 4 | plain = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ## This is the plain text 5 | code = '01230120022455012623010202' ## Here I have assigned the code value respective to the alphabet 6 | l=[] ## Create empty list 7 | l.append(text[0]) ## So first character goes as it is (here it will be A) 8 | for i in range(1,len(text)): ## Traversing from 1st Index i.e. M to R over here that is the last character 9 | if(code[plain.index(text[i-1])]!=code[plain.index(text[i])]): ## Removing Zeroes from the list 10 | if (code[plain.index(text[i])] != '0'): ## If not zero 11 | l.append(code[plain.index(text[i])]) ## then append into list 12 | for i in range(4): ## Soundex considers only Four characters therefore traversing only four times 13 | if (len(l)<4): ## Suppose the Character less than four then we append 0 in last 14 | l.append('0') 15 | 16 | 17 | print(l) ##printing list 18 | print(''.join(l[:4])) ##lastly merging the list 19 | 20 | 21 | ## Happy Coding :) -------------------------------------------------------------------------------- /strong.py: -------------------------------------------------------------------------------- 1 | sum1=0 2 | num=int(input("Enter a number:")) 3 | temp=num 4 | while(num): 5 | i=1 6 | f=1 7 | r=num%10 8 | while(i<=r): 9 | f=f*i 10 | i=i+1 11 | sum1=sum1+f 12 | num=num//10 13 | if(sum1==temp): 14 | print("The number is a strong number") 15 | else: 16 | print("The number is not a strong number") 17 | -------------------------------------------------------------------------------- /substring.py: -------------------------------------------------------------------------------- 1 | def substring(str1,n): 2 | for i in range(0,n): 3 | for j in range(i+1,n+1): 4 | # Printing the substrings using slicing 5 | # Suppose we have str1="Hello" Str1[0:1] will print "H" 6 | # Str1[1:2] will print "He" 7 | # Str1[1:3] will print "Hel" 8 | # Str1[1:4] will print "Hell" 9 | # Str1[1:5] will print "Hello" 10 | # then i will increment i=2 11 | # Str1[2:3] will print "e" 12 | # Str1[2:4] will print "el" 13 | # And So On 14 | print(str1[i:j]) 15 | 16 | 17 | str1 = input("Enter a String:") 18 | n=len(str1) 19 | substring(str1,n) -------------------------------------------------------------------------------- /subtitle_synchronizer.py: -------------------------------------------------------------------------------- 1 | def convertToMilliseconds(time): 2 | milliseconds = 0 3 | hh,mm,ms = time.split(":") 4 | ms = ms.strip().replace(",","") 5 | hh = int(hh) 6 | mm = int(mm) 7 | ms = int(ms) 8 | 9 | milliseconds = hh*3600000+mm*60000+ms 10 | return milliseconds 11 | 12 | def synchronize(time,shift): 13 | return time-shift 14 | 15 | def convertToTime(milliseconds): 16 | hh = milliseconds//3600000 17 | milliseconds = milliseconds%3600000 18 | hh = str(hh) 19 | if len(hh) < 2: hh = "0"+hh 20 | 21 | mm = milliseconds//60000 22 | milliseconds = milliseconds%60000 23 | mm = str(mm) 24 | if len(mm) < 2: mm = "0"+mm 25 | 26 | ss = milliseconds//1000 27 | milliseconds = milliseconds%1000 28 | ss = str(ss) 29 | if len(ss) < 2: ss = "0"+ss 30 | 31 | milliseconds = str(milliseconds) 32 | while len(milliseconds) < 3: 33 | milliseconds = "0"+milliseconds 34 | 35 | return f"{hh}:{mm}:{ss},{milliseconds}" 36 | 37 | 38 | def main(): 39 | SHIFT = int(input("Please enter the shift in milliseconds: ")) 40 | f = open("input.txt", "r", errors="ignore") 41 | output = open("output.txt","a") 42 | for x in f: 43 | if "-->" in x: 44 | start,end = x.split("-->") 45 | start,end = convertToMilliseconds(start), convertToMilliseconds(end) 46 | start,end = synchronize(start,SHIFT),synchronize(end,SHIFT) 47 | start,end = convertToTime(start),convertToTime(end) 48 | output.write(f"{start} --> {end}\n") 49 | else: 50 | output.write(x) 51 | 52 | 53 | #Right click the subtitles file you want to synchronize and open it in a notepad 54 | #Then copy all of its content and paste it into a new file and name it as "input.txt" 55 | 56 | #You must have your "input.txt" in the same folder as this program 57 | 58 | #Once you run this program you will be asked to enter a shift in milliseconds. 59 | 60 | #You can find the shift when you are watching the video as it is impossible to 61 | #determine that using any program since it is variable for every video. 62 | 63 | #Once the program has finished running, you will have your subtitles synchronized 64 | #in a file that says "output.txt". Copy its content and paste it into your original subtitles file. 65 | main() -------------------------------------------------------------------------------- /sum-of-divisors.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python program to find sum of divisors of a number n, 3 | for example: 4 | print(sum_divisors(0)) 5 | # 0 6 | print(sum_divisors(3)) 7 | # Should sum of 1 8 | # 1 9 | print(sum_divisors(36)) 10 | # Should sum of 1+2+3+4+6+9+12+18 11 | # 55 12 | print(sum_divisors(102)) 13 | # Should be sum of 2+3+6+17+34+51 14 | # 114 15 | """ 16 | 17 | 18 | def sum_divisors(n): 19 | sum = 0 20 | x = 1 21 | while x < n: 22 | if n % x == 0: 23 | sum += x 24 | else: 25 | x += 1 26 | 27 | return sum 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /temperature_convertor_gui.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import tkinter.messagebox as tmsg 3 | 4 | def calculate(): 5 | c = c_value.get() 6 | f = f_value.get() 7 | k = k_value.get() 8 | if c !=0: 9 | f = (c*(9/5)) + 32 10 | k = c + 273.15 11 | f_value.set(f) 12 | k_value.set(k) 13 | elif f != 0: 14 | c = (f-32) * (5/9) 15 | k = ((5/9) + f) + 459.67 16 | c_value.set(c) 17 | k_value.set(k) 18 | elif k != 0: 19 | c = k - 273.15 20 | f = ((k - 273.15) * (9/5)) + 32 21 | c_value.set(c) 22 | f_value.set(f) 23 | else: 24 | tmsg.showerror("Error","Enter 1 value and press calculate") 25 | 26 | def show(): 27 | show_root = Tk() 28 | show_root.title("Formula List") 29 | show_root.geometry("300x300") 30 | show_root.minsize(300,300) 31 | show_root.maxsize(300,300) 32 | show_root.configure(bg = "powder blue") 33 | lbs = Label(show_root,bg = "powder blue", text="Formulae: " ,font ="comicsansms 12 bold", padx=5, pady=5) 34 | lbs.grid(row=0, column=3) 35 | lbs = Label(show_root,bg = "powder blue", text="Celsius conversion: \nF = (9/5 x C) + 32 \nK = C + 273.15 " ,font ="comicsansms 10 bold",padx=5) 36 | lbs.grid(row=1, column=3) 37 | lbs = Label(show_root,bg = "powder blue", text="Fahrenheit conversion: \nC = (F - 32) x 5/9 \nK = (5/9 x F) + 459.67 " ,font ="comicsansms 10 bold",padx=5) 38 | lbs.grid(row=2, column=3) 39 | lbs = Label(show_root,bg = "powder blue", text="Kelvin conversion: \nC = K - 273.15 \nF = ((K - 273.15) x 9/5) + 32 ", font="comicsansms 10 bold", padx=5) 40 | lbs.grid(row=3, column=3) 41 | show_root.mainloop() 42 | 43 | def reset(): 44 | c_value.set(0) 45 | f_value.set(0) 46 | k_value.set(0) 47 | 48 | root = Tk() 49 | root.title("Temperature Converter") 50 | root.geometry("500x500") 51 | root.minsize(500,500) 52 | root.maxsize(500,500) 53 | root.configure(bg="orange") 54 | 55 | lb = Label(root, text="Temperature converter", bg="orange", fg="white", font = "comicsansms 20 bold", padx=10, pady=20) 56 | lb.grid(row=0,column=3) 57 | 58 | lb_c = Label(root, text="Celsius", bg="orange", padx=10, pady=10, font="comicsansms 14", fg="white") 59 | lb_c.grid(row=1, column=2) 60 | lb_f = Label(root, text="Fahrenheit", bg="orange", padx=10, pady=10, font="comicsansms 14", fg="white") 61 | lb_f.grid(row=2, column=2) 62 | lb_k = Label(root, text="Kelvin", bg="orange", padx=10, pady=10, font="comicsansms 14", fg="white") 63 | lb_k.grid(row=3, column=2) 64 | 65 | c_value = IntVar() 66 | f_value = IntVar() 67 | k_value = IntVar() 68 | 69 | c_entry = Entry(root,textvariable=c_value) 70 | c_entry.grid(row=1,column=3) 71 | f_entry = Entry(root,textvariable=f_value) 72 | f_entry.grid(row=2,column=3) 73 | k_entry = Entry(root,textvariable=k_value) 74 | k_entry.grid(row=3,column=3) 75 | 76 | fr = Frame(root) 77 | fr.grid(row=5,column=3) 78 | l = Label(bg="orange") #Empty label 79 | l.grid(row=4) 80 | b = Button(fr, text="Calculate", command=calculate, width=15) 81 | b.grid(row=5, column=3) 82 | 83 | fr = Frame(root) 84 | fr.grid(row=7,column=3) 85 | l = Label(bg="orange") #Empty label 86 | l.grid(row=6) 87 | b = Button(fr, text="Reset", command=reset, width=15) 88 | b.grid(row=7, column=3) 89 | 90 | fr = Frame(root) 91 | fr.grid(row=5,column=2) 92 | b = Button(fr, text="Show conversion formulas", command=show) 93 | b.grid(row=5, column=2) 94 | 95 | root.mainloop() 96 | -------------------------------------------------------------------------------- /text-audio-generator.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Before running this code, do type these commands in command prompt. 3 | --> pip install gTTS 4 | --> pip install playsound 5 | ''' 6 | from gtts import gTTS 7 | 8 | from playsound import playsound 9 | text_val = input("Enter the text which you want to convert: ") # Example : 'Learn Some Cool and Basic Python Programs here.' # 10 | 11 | language = 'en' 12 | obj = gTTS(text=text_val, lang=language, slow=False) 13 | obj.save("python.mp3") # This helps to save our audio file in the existing folder. 14 | 15 | playsound("python.mp3") # This runs the audio when you run the program. -------------------------------------------------------------------------------- /text-to-emoji.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print(convert(input("Enter any text: "))) 3 | 4 | def convert(text): 5 | return text.replace(":(", "🙁").replace(":)", "🙂") 6 | 7 | main() -------------------------------------------------------------------------------- /turtle race.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | from random import randint 3 | 4 | aman=Turtle() 5 | aman.color('blue') 6 | aman.shape('turtle') 7 | aman.penup() 8 | aman.goto(-180,100) 9 | aman.pendown() 10 | 11 | swati=Turtle() 12 | swati.color('red') 13 | swati.shape('turtle') 14 | swati.penup() 15 | swati.goto(-180,70) 16 | swati.pendown() 17 | 18 | ram=Turtle() 19 | ram.color('green') 20 | ram.shape('turtle') 21 | ram.penup() 22 | ram.goto(-180,40) 23 | ram.pendown() 24 | 25 | krishna=Turtle() 26 | krishna.color('dark blue') 27 | krishna.shape('turtle') 28 | krishna.penup() 29 | krishna.goto(-180,10) 30 | krishna.pendown() 31 | 32 | for movement in range(100): 33 | aman.forward(randint(1,5)) 34 | swati.forward(randint(1, 5)) 35 | ram.forward(randint(1, 5)) 36 | krishna.forward(randint(1, 5)) 37 | if aman.position() > (swati.position() and ram.position()and krishna.position()): 38 | print(("Aman won the race")) 39 | elif swati.position()>(aman.position() and ram.position() and krishna.position()): 40 | print("swati won the race") 41 | elif ram.position()> (aman.position() and swati.position() and krishna.position()): 42 | print("ram won the race") 43 | else: 44 | print("Krishna won the race") 45 | 46 | 47 | 48 | input(" ...") 49 | -------------------------------------------------------------------------------- /twoSumusingHashMap.py: -------------------------------------------------------------------------------- 1 | 2 | '''The below approach is using Hash data structure where we store only the unique values of the array 3 | This approach can be extended to 3sum problem as well 4 | ''' 5 | def printPairs(arr, arr_size, sum): 6 | hashmap = {} 7 | 8 | for i in range(0, arr_size): 9 | temp = sum-arr[i] 10 | if (temp in hashmap): 11 | print('Yes') 12 | return 13 | hashmap[arr[i]] = i 14 | print("No") 15 | 16 | 17 | A = [1, 4, 45, 6, 10, 8] 18 | n = 16 19 | printPairs(A, len(A), n) 20 | -------------------------------------------------------------------------------- /two_sum_using_two_pointers.py: -------------------------------------------------------------------------------- 1 | # This function takes 2 parameters the numbers array and the target 2 | # If the target is found it returns the indices of the numbers which add up to the target 3 | # If not found, it returns [-1,-1] 4 | 5 | # Time Complexity for this is O(NlogN) due to sorting 6 | # Space Complexity is O(1) because we are not using any additional space 7 | 8 | def twoSum(nums, target): 9 | nums.sort() 10 | l, r = 0, len(nums) - 1 11 | 12 | while l < r: 13 | cur_sum = nums[l] + nums[r] 14 | if cur_sum < target: 15 | l += 1 16 | elif cur_sum > target: 17 | r -= 1 18 | else: 19 | return [l, r] 20 | 21 | return [-1, -1] 22 | -------------------------------------------------------------------------------- /university.csv: -------------------------------------------------------------------------------- 1 | Name,Branch,Year,CGPA 2 | Nikhil,COE,2,9.0 3 | Sanchit,COE,2,9.1 4 | Aditya,IT,2,9.3 5 | Sagar,SE,1,9.5 6 | Prateek,MCE,3,7.8 7 | Sahil,EP,2,9.1 8 | -------------------------------------------------------------------------------- /vendingitems.txt: -------------------------------------------------------------------------------- 1 | Potato Chips|20 2 | Popcorn|30 3 | Chocolate|15 4 | Biscuit|10 5 | Soft Drink|12 -------------------------------------------------------------------------------- /video_jpeg_converter.py: -------------------------------------------------------------------------------- 1 | # File name: video_jpeg_converter.py 2 | # Objective: To return a set of continuous JPEG images from an input video (useful for annotation of videos) 3 | 4 | from imutils import paths 5 | import cv2 6 | import os 7 | 8 | # Path for input videos (which will be converted to a series of JPEG images) 9 | dataPath = str(input("Copy the path to your video input data and paste it here: ")) 10 | 11 | # Path for output JPEG images 12 | outPath = str(input("Copy the path to your output folder storing the JPEG images and paste it here: ")) 13 | 14 | for classPath in os.listdir(dataPath): 15 | clipPaths = os.listdir(dataPath + "\\" + classPath) 16 | os.mkdir((outPath + '\\' + classPath)) 17 | 18 | k = 1 19 | for clips in clipPaths: 20 | os.mkdir((outPath + '\\' + classPath + '\\' + clips)) 21 | os.chdir((outPath + '\\' + classPath + '\\' + clips)) 22 | 23 | f = dataPath + "\\" + classPath + "\\" + clips 24 | cam = cv2.VideoCapture(f) 25 | ret, frame = cam.read() 26 | currentframe = 0 27 | i = 0 28 | 29 | # a variable to set how many frames you want to skip 30 | frame_skip = 5 # Since the videos are in 30 FPS, and we want 10 frames per clip 31 | 32 | while cam.isOpened(): 33 | ret, frame = cam.read() 34 | k += 1 35 | if not ret: 36 | break 37 | if (i > frame_skip - 1): 38 | cv2.imwrite(classPath + '_' + clips + '_' + str(k) +'.jpg', frame) 39 | i = 0 40 | continue 41 | i += 1 42 | 43 | cam.release() 44 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /weather_gui.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import requests 3 | import time 4 | 5 | 6 | def getWeather(canvas): 7 | city = textField.get() 8 | api = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=06c921750b9a82d8f5d1294e1586276f" 9 | 10 | json_data = requests.get(api).json() 11 | condition = json_data['weather'][0]['main'] 12 | temp = int(json_data['main']['temp'] - 273.15) 13 | min_temp = int(json_data['main']['temp_min'] - 273.15) 14 | max_temp = int(json_data['main']['temp_max'] - 273.15) 15 | pressure = json_data['main']['pressure'] 16 | humidity = json_data['main']['humidity'] 17 | wind = json_data['wind']['speed'] 18 | sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600)) 19 | sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600)) 20 | 21 | final_info = condition + "\n" + str(temp) + "°C" 22 | final_data = "\n"+ "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str(max_temp) + "°C" +"\n" + "Pressure: " + str(pressure) + "\n" +"Humidity: " + str(humidity) + "\n" +"Wind Speed: " + str(wind) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset 23 | label1.config(text = final_info) 24 | label2.config(text = final_data) 25 | 26 | 27 | canvas = tk.Tk() 28 | canvas.geometry("600x500") 29 | canvas.title("Weather App") 30 | f = ("poppins", 15, "bold") 31 | t = ("poppins", 35, "bold") 32 | 33 | textField = tk.Entry(canvas, justify='center', width = 20, font = t) 34 | textField.pack(pady = 20) 35 | textField.focus() 36 | textField.bind('', getWeather) 37 | 38 | label1 = tk.Label(canvas, font=t) 39 | label1.pack() 40 | label2 = tk.Label(canvas, font=f) 41 | label2.pack() 42 | canvas.mainloop() 43 | -------------------------------------------------------------------------------- /webscraper.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | # Make a request 4 | page = requests.get("Paste a Domain here") 5 | soup = BeautifulSoup(page.content, 'html.parser') 6 | 7 | # Create all_h1_tags as empty list 8 | all_h1_tags = [] 9 | 10 | # Set all_h1_tags to all h1 tags of the soup 11 | for element in soup.select('h1'): 12 | all_h1_tags.append(element.text) 13 | 14 | print(all_h1_tags) 15 | 16 | # give you all h1 tags -------------------------------------------------------------------------------- /weightConverterGUI.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | window = Tk() 3 | def from_kg(): 4 | gram = float(e2_value.get())*1000 5 | pound = float(e2_value.get())*2.20462 6 | ounce = float(e2_value.get())*35.274 7 | t1.delete("1.0",END) 8 | t1.insert(END, gram) 9 | t2.delete("1.0", END) 10 | t2.insert(END, pound) 11 | t3.delete("1.0", END) 12 | t3.insert(END, ounce) 13 | 14 | e1 = Label(window, text="Input the weight in KG") 15 | e2_value = StringVar() 16 | e2 = Entry(window, textvariable=e2_value) 17 | e3 = Label(window, text="Gram") 18 | e4 = Label(window, text="Pound") 19 | e5 = Label(window, text="Ounce") 20 | 21 | t1 = Text(window, height=5, width=30) 22 | t2 = Text(window, height=5, width=30) 23 | t3 = Text(window, height=5, width=30) 24 | 25 | b1 = Button(window, text="Convert", command=from_kg) 26 | 27 | e1.grid(row=0, column=0) 28 | e2.grid(row=0, column=1) 29 | e3.grid(row=1, column=0) 30 | e4.grid(row=1, column=1) 31 | e5.grid(row=1, column=2) 32 | t1.grid(row=2, column=0) 33 | t2.grid(row=2, column=1) 34 | t3.grid(row=2, column=2) 35 | b1.grid(row=0, column=2) 36 | 37 | window.mainloop() 38 | --------------------------------------------------------------------------------