diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b6e47617 --- /dev/null +++ b/.gitignore @@ -0,0 +1,129 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/2048game.py b/2048game.py new file mode 100644 index 00000000..868279e8 --- /dev/null +++ b/2048game.py @@ -0,0 +1,255 @@ +# logic.py to be +# imported in the 2048.py file + +# importing random package +# for methods to generate random +# numbers. +import random + +# function to initialize game / grid +# at the start +def start_game(): + + # declaring an empty list then + # appending 4 list each with four + # elements as 0. + mat =[] + for i in range(4): + mat.append([0] * 4) + + # printing controls for user + print("Commands are as follows : ") + print("'W' or 'w' : Move Up") + print("'S' or 's' : Move Down") + print("'A' or 'a' : Move Left") + print("'D' or 'd' : Move Right") + + # calling the function to add + # a new 2 in grid after every step + add_new_2(mat) + return mat + +# function to add a new 2 in +# grid at any random empty cell +def add_new_2(mat): + +# choosing a random index for +# row and column. + r = random.randint(0, 3) + c = random.randint(0, 3) + + # while loop will break as the + # random cell chosen will be empty + # (or contains zero) + while(mat[r] != 0): + r = random.randint(0, 3) + c = random.randint(0, 3) + + # we will place a 2 at that empty + # random cell. + mat[r] = 2 + +# function to get the current +# state of game +def get_current_state(mat): + + # if any cell contains + # 2048 we have won + for i in range(4): + for j in range(4): + if(mat[i][j]== 2048): + return 'WON' + + # if we are still left with + # atleast one empty cell + # game is not yet over + for i in range(4): + for j in range(4): + if(mat[i][j]== 0): + return 'GAME NOT OVER' + + # or if no cell is empty now + # but if after any move left, right, + # up or down, if any two cells + # gets merged and create an empty + # cell then also game is not yet over + for i in range(3): + for j in range(3): + if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]): + return 'GAME NOT OVER' + + for j in range(3): + if(mat[3][j]== mat[3][j + 1]): + return 'GAME NOT OVER' + + for i in range(3): + if(mat[i][3]== mat[i + 1][3]): + return 'GAME NOT OVER' + + # else we have lost the game + return 'LOST' + +# all the functions defined below +# are for left swap initially. + +# function to compress the grid +# after every step before and +# after merging cells. +def compress(mat): + + # bool variable to determine + # any change happened or not + changed = False + + # empty grid + new_mat = [] + + # with all cells empty + for i in range(4): + new_mat.append([0] * 4) + + # here we will shift entries + # of each cell to it's extreme + # left row by row + # loop to traverse rows + for i in range(4): + pos = 0 + + # loop to traverse each column + # in respective row + for j in range(4): + if(mat[i][j] != 0): + + # if cell is non empty then + # we will shift it's number to + # previous empty cell in that row + # denoted by pos variable + new_mat[i][pos] = mat[i][j] + + if(j != pos): + changed = True + pos += 1 + + # returning new compressed matrix + # and the flag variable. + return new_mat, changed + +# function to merge the cells +# in matrix after compressing +def merge(mat): + + changed = False + + for i in range(4): + for j in range(3): + + # if current cell has same value as + # next cell in the row and they + # are non empty then + if(mat[i][j] == mat[i][j + 1] and mat[i][j] != 0): + + # double current cell value and + # empty the next cell + mat[i][j] = mat[i][j] * 2 + mat[i][j + 1] = 0 + + # make bool variable True indicating + # the new grid after merging is + # different. + changed = True + + return mat, changed + +# function to reverse the matrix +# means reversing the content of +# each row (reversing the sequence) +def reverse(mat): + new_mat =[] + for i in range(4): + new_mat.append([]) + for j in range(4): + new_mat[i].append(mat[i][3 - j]) + return new_mat + +# function to get the transpose +# of matrix means interchanging +# rows and column +def transpose(mat): + new_mat = [] + for i in range(4): + new_mat.append([]) + for j in range(4): + new_mat[i].append(mat[j][i]) + return new_mat + +# function to update the matrix +# if we move / swipe left +def move_left(grid): + + # first compress the grid + new_grid, changed1 = compress(grid) + + # then merge the cells. + new_grid, changed2 = merge(new_grid) + + changed = changed1 or changed2 + + # again compress after merging. + new_grid, temp = compress(new_grid) + + # return new matrix and bool changed + # telling whether the grid is same + # or different + return new_grid, changed + +# function to update the matrix +# if we move / swipe right +def move_right(grid): + + # to move right we just reverse + # the matrix + new_grid = reverse(grid) + + # then move left + new_grid, changed = move_left(new_grid) + + # then again reverse matrix will + # give us desired result + new_grid = reverse(new_grid) + return new_grid, changed + +# function to update the matrix +# if we move / swipe up +def move_up(grid): + + # to move up we just take + # transpose of matrix + new_grid = transpose(grid) + + # then move left (calling all + # included functions) then + new_grid, changed = move_left(new_grid) + + # again take transpose will give + # desired results + new_grid = transpose(new_grid) + return new_grid, changed + +# function to update the matrix +# if we move / swipe down +def move_down(grid): + + # to move down we take transpose + new_grid = transpose(grid) + + # move right and then again + new_grid, changed = move_right(new_grid) + + # take transpose will give desired + # results. + new_grid = transpose(new_grid) + return new_grid, changed + +# this file only contains all the logic +# functions to be called in main function +# present in the other file diff --git a/ATM.py b/ATM.py new file mode 100644 index 00000000..da2c64ab --- /dev/null +++ b/ATM.py @@ -0,0 +1,82 @@ +#ATM Machine Using python + +print("="*30, "Welcome to Python Bank ATM", "="*30) + +restart = ("Y") +chances = 3 +balance = 999.99 + +while chances >= 0: + pin = int(input("\nPlease enter your 4 Digit pin: ")) + if pin == (1234): + print("\nCorrect pin!!") + + while restart not in ("n", "no", "N", "NO"): + print("\nPlease Press 1 For Your Balance.") + print("Please Press 2 To Make a Withdrawl.") + print("Please Press 3 To Pay in.") + print("Please Press 4 To Return Card.") + + option = int(input("\nWhat Would you like to Choose?: ")) + + if option == 1: + print(f"\nYour Balance is: ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif option == 2: + option2 = ("y") + withdrawl = float(input("\nHow Much Would you like to withdraw? 10, 20, 40, 60, 80, 100 for other enter 1: ")) + + if withdrawl in [10, 20, 40, 60, 80, 100]: + balance = balance - withdrawl + print(f"\nYour balance after the withdrawl is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif withdrawl == 1: + withdrawl = float(input("\nPlease Enter Desired amount: ")) + balance = balance - withdrawl + print(f"\nYour balance after the withdrawl is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif withdrawl != [10, 20, 40, 60, 80, 100]: + print("\nINVALID AMOUNT, Please try Again\n") + restart = ("y") + + elif option == 3: + pay_in = float(input("\nHow Much Would you like to Pay In? ")) + balance = balance + pay_in + print(f"\nYour balance after the Pay-in is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif option == 4: + print("\nPlease wait whilst your card is Returned....") + print("\nThank you for your service") + break + + else: + print("\nPlease enter a correct number.\n") + restart = ("y") + + elif pin != (1234): + print("\nINCORRECT PIN!!\n") + chances = chances - 1 + + if chances == 0: + print("Calling the Police...\n") + break \ No newline at end of file diff --git a/Age Calculator.py b/Age Calculator.py new file mode 100644 index 00000000..af545f45 --- /dev/null +++ b/Age Calculator.py @@ -0,0 +1,24 @@ +# Calculate the complete age of a person in years, months and days + +import datetime + +def calculate_age(born): + today = datetime.date.today() + return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) + +def main(): + + # Get the date of birth + dob = input("Enter your date of birth (YYYY-MM-DD): ") + + # Split the date into year, month and day + year, month, day = map(int, dob.split('-')) + + # Calculate the age + age = calculate_age(datetime.date(year, month, day)) + + # Print the age + print("Your age is: {}".format(age)) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/Areas.py b/Areas.py new file mode 100644 index 00000000..80518366 --- /dev/null +++ b/Areas.py @@ -0,0 +1,56 @@ +# Program to calculate the areas of 2d shapes + +import math + +def square(side): + area = side * side + return area + +def rectangle(length, breadth): + area = length * breadth + return area + +def triangle(side1, side2, side3): + s = (side1 + side2 + side3)/2 + area = math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) + return area + +def circle(radius): + area = 3.14 * radius * radius + return area + +final_area = 0.0 +print("Choose the shape you want to calculate area of: ") + +while True: + print("Square, Rectangle, Triangle, Circle") + shape = input('>> ') + print(shape.lower()) + + if shape.lower() == "square": + side = float(input("Enter the value of side: ")) + final_area = square(side) + break + + elif shape.lower() == "rectangle": + length = float(input("Enter value of length: ")) + breadth = float(input("Enter value of breadth: ")) + final_area = rectangle(length, breadth) + break + + elif shape.lower() == "triangle": + side1 = float(input("Enter the value of 1st side: ")) + side2 = float(input("Enter the value of 2nd side: ")) + side3 = float(input("Enter the value of 3rd side: ")) + final_area = triangle(side1, side2, side3) + break + + elif shape.lower() == "circle": + radius = float(input("Enter the value of radius: ")) + final_area = circle(radius) + break + + else: + print("Please choose a shape from the given 4 or check your spelling again") + +print(f"The area of the shape is: {final_area}") \ No newline at end of file diff --git a/ArmstrongNumberCheck.py b/ArmstrongNumberCheck.py new file mode 100644 index 00000000..1cfa836c --- /dev/null +++ b/ArmstrongNumberCheck.py @@ -0,0 +1,9 @@ +print("An Armstrong Number is a number which is equal to the sum of the cubes of it's digits.") +inputNumber = input("Enter a number to check if it's an Armstrong Number or not: ") +sumOfCubes=0 + +for digit in inputNumber: + sumOfCubes+=int(digit)**3 + +if sumOfCubes==int(inputNumber): print(inputNumber,"is an Armstrong Number.") +else: print(inputNumber,"is NOT an Armstrong Number.") diff --git a/Average.py b/Average.py new file mode 100644 index 00000000..da6f0da3 --- /dev/null +++ b/Average.py @@ -0,0 +1,7 @@ +n=int(input("Enter the number of elements to be inserted: ")) +a=[] +for i in range(0,n): + elem=int(input("Enter element: ")) + a.append(elem) +avg=sum(a)/n +print("Average of elements in the list",round(avg,2)) diff --git a/BMI.py b/BMI.py new file mode 100644 index 00000000..40219a3b --- /dev/null +++ b/BMI.py @@ -0,0 +1,131 @@ +from tkinter import * +from tkinter import messagebox + +def reset_entry(): + age_tf.delete(0,'end') + height_tf.delete(0,'end') + weight_tf.delete(0,'end') + +def calculate_bmi(): + kg = int(weight_tf.get()) + m = int(height_tf.get())/100 + bmi = kg/(m*m) + bmi = round(bmi, 1) + bmi_index(bmi) + +def bmi_index(bmi): + + if bmi < 18.5: + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Underweight') + elif (bmi > 18.5) and (bmi < 24.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Normal') + elif (bmi > 24.9) and (bmi < 29.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Overweight') + elif (bmi > 29.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Obesity') + else: + messagebox.showerror('bmi-pythonguides', 'something went wrong!') + +ws = Tk() +ws.title('BMI') +ws.geometry('400x300') +ws.config(bg='#686e70') + +var = IntVar() + +frame = Frame( + ws, + padx=10, + pady=10 +) +frame.pack(expand=True) + + +age_lb = Label( + frame, + text="Enter Age (2 - 120)" +) +age_lb.grid(row=1, column=1) + +age_tf = Entry( + frame, +) +age_tf.grid(row=1, column=2, pady=5) + +gen_lb = Label( + frame, + text='Select Gender' +) +gen_lb.grid(row=2, column=1) + +frame2 = Frame( + frame +) +frame2.grid(row=2, column=2, pady=5) + +male_rb = Radiobutton( + frame2, + text = 'Male', + variable = var, + value = 1 +) +male_rb.pack(side=LEFT) + +female_rb = Radiobutton( + frame2, + text = 'Female', + variable = var, + value = 2 +) +female_rb.pack(side=RIGHT) + +height_lb = Label( + frame, + text="Enter Height (cm) " +) +height_lb.grid(row=3, column=1) + +weight_lb = Label( + frame, + text="Enter Weight (kg) ", + +) +weight_lb.grid(row=4, column=1) + +height_tf = Entry( + frame, +) +height_tf.grid(row=3, column=2, pady=5) + +weight_tf = Entry( + frame, +) +weight_tf.grid(row=4, column=2, pady=5) + +frame3 = Frame( + frame +) +frame3.grid(row=5, columnspan=3, pady=10) + +cal_btn = Button( + frame3, + text='Calculate', + command=calculate_bmi +) +cal_btn.pack(side=LEFT) + +reset_btn = Button( + frame3, + text='Reset', + command=reset_entry +) +reset_btn.pack(side=LEFT) + +exit_btn = Button( + frame3, + text='Exit', + command=lambda:ws.destroy() +) +exit_btn.pack(side=RIGHT) + +ws.mainloop() diff --git a/BankGame.py b/BankGame.py new file mode 100644 index 00000000..6560f87e --- /dev/null +++ b/BankGame.py @@ -0,0 +1,115 @@ +#default password is 4758 +import random +class BankGame : + @staticmethod + def main( args) : + print("---WELCOME TO ELIX BANKING SERVICES---") + print("") + print("________________________") + print("Enter your name: ") + name = input() + # I am inserting do loop to make the program run forever under correct inputs. + print("Hi, " + name + "\bWelcome to my program!") + print("____________________________") + print("Do you want to start/repeat the program?") + print("Enter Y for Yes and N for No: ") + temp = input()[0] + passw = 4758 + bal = 10000 + leftbal = 0 + print("If you don\'t know the password refer the first line of the program") + print("Please enter the password: ") + # Condition when the statement goes true i.e.- temp equals 1 + while True : + if (temp == 'Y' or temp == 'y') : + if (passw == 4758) : + print("") + print("Your initial account balance is Rs. 10000") + # Using for statement to perform 5 operation on each login + x = 0 + while (x <= 6) : + print("0. Exit") + print("1. Deposit") + print("2. Withdraw") + print("3. Change passcode") + print("4. Check balance") + print("5. Customer care") + print("Enter the serial no. of your choice") + choice = int(input()) + print("Enter captha to verify that you are not a robot.") + captha = random.randrange(10000) + print(captha) + print("Enter the number shown above: ") + verify = int(input()) + if (verify == captha) : + # If captha gets matched, then these switch statements are executed. + if (choice==0): + print("BYE!......" + name + " HAVE A NICE DAY!") + print("__________________________") + print("@author>[@programmer-yash") + print("Please comment here or open an issue if you have any queries or suggestions!") + print("") + print("#hacktoberfest") + return 0 + elif(choice==1): + print("You have chosen to deposit.") + print("Enter the amount to deposit : ") + deposit = int(input()) + bal = bal + deposit + print(str(deposit) + " has been deposited to your account.") + print("Left balance is " + str(bal)) + elif(choice==2): + print("You have chosen to withdraw.") + print("Enter the amount to be withdrawn") + withdraw = int(input()) + print(str(+withdraw) + " has been withdrawn from your account.") + bal = bal - withdraw + print("Check the cash printer.") + print("Left balance is " + str(bal)) + elif(choice==3): + print("You have chosen to change passcode.") + print("Enter the current passcode: ") + check = int(input()) + if (check == passw) : + print("Enter the new passcode") + newP = int(input()) + passw = newP + print("Your new password is " + str(newP)) + else : + print("Wrong passcode!") + elif(choice==4): + print("You have chosen to check balanace.") + print("Your current account balance is " + str(bal)) + elif(choice==5): + print("You have chosen for customer care.") + print("Contact us at:") + print(" Email: yash197911@gmail.com") + else: + print("Wrong choice!!! Choose again...!") + else : + print("xCAPTHA NOT CORRECTx") + x += 1 + continue + elif(temp == 'N' or temp == 'n') : + print("BYE!......" + name + " HAVE A NICE DAY!") + print("__________________________") + print("@author>[@programmer-offbeat]") + print("Please comment here if you have any queries or suggestions!") + print("--OR--") + print("create an issue") + print("I will rightly see and reply to your messages and suggestions!") + print() + print("HAPPY CODING!:-)") + return 0 + else : + print("Err!..... You have entered a wrong choice!") + print("Try again....!") + # Comdition if password mismatches. + if (passw != 4758) : + print("You have entered wrong password.....Try again!") + if((temp < 100) == False) : + break + + +if __name__=="__main__": + BankGame.main([]) diff --git a/Bifurcation diagram .py b/Bifurcation diagram .py new file mode 100644 index 00000000..aeac4f41 --- /dev/null +++ b/Bifurcation diagram .py @@ -0,0 +1,63 @@ +# Bifurcation diagram + + +from cmath import inf +import numpy as np +import matplotlib.pyplot as plt +import math +import csv +import matplotlib as mpl +import time +from numba import njit +import multiprocessing +from multiprocessing import Pool +multiprocessing.cpu_count() +from functools import reduce + +from functools import partial + + + +start_time = time.time() + + +#change these values +x0=0.1 +begin_r=0 +end_r=4 +step=0.0001 + + + +r=np.arange(begin_r,end_r,step) +X=[] +Y=[] + +@njit +def bif(x0, r): + N=1000 + x = np.zeros(len(range(0, N))) + x[0]=x0 + for i in range(1,N): + x[i] = r * x[i-1] * (1 - x[i-1]) #logistic map #logistic with extra parameter + + return (x[-130:]) + +bif1 = partial(bif,x0) +if __name__ == '__main__': + # create and configure the process pool + with Pool(4) as p: + + for i,ch in enumerate(p.map(bif1,r,chunksize=2500)) : + x1=np.ones(len(ch))*r[i] + X.append(x1) + Y.append(ch) + print("--- %s seconds ---" % (time.time() - start_time)) + + plt.style.use('dark_background') + plt.plot(X,Y, ".w", alpha=1, ms=1.2) + figure = plt.gcf() # get current figure + figure.set_size_inches(1920 / 40, 1080 / 40) + # print("--- %s seconds ---" % (time.time() - start_time)) +plt.show() + diff --git a/Blackjack.py b/Blackjack.py new file mode 100644 index 00000000..d81e3907 --- /dev/null +++ b/Blackjack.py @@ -0,0 +1,91 @@ +logo=""" +.------. _ _ _ _ _ +|A_ _ |. | | | | | | (_) | | +|( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __ +| \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ / +| \/ | / \ | | |_) | | (_| | (__| <| | (_| | (__| < +`-----| \ / | |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\ + | \/ K| _/ | + `------' |__/ +""" +import random + +print(logo) +cards=[11,2,3,4,5,6,7,8,9,10,10,10,10] + +player=[] +computer=[] + +player_sum=0 +computer_sum=0 + +player.append(random.choice(cards)) + + +rand = random.choice(cards) +if (rand == 11 and rand + computer_sum > 21): + player.append(1) +else: + player.append(rand) + + +computer.append(random.choice(cards)) + + +randco = random.choice(cards) +if (rand == 11 and rand + computer_sum > 21): + computer.append(1) +else: + computer.append(rand) + +player_sum+=player[0]+player[1] +computer_sum+=computer[0]+computer[1] + +while(player_sum<=21): + print(f"Your cards : {player} ,current score : {player_sum}") + print(f"Computer's first card : {computer[0]}") + + accept=input("Type y to get another card , Type n to pass : ") + if(accept=='y'): + rand=random.choice(cards) + if(rand==11 and rand+player_sum>21): + player_sum+=1 + player.append(1) + else: + player_sum+=rand + player.append(rand) + else:break + +if player_sum>21: + print(f"Your cards : {player} ,current score : {player_sum}") + print("You Lost") + exit() + +while computer_sum 21): + computer_sum += 1 + computer.append(1) + else: + computer_sum += rand + computer.append(rand) + +if computer_sum>21 or player_sum>computer_sum : + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("You Won") + exit() +if(computer_sum==player_sum): + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("Draw!!") + exit() + +if(computer_sum>player_sum): + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("You Lost") + exit() \ No newline at end of file diff --git a/Bubble_Sort.py b/Bubble_Sort.py index b801c382..90a2690d 100644 --- a/Bubble_Sort.py +++ b/Bubble_Sort.py @@ -44,6 +44,14 @@ def main(): sort.bubbleSortRecursive() print("Sorted array :\n", sort) + +# Tests ('pip install pytest'; run with 'pytest Bubble_Sort.py') +def test_result_in_order(): + array = [64, 34, 25, 12, 22, 11, 90] + sort = bubbleSort(array) + sort.bubbleSortRecursive() + for i in range(sort.length-1): + assert sort.array[i] < sort.array[i+1] if __name__ == "__main__": diff --git a/Count_Number_of_Vowels_in_a_File.py b/Count_Number_of_Vowels_in_a_File.py new file mode 100644 index 00000000..8fb6e6ad --- /dev/null +++ b/Count_Number_of_Vowels_in_a_File.py @@ -0,0 +1,26 @@ +######## This program counts and returns the number of vowels in a text file. ######## + +# Ask the user for the name of the file. The file should be in the same folder and should be a text file. +print("Enter the Name of File: ") + +# Convert the name to string and open the file in read mode +fileName = str(input()) +fileHandle = open(fileName, "r") + +# Declare a variable to store the number of vowels. Initally it is zero. +count = 0 + +# create an array of all the vowels (upper and lower case) that can be used to compare and determine if a character is a vowel +vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] + +# Read each character and compare it to the characters in the array. If found in the vowels array, then increase count. +for char in fileHandle.read(): + if char in vowels: + count = count+1 + +# Close the file +fileHandle.close() + +# Print the count to the screen for the user to see. +print("\nThe total number of vowels in the text are:") +print(count) diff --git a/Decomposing_factors.py b/Decomposing_factors.py new file mode 100644 index 00000000..e6f82f29 --- /dev/null +++ b/Decomposing_factors.py @@ -0,0 +1,17 @@ +def prime_factors(n): + final = [] + rstr = '' + while n != 1: + for x in range(2,n+1): + if n % x == 0: + n //= x + final.append(x) + break + for x in final: + if f'({x}**{final.count(x)})' in rstr: + continue + rstr += f'({x}**{final.count(x)})' if final.count(x) > 1 else f'({x})' + return rstr + +#Function that decomposes number into their base multiplicants. Usefull for simplifications of square roots etc. +#Example: prime_factors(30) outputs (2)(3)(5) because 30 = 2 * 3 * 5 diff --git a/Designer_door_mat.py b/Designer_door_mat.py new file mode 100644 index 00000000..521a9d79 --- /dev/null +++ b/Designer_door_mat.py @@ -0,0 +1,10 @@ +pattern = '.|.' +a, b = map(int, input().split()) # 5 < a < 101 and 15 < b < 303 + +for i in range(1,a,2): + print((pattern*i).center(b, '-')) + +print('WELCOME'.center(b,'-')) + +for i in reversed(range(1,a,2)): + print((pattern*i).center(b, '-')) \ No newline at end of file diff --git a/DigitalClock.py b/DigitalClock.py new file mode 100644 index 00000000..8fba4bdc --- /dev/null +++ b/DigitalClock.py @@ -0,0 +1,31 @@ +# importing whole module +from tkinter import * +from tkinter.ttk import * + +# importing strftime function to +# retrieve system's time +from time import strftime + +# creating tkinter window +root = Tk() +root.title('Clock') + +# This function is used to +# display time on the label +def time(): + string = strftime('%H:%M:%S %p') + lbl.config(text = string) + lbl.after(1000, time) + +# Styling the label widget so that clock +# will look more attractive +lbl = Label(root, font = ('calibri', 40, 'bold'), + background = 'purple', + foreground = 'white') + +# Placing clock at the centre +# of the tkinter window +lbl.pack(anchor = 'center') +time() + +mainloop() diff --git a/DjikistraAlgorithm.py b/DjikistraAlgorithm.py new file mode 100644 index 00000000..65238794 --- /dev/null +++ b/DjikistraAlgorithm.py @@ -0,0 +1,43 @@ +class Graph: + def __init__(self): + self.nodes = set() + self.edges = defaultdict(list) + self.distances = {} + + def add_node(self, value): + self.nodes.add(value) + + def add_edge(self, from_node, to_node, distance): + self.edges[from_node].append(to_node) + self.edges[to_node].append(from_node) + self.distances[(from_node, to_node)] = distance + + +def dijsktra(graph, initial): + visited = {initial: 0} + path = {} + + nodes = set(graph.nodes) + + while nodes: + min_node = None + for node in nodes: + if node in visited: + if min_node is None: + min_node = node + elif visited[node] < visited[min_node]: + min_node = node + + if min_node is None: + break + + nodes.remove(min_node) + current_weight = visited[min_node] + + for edge in graph.edges[min_node]: + weight = current_weight + graph.distance[(min_node, edge)] + if edge not in visited or weight < visited[edge]: + visited[edge] = weight + path[edge] = min_node + + return visited, path \ No newline at end of file diff --git a/Economy_chart.py b/Economy_chart.py new file mode 100644 index 00000000..40a095ae --- /dev/null +++ b/Economy_chart.py @@ -0,0 +1,15 @@ +import matplotlib.pyplot as plt; plt.rcdefaults() +import numpy as np +import matplotlib.pyplot as plt + +#objects = ('America', 'India', 'Africa', 'UK', 'UAE','Iran') +objects = ('Brazil', 'Italy', 'Canada', 'France', 'UK','India','Germany','Japan','China','USA') +y_pos = np.arange(len(objects)) +performance=[1.80,2.00,2.10,2.80,3.30,3.50,4.10,4.80,19.80,24.10] + +plt.barh(y_pos, performance, align='center', alpha=1) +plt.yticks(y_pos, objects) +plt.xlabel('Usage') +plt.title('Top 10 Economies of the World in 2022') + +plt.show() diff --git a/Emoji_Convertor b/Emoji_Convertor new file mode 100644 index 00000000..d105353f --- /dev/null +++ b/Emoji_Convertor @@ -0,0 +1,12 @@ +message = input("> ") +words = message.split() +emojis = { + ":)" :"😄", + ":(" :"😔", + ":D" :"😁" + +} +output = " " +for word in words: + output+=emojis.get( word,word) + " " +print(output) diff --git a/Extracting_Numbers_from_textString.py b/Extracting_Numbers_from_textString.py new file mode 100644 index 00000000..fcd50640 --- /dev/null +++ b/Extracting_Numbers_from_textString.py @@ -0,0 +1,40 @@ +# Given Sentence +sentence="Ramu have 150 Apples and 10 bananas" +sentence2="Ramu Sell 1 Apple at 15.5 Rupees" + +list1=[] +list2=[] + +sum=0 +sum2=0 +# split is used to split sentence +# This code is not fit for Decimal Nos. + +print("---------------EXTRACTING NUMBER FROM STRING---------------\n") +for word in sentence.split(): + if word.isdigit(): + list1.append(word) + +print("New List",list1) + + + +# Calculating the SUM +for i in list1: + sum=sum+int(i) + +print("No. without Fraction \nsum=",sum,"\n") + +# If Decimal Numbers occured in the Sentence +for word2 in sentence2.split(): + if not word2.isalpha(): + list2.append(word2) + +print("New List",list2) + +# Calculating the SUM +for j in list2: + sum2=sum2+float(j) + +print("No. with Fraction \nsum=",sum2) +print("-----------------------------------------------------------") \ No newline at end of file diff --git a/GUI_Tic_Tac_Toe_pvp.py b/GUI_Tic_Tac_Toe_pvp.py new file mode 100644 index 00000000..5e600a40 --- /dev/null +++ b/GUI_Tic_Tac_Toe_pvp.py @@ -0,0 +1,115 @@ +import tkinter as tk +from functools import partial +import time + +gui=tk.Tk() +gui.geometry('500x200') +gui.title('Tic Tac Toe') + +movesPlayed=[] +game_over=False + +Xcount=0 +Ocount=0 +player,turn=1,'x' + +def clicked(obj): + global player,turn,Xcount,Ocount + + button_clicked=''.join(obj.split()) + #row,column=obj.split() + #row=row.split('w')[1] + + + if button_clicked not in movesPlayed: + globals()[button_clicked].configure(text=turn.center(6)) + movesPlayed.append(button_clicked) + globals()[button_clicked]['state']='disabled' + if player==1: + player,turn=2,'0' + Xcount+=1 + player_data.configure(text='Player-2(0) chance') + + + else: + player,turn=1,'x' + Ocount+=1 + player_data.configure(text='Player-1(x) chance') + + win_check() + else: + print('Move already played') + +def finish(string): + global game_over + game_over=True + player_data.configure(text='') + player_win.configure(text=string) + player_win.pack() + for i in ('row1','row2','row3'): + for j in range(3): + globals()[i+str(j+1)]['state']='disabled' + rtry=tk.Button(gui,text='Retry',command=Retry) + rtry.pack() + finish.rtry=rtry + +def Retry(): + global movesPlayed,player,turn,Xcount,Ocount,rtry + movesPlayed=[] + player,turn=1,'x' + Xcount,Ocount=0,0 + for i in ('row1','row2','row3'): + for j in range(3): + + globals()[i+str(j+1)].configure(text=f' ') + globals()[i+str(j+1)]['state']='active' + finish.rtry.pack_forget() + player_win.pack_forget() + player_data.configure(text='Player-1(x) chance') + +def win_check(): + + + + + if (row11['text'] == row12['text'] == row13['text'] != ' ' or + row21['text'] == row22['text'] == row23['text'] != ' ' or + row31['text'] == row32['text'] == row33['text'] != ' ' or + row11['text'] == row21['text'] == row31['text'] != ' ' or + row12['text'] == row22['text'] == row32['text'] != ' ' or + row13['text'] == row23['text'] == row33['text'] != ' ' or + row11['text'] == row22['text'] == row33['text'] != ' ' or + row13['text'] == row22['text'] == row31['text'] != ' ' + ): + + + if Xcount>Ocount: + string='Player 1(X) won' + else: + string='Player 2(O) won' + finish(string) + + if not game_over: + if (Xcount==5 and Ocount==4 or + Xcount==4 and Ocount==5): + finish('Draw match') +tk.Label(gui,text="PLAYER-1=X\nPLAYER-2=0").pack() +player_data=tk.Label(gui,text='Player-1(x) chance') +player_data.pack() + +row1=tk.Frame(gui) +row1.pack() +row2=tk.Frame(gui) +row2.pack() +row3=tk.Frame(gui) +row3.pack() + +player_win=tk.Label(gui,text='') +for i in ('row1','row2','row3'): + for j in range(3): + + vars()[i+str(j+1)]=tk.Button(vars()[i], text=f' ',bd='1',command=partial(clicked,i+' '+str(j+1))) + vars()[i+str(j+1)].pack(side='left') + + +gui.mainloop() diff --git a/GeoMetric_sum.py b/GeoMetric_sum.py new file mode 100644 index 00000000..4aa53151 --- /dev/null +++ b/GeoMetric_sum.py @@ -0,0 +1,16 @@ +# Geometric Sum = 1 + 1/2 + 1/4 + 1/8 + 1/16 + ... + 1/(2^n) +# where n is the input from the user +# Example: +# Input: 3 +# Output: 1.875 + +def geometricSum(n): + if n == 0: # base case + return 1 # return 1 if n == 0 + smallOutput = geometricSum(n - 1) # recursion call + # adding and smallOutput vaule + 1 and divide using 2^n + return smallOutput + 1 / pow(2, n) + + +n = int(input()) # taking input from user +print(geometricSum(n)) # calling the function and printing the result diff --git a/GrayCodetoBinary.py b/GrayCodetoBinary.py new file mode 100644 index 00000000..d3396448 --- /dev/null +++ b/GrayCodetoBinary.py @@ -0,0 +1,37 @@ +def flip_num(my_nu): + return '1' if(my_nu == '0') else '0'; + +def gray_to_binary(gray): + binary_code="" + binary_code += gray[0] + for i in range(1,len(gray)): + + if (gray[i]=='0'): + binary_code += binary_code[i-1] + else: + binary_code += flip_num(binary_code[i-1]) + + return binary_code + +# gray_code="01101001" + + +gray_code=input("please enter the gray code\n") +print("the gray code is : ") +print(gray_code) +# x=gray_to_binary(gray_code) +print("binary code of", gray_code, "is",gray_to_binary(gray_code)) + +# for converting binary numb to decimal +value=0 +b_num=list(gray_to_binary(gray_code)) + +for i in range(len(b_num)): + digit=b_num.pop() + if digit =='1': + value = value + pow(2,i) + +print("the decimal value of the number is ", value) + + +# print(12//5) diff --git a/Guessnumber.py b/Guessnumber.py new file mode 100644 index 00000000..278b02cd --- /dev/null +++ b/Guessnumber.py @@ -0,0 +1,37 @@ +import random +number=random.randint(1,100) + + +def guessNUmber(number, num , level): + + while level!=1: + if(num>number): + print("Too High") + else:print("Too Low") + level-=1 + print(f"YOU have {level} attemps left") + num = int(input("Guess the number : ")) + + if(num==number):print(f"YOU GUESSED IT CORRECT IT WAS {num}") + else:print(f"YOU GUESSED IT WRONG IT WAS {number}") + +print("choose the level of game 'hard' or 'easy'") +level = input().lower() + +while True: + + + if(level!="hard" and level!="easy"): + print("Invalid Choice") + else:break + + print("choose the level of game 'hard' or 'easy'") + level = input().lower() + +print("I am thinking of a number betwen 1-100. \n ") +num = int(input("Guess the number : ")) + +if level == "hard": + guessNUmber(number, num, 5) +elif level == "easy:": + guessNUmber(number, num, 10) diff --git a/HangmanGame.py b/HangmanGame.py new file mode 100644 index 00000000..c9d9d07e --- /dev/null +++ b/HangmanGame.py @@ -0,0 +1,88 @@ +import random + +stages = [''' + +---+ + | | + O | + /|\ | + / \ | + | +========= +''', ''' + +---+ + | | + O | + /|\ | + / | + | +========= +''', ''' + +---+ + | | + O | + /|\ | + | + | +========= +''', ''' + +---+ + | | + O | + /| | + | + | +=========''', ''' + +---+ + | | + O | + | | + | + | +========= +''', ''' + +---+ + | | + O | + | + | + | +========= +''', ''' + +---+ + | | + | + | + | + | +========= +'''] +lives = 6 +word_list = ["baboon", "delhi", "adamantium", "dehradun"] +# choosing a random word from the list +word = random.choice(word_list); +print(f"The chosen word is {word}") +blank_list = [] + +for i in range(len(word)): + blank_list += "_" +end_game=False +while end_game == False: + guess = input("Guess a letter\n") + + if guess not in word: + lives=lives-1 + else: + for i in range(len(word)): + if word[i]==guess: + blank_list[i]=guess + + if lives==0 or "_" not in blank_list: + end_game=True + + # Clear.clear() + for i in blank_list: + print(i,end=" ") + print(stages[lives]) + +if(lives==0):print("YOU LOSE!!") +else :print("YOU WON!!") \ No newline at end of file diff --git a/Indianflag-Turtle.py b/Indianflag-Turtle.py new file mode 100644 index 00000000..71744244 --- /dev/null +++ b/Indianflag-Turtle.py @@ -0,0 +1,90 @@ +import turtle +from turtle import* + +#screen for output +screen = turtle.Screen() + +# Defining a turtle Instance +t = turtle.Turtle() +speed(0) + +# initially penup() +t.penup() +t.goto(-400, 250) +t.pendown() + +# Orange Rectangle +#white rectangle +t.color("orange") +t.begin_fill() +t.forward(800) +t.right(90) +t.forward(167) +t.right(90) +t.forward(800) +t.end_fill() +t.left(90) +t.forward(167) + +# Green Rectangle +t.color("green") +t.begin_fill() +t.forward(167) +t.left(90) +t.forward(800) +t.left(90) +t.forward(167) +t.end_fill() + +# Big Blue Circle +t.penup() +t.goto(70, 0) +t.pendown() +t.color("navy") +t.begin_fill() +t.circle(70) +t.end_fill() + +# Big White Circle +t.penup() +t.goto(60, 0) +t.pendown() +t.color("white") +t.begin_fill() +t.circle(60) +t.end_fill() + +# Mini Blue Circles +t.penup() +t.goto(-57, -8) +t.pendown() +t.color("navy") +for i in range(24): + t.begin_fill() + t.circle(3) + t.end_fill() + t.penup() + t.forward(15) + t.right(15) + t.pendown() + +# Small Blue Circle +t.penup() +t.goto(20, 0) +t.pendown() +t.begin_fill() +t.circle(20) +t.end_fill() +# Spokes +t.penup() +t.goto(0, 0) +t.pendown() +t.pensize(2) +for i in range(24): + t.forward(60) + t.backward(60) + t.left(15) + +#to hold the +#output window +turtle.done() \ No newline at end of file diff --git a/InsertionSort.py b/InsertionSort.py new file mode 100644 index 00000000..3a1aaad6 --- /dev/null +++ b/InsertionSort.py @@ -0,0 +1,17 @@ +def insertion_sort(arr): + + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + + while j >= 0 and key < arr[j]: + arr[j + 1] = arr[j] + j = j - 1 + + + arr[j + 1] = key + +arr = [9, 8, 6, 7, 1] +print("Unsorted Array:", arr) +insertion_sort(arr) +print('Sorted Array: ', arr) diff --git a/JumpSearch.py b/JumpSearch.py new file mode 100644 index 00000000..d5b7e0e3 --- /dev/null +++ b/JumpSearch.py @@ -0,0 +1,47 @@ + +# Python3 code to implement Jump Search +import math + +def jumpSearch( arr , x , n ): + + # Finding block size to be jumped + step = math.sqrt(n) + + # Finding the block where element is + # present (if it is present) + prev = 0 + while arr[int(min(step, n)-1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + + # Doing a linear search for x in + # block beginning with prev. + while arr[int(prev)] < x: + prev += 1 + + # If we reached next block or end + # of array, element is not present. + if prev == min(step, n): + return -1 + + # If element is found + if arr[int(prev)] == x: + return prev + + return -1 + +# Driver code to test function +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 ] +x = 55 +n = len(arr) + +# Find the index of 'x' using Jump Search +index = jumpSearch(arr, x, n) + +# Print the index where 'x' is located +print("Number" , x, "is at index" ,"%.0f"%index) + +#contributed by Rover Phoenix \ No newline at end of file diff --git a/Levenshtein_distance.py b/Levenshtein_distance.py new file mode 100644 index 00000000..710a3910 --- /dev/null +++ b/Levenshtein_distance.py @@ -0,0 +1,41 @@ +# The Levenshtein distance (Edit distance) Problem + +# Informally, the Levenshtein distance between two words is +# the minimum number of single-character edits (insertions, deletions or substitutions) +# required to change one word into the other. + +# For example, the Levenshtein distance between kitten and sitting is 3. +# The minimal edit script that transforms the former into the latter is: + +# kitten —> sitten (substitution of s for k) +# sitten —> sittin (substitution of i for e) +# sittin —> sitting (insertion of g at the end) + +def levenshtein_distance(word_1, chars_1, word_2, chars_2): + # base case if the strings are empty + if chars_1 == 0: + return chars_2 + if chars_2 == 0: + return chars_1 + + # if last characters of the string match, the cost of + # operations is 0, i.e. no changes are made + if word_1[chars_1 - 1] == word_2[chars_2 - 1]: + cost = 0 + else: + cost = 1 + + # calculating the numbers of operations recursively + deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1 + insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1 + substitution = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2 - 1) + cost + + return min(deletion, insertion, substitution) + +# driving script +if __name__ == '__main__': + word_1 = input("Enter Word 1 :") + word_2 = input("Enter Word 2 :") + + print('The Levenshtein distance is:') + print(levenshtein_distance(word_1, len(word_1), word_2, len(word_2))) \ No newline at end of file diff --git a/Linear_Search.py b/Linear_Search.py new file mode 100644 index 00000000..a1b14e77 --- /dev/null +++ b/Linear_Search.py @@ -0,0 +1,20 @@ +# Linear Search in Python + + +def linearSearch(array, n, x): + + + for i in range(0, n): + if (array[i] == x): + return i + return -1 + + +array = [2, 4, 0, 1, 9] +x = 1 +n = len(array) +result = linearSearch(array, n, x) +if(result == -1): + print("Element not found") +else: + print("Element found at index: ", result) diff --git a/Linkedlist_reverse.py b/Linkedlist_reverse.py new file mode 100644 index 00000000..a50c0cb3 --- /dev/null +++ b/Linkedlist_reverse.py @@ -0,0 +1,59 @@ +# Python program to reverse a linked list + + +# Node class + + +class Node: + + # Constructor to initialize the node object + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to reverse the linked list + def reverse(self): + prev = None + current = self.head + while(current is not None): + next = current.next + current.next = prev + prev = current + current = next + self.head = prev + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Utility function to print the LinkedList + def printList(self): + temp = self.head + while(temp): + print (temp.data,end=" ") + temp = temp.next + + +# Driver program to test above functions +llist = LinkedList() +llist.push(20) +llist.push(4) +llist.push(15) +llist.push(85) + +print ("Given Linked List") +llist.printList() +llist.reverse() +print ("\nReversed Linked List") +llist.printList() + + diff --git a/MatrixOperation.py b/MatrixOperation.py new file mode 100644 index 00000000..811c2ce1 --- /dev/null +++ b/MatrixOperation.py @@ -0,0 +1,49 @@ +#Prgram Code Created by Shivsagar Mishra +#This is a program to perform basic matrix operarations such as 1. Addition 2.Substraction 3.Multiplication 4.Transpose + + +import numpy as np + +# Initialize matrix +a = np.array([[1,2,1], [6,5,4], [9,5,8]]) +b = np.array([[3,2,1], [8,6,4], [4,0,0]]) + +while True: + print("List of operations:\n1.Display\n2.Addition\n3.Substraction\n4.Multiplication\n5.Transpose") + counter=int(input("Enter the your Choice:")) + + if counter == 1: + #printing 1st matrix + print("First Matrix:") + print (a,"\n") + # printing 2nd Matrix + print("Second Matrix:") + print(b,"\n") + + elif counter == 2: + print ("The addition of matrices is : ") + print(a.__add__(b),"\n") + + elif counter == 3: + print ("The Substraction of matrices is : ") + print ("Substraction is:") + print(a.__sub__(b),"\n") + + elif counter == 4: + print ("The multiplication of matrices is : ") + print(a.__mul__(b),"\n") + + elif counter == 5: + print ("The Transposition of First matrix is: ") + print(np.transpose(a),"\n") + print("The Transposition of Second Matrix is:") + print(np.transpose(b),"\n") + else: + print("Invalid Option!") + + cont=int(input("Do you want to continue?: 1.Yes\t 2.No\t Enter your choice:")) + if cont==1: + continue + else: + break + diff --git a/MaximizeProfitStockProblem.py b/MaximizeProfitStockProblem.py new file mode 100644 index 00000000..85726c93 --- /dev/null +++ b/MaximizeProfitStockProblem.py @@ -0,0 +1,40 @@ +# Module to return the maximum profit that can be made after buying and selling the given stocks + +def maxProfit(price, start, end): + + # If the stocks can't be bought + if (end <= start): + return 0 + + # Initialise the profit + profit = 0 + + # The day at which the stock must be bought + for i in range(start, end, 1): + + # The day at which the stock must be sold + for j in range(i+1, end+1): + + # If buying the stock at ith day and selling it at jth day is profitable + if (price[j] > price[i]): + + # Update the current profit + current_profit = price[j] - price[i] +\ + maxProfit(price, start, i - 1) + \ + maxProfit(price, j + 1, end) + + # Update the maximum profit so far + profit = max(profit, current_profit) + + return profit + +# Example Driver Code +if __name__ == '__main__': + price = [100, 180, 260, 310, 40, 535, 695] + n = len(price) + + print(maxProfit(price, 0, n - 1)) + +# Solution: 865 + +# This code is contributed by Laksh Gupta diff --git a/Minesweeper_Game.py b/Minesweeper_Game.py new file mode 100644 index 00000000..2de12f51 --- /dev/null +++ b/Minesweeper_Game.py @@ -0,0 +1,121 @@ +import random + +# Generate a random map to start the game. +def randomMap(n, k): + + arr = [[0 for row in range(0,n)] for column in range(0,n)] + + for num in range(0,k): + x = random.randint(0,n-1) + y = random.randint(0,n-1) + arr[y][x] = 'X' + + if (x >=0 and x <= n-2) and (y >= 0 and y <= n-1): + if arr[y][x+1] != 'X': + arr[y][x+1] += 1 # center right + + if (x >=1 and x <= n-1) and (y >= 0 and y <= n-1): + if arr[y][x-1] != 'X': + arr[y][x-1] += 1 # center left + + if (x >= 1 and x <= n-1) and (y >= 1 and y <= n-1): + if arr[y-1][x-1] != 'X': + arr[y-1][x-1] += 1 # top left + + if (x >= 0 and x <= n-2) and (y >= 1 and y <= n-1): + if arr[y-1][x+1] != 'X': + arr[y-1][x+1] += 1 # top right + + if (x >= 0 and x <= n-1) and (y >= 1 and y <= n-1): + if arr[y-1][x] != 'X': + arr[y-1][x] += 1 # top center + + if (x >=0 and x <= n-2) and (y >= 0 and y <= n-2): + if arr[y+1][x+1] != 'X': + arr[y+1][x+1] += 1 # bottom right + + if (x >= 1 and x <= n-1) and (y >= 0 and y <= n-2): + if arr[y+1][x-1] != 'X': + arr[y+1][x-1] += 1 # bottom left + + if (x >= 0 and x <= n-1) and (y >= 0 and y <= n-2): + if arr[y+1][x] != 'X': + arr[y+1][x] += 1 # bottom center + return arr + +# Generate the map for the player. +def playerMap(n): + arr = [['-' for row in range(0,n)] for column in range(0,n)] + return arr + +# Display the map on the screen. +def showMap(map): + for row in map: + print(" ".join(str(cell) for cell in row)) + print("") + +# Check if player has won. +def checkWin(map): + for row in map: + for cell in row: + if cell == '-': + return False + return True + +# Check if player is willing to continue the game. +def checkContinue(score): + print("Your score: ", score) + isContinue = input("Do you want to try again? (y/n) :") + if isContinue == 'n': + return False + return True + +# MINESWEEPER GAME +def Game(): + + GameStatus = True + while GameStatus: + difficulty = input("Select your difficulty (0,1,2):") + if difficulty.lower() == '0': + n = 5 + k = 3 + elif difficulty.lower() == '1': + n = 6 + k = 8 + else: + n = 8 + k = 20 + + minesweeper_map = randomMap(n, k) + player_map = playerMap(n) + score = 0 + + while True: + + if checkWin(player_map) == False: + print("Enter the cell you want to open :") + x,y = map(int,input().split()) + x -= 1 # 0 based indexing + y -= 1 # 0 based indexing + if (minesweeper_map[y][x] == 'X'): + print("Game Over!") + showMap(minesweeper_map) + GameStatus = checkContinue(score) + break + else: + player_map[y][x] = minesweeper_map[y][x] + showMap(player_map) + score += 1 + + else: + showMap(player_map) + print("Congratulation! You Win!") + GameStatus = checkContinue(score) + break + +# Main Program +if __name__ == "__main__": + try: + Game() + except KeyboardInterrupt: + print('\nGoodbye!') \ No newline at end of file diff --git a/OTP generator.py b/OTP generator.py new file mode 100644 index 00000000..f9d64c6c --- /dev/null +++ b/OTP generator.py @@ -0,0 +1,22 @@ +import os +import math +import random +import smtplib +digits = "012456789" +OTP = "" +for i in range(4): + OTP += digits[math.floor(random.random() * 10)] +msg = str(OTP) + "Your OTP is" + +s = smtplib.SMTP('smtp.gmail.com', 587) +s.starttls() + +emailid = "receiver's id" +s.login("sender's id", "google app password") +s.sendmail("sender's id", emailid, msg) +a = input("Enter the OTP >>: ") +if a == OTP: + print("Verified") +else: + print("Incorrect OTP") +s.quit() diff --git a/PasswordGenerator.py b/PasswordGenerator.py new file mode 100644 index 00000000..ae774e82 --- /dev/null +++ b/PasswordGenerator.py @@ -0,0 +1,56 @@ +#Password Generator Project +import random +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'] +numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + +print("Welcome to the PyPassword Generator!") + + +no_letters=int(input("How many letters would you like to use in password?\n")) +no_symbols=int(input("How many symbols would you like? \n")) +no_numbers=int(input("How many numbers would you like? \n")) + + + + +def easy_version(): + password = "" + for i in range(no_letters): + ran=random.randint(0,len(letters)) + password+=letters[ran] + for i in range(no_numbers): + ran=random.randint(0,len(numbers)) + password+=str(numbers[ran]) + for i in range(no_symbols): + ran=random.randint(0,len(symbols)) + password+=str(symbols[ran]) + print(password) + +def hard_version(): + password_list=[] + password="" + for i in range(no_letters): + ran=random.randint(0,len(letters)-1) + password_list+=letters[ran] + for i in range(no_numbers): + ran=random.randint(0,len(numbers)-1) + password_list+=str(numbers[ran]) + for i in range(no_symbols): + ran=random.randint(0,len(symbols)-1) + password_list+=str(symbols[ran]) + + random.shuffle(password_list) + for i in password_list: + password+=i + + print(password) + + +hard_version() + + diff --git a/Password_generator.py b/Password_generator.py new file mode 100644 index 00000000..62d3368a --- /dev/null +++ b/Password_generator.py @@ -0,0 +1,74 @@ +#Password Generator Project +import random as r +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'] +numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + + +def easy_pass(nr_letters,nr_symbols,nr_numbers): + random_letters = "" + for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters += random_letter + + random_symbols = "" + for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols += random_symbol + + random_numbers = "" + for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers += random_number + + #Easy Level - Order not randomised: + #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 + final_password = random_letters + random_symbols + random_numbers + print(f"Here is your easy password : {final_password}") + +def hard_pass(nr_letters,nr_symbols,nr_numbers): + random_letters = [] + for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters.append(random_letter) + + random_symbols = [] + for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols.append(random_symbol) + + random_numbers = [] + for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers.append(random_number) + + final_password_list = random_letters + random_symbols + random_numbers + r.shuffle(final_password_list) + + + #Hard Level - Order of characters randomised: + #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P + final_pass_in_str = "" + for char in final_password_list: + final_pass_in_str += char + print(f"Here is your hard password : {final_pass_in_str}") + + +def password_generator(): + print("Welcome to the PyPassword Generator!") + nr_letters= int(input("How many letters would you like in your password?\n")) + nr_symbols = int(input(f"How many symbols would you like?\n")) + nr_numbers = int(input(f"How many numbers would you like?\n")) + + print() + easy_pass(nr_letters,nr_symbols,nr_numbers) + print() + hard_pass(nr_letters,nr_symbols,nr_numbers) + + +def main(): + password_generator() + + +if __name__ == '__main__': + main() diff --git a/Player.py b/Player.py new file mode 100644 index 00000000..7b28c746 --- /dev/null +++ b/Player.py @@ -0,0 +1,84 @@ +import math +import random + + +class Player(): + def __init__(self, player): + self.player = player + + def get_move(self, game): + pass + + +class Human(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + valid_square = False + val = None + while not valid_square: + square = input(self.player + ' turn. Please introduce a move (1-9): ') + try: + val = int(square) - 1 + if val not in game.remaining_moves(): + raise ValueError + valid_square = True + except ValueError: + print('Invalid square. Try again.') + return val + + +class RandomComputer(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + square = random.choice(game.remaining_moves()) + return square + + +class SmartComputer(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + if len(game.remaining_moves()) == 9: + square = random.choice(game.remaining_moves()) + else: + square = self.minimax(game, self.player)['position'] + return square + + def minimax(self, state, player): + max_player = self.player + min_player = '0' if player == 'X' else 'X' + + # checking if the previous move is winner + if state.actual_winner == min_player: + return {'position': None, + 'score': 1 * (state.number_null_squares() + 1) if min_player == max_player + else -1 * (state.number_null_squares() + 1)} + elif not state.null_squares(): + return {'position': None, 'score': 0} + + if player == max_player: + best = {'position': None, 'score': -math.inf} + else: + best = {'position': None, 'score': math.inf} + + for possible_move in state.remaining_moves(): + state.make_a_move(possible_move, player) + sim_score = self.minimax(state, min_player) + + # undo move + state.board[possible_move] = ' ' + state.actual_winner = None + sim_score['position'] = possible_move + + if player == max_player: + if sim_score['score'] > best['score']: + best = sim_score + else: + if sim_score['score'] < best['score']: + best = sim_score + return best diff --git a/Pong_Game.py b/Pong_Game.py new file mode 100644 index 00000000..e2afeede --- /dev/null +++ b/Pong_Game.py @@ -0,0 +1,121 @@ +import turtle as t +playerAscore=0 +playerBscore=0 + +#create a window and declare a variable called window and call the screen() +window=t.Screen() +window.title("The Pong Game") +window.bgcolor("green") +window.setup(width=800,height=600) +window.tracer(0) + +#Creating the left paddle +leftpaddle=t.Turtle() +leftpaddle.speed(0) +leftpaddle.shape("square") +leftpaddle.color("white") +leftpaddle.shapesize(stretch_wid=5,stretch_len=1) +leftpaddle.penup() +leftpaddle.goto(-350,0) + +#Creating the right paddle +rightpaddle=t.Turtle() +rightpaddle.speed(0) +rightpaddle.shape("square") +rightpaddle.color("white") +rightpaddle.shapesize(stretch_wid=5,stretch_len=1) +rightpaddle.penup() +rightpaddle.goto(-350,0) + +#Code for creating the ball +ball=t.Turtle() +ball.speed(0) +ball.shape("circle") +ball.color("red") +ball.penup() +ball.goto(5,5) +ballxdirection=0.2 +ballydirection=0.2 + +#Code for creating pen for scorecard update +pen=t.Turtle() +pen.speed(0) +pen.color("Blue") +pen.penup() +pen.hideturtle() +pen.goto(0,260) +pen.write("score",align="center",font=('Arial',24,'normal')) + +#code for moving the leftpaddle +def leftpaddleup(): + y=leftpaddle.ycor() + y=y+90 + leftpaddle.sety(y) + +def leftpaddledown(): + y=leftpaddle.ycor() + y=y+90 + leftpaddle.sety(y) + +#code for moving the rightpaddle +def rightpaddleup(): + y=rightpaddle.ycor() + y=y+90 + rightpaddle.sety(y) + +def rightpaddledown(): + y=rightpaddle.ycor() + y=y+90 + rightpaddle.sety(y) + +#Assign keys to play +window.listen() +window.onkeypress(leftpaddleup,'w') +window.onkeypress(leftpaddledown,'s') +window.onkeypress(rightpaddleup,'Up') +window.onkeypress(rightpaddledown,'Down') + +while True: + window.update() + + #moving the ball + ball.setx(ball.xcor()+ballxdirection) + ball.sety(ball.ycor()+ballxdirection) + + #border set up + if ball.ycor()>290: + ball.sety(290) + ballydirection=ballydirection*-1 + if ball.ycor()<-290: + ball.sety(-290) + ballydirection=ballydirection*-1 + + if ball.xcor() > 390: + ball.goto(0,0) + ball_dx = ball_dx * -1 + player_a_score = player_a_score + 1 + pen.clear() + pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + os.system("afplay wallhit.wav&") + + + + if(ball.xcor()) < -390: # Left width paddle Border + ball.goto(0,0) + ball_dx = ball_dx * -1 + player_b_score = player_b_score + 1 + pen.clear() + pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + os.system("afplay wallhit.wav&") + + # Handling the collisions with paddles. + + if(ball.xcor() > 340) and (ball.xcor() < 350) and (ball.ycor() < rightpaddle.ycor() + 40 and ball.ycor() > rightpaddle.ycor() - 40): + ball.setx(340) + ball_dx = ball_dx * -1 + os.system("afplay paddle.wav&") + + if(ball.xcor() < -340) and (ball.xcor() > -350) and (ball.ycor() < leftpaddle.ycor() + 40 and ball.ycor() > leftpaddle.ycor() - 40): + ball.setx(-340) + ball_dx = ball_dx * -1 + os.system("afplay paddle.wav&") diff --git a/ProductOfSumAndDifference.py b/ProductOfSumAndDifference.py new file mode 100644 index 00000000..560b0c9b --- /dev/null +++ b/ProductOfSumAndDifference.py @@ -0,0 +1,8 @@ +def solve(a, b): + return (a+b)*(a-b) + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + res = solve(a, b) + print(res) diff --git a/Queue.py b/Queue.py new file mode 100644 index 00000000..a1397f65 --- /dev/null +++ b/Queue.py @@ -0,0 +1,24 @@ +class Queue: + arr = [] + def enqueue(self,item): + self.arr.append(item) + + def dequeue(self): + if len(self.arr) > 0: + ditem = self.arr[0] + del self.arr[0] + return ditem + else: + return #queue is empty + + def dispaly(self): + print(self.arr) + +x = Queue() # Creating object of queue class +x.enqueue(1) +x.enqueue(2) +x.dispaly() # arr = [1,2] +x.dequeue() # Deleting the first element of the queue. +x.dispaly() # arr = [2] +print(x.dequeue()) # 2 +print(x.dequeue()) # None(because queue is already empty) \ No newline at end of file diff --git a/Queue_using_LL.py b/Queue_using_LL.py new file mode 100644 index 00000000..0bfa00b7 --- /dev/null +++ b/Queue_using_LL.py @@ -0,0 +1,39 @@ +class Node: + def __init__(self, data = None): + self.data = data + self.next = None + +class Queue: + def __init__(self): + self.head = None + self.last = None + + def enqueue(self, data): + if not self.last: + self.head = Node(data) + self.last = self.head + else: + self.last.next = Node(data) + self.last = self.last.next + + def dequeue(self): + if not self.head: + return None + val = self.head.data + self.head = self.head.next + return val + + def display(self): + temp = self.head + while temp != None: + print(temp.data) + temp = temp.next + +x = Queue() # Creating object of queue class +x.enqueue(1) # Add 1 to the queue +x.enqueue(2)# Add 2 to the queue +x.display() # 1 => 2 +print(x.dequeue()) # Deleting the first element of the queue. +x.display() # 2 +print(x.dequeue()) # 2 +print(x.dequeue()) # None(because queue is already empty) \ No newline at end of file diff --git a/README.md b/README.md index 5c2df28e..908b36ab 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Basic-Python-Programs This repository will contain basic python programming questions and their solutions. +# Do give us a Star # Contributions diff --git a/Radix_sort.py b/Radix_sort.py new file mode 100644 index 00000000..0c6f84fe --- /dev/null +++ b/Radix_sort.py @@ -0,0 +1,43 @@ +# Radix sort in Python +# Using counting sort to sort the elements in the basis of significant places +def countingSort(array, place): + size = len(array) + output = [0] * size + count = [0] * 10 + + # Calculate count of elements + for i in range(0, size): + index = array[i] // place + count[index % 10] += 1 + + # Calculate cumulative count + for i in range(1, 10): + count[i] += count[i - 1] + + # Place the elements in sorted order + i = size - 1 + while i >= 0: + index = array[i] // place + output[count[index % 10] - 1] = array[i] + count[index % 10] -= 1 + i -= 1 + + for i in range(0, size): + array[i] = output[i] + + +# Main function to implement radix sort +def radixSort(array): + # Get maximum element + max_element = max(array) + + # Apply counting sort to sort elements based on place value. + place = 1 + while max_element // place > 0: + countingSort(array, place) + place *= 10 + + +data = [121, 432, 564, 23, 1, 45, 788] +radixSort(data) +print(data) \ No newline at end of file diff --git a/Random Team Generator.py b/Random Team Generator.py new file mode 100644 index 00000000..73d6d3b5 --- /dev/null +++ b/Random Team Generator.py @@ -0,0 +1,15 @@ +import random +y = list(map(str,input().split())) +t1 = [] +t2 = [] +while (len(y) != 0): + x = random.choice(y) + if (len(t1) == len(t2)): + t1.append(x) + y.remove(x) + elif (len(t1) > len(t2)): + t2.append(x) + y.remove(x) +print("Team A: ", t1) +print("Team B: ", t2) + diff --git a/RockPaperScissors.py b/RockPaperScissors.py new file mode 100644 index 00000000..2bb0ddd1 --- /dev/null +++ b/RockPaperScissors.py @@ -0,0 +1,16 @@ +import random + +randomInteger=random.randint(0,2) +userInput=int(input("What do you choose ? Type 0 for Rock,1 for Paper or 2 for Scissors\n")) +if(userInput!=0 and userInput!=1 and userInput!=2): + print("Wrong choise") + exit() + +if(userInput==randomInteger): + print("DRAW!!!") +elif (userInput==randomInteger-1 or (userInput==2 and randomInteger==0)): + print("Computer Won") +elif (randomInteger==userInput-1 or (randomInteger==2 and userInput==0)): + print("YOU WON!!!") +print(userInput) +print(f"computer choose {randomInteger}") \ No newline at end of file diff --git a/RomanToInt.py b/RomanToInt.py new file mode 100644 index 00000000..1846a8b4 --- /dev/null +++ b/RomanToInt.py @@ -0,0 +1,21 @@ +val = input("Enter your value: ") +class Solution(object): + def romanToInt(self, s): + """ + :type s: str + :rtype: int + """ + 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} + i = 0 + num = 0 + while i < len(s): + if i+1 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: + time.sleep(1) + head.goto(0, 0) + head.direction = "stop" + + #hiding segments of snake + for segment in segments: + segment.goto(1000,1000) + #clearing the segments + segments.clear() + + #reset score + score = 0 + + #reset delay + delay = 0.1 + + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + + #checking collision with food + if head.distance(food) < 20: + x = random.randint(-270, 270) + y = random.randint(-270, 270) + food.goto(x, y) + d = ["red","yellow","blue"] + colors = random.choice(d) + food.color(colors) + e = ["circle","square","triangle"] + shapes = random.choice(e) + food.shape(shapes) + + + #adding new segment + new_segment = turtle.Turtle() + new_segment.speed(0) + new_segment.color("green") + new_segment.shape("square") + new_segment.penup() + segments.append(new_segment) + + delay -= 0.001 + score += 10 + + if score>high_score: + high_score = score + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + + #moving segments in reverse order + for i in range(len(segments)-1,0,-1): + x = segments[i-1].xcor() + y = segments[i-1].ycor() + segments[i].goto(x,y) + if len(segments) > 0: + x = head.xcor() + y = head.ycor() + segments[0].goto(x, y) + + move() + + #Checking collisions with body + for segment in segments: + if segment.distance(head) < 20: + time.sleep(1) + head.goto(0,0) + head.direction = "stop" + + #hide segments + for segment in segments: + segment.goto(1000,1000) + segment.clear() + + score = 0 + delay = 0.1 + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + time.sleep(delay) + +turtle.done() + diff --git a/Sell Buy Stocks to Max Profit.py b/Sell Buy Stocks to Max Profit.py new file mode 100644 index 00000000..092e02d9 --- /dev/null +++ b/Sell Buy Stocks to Max Profit.py @@ -0,0 +1,13 @@ +p = list(map(int, input().split())) #Enter the prices of each day + +maxProfit = 0 +currentMax = 0 + +for i in reversed(p): + currentMax = max(currentMax, i) + profit = currentMax - i + maxProfit = max(profit, maxProfit) + +print("Buy stock when price is:", currentMax-maxProfit) #Buying Price +print("Sell stock when price is:", currentMax) #Selling Price +print("Maximum profit earned:", maxProfit) #Profit Earned \ No newline at end of file diff --git a/Sieve_of _Eratosthenes.py b/Sieve_of _Eratosthenes.py new file mode 100644 index 00000000..e23ea370 --- /dev/null +++ b/Sieve_of _Eratosthenes.py @@ -0,0 +1,23 @@ +def SieveOfEratosthenes(n): + numbers = {i: True for i in range(2, n+1)} + primes = [] + + p = 2 + + while p**2 < n : + if numbers[p] : + for i in range(p**2, n+1, p): + numbers[i] = False + p+=1 + for i in range(2, n+1) : + if numbers[i] : + primes.append(i) + + return primes + +def main() : + n = int(input("Enter value of n to find primes between 1 and n (inclusive):")) + arr = SieveOfEratosthenes(n) + print("Primes:", *arr) + +main() diff --git a/SpeedTypingTestInPython.py b/SpeedTypingTestInPython.py new file mode 100644 index 00000000..aeb03db5 --- /dev/null +++ b/SpeedTypingTestInPython.py @@ -0,0 +1,61 @@ +### Speed Typing Test in python ### + +# Imported Library + +import time +import threading + +# Created Class + +class tester: + def __init__(self, paragraph): + self.correctWords = [] + self.incorrectWords = {} + self.typedWords = [] + self.totalWords = [] + self.input = None + self.paragraph = paragraph + self.accuracy = 0 + self.time = 0 + self.wordPermin = 0 + self.run() + +#### Defined the Variable ### + + def clock(self): + while len(self.typedWords) == 0: + self.time += 1 + time.sleep(1) + + def run(self): + threading.Thread(target=self.clock).start() + threading.Thread(target=self.testSpeed).start() + + def testSpeed(self): + print('\n\n'+self.paragraph+'\n\n') + self.input = str(input('\t\n'+'Type The Word Which You Want To Know the Speed As well as Incorrect \n\n')) + self.totalWords = self.paragraph.split(' ') + self.typedWords = self.input.split(' ') + + try: + for i in range(len(self.typedWords)): + if(self.typedWords[i] == self.totalWords[i]): + self.correctWords.append(self.typedWords[i]) + else: + self.incorrectWords.update({self.totalWords[i] : self.typedWords[i]}) + + except Exception as e: + print(e) + + + self.accuracy = len(self.correctWords)/len(self.typedWords) * 100 + self.wordPerMin = len(self.typedWords) / (self.time/60) + + print('\n\nResult :--') + print(f'Accuracy: -- {self.accuracy}') + print(f'Word Per Minute :-- {self.wordPerMin}') + print(f'Incorrect Words :-- {self.incorrectWords}') + +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.") + +### The Code is ended, Thank You #### \ No newline at end of file diff --git a/Spy_number.py b/Spy_number.py new file mode 100644 index 00000000..9c46d15a --- /dev/null +++ b/Spy_number.py @@ -0,0 +1,15 @@ +num=int(input("Enter your number ")) +sum=0 +product=1 +num1 = num + +while(num>0): + d=num%10 + sum=sum+d + product=product*d + num=num//10 + +if(sum==product): + print("{} is a Spy number!".format(num1)) +else: + print("{} is not a Spy number!".format(num1)) diff --git a/Story-generator-game.py b/Story-generator-game.py new file mode 100644 index 00000000..7242fda0 --- /dev/null +++ b/Story-generator-game.py @@ -0,0 +1,139 @@ +import time +import random +from string import ascii_lowercase + +print('This is a game where you guess the randomly chosen word and if you win, you get a randomly generated short story !') +print('Enjoy !!') +print('\n') + +time.sleep(4) + +name=input('Player Name :- ') +print('\n') +print('Welcome ' + name + '. Let''s play Hangman') +print('') + +time.sleep(1) + +friends=['Chandler','Joey','Monica','Rachel','Ross','Phoebe','Gunther','Janice','Ugly Naked Guy','Mr Heckles','Judy','Jack'] +ramaayan=['Shri Ram','Sita maa','Lakshman','Bharat','Raavan','Hanuman','Maarich','Dashrath','Kaikeyi','King Janak','KumbhKarn','Baali'] +Got=['Theon','Danaerys','Jon Snow','Joeffry','Cersie','Tyrion','Drogon','Baratheon','Starks','Greyjoy','Viserys'] + +print('Choose Category :- ') +choose=int(input('1. F.R.I.E.N.D.S 2. Game Of Thrones 3. Ramaayan ')) +if choose==1: + word=random.choice(friends) +elif choose==2: + word=random.choice(Got) +elif choose==3: + word=random.choice(ramaayan) + +print('HINT : Starts with' + word[0]) +print('\n') +print("Start guessing...") +time.sleep(0.5) +guess='' +turn=10 + +while turn>0: + fail=0 + for c in word: + if c in guess: + print(c) + else: + print('_') + fail+=1 + if fail==0: + print('You Won ' + name + ' !') + print('\n') + print('Here is your story - ') + theme=random.choice(["real world","high fantasy","space sci-fi","alt-history","cyberpunk"]) + if theme == "real world": + subsetting=random.choice(["the Ayodhya","Kishkindha","Lanka","Panchvati","Janakpuri"]) + setting=random.choice(["a small town in ","a big city in ","a farm in ","a school in ","the ocean","the entire world"]) + if setting != "the ocean" or "the entire world": + setting=setting+subsetting + age=random.choice(["newborn ","toddler ","child ","teenager ","young adult ","adult ","middle aged ","elder "]) + race=random.choice(["ayodhyan ","janakis ","lankan ","indian "]) + gengender=random.randint(0,100) + if gengender <= 10: + gender = ("transgender ") + if gengender >= 9: + if gengender >= 47: + gender = ("male ") + if gengender <= 46: + gender = ("female ") + protagonist=age+race+gender + 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"]) + if theme == "high fantasy": + 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"]) + gender=random.choice(["male ","male ","male ","female ","female ","female ","magical transgender ","agender ","third gender "]) + race=random.choice(["human ","human ","elf ","orc ","dwarf ","gnome ","demon ","angel ","kitsune ","dark elf ","troll ","unicorn "]) + classs=random.choice(["marksmen ","warrior ","wizard ","bard ","thief ","merchant","knight ","spellsword ","peasant ","necromancer ","preist ","bandit ","monarch"]) + protagonist = gender+race+classs + 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"]) + if theme == "space sci-fi": + 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"]) + protagonist=random.choice(["human","robot","hive mind","alien","alien","blob","human"]) + 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"]) + if theme == "alt-history": + 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"]) + if setting == "America": + 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"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "Religion": + figure=random.choice(["Jesus","Muhammad","Buddha","Krishna","Moses","L. Ron Hubbard","Joseph Smith","Zeus","Ra","Thor"]) + antagonist=random.choice(["Christianity","Islam","Hinduism","Buddhism","Greek mythology","Scientology","the Mormons","Paganism","Heresies"]) + if setting == "the Classical Era": + figures=["Alexander The Great","Julius Caesar","Aristotle","King Tut","Qin Shi Huang","Homer","Augustus","Plato","Cleopatra","Ashoka","Attila the Hun","Leonidas"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Middle Ages": + 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"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Renaissance": + 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"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Industrial Era": + 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"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "World War I": + figure=random.choice(["Woodrow Wilson","Winston Churchill","Tsar Nicholas II","Lenin","Paul von Hindenburg","Ataturk"]) + antagonist=random.choice(["the Ottoman Empire","Germany","the United States","Britain","Austria-Hungary","France"]) + if setting == "World War II": + figure=random.choice(["Hitler","Queen Elizabeth","Franklin D. Roosevelt","Joseph Stalin","Harry Truman","General Hideki Tojo"]) + antagonist=random.choice(["the United States","Germany","the Soviet Union","the United Kingdom","Japan","Italy"]) + if setting == "the Modern Era": + figures=["Obama","Putin","Kim Jong-un","Kanye West","Bill Gates","Guido van Rossum","The Beatles","ISIS","Pope Francis","Mike Tyson","Pewdiepie","Hilary Cliton"] + figure=random.choice(figures) + antagonist=random.choice(figures) + afigure=("figure known as ") + protagonist= afigure+figure + if theme == "cyberpunk": + setting=random.choice(["high-tech Tokyo","New New York","a dystopia","a utopia","a computer simulation","the SuperWeb","Mega Silicon Valley","an underwater city","an extensive underground facility"]) + gender=random.choice(["male ","male ","female ","female ","robogender ","unigender ","agender ","mega genderfluid ","third gender "]) + classs=random.choice(["hacker","cyborg","DJ","technopath","engineer","bomber","corporate","street rat","anarchist"]) + protagonist=gender+classs + 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"]) + 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 "]) + 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."]) + print("In the",theme,"setting of",setting,", there was a", protagonist, "who",conflict,antagonist,".",end) + + break + + + + guesses=input('Guess a character :- ') + guess=guess+guesses + if guesses not in word: + turn-=1 + print('Wrong. You have ' + str(turn) + ' more guesses.') + if turn==0: + print('You lose ! The word was ' + word + '. Sorry, you don''t get the story.') + print('\n') + print('Write your story on your own.') +#Winstoryhangman diff --git a/TicTacToe.py b/TicTacToe.py new file mode 100644 index 00000000..04329745 --- /dev/null +++ b/TicTacToe.py @@ -0,0 +1,124 @@ +from tkinter import * +from tkinter import messagebox +import random as r +import functools + + +def button(f): + button1 = Button(f, text=" ", fg="Black", font="Arial 20 bold", height=1, width=2, padx=25, pady=20, bg="White", borderwidth=0, + activebackground="White", cursor="hand2", state=NORMAL) + return button1 + + +def full(): + for row in range(3): + for col in range(3): + if b[row][col]['text'] == " ": + return False + return True + + +def empty(): + for row in range(3): + for col in range(3): + b[row][col].config(text=" ", state=NORMAL) + + +def winner(s): + 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\ + 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\ + 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\ + 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 + + +user_checked = [] +com_checked = [] + + +def click(event, param1, param2): + sign = 0 + if (param1, param2) in user_checked or (param1, param2) in com_checked: + messagebox.showwarning("Warning", "Select Another Box.") + else: + user_checked.append((param1, param2)) + b[param1][param2]['text'] = 'O' + + if winner("O"): + messagebox.showinfo("Winner", "You Won...") + user_score.set(user_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + sign = 1 + + if full(): + messagebox.showinfo("Tie", "Match Tie...!") + tie_score.set(tie_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + sign = 1 + + if sign == 0: + unchecked = [] + for row in range(3): + for col in range(3): + if b[row][col]['text'] == " ": + unchecked.append([row, col]) + index = r.sample(unchecked, 1) + b[index[0][0]][index[0][1]].config(text="X", state=DISABLED) + com_checked.append((index[0][0], index[0][1])) + if winner("X"): + messagebox.showinfo("Winner", "Computer Won...") + com_score.set(com_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + else: + pass + + +root = Tk() +root.title("Tic Tac Toe") +root.geometry("420x500") +root.resizable(0, 0) +root.configure(bg="Black") +Label(root, text="TIC TAC TOE", fg="White", bg="Black", font="times 25 bold").pack() + +Frame(root, bg="White").pack(fill=X, pady=10) +frame = Frame(root, bg="Black") +Label(frame, text="YOU", fg="Yellow", bg="Black", font="System 10 bold", padx=50, pady=5).pack(side=LEFT) +Label(frame, text="TIE", fg="Yellow", bg="Black", font="System 10 bold", padx=48, pady=5).pack(side=LEFT) +Label(frame, text="COMPUTER", fg="Yellow", bg="Black", font="System 10 bold", padx=30, pady=5).pack(side=LEFT) +frame.pack(pady=5) + +frame = Frame(root, bg="Black") +user_score = IntVar() +tie_score = IntVar() +com_score = IntVar() +user_score.set(0) +tie_score.set(0) +com_score.set(0) +user = Entry(frame, textvariable=user_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +user.pack(side=LEFT, padx=35) +tie = Entry(frame, textvariable=tie_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +tie.pack(side=LEFT, padx=15) +com = Entry(frame, textvariable=com_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +com.pack(side=LEFT, padx=50) +frame.pack(pady=10) + +Frame(root, bg="White").pack(fill=X, pady=15) + +b = [[], [], []] +for i in range(3): + frame = Frame(root, highlightbackground="Black", highlightthickness=3, bg="Black") + for j in range(3): + b[i].append(button(frame)) + b[i][j].bind("", functools.partial(click, param1=i, param2=j)) + b[i][j].pack(side=LEFT, padx=5) + frame.pack() + +root.mainloop() diff --git a/TowerOfHanoi.py b/TowerOfHanoi.py new file mode 100644 index 00000000..e3f76e49 --- /dev/null +++ b/TowerOfHanoi.py @@ -0,0 +1,12 @@ +def TowerOfHanoi(Disks, source, temp, destination): + if(Disks == 1): + print("Move Disk 1 From {} to {}".format(source, destination)) + return + TowerOfHanoi(Disks - 1, source, destination, temp) + print("Move Disk {} From {} to {}".format(Disks, source, destination)) + TowerOfHanoi(Disks - 1, temp, source, destination) + +Disks = int(input("Enter Number of Disks: ")) + +# Source : A, Intermediate : B, Destination : C +TowerOfHanoi(Disks, 'A', 'B', 'C') \ No newline at end of file diff --git a/YoutubeDownloader.py b/YoutubeDownloader.py new file mode 100644 index 00000000..c063f64d --- /dev/null +++ b/YoutubeDownloader.py @@ -0,0 +1,32 @@ +#pip install pytube to install library +from pytube import YouTube +link = input("Enter youtube url:") +yt = YouTube(link) + +SAVE_PATH = "E:/" + +#Title of Video +print("Title:",yt.title) + +#Number of Views +print("Views:",yt.views) + +#Length of Video +print("Length of Video:",yt.length,"seconds") + +#Rating of Video +print("Rating:",yt.rating) + +x = input("Do you want video or audio(v/a): ") +if x=="v": + print(yt.streams.filter(progressive=True)) + ys = yt.streams.get_by_itag('22') + +else: + print(yt.streams.filter(only_audio=True)) + ys = yt.streams.get_by_itag('251') + +#Downloading +print("***DOWNLOADING***") +ys.download(SAVE_PATH) +print("***DOWNLOADED***") \ No newline at end of file diff --git a/adventure_game.py b/adventure_game.py new file mode 100644 index 00000000..0acc375b --- /dev/null +++ b/adventure_game.py @@ -0,0 +1,135 @@ +from time import * + +print("Hello! Welcome to the game") +choice = input("Do you want to start the game? Y/N: ").upper() +if choice == 'Y': + print("Let's Go!!") +else: + print("Let's play next time ☹") + sleep(20) +print("""In which path you want to go + A- Concrete road + B- Road in middle of forest + C- Swimming through the ocean\n""") +choice = input("Enter your choice: ").upper() +if choice == 'A': + ch = input("\nThere is a building in the front would u want to enter it? Y/N: ").upper() + if ch == 'Y': + print("\nYou entered the building....") + ch1 = input("Would you like to take the lift (type Y) or go from the stairs (type N)? ").upper() + if ch1 == 'Y': + print("\nYou took the lift and the lift stopped working and it crashed, you died") + sleep(20) + elif ch1 == 'N': + ch2 = input("\nYou reached the terrace u saw a parachute would you like to take it? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou took the parachute and landed on a playground.") + print("You went home empty handed. ") + sleep(20) + elif ch2 == 'N': + print("\nYou can't do anything the building security guard caught you and handed you to the police. ") + print("You failed") + sleep(20) + elif ch == 'N': + ch1 = input("\nYou passed the building and now there is a restaurant would you like to go and have lunch? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou entered the restaurant....") + ch2 = input("You had lunch, would you like to pay the bill(type Y) or run away(type N)? ").upper() + if ch2 == 'Y': + print("\nYou paid the bill but you had no money so the manager called the police and you got arrested") + sleep(20) + elif ch2 == 'N': + print("\nYou ran away... but somehow the police found you so u are arrested") + sleep(20) + elif ch1 == 'N': + print("\nYou were just walking randomly and fell into a manhole...U died") + sleep(20) +elif choice == 'B': + print("\nYou are lost in the forest...") + ch = input("There is a cave in front would you like to enter it? Y/N: ").upper() + if ch == 'Y': + print("\nYou entered the cave there was a giant inside...he wants to become your friend") + ch1 = input("Would you like to become is friend? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou both became friends and he took you to his kingdom made you the price of the kingdom...") + print("You both live a happy life...") + sleep(20) + if ch1 == 'N': + print("\nGiant became angry and ate you raw....RIP") + sleep(20) + elif ch =='N': + print("\nYou ignored the cave and continued your journey") + ch1 = input("You see something buried underground would you like to dig and remove it? Y/N: ").upper() + if ch1 == 'Y': + print("\nLucky you! It was a map and it lead to something ") + ch2 = input("Would you like to follow the map? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou are following the map and you ended up under a big tree and theres a \"X\" mark") + ch3 = input("Would you like to dig it? Y/N: ").upper() + if ch3 == 'Y': + print("\nYou found nothing...") + print("And you got lost in the forest and now you died due to starvation") + sleep(20) + elif ch3 == 'N': + print("\nAnd you got lost in the forest and now you died due to starvation") + sleep(20) + elif ch2 == 'N': + print("\nYou didn't follow the map and went ahead...") + ch3 = input("You saw a \"X\" mark in the ground would you like to dig and see whats there? Y/N: ").upper() + if ch3 == 'Y': + print("\nYou found and treasure worth billions...You realised that the map was a distraction") + print("You are now a billionaire and living your life peacefully") + sleep(20) + elif ch3 == 'N': + print("\nYou went too deep in the forest") + print("You got lost and now you died due to starvation") + sleep(20) + elif ch1 == 'N': + print("\nYou continued your journey and came across a river") + ch2 = input("Would you like to swim and cross the river? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou jumped in the river and there was a crocodile...and you know what happened next lol ") + sleep(20) + elif ch2 == 'N': + print("\nYou went ahead and found a bridge and you crossed the river") + ch3 = input("There are two ways would you like to go right or left? R/L: ").upper() + if ch3 == 'R': + print("\nYou chose the right path and you reached the city and safely went back home!") + sleep(20) + elif ch3 == 'L': + print("\nYou went along the left path...") + print("You saw a cave but you realise that it is the same cave you found at beginning...") + print("And now you are in a infinite loop...Bye Have Fun ") + sleep(20) +elif choice == 'C': + print("\nYou are swimming in the ocean") + ch1 = input("You found an island would like to go there? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou are now walking in the island...") + print("You find that the island is full of cannibals 💀") + ch2 = input("Do you want to run away(type Y) or be friends with them(type N)? ").upper() + if ch2 == 'Y': + print("\nYou are running and there was a bear trap and you stepped on it") + print("They found you....") + sleep(20) + elif ch2 == 'N': + print("\nYou tried to be their friend but you forgot that they don't understand your language...") + print("They thought you were teasing them and they had tasty lunch 🍴") + sleep(20) + elif ch1 == 'N': + print("\nYou ignored the island and swam ahead") + print("You found 2 fisherman in a boat") + ch2 = input("Would you like to join them? Y/N: ").upper() + if ch2 == 'Y': + print("\nThey were very good and they took you with them and you safely made to the land") + print("You are now at home chilling 😎") + sleep(20) + elif ch2 == 'N': + print("\nYou told them that you won't come with them") + print("You are now swimming ahead and you are in middle of nowhere...") + print("You died....") + sleep(20) +else: + print("\nSelect correction option!! ") + sleep(20) + diff --git a/alphabet_rangoli.py b/alphabet_rangoli.py new file mode 100644 index 00000000..eaa0df0e --- /dev/null +++ b/alphabet_rangoli.py @@ -0,0 +1,16 @@ +def print_rangoli(size): + rangoli = [] + l = (size-1)*4+1 + pattern = "" + for i in range(97+size-1, 96, -1): + pattern = f"{pattern}-{chr(i)}" if pattern != "" else chr(i) + leftSide = f"{pattern :->{l//2+1}}" + rightSide = leftSide[-2::-1] + rangoli.append(leftSide + rightSide) + + print('\n'.join(rangoli)) + print('\n'.join(rangoli[-2::-1])) + +if __name__ == '__main__': + n = int(input()) + print_rangoli(n) \ No newline at end of file diff --git a/an4gram.py b/an4gram.py new file mode 100644 index 00000000..6188034e --- /dev/null +++ b/an4gram.py @@ -0,0 +1,45 @@ +#anagram is where both the strings have each characters of the same frequency +#danger and garden is an example of an anagram + +def isanagram(s1,s2): + if(len(s1)!=len(s2)): + return False + + # return sorted(s1) == sorted(s2) + freq1 = {} #declaring dictionaries for mapping purpose + freq2 = {} + + #using dictionary(hash table) for assigning the character as key and no of times it repeated as values + # { + # char1:value1 + # } + for char in s1: + if char in freq1: + freq1[char] += 1 + else: + freq1[char] = 1 + + for char in s2: + if char in freq2: + freq2[char] += 1 + else: + freq2[char] = 1 + + # for every key in dictionary freq1 we are comparing it with the key in dictionary freq2 + # if the key is not found then it will return false + # and simillarly the values from both the dictionaries are being compared + # if any one of the condition is false it will return false "or" is being used + for key in freq1: + if key not in freq2 or freq1[key]!=freq2[key]: + return False + return True + + + +s1 = input("Enter a string\n") +s2 = input("Enter second string\n") + +if isanagram(s1,s2): + print(f"\nThe {s1} and {s2} are Anagrams") +else: + print(f"{s1} and {s2} are not anagram") \ No newline at end of file diff --git a/area-of-circle.py b/area-of-circle.py index ea74423b..b05d9d76 100644 --- a/area-of-circle.py +++ b/area-of-circle.py @@ -1,6 +1,6 @@ def findArea(r): PI = 3.142 - return PI * (r*r); + return PI * (r*r) -print("Area is %.6f" % findArea(5)); +print("Area is %.2f" % findArea(5)) diff --git a/arithmetic_progression.py b/arithmetic_progression.py new file mode 100644 index 00000000..c52e177f --- /dev/null +++ b/arithmetic_progression.py @@ -0,0 +1,31 @@ +########################################################################### + +# Question - Arithmetic Progression Generator + +# # Develop a program that: +# 1- read the first term and the common difference of a arithmetic progression +# 2- show the first 10 terms of this progression +# 3- ask to user if he wants show some more terms +# 4- finish the program when user says he wants to show 0 terms + +########################################################################### + +print("Arithmetic Progression Generator") +print("-=" * 50) +first_term = int(input("First term: ")) +common_difference = int(input("Common difference: ")) +term = first_term +cont = 1 +more = 10 +total = 0 +while more != 0: + total += more + while cont <= total: + print(f"{term}", end=" --> ") + term += common_difference + cont += 1 + + print("PAUSE.\n") + + more = int(input("How many terms you want to show more? ")) +print(f"\n\nArithmetic Progression was finished with {total} terms shown.\n\n") diff --git a/banking_system.py b/banking_system.py new file mode 100644 index 00000000..c729cc91 --- /dev/null +++ b/banking_system.py @@ -0,0 +1,70 @@ +# TODO: +# Parent Class : User +# Holds details about an user +# Has function to show user details +# Child Class : Bank +# Stores details about the account balance +# Stores details about the amount +# Allows for deposit, withdraw and view balance + +# Parent Class +class User(): + def __init__(self,name,age,gender): + self.name = name + self.age = age + self.gender = gender + + def show_details(self): + print(f""" + Personal Details + ------------------------- + Name : {self.name} + Age : {self.age} + Gender : {self.gender} + """) + +# arjun = User('Arjun',20,'Male') +# print(arjun) +# arjun.show_details() + +# Child Class +class Bank(User): + def __init__(self, name, age, gender): + super().__init__(name, age, gender) + self.balance = 0 + + def deposit(self,amount): + self.amount = amount + self.balance += self.amount + print(f"Successfully Deposited : ${self.amount}") + print(f"Current Balance : ${self.balance}") + print() + + def withdraw(self,amount): + self.amount = amount + if self.amount < self.balance: + self.balance -= self.amount + print(f"Successfully Withdrawn ${self.amount}") + print(f"Current Balance : ${self.balance}") + print() + else: + print("Not Enough Balance!!!") + print(f"Current Balance : ${self.balance}") + print() + + def view_balance(self): + self.show_details() + print(" -------------------------") + print(f" Current Balance : ${self.balance}") + print() + +#-------------------------------------------------- + +sbi = Bank('Akshay',20,'Male') +print(sbi) +# sbi.show_details() +# sbi.view_balance() +# sbi.deposit(100) +sbi.deposit(1000) +sbi.withdraw(100) +# sbi.withdraw(1100) diff --git a/binarySearch.py b/binarySearch.py index d815d09c..c6cd336e 100644 --- a/binarySearch.py +++ b/binarySearch.py @@ -28,4 +28,16 @@ def userInput(): else: print("The element was found at index ", result) -userInput() +# Tests ('pip install pytest'; run with 'pytest binarySearch.py') +def test_find_element_in_list(): + arr = [11, 12, 22, 25, 34, 64, 90, 91] + result = binarySearch(arr, 25) + assert result == 3 + +def test_elem_missing(): + arr = [11, 12, 22, 25, 34, 64, 90, 91] + result = binarySearch(arr, 16) + assert result == -1 + +if __name__ == "__main__": + userInput() \ No newline at end of file diff --git a/calendar_program.py b/calendar_program.py new file mode 100644 index 00000000..533a7930 --- /dev/null +++ b/calendar_program.py @@ -0,0 +1,33 @@ +import calendar +''' +Write a Python program that prints the calendar of a given month in a given year after validating the user input. +''' + + +def validate_user_input(): + is_valid_year = False + is_valid_month = False + '''user should enter a valid year''' + while not is_valid_year: + year = input("Enter the year \n format: YYYY: ") + if len(year) == 4 and year.isdigit(): + is_valid_year = True + else: + print("Kindly Enter a vaild four-digit year number") + '''user should enter a valid month''' + while not is_valid_month: + month = input("Enter month \n format: 1-12: ") + if month.isdigit() and 12 >= int(month) >= 1: + is_valid_month = True + else: + print("Kindly Enter a vaild month number between 1 and 12") + return [int(year), int(month)] + + +def print_given_month(): + year, month = validate_user_input() + print(year, month) + print(calendar.month(year, month)) + + +print_given_month() \ No newline at end of file diff --git a/camelCase-to-snake_case.py b/camelCase-to-snake_case.py new file mode 100644 index 00000000..f4833605 --- /dev/null +++ b/camelCase-to-snake_case.py @@ -0,0 +1,9 @@ +name = input("Enter name of variable in camelCase: ") + +j = 0 + +for char in name: + if char.isupper(): + print("_" + char.lower(), end = "") + else: + print(char, end = "") \ No newline at end of file diff --git a/cielingOfNumInList.py b/cielingOfNumInList.py new file mode 100644 index 00000000..4016b27f --- /dev/null +++ b/cielingOfNumInList.py @@ -0,0 +1,26 @@ +# In this problem we have to find a number equal to or the smallest greatest number to the given target number. + +# so we use binary search for this +# case 1: mid==target +# so we have found a number equal to the target. problem solved +# case 2 : element is not in the array +# in this case we would reach the start>end and the while loop would stop. +# and the next greater element would be pointed at by the start. +# so the ceiling of the number would be arr[start]. + +arr =[1,2,3,4,8,9,10,15,19,23,27,29,34,39,45,46,55,59,60,63,68,69] +target = int(input("Enter the target element->")) +start = 0 +end = len(arr)-1 + +while(startarr[mid]: + start=mid+1 +else: + print(f"The ceiling of the element is {arr[start]}") diff --git a/collatz_sequence.py b/collatz_sequence.py new file mode 100644 index 00000000..564afaf8 --- /dev/null +++ b/collatz_sequence.py @@ -0,0 +1,18 @@ +# The Collatz Conjecture is a famous math problem. +# The conjecture is that after applying a sequence of one of two transformations, +# every positive integer will eventually transform into 1. +# The transformations are: divide by 2 if the number is even, multiply by 3 and add 1 if its odd. +# You can see more about it here https://en.wikipedia.org/wiki/Collatz_conjecture + +def collatz(initial_number): + num = initial_number + print(f'Initial number is: {initial_number}') + while num != 1: + print(num) + if num % 2 == 0: + num = int(num / 2) + else: + num = int(3 * num + 1) + else: + print(num) + print('Finally!') \ No newline at end of file diff --git a/college.csv b/college.csv new file mode 100644 index 00000000..bf9d3a22 --- /dev/null +++ b/college.csv @@ -0,0 +1,7 @@ +branch,cgpa,name,year +COE,9.0,Nikhil,2 +COE,9.1,Sanchit,2 +IT,9.3,Aditya,2 +SE,9.5,Sagar,1 +MCE,7.8,Prateek,3 +EP,9.1,Sahil,2 diff --git a/csvgen.py b/csvgen.py new file mode 100644 index 00000000..0485bded --- /dev/null +++ b/csvgen.py @@ -0,0 +1,16 @@ +#This file generates a CSV file with integer values, +# 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. + +import random as rd; + +minNum = 0; +maxNum = 1000; #maximum number in array +lengthOfItems= 500; #this will generate 500 random numbers. + +file = open("newFile.csv", "a") # creates a new file named newFile.csv - feel free to edit file name + +for i in range(lengthOfItems): + file.write(str(str(rd.randint(minNum,maxNum)) + ",")) + +file.close() +#note - you will have to split first line at "," and convert to int diff --git a/dfs.py b/dfs.py new file mode 100644 index 00000000..25244444 --- /dev/null +++ b/dfs.py @@ -0,0 +1,23 @@ +#DFS +n = int(input("Enter the number of nodes : ")) +graph = {}; +for i in range(n): + temp = list(map(str, input().split())) + if len(temp) > 1: + graph[temp[0]] = temp[1:] + else: + graph[temp[0]] = [] + +visited = set(); + +def dfs(visited, graph, node): + if node not in visited: + print(node, end = ' ') + + visited.add(node) + for neighbour in graph[node]: + dfs(visited, graph, neighbour); + +source = str(input("Enter the source node : ")) +print("Following DFS is : ") +dfs(visited, graph, source) \ No newline at end of file diff --git a/dice.py b/dice.py new file mode 100644 index 00000000..2198ce88 --- /dev/null +++ b/dice.py @@ -0,0 +1,146 @@ +"""Simulate a six-sided dice roll. + +Usage: + + $ python dice.py + How many dice do you want to roll? [1-6] 5 + +~~~~~~~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~~~~~~~ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ +│ ● │ │ │ │ ● │ │ ● │ │ ● │ +│ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ +""" + +import random + +DICE_ART = { + 1: ( + "┌─────────┐", + "│ │", + "│ ● │", + "│ │", + "└─────────┘", + ), + 2: ( + "┌─────────┐", + "│ ● │", + "│ │", + "│ ● │", + "└─────────┘", + ), + 3: ( + "┌─────────┐", + "│ ● │", + "│ ● │", + "│ ● │", + "└─────────┘", + ), + 4: ( + "┌─────────┐", + "│ ● ● │", + "│ │", + "│ ● ● │", + "└─────────┘", + ), + 5: ( + "┌─────────┐", + "│ ● ● │", + "│ ● │", + "│ ● ● │", + "└─────────┘", + ), + 6: ( + "┌─────────┐", + "│ ● ● │", + "│ ● ● │", + "│ ● ● │", + "└─────────┘", + ), +} +DIE_HEIGHT = len(DICE_ART[1]) +DIE_WIDTH = len(DICE_ART[1][0]) +DIE_FACE_SEPARATOR = " " + + +def parse_input(input_string): + """Return `input_string` as an integer between 1 and 6. + + Check if `input_string` is an integer number between 1 and 6. + If so, return an integer with the same value. Otherwise, tell + the user to enter a valid number and quit the program. + """ + if input_string.strip() in {"1", "2", "3", "4", "5", "6"}: + return int(input_string) + else: + print("Please enter a number from 1 to 6.") + raise SystemExit(1) + + +def roll_dice(num_dice): + """Return a list of integers with length `num_dice`. + + Each integer in the returned list is a random number between + 1 and 6, inclusive. + """ + roll_results = [] + for _ in range(num_dice): + roll = random.randint(1, 6) + roll_results.append(roll) + return roll_results + + +def generate_dice_faces_diagram(dice_values): + """Return an ASCII diagram of dice faces from `dice_values`. + + The string returned contains an ASCII representation of each die. + For example, if `dice_values = [4, 1, 3, 2]` then the string + returned looks like this: + + ~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~ + ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ + │ ● ● │ │ │ │ ● │ │ ● │ + │ │ │ ● │ │ ● │ │ │ + │ ● ● │ │ │ │ ● │ │ ● │ + └─────────┘ └─────────┘ └─────────┘ └─────────┘ + """ + dice_faces = _get_dice_faces(dice_values) + dice_faces_rows = _generate_dice_faces_rows(dice_faces) + + # Generate header with the word "RESULTS" centered + width = len(dice_faces_rows[0]) + diagram_header = " RESULTS ".center(width, "~") + + dice_faces_diagram = "\n".join([diagram_header] + dice_faces_rows) + return dice_faces_diagram + + +def _get_dice_faces(dice_values): + dice_faces = [] + for value in dice_values: + dice_faces.append(DICE_ART[value]) + return dice_faces + + +def _generate_dice_faces_rows(dice_faces): + dice_faces_rows = [] + for row_idx in range(DIE_HEIGHT): + row_components = [] + for die in dice_faces: + row_components.append(die[row_idx]) + row_string = DIE_FACE_SEPARATOR.join(row_components) + dice_faces_rows.append(row_string) + return dice_faces_rows + + +# ~~~ App's main code block ~~~ +# 1. Get and validate user's input +num_dice_input = input("How many dice do you want to roll? [1-6] ") +num_dice = parse_input(num_dice_input) +# 2. Roll the dice +roll_results = roll_dice(num_dice) +# 3. Generate the ASCII diagram of dice faces +dice_face_diagram = generate_dice_faces_diagram(roll_results) +# 4. Display the diagram +print(f"\n{dice_face_diagram}") diff --git a/dice_roller.py b/dice_roller.py new file mode 100644 index 00000000..c981a987 --- /dev/null +++ b/dice_roller.py @@ -0,0 +1,21 @@ +from random import randint, seed + +# The randint(a,b) function return a pseudorandom number between a and b, including both. +# The seed() function defines a new seed for pseudorandom numbers. + +# This function defines a die roll. If no specific side is defined, it 'rolls' a six-sided die. + +def die(sides=6): + seed() + result = randint(1, sides) + return result + +# This function defines a dice roll. +# If no specific side and number of dies are defined, it 'rolls' a six-sided die. +#Returns a list of ints with the dice rolls. + +def dice(number_of_die=1, sides=6): + rolls = [] + for roll in range(0, number_of_die): + rolls.append(die(sides)) + return rolls \ No newline at end of file diff --git a/dirTree.py b/dirTree.py new file mode 100644 index 00000000..bc5db55f --- /dev/null +++ b/dirTree.py @@ -0,0 +1,29 @@ +import os +import os.path +from pathlib import Path + +def display(path, level = 0): + try : + path = Path(path) + except: + print("Enter right path") + return + k = os.listdir(path) + for i in k: + if os.path.isfile(os.path.join(path, i)): + print(" "*level, "--F--", i) + elif os.path.isdir(os.path.join(path, i)): + print(" "*level, "+-D--", i) + display(os.path.join(path, i), level = level + 1) + else: + print(i) + return + + +if __name__ == "__main__": + print("Enter a path") + s = input() + if s == "" : + s = os.getcwd() + l = 0 + display(s, level = 0) diff --git a/disjoint_set_union.py b/disjoint_set_union.py new file mode 100644 index 00000000..83f360c0 --- /dev/null +++ b/disjoint_set_union.py @@ -0,0 +1,22 @@ +N = 1000 +P = [i for i in range(0,N+1)] # parent +S = [1 for i in range(0,N+1)] # size of set + +def find(u): + if u == P[u]: + return u + else: + P[u] = find(P[u]) + return P[u] + +def union(u,v): + u = find(u) + v = find(v) + if u != v: + # merge smaller set into bigger set + if S[u] < S[v]: + P[u] = v + S[v] += S[u] + else: + P[v] = u + S[u] += S[v] diff --git a/emi-calculator.py b/emi-calculator.py new file mode 100644 index 00000000..e9b570d8 --- /dev/null +++ b/emi-calculator.py @@ -0,0 +1,20 @@ +def emi_calculator(p:float, r:float, t:float): + """EMI Calculator for one months + -------------------------------- + Parameters: + p - principal + r - interest rate per month + t - time period (in years) + """ + r = r / (12 * 100) # one month interest + t = t * 12 # one month period + emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) + return emi + + +principal = float(input("Enter principal amount (in ₹):")) +rate = float(input("Enter Interest Rate per month (%):")) +time = float(input("Enter Time period (in years):")) +emi = emi_calculator(principal, rate, time) +print("Your Monthly EMI is ₹", round(emi,2)) + diff --git a/employee.csv b/employee.csv new file mode 100644 index 00000000..558e682f --- /dev/null +++ b/employee.csv @@ -0,0 +1,6 @@ +name,department,birthday month +John Smith,Accounting,November +Erica Meyers,IT,March +David Warne,Accounting,April +May Myers,IT,October +Ryan Gosling,HR,November \ No newline at end of file diff --git a/fast_recursive_fibonacci.py b/fast_recursive_fibonacci.py new file mode 100644 index 00000000..46fb7cab --- /dev/null +++ b/fast_recursive_fibonacci.py @@ -0,0 +1,21 @@ +def fast_rec_fib_helper(n): + """returns the last two elements of the fibonacci sequence.""" + if n <= 1: + return (0,1) + m = n//2 + hprv, hcur = fast_rec_fib_helper(m) + prev = (hprv ** 2) + (hcur **2) + curr = hcur * (2 * hprv + hcur) + next = prev + curr + if n % 2 == 0: + return (prev, curr) + else: + return (curr, next) + +def fast_rec_fib(n): + if n==0: + return 0 + previous, current = fast_rec_fib_helper(n) + return current + +print(fast_rec_fib(2)) \ No newline at end of file diff --git a/get_coordinates.py b/get_coordinates.py new file mode 100644 index 00000000..33e634ff --- /dev/null +++ b/get_coordinates.py @@ -0,0 +1,10 @@ +from geopy.geocoders import Nominatim + +your_address = str(input()) + +geolocator = Nominatim(user_agent="basic_app") +location = geolocator.geocode(your_address) +if location: + print((location.latitude, location.longitude)) +else: + print("Can not find your address!") \ No newline at end of file diff --git a/hcf_lcm.py b/hcf_lcm.py new file mode 100644 index 00000000..5992f73c --- /dev/null +++ b/hcf_lcm.py @@ -0,0 +1,32 @@ +#Finding HCF in python + +a = int(input("Enter the first number: ")) +b = int(input("Enter the second number: ")) + +HCF = 1 + +for i in range(2,a+1): + if(a%i==0 and b%i==0): + HCF = i + +print("First Number is: ",a) +print("Second Number is: ",b) +print("HCF of the numbers is: ",HCF) + + +#Finding LCM in python +a = int(input("Enter the first number: ")) +b = int(input("Enter the second number: ")) + +HCF = 1 + +for i in range(2,a+1): + if(a%i==0 and b%i==0): + HCF = i + +print("First Number is: ",a) +print("Second Number is: ",b) + +LCM = int((a*b)/(HCF)) +print("LCM of the two numbers is: ",LCM) + diff --git a/huffmantree.py b/huffmantree.py new file mode 100644 index 00000000..ccbc6324 --- /dev/null +++ b/huffmantree.py @@ -0,0 +1,25 @@ +Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +from heapq import heapify as hpf +from heapq import heappop as hpp +from heapq import heappush as hppu +class Node: + def __init(self,ch,freq,left=None,right=None): + self.ch,self.freq=ch,freq + self.left,self.right=left,right + def __lt__(self,other): + return self.freq1: + left,right=hpp(pq),hpp(pq); + newFreq=left.freq+right.freq + hppu(pq,Node(None,newFreq,left,right)) + root=pq[0] + return root + diff --git a/image_compress.py b/image_compress.py new file mode 100644 index 00000000..162e8eb6 --- /dev/null +++ b/image_compress.py @@ -0,0 +1,27 @@ +# For inforation on Pillow visit https://pypi.org/project/Pillow/ +import os, sys +from PIL import Image + +def compressMe(file, verbose = False): + filepath = os.path.join(os.getcwd(), file) + picture = Image.open(filepath) + picture.save("Compressed_"+file, "JPEG", optimize = True, quality = 10) + return + +def main(): + verbose = False + if (len(sys.argv)>1): + if (sys.argv[1].lower()=="-v"): + verbose = True + cwd = os.getcwd() + formats = ('.jpg', '.jpeg') + + for file in os.listdir(cwd): + if os.path.splitext(file)[1].lower() in formats: + print('compressing', file) + compressMe(file, verbose) + print("Done") + +# Driver code +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/img_to_pencil.py b/img_to_pencil.py new file mode 100644 index 00000000..fc4b9c9e --- /dev/null +++ b/img_to_pencil.py @@ -0,0 +1,15 @@ +import cv2 +print("Enter file_name with extension in this folder(image):") +name = input() +print("Enter output file name without extension") +out = input() +out = out+".png" +image = cv2.imread(name) + +grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) +invert = cv2.bitwise_not(grey_img) + +blur = cv2.GaussianBlur(invert, (21, 21), 0) +invertedblur = cv2.bitwise_not(blur) +sketch = cv2.divide(grey_img, invertedblur, scale=256.0) +cv2.imwrite(out, sketch) diff --git a/insertion_sort.py b/insertion_sort.py new file mode 100644 index 00000000..b6b6da16 --- /dev/null +++ b/insertion_sort.py @@ -0,0 +1,12 @@ +def insertion_sort(InputList): + for i in range(1, len(InputList)): + j = i-1 + nxt_element = InputList[i] +# Compare the current element with next one + while (InputList[j] > nxt_element) and (j >= 0): + InputList[j+1] = InputList[j] + j=j-1 + InputList[j+1] = nxt_element +list = [19,2,31,45,30,11,121,27] +insertion_sort(list) +print(list) \ No newline at end of file diff --git a/kadanes_algorithm.py b/kadanes_algorithm.py new file mode 100644 index 00000000..d719823a --- /dev/null +++ b/kadanes_algorithm.py @@ -0,0 +1,18 @@ +""" +This algorithm is used to find the largest sum in the given array in O(n) Time complexity +""" + +arr=[-1,0,3,4,2,6,-10,5,-9] + +max_sum=0 +curr_sum=0 + +for i in arr: + curr_sum += i + max_sum=max(max_sum,curr_sum) + + if curr_sum<0: + curr_sum=0 + + +print(max_sum) \ No newline at end of file diff --git a/mask_email_address.py b/mask_email_address.py new file mode 100644 index 00000000..5cdbd8ea --- /dev/null +++ b/mask_email_address.py @@ -0,0 +1,42 @@ +""" Mask an email address +Search for email addresses in a string, extract the email addresses, mask them and re-insert them in the string. + +Author: Musketeer Computing +Created: 10th October 2022 +""" +import re + + +def main(): + sentence = input("Enter a sentence") + emails = re.findall(r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', sentence) + if not emails: + print(' No email address to mask') + exit() + d_emails = {} + for email in emails: + m_email = mask_email(email) + if m_email == 'error': + print('There was an error when masking the email. Stopping the program') + exit() + d_emails[email] = m_email + for k_email, v_email in d_emails.items(): + sentence = re.sub(k_email, v_email, sentence) + print(sentence) + + +def mask_email(email): + lo = email.find('@') + domain_extension = email.rfind('.') + word_count = len(email) + if lo > 0: + return "{0}#####{1}@{2}###{3}".format(email[0], + email[lo-1], + email[lo+1], + email[domain_extension:word_count]) + else: + return "error" + + +if __name__ == "__main__": + main() diff --git a/meal-of-the-day.py b/meal-of-the-day.py new file mode 100644 index 00000000..3e9be0fa --- /dev/null +++ b/meal-of-the-day.py @@ -0,0 +1,20 @@ +def main(): + x = convert(input("Enter time of the day [in hh:mm 24 hour format] : ")) + + if 7 <= x <= 8: + print("breakfast time") + elif 12 <= x <= 13: + print("lunch time") + elif 18 <= x <= 19: + print("dinner time") + + +def convert(time): + hours, minutes = time.split(":") + hours = int(hours) + minutes = float(minutes)/60 + return hours + minutes + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/medianOf2SortedArray.py b/medianOf2SortedArray.py new file mode 100644 index 00000000..5162d202 --- /dev/null +++ b/medianOf2SortedArray.py @@ -0,0 +1,41 @@ +# Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. +# example 1 +# Input: nums1 = [1,3], nums2 = [2] +# Output: 2.00000 +# Explanation: merged array = [1,2,3] and median is 2. + +#Input: nums1 = [1,2], nums2 = [3,4] +# Output: 2.50000 +# Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + +#nums1 and nums2 are 2 sorted arrays +def findMedianSortedArrays(A, B): + + med1 = med2 = i = j = 0 + n = len(A) + len(B) + + while (i + j) <= n / 2: + if i < len(A) and j < len(B): + med2 = med1 + if A[i] < B[j]: + med1 = A[i] + i += 1 + else: + med1 = B[j] + j += 1 + elif i < len(A): + med2 = med1 + med1 = A[i] + i += 1 + elif j < len(B): + med2 = med1 + med1 = B[j] + j += 1 + + if n % 2 == 0: + return (med1 + med2) / 2.0 + else: + return med1 + + + diff --git a/menu-based_student_record.py b/menu-based_student_record.py new file mode 100644 index 00000000..2d892f77 --- /dev/null +++ b/menu-based_student_record.py @@ -0,0 +1,68 @@ +singlerecord=[] +studList=[] +choice='y' +while choice.lower()!='n': + studName=input('enter your name ') + Rollno=input('enter your Rollno ') + cgpa=int(input('cgpa :')) + singlerecord.append(studName) + singlerecord.append(Rollno) + singlerecord.append(cgpa) + studList.append(singlerecord) + singlerecord=[] + choice=input('enter your choice [y/n]') + +#append +def appendStudent(): + global studList + singlr = [] + studName=input('enter your name') + Rollno=input('enter your Rollno') + cgpa=int(input('cgpa :')) + singlr.append(studName) + singlr.append(Rollno) + singlr.append(cgpa) + studList.append(singlr) + + +# remove existing record by rollno +def removeRecord(): + global studList + rolln=int(input("enter student's rollno:")) + for record in studList: + if rolln in record: + studList.remove(record) + +# view student by name: +def viewRecord(): + name=input("enter student's name:") + for record in studList: + if name in record: + print(record) + +# copy +def copyList(): + print("what to do??") + +#remove all +def removeAll(): + studList.clear() + +flag = 'y' +while (flag == 'y'): + 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")) + if (find == 1): + appendStudent() + elif (find == 2): + removeRecord() + elif (find == 3): + viewRecord() + elif (find == 4): + copyList() + elif (find == 5): + removeAll() + elif (find == 6): + exit + else: + print("enter correct option !!") + flag = input("do u want to continue ? say y or n : \n") diff --git a/notification.py b/notification.py new file mode 100644 index 00000000..bb38b8c1 --- /dev/null +++ b/notification.py @@ -0,0 +1,35 @@ +import time +from plyer import notification +print("Enter the Remainder Message:") +msg = input() +print("Enter the mode of time seconds or minutes or hours") +mode = input() +print("Enter the time left for remainder or time after which remainder should show:") +t = int(input()) +if mode == "seconds": + + time.sleep(t) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + +elif mode == "minutes": + + time.sleep(t*60) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + +elif mode == "hours": + + time.sleep(t*3600) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + \ No newline at end of file diff --git a/novowels.py b/novowels.py new file mode 100644 index 00000000..0fdceb7f --- /dev/null +++ b/novowels.py @@ -0,0 +1,14 @@ +def main(): + sts = str(input("Input: ")) + without_vowels = shorten(sts) + print("Output: " + without_vowels) + +def shorten(word): + lttr = "" + for letter in word: + if not letter.lower() in ['a', 'e', 'i', 'o', 'u']: + lttr += letter + return lttr + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/number_base_converter.py b/number_base_converter.py new file mode 100644 index 00000000..b4d48585 --- /dev/null +++ b/number_base_converter.py @@ -0,0 +1,36 @@ +#################################################################################################### + +# Question +# Write a Python script that reads any integer and asks the user to choose which option to convert: +# 1 for Binary +# 2 for Octal +# 3 for Hexadecimal + +#################################################################################################### +num = 0 +num = int(input("\nDigit an integer positive or -1 to finish: ")) + +while num != -1: + print(""" + Choose one of the bases to convert: + + [ 1 ] convert to BINARY + [ 2 ] convert to OCTAL + [ 3 ] convert to HEXADECIMAL + """) + + option = int(input("Your choose: ")) + + if option == 1: + print(f"\n{num} converted to BINARY is {bin(num)[2:]}") + elif option == 2: + print(f"\n{num} converted to OCTAL is {oct(num)[2:]}") + elif option == 3: + print(f"\n{num} converted to HEXADECIMAL is {hex(num)[2:].upper()}") + else: + print("\n #### Invalid option. Try again. ####") + + num = int(input("\nDigit an integer positive or -1 to finish: ")) + +print("Bye!!!") +#################################################################################################### diff --git a/parse_csv.py b/parse_csv.py new file mode 100644 index 00000000..c3525697 --- /dev/null +++ b/parse_csv.py @@ -0,0 +1,52 @@ +import csv +#read from csv +fields=list() +rows=list() +with open('employee.csv','r') as csv_file: + csv_reader=csv.reader(csv_file) + fields=next(csv_reader) #csv reader object + for row in csv_reader: + rows.append(row) + print("Total no. of rows={}".format(csv_reader.line_num)) +print("Field Names are:"+",".join(field for field in fields)) +print("First 5 rows are:\n") +for row in rows[:5]: + for col in row: + print("{}".format(col),end=" "), + print("\n") +#write to csv +flds=['Name','Branch','Year','CGPA'] +rw= [['Nikhil', 'COE', '2', '9.0'], + ['Sanchit', 'COE', '2', '9.1'], + ['Aditya', 'IT', '2', '9.3'], + ['Sagar', 'SE', '1', '9.5'], + ['Prateek', 'MCE', '3', '7.8'], + ['Sahil', 'EP', '2', '9.1']] +with open("university.csv",'w') as csvfile: + csvwriter=csv.writer(csvfile) + csvwriter.writerow(flds) + csvwriter.writerows(rw) +#write dictionary to csv + +mydict =[{'branch': 'COE', 'cgpa': '9.0', + 'name': 'Nikhil', 'year': '2'}, + {'branch': 'COE', 'cgpa': '9.1', + 'name': 'Sanchit', 'year': '2'}, + {'branch': 'IT', 'cgpa': '9.3', + 'name': 'Aditya', 'year': '2'}, + {'branch': 'SE', 'cgpa': '9.5', + 'name': 'Sagar', 'year': '1'}, + {'branch': 'MCE', 'cgpa': '7.8', + 'name': 'Prateek', 'year': '3'}, + {'branch': 'EP', 'cgpa': '9.1', + 'name': 'Sahil', 'year': '2'}] + +with open("college.csv",'w',newline='') as cv: + fieldnames=["branch","cgpa","name","year"] + writer=csv.DictWriter(cv,fieldnames=fieldnames) + writer.writeheader() + writer.writerows(mydict) +with open("college.csv",'r') as cvf: + reader=csv.DictReader(cvf) + for row in reader: + print(row['name'],row['branch']) \ No newline at end of file diff --git a/perfect_num.py b/perfect_num.py new file mode 100644 index 00000000..ae5e28b9 --- /dev/null +++ b/perfect_num.py @@ -0,0 +1,11 @@ +#Perfect Number or Not Check + +n = int(input("Enter the number : ")) +sum=0 +for i in range(1,n): + if n%i==0: + sum+=i +if sum==n: + print("Perfect !") +else: + print("Nah !") diff --git a/prime factors of a given number.py b/prime factors of a given number.py new file mode 100644 index 00000000..1ccdc9e4 --- /dev/null +++ b/prime factors of a given number.py @@ -0,0 +1,29 @@ +# Python program to print prime factors + +import math + + +def primeFactors(n): + + # Print the number of two\'s that divide n + while n % 2 == 0: + print (2), + n = n / 2 + + # n must be odd at this point + # so a skip of 2 ( i = i + 2) can be used + for i in range(3,int(math.sqrt(n))+1,2): + + # while i divides n , print i ad divide n + while n % i== 0: + print (i), + n = n / i + + + if n > 2: + print (n) + + +n = 315 +primeFactors(n) + diff --git a/print_star_using_loops.py b/print_star_using_loops.py new file mode 100644 index 00000000..66fc5663 --- /dev/null +++ b/print_star_using_loops.py @@ -0,0 +1,15 @@ +print("How Many Row You Want To Print") +one= int(input()) +print("Type 1 Or 0") +two = int(input()) +new =bool(two) +if new == True: + for i in range(1,one+1): + for j in range(1,i+1): + print("*",end=" ") + print() +elif new ==False: + for i in range(one,0,-1): + for j in range(1,i+1): + print("*", end="") + print() diff --git a/python graphics.py b/python graphics.py new file mode 100644 index 00000000..f2bd7e6d --- /dev/null +++ b/python graphics.py @@ -0,0 +1,23 @@ +import random +import turtle +colors = ['violet','indigo','blue','green','yellow','orange','red'] # Added VIBGYOR +t = turtle.Turtle() +t.speed(10) +turtle.bgcolor("black") +length=100 +angle =50 +size=5 +for i in range(length): + color=random.choice(colors) + t.pencolor(color) + t.fillcolor(color) + t.penup() + t.forward(i+50) + t.pendown() + t.left(angle) + t.begin_fill() + t.circle(size) + t.end_fill() +turtle.exitonclick() +turtle.bgcolor("black") + \ No newline at end of file diff --git a/radixSort.py b/radixSort.py new file mode 100644 index 00000000..ae4955fd --- /dev/null +++ b/radixSort.py @@ -0,0 +1,60 @@ +# Python program for implementation of Radix Sort + +# A function to do counting sort of arr[] according to +# the digit represented by exp. +def countingSort(arr, exp1): + + n = len(arr) + + # The output array elements that will have sorted arr + output = [0] * (n) + + # initialize count array as 0 + count = [0] * (10) + + # Store count of occurrences in count[] + for i in range(0, n): + index = (arr[i]/exp1) + count[int((index)%10)] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this digit in output array + for i in range(1,10): + count[i] += count[i-1] + + # Build the output array + i = n-1 + while i>=0: + index = (arr[i]/exp1) + output[ count[ int((index)%10) ] - 1] = arr[i] + count[int((index)%10)] -= 1 + i -= 1 + + # Copying the output array to arr[], + # so that arr now contains sorted numbers + i = 0 + for i in range(0,len(arr)): + arr[i] = output[i] + +# Method to do Radix Sort +def radixSort(arr): + + # Find the maximum number to know number of digits + max1 = max(arr) + + # Do counting sort for every digit. Note that instead + # of passing digit number, exp is passed. exp is 10^i + # where i is current digit number + exp = 1 + while max1/exp > 0: + countingSort(arr,exp) + exp *= 10 + +# Driver code to test above +arr = [ 170, 45, 75, 90, 802, 24, 2, 66] +radixSort(arr) + +for i in range(len(arr)): + print(arr[i],end=" ") + + diff --git a/rainbowSpiral.py b/rainbowSpiral.py new file mode 100644 index 00000000..d4b6979b --- /dev/null +++ b/rainbowSpiral.py @@ -0,0 +1,27 @@ +import turtle +from turtle import * + +turtle.title("rainbow spiral") +speed(15) +bgcolor("black") +r,g,b=255,0,0 + +for i in range(255*2): + colormode(255) + if i<255//3: + g+=3 + elif i<255*2//3: + r-=3 + elif i<255: + b+=3 + elif i<255*4//3: + g-=3 + elif i<255*5//3: + r+=3 + else: + b-=3 + fd(50+i) + rt(91) + pencolor(r,g,b) + +done() diff --git a/random_password_generator.py b/random_password_generator.py new file mode 100644 index 00000000..c7a12fae --- /dev/null +++ b/random_password_generator.py @@ -0,0 +1,22 @@ +import secrets +import string + +letters = string.ascii_letters +digits = string.digits +special_chars = string.punctuation + +alphabet = letters + digits + special_chars + +# fix password length +pwd_length = 12 + +# generate password meeting constraints +while True: + pwd = '' + for i in range(pwd_length): + pwd += ''.join(secrets.choice(alphabet)) + + if (any(char in special_chars for char in pwd) and + sum(char in digits for char in pwd) >= 2): + break +print(pwd) diff --git a/reddit_scraper.py b/reddit_scraper.py new file mode 100644 index 00000000..0b5f9bf4 --- /dev/null +++ b/reddit_scraper.py @@ -0,0 +1,60 @@ +import requests +import csv +import time +from bs4 import BeautifulSoup + + +class HaikuScraper: + """ + This scraper is designed with the purpose of scraping Haikus (Japanese poems) from Reddit. + """ + def __init__(self, url: str, headers: dict): + self.url = url + self.headers = headers + + def make_request(self): + time.sleep(3) + page = requests.get(self.url, headers=self.headers) + soup = BeautifulSoup(page.text, 'html.parser') + return soup + + def get_next_page(self, soup: BeautifulSoup): + time.sleep(3) + next_button = soup.find('span', class_='next-button') + next_page_link = next_button.find("a").attrs['href'] + return next_page_link + + def get_haikus(self, soup: BeautifulSoup): + haikus = [str(title.text) for title in soup.find_all("a", class_="title may-blank ")] + return haikus + + def write_haikus_to_csv(self, haikus: list): + with open('scraped_haikus_v2.txt', 'a') as f: + writer = csv.writer(f) + for haiku in haikus: + writer.writerow([haiku]) + f.close() + + + +url = "https://old.reddit.com/r/haiku/" +# Headers to mimic a browser visit +headers = {'User-Agent': 'Mozilla/5.0'} + +scraper = HaikuScraper(url, headers) +soup = scraper.make_request() + +haikus = scraper.get_haikus(soup) +scraper.write_haikus_to_csv(haikus) + +counter = 1 + +while (counter <= 2500): + time.sleep(2) + link = scraper.get_next_page(soup) + print(f"Page {counter + 1}. Link {link}.") + scraper = HaikuScraper(link, headers) + soup = scraper.make_request() + haikus = scraper.get_haikus(soup) + scraper.write_haikus_to_csv(haikus) + counter += 1 \ No newline at end of file diff --git a/remove-vowels.py b/remove-vowels.py new file mode 100644 index 00000000..4b8d0d43 --- /dev/null +++ b/remove-vowels.py @@ -0,0 +1,9 @@ +vowels = ['a', 'e', 'i', 'o', 'u'] + +text = input("Enter some text: ") + +for char in text: + if(char.lower() in vowels): + continue + else: + print(char, end = '') \ No newline at end of file diff --git a/reverse32bitsignedint.py b/reverse32bitsignedint.py new file mode 100644 index 00000000..986604c2 --- /dev/null +++ b/reverse32bitsignedint.py @@ -0,0 +1,19 @@ +# reverse a 32 bit signed int +# if ans overflows then returns 0 +def reverse32bitsignedint(n): + is_negative = 0 + if n < 0: + is_negative = 1 + n = -n + ans = 0 + while n: + quotient = n // 10 + remainder = n % 10 + n = quotient + ans = ans * 10 + remainder + limit = 1 << 31 + if is_negative: + ans = -ans + if (ans <= -limit) or (ans >= limit - 1): + return 0 + return ans diff --git a/reverse_number.py b/reverse_number.py new file mode 100644 index 00000000..b6298ced --- /dev/null +++ b/reverse_number.py @@ -0,0 +1,29 @@ +"""This file has the function which reverses real integer.""" + + +def reverse_number(number: int) -> int: + """ + This function reverses a number where number can be real integer + """ + if number == 0: + return 0 + + sign = 1 if number > 0 else -1 + number = abs(number) + reverse = 0 + while number > 0: + current_digit = number % 10 + reverse = reverse * 10 + current_digit + number //= 10 + return reverse if sign == 1 else reverse * -1 + +N = 567 +print(reverse_number(N)) + + +N = 0 +print(reverse_number(N)) + + +N = -35670 +print(reverse_number(N)) diff --git a/reverse_words_of_string.py b/reverse_words_of_string.py new file mode 100644 index 00000000..dab11533 --- /dev/null +++ b/reverse_words_of_string.py @@ -0,0 +1,14 @@ +""" + This is Leetcode question: https://leetcode.com/problems/reverse-words-in-a-string/ + +""" + +def reverseWords(s: str) -> str: + s = s.split() + s.reverse() + return " ".join(s) + + +assert reverseWords(" Hello World ")=="World Hello" +assert reverseWords("a good example")=="example good a" +assert reverseWords("okay")=="okay" diff --git a/rupiah_budgeting_plan.py b/rupiah_budgeting_plan.py new file mode 100644 index 00000000..ecb1b6e3 --- /dev/null +++ b/rupiah_budgeting_plan.py @@ -0,0 +1,77 @@ +from turtle import delay +from modul import * +import time + +# assume value is a decimal +def transform_to_rupiah_format(value): + str_value = str(value) + separate_decimal = str_value.split(".") + after_decimal = separate_decimal[0] + before_decimal = separate_decimal[1] + + reverse = after_decimal[::-1] + temp_reverse_value = "" + + for index, val in enumerate(reverse): + if (index + 1) % 3 == 0 and index + 1 != len(reverse): + temp_reverse_value = temp_reverse_value + val + "." + else: + temp_reverse_value = temp_reverse_value + val + + temp_result = temp_reverse_value[::-1] + + return "Rp " + temp_result + ",0" + before_decimal + + +def formatrupiah(uang): + y = str(uang) + if len(y) <= 3: + return 'Rp ' + y + else: + p = y[-3:] + q = y[:-3] + return formatrupiah(q) + '.' + p + + +# default budgeting percentage (single) +living = 0.30 +playing = 0.20 +saving = 0.50 + +# # default budgeting percentage (married) +# living = 0.30 +# playing = 0.15 +# saving = 0.55 + +budget = int(input('Masukkan pemasukan anda: ')) + + +# tiap tiap kategorinya +percent_living = living * 100 +percent_playing = playing * 100 +percent_saving = saving * 100 +percentage = [percent_playing, percent_living, percent_saving] +sum = 00.0 +percent_budget = (living + playing + saving)*100 + +budget_living = budget * living +budget_playing = budget * playing +budgett_saving = budget * saving + +print('========================================================') +for x in percentage: + print('Checking Persen Budgeting '+'{}'.format(sum)+' %'+' (Checking)') + time.sleep(2) + sum += x + +print('Checking Persen Budgeting '+'{}'.format(percent_budget)+'%'+' (Done)') +time.sleep(2) +print('Budgeting anda adalah sebesar {}'.format(formatrupiah(budget))+',00') +print('Pemasukan anda untuk kebutuhan hidup adalah\t: {}'.format( + transform_to_rupiah_format(budget_living))) + +print('Pemasukan anda untuk kegiatan adalah\t\t: {}'.format( + transform_to_rupiah_format(budget_playing))) +print('Pemasukan anda untuk tabungan adalah\t\t: {}'.format( + transform_to_rupiah_format(budgett_saving))) +print('========================================================') diff --git a/selection_sort.py b/selection_sort.py new file mode 100644 index 00000000..c8450f2d --- /dev/null +++ b/selection_sort.py @@ -0,0 +1,48 @@ +# The selection sort algorithm sorts an array by repeatedly finding the minimum element. +# Time Complexity : O(n*n) + +""" +Algorithm :- +Step 1 − Set MIN to location 0 +Step 2 − Search the minimum element in the list +Step 3 − Swap with value at location MIN +Step 4 − Increment MIN to point to next element +Step 5 − Repeat until list is sorted +Pseudocode Selection Sort :- + list : array of items + n : size of list + for i = 1 to n - 1 + /* set current element as minimum*/ + min = i + + /* check the element to be minimum */ + for j = i+1 to n + if list[j] < list[min] then + min = j; + end if + end for + /* swap the minimum element with the current element*/ + if indexMin != i then + swap list[min] and list[i] + end if + end for + +end procedure +""" + + +def selection_sort(alist): + for i in range(0, len(alist) - 1): + smallest = i + for j in range(i + 1, len(alist)): + if alist[j] < alist[smallest]: + smallest = j + alist[i], alist[smallest] = alist[smallest], alist[i] + + +# Created a User-Input Array +alist = input('Enter The Numbers : ').split() +alist = [int(x) for x in alist] +selection_sort(alist) +print('Sorted List: ', end='') +print(alist) \ No newline at end of file diff --git a/sha256_hashing.py b/sha256_hashing.py new file mode 100644 index 00000000..ba166ade --- /dev/null +++ b/sha256_hashing.py @@ -0,0 +1,5 @@ +from hashlib import sha256 +print("Please enter password to be hashed:") +passwd = input() +hashed = sha256(passwd.encode()).hexdigest() +print("Hashed password:\n" + hashed) diff --git a/simple_custom_hash_map_implementation.py b/simple_custom_hash_map_implementation.py new file mode 100644 index 00000000..83a70919 --- /dev/null +++ b/simple_custom_hash_map_implementation.py @@ -0,0 +1,79 @@ +# This class is to demonstate the how Hashmap generally works +# Feel free to make changes and play with it + +class MyHashMap: + def __init__(self, max_size=10): + self.MAX_SIZE = max_size + self.map = [None] * self.MAX_SIZE + + # function will return index in the array based on the key + def _hash_function(self, key): + if type(key) == str: + hash_val = 0 + for i in range(len(key)): + hash_val += ((i+1)*ord(key[i])) + else: + hash_val = int(key) + + return hash_val % self.MAX_SIZE + + # function to add key and value and + # if key already present updates the value + def add(self, key, val): + idx = self._hash_function(key) + if self.map[idx] is None: + self.map[idx] = [[key, val]] + else: + if self.is_present(key): + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + self.map[idx][i][1] = val + else: + self.map[idx].append([key, val]) + + # returns value if key exits + # else raises an error + def get(self, key): + if self.is_present(key): + idx = self._hash_function(key) + for key_val in self.map[idx]: + if key_val[0] == key: + return key_val[1] + else: + raise KeyError("Key: {} doesn't exist".format(key)) + + # deletes a value if key exists + # else raises error + def delete(self, key): + if self.is_present(key): + idx = self._hash_function(key) + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + del self.map[idx][i] + else: + raise KeyError("Key: {} doesn't exist".format(key)) + + # returns True if key exists + # else False + def is_present(self, key): + idx = self._hash_function(key) + + if self.map[idx] is None: + return False + + for key_val in self.map[idx]: + if key_val[0] == key: + return True + + return False + + +if __name__ == '__main__': + h = MyHashMap() + h.add('name', "Hari") + h.add('roll', 202089) + h.add('name', "kiran") + h.add(3.2, 'float') + print(h.get('name')) + print(h.get('roll')) + print(h.get(3.2)) diff --git a/simple_vending_machine.py b/simple_vending_machine.py new file mode 100644 index 00000000..b9582807 --- /dev/null +++ b/simple_vending_machine.py @@ -0,0 +1,35 @@ +a=dict() +key_list=list() +def readFile(): + with open("vendingitems.txt",'r') as f: + for line in f: + (k,v)=line.strip().split('|') + a[k]=int(v) + key_list=a.keys() + print("Items available in vending machine",key_list) + +def vendingMachine(): + readFile() + while True: + item=input("Enter item name\n") + if(item in a.keys()): + print("Valid Item Name") + #break + cash=int(input("Enter money to deposit\n")) + if(isinstance(cash,int)==False): + print("Bad Input {}\n Try Again!".format(str(cash))) + #continue + else: + if(cash>a[item]): + print("Thank you for your purchase.Enjoy\n") + print("Do not forget to collect your change,{} Rs".format(cash-a[item])) + break + else: + print("Not enough Money to but the item\n") + continue + else: + print("Available Items are {} ,\nTry Again!".format(a.keys())) + continue + + +vendingMachine() \ No newline at end of file diff --git a/strong.py b/strong.py new file mode 100644 index 00000000..13cf2dc5 --- /dev/null +++ b/strong.py @@ -0,0 +1,16 @@ +sum1=0 +num=int(input("Enter a number:")) +temp=num +while(num): + i=1 + f=1 + r=num%10 + while(i<=r): + f=f*i + i=i+1 + sum1=sum1+f + num=num//10 +if(sum1==temp): + print("The number is a strong number") +else: + print("The number is not a strong number") diff --git a/substring.py b/substring.py new file mode 100644 index 00000000..657abe9e --- /dev/null +++ b/substring.py @@ -0,0 +1,19 @@ +def substring(str1,n): + for i in range(0,n): + for j in range(i+1,n+1): + # Printing the substrings using slicing + # Suppose we have str1="Hello" Str1[0:1] will print "H" + # Str1[1:2] will print "He" + # Str1[1:3] will print "Hel" + # Str1[1:4] will print "Hell" + # Str1[1:5] will print "Hello" + # then i will increment i=2 + # Str1[2:3] will print "e" + # Str1[2:4] will print "el" + # And So On + print(str1[i:j]) + + +str1 = input("Enter a String:") +n=len(str1) +substring(str1,n) \ No newline at end of file diff --git a/subtitle_synchronizer.py b/subtitle_synchronizer.py new file mode 100644 index 00000000..65d55991 --- /dev/null +++ b/subtitle_synchronizer.py @@ -0,0 +1,65 @@ +def convertToMilliseconds(time): + milliseconds = 0 + hh,mm,ms = time.split(":") + ms = ms.strip().replace(",","") + hh = int(hh) + mm = int(mm) + ms = int(ms) + + milliseconds = hh*3600000+mm*60000+ms + return milliseconds + +def synchronize(time,shift): + return time-shift + +def convertToTime(milliseconds): + hh = milliseconds//3600000 + milliseconds = milliseconds%3600000 + hh = str(hh) + if len(hh) < 2: hh = "0"+hh + + mm = milliseconds//60000 + milliseconds = milliseconds%60000 + mm = str(mm) + if len(mm) < 2: mm = "0"+mm + + ss = milliseconds//1000 + milliseconds = milliseconds%1000 + ss = str(ss) + if len(ss) < 2: ss = "0"+ss + + milliseconds = str(milliseconds) + while len(milliseconds) < 3: + milliseconds = "0"+milliseconds + + return f"{hh}:{mm}:{ss},{milliseconds}" + + +def main(): + SHIFT = int(input("Please enter the shift in milliseconds: ")) + f = open("input.txt", "r", errors="ignore") + output = open("output.txt","a") + for x in f: + if "-->" in x: + start,end = x.split("-->") + start,end = convertToMilliseconds(start), convertToMilliseconds(end) + start,end = synchronize(start,SHIFT),synchronize(end,SHIFT) + start,end = convertToTime(start),convertToTime(end) + output.write(f"{start} --> {end}\n") + else: + output.write(x) + + +#Right click the subtitles file you want to synchronize and open it in a notepad +#Then copy all of its content and paste it into a new file and name it as "input.txt" + +#You must have your "input.txt" in the same folder as this program + +#Once you run this program you will be asked to enter a shift in milliseconds. + +#You can find the shift when you are watching the video as it is impossible to +#determine that using any program since it is variable for every video. + +#Once the program has finished running, you will have your subtitles synchronized +#in a file that says "output.txt". Copy its content and paste it into your original subtitles file. +main() \ No newline at end of file diff --git a/text-audio-generator.py b/text-audio-generator.py new file mode 100644 index 00000000..cd6e8c6f --- /dev/null +++ b/text-audio-generator.py @@ -0,0 +1,15 @@ +''' + Before running this code, do type these commands in command prompt. + --> pip install gTTS + --> pip install playsound +''' +from gtts import gTTS + +from playsound import playsound +text_val = input("Enter the text which you want to convert: ") # Example : 'Learn Some Cool and Basic Python Programs here.' # + +language = 'en' +obj = gTTS(text=text_val, lang=language, slow=False) +obj.save("python.mp3") # This helps to save our audio file in the existing folder. + +playsound("python.mp3") # This runs the audio when you run the program. \ No newline at end of file diff --git a/text-to-emoji.py b/text-to-emoji.py new file mode 100644 index 00000000..f79bb8be --- /dev/null +++ b/text-to-emoji.py @@ -0,0 +1,7 @@ +def main(): + print(convert(input("Enter any text: "))) + +def convert(text): + return text.replace(":(", "🙁").replace(":)", "🙂") + +main() \ No newline at end of file diff --git a/turtle race.py b/turtle race.py new file mode 100644 index 00000000..4693c252 --- /dev/null +++ b/turtle race.py @@ -0,0 +1,48 @@ +from turtle import Turtle +from random import randint + +aman=Turtle() +aman.color('blue') +aman.shape('turtle') +aman.penup() +aman.goto(-180,100) +aman.pendown() + +swati=Turtle() +swati.color('red') +swati.shape('turtle') +swati.penup() +swati.goto(-180,70) +swati.pendown() + +ram=Turtle() +ram.color('green') +ram.shape('turtle') +ram.penup() +ram.goto(-180,40) +ram.pendown() + +krishna=Turtle() +krishna.color('dark blue') +krishna.shape('turtle') +krishna.penup() +krishna.goto(-180,10) +krishna.pendown() + +for movement in range(100): + aman.forward(randint(1,5)) + swati.forward(randint(1, 5)) + ram.forward(randint(1, 5)) + krishna.forward(randint(1, 5)) +if aman.position() > (swati.position() and ram.position()and krishna.position()): + print(("Aman won the race")) +elif swati.position()>(aman.position() and ram.position() and krishna.position()): + print("swati won the race") +elif ram.position()> (aman.position() and swati.position() and krishna.position()): + print("ram won the race") +else: + print("Krishna won the race") + + + +input(" ...") diff --git a/two_sum_using_two_pointers.py b/two_sum_using_two_pointers.py new file mode 100644 index 00000000..de142cb4 --- /dev/null +++ b/two_sum_using_two_pointers.py @@ -0,0 +1,21 @@ +# This function takes 2 parameters the numbers array and the target +# If the target is found it returns the indices of the numbers which add up to the target +# If not found, it returns [-1,-1] + +# Time Complexity for this is O(NlogN) due to sorting +# Space Complexity is O(1) because we are not using any additional space + +def twoSum(nums, target): + nums.sort() + l, r = 0, len(nums) - 1 + + while l < r: + cur_sum = nums[l] + nums[r] + if cur_sum < target: + l += 1 + elif cur_sum > target: + r -= 1 + else: + return [l, r] + + return [-1, -1] diff --git a/university.csv b/university.csv new file mode 100644 index 00000000..eee3eaf5 --- /dev/null +++ b/university.csv @@ -0,0 +1,7 @@ +Name,Branch,Year,CGPA +Nikhil,COE,2,9.0 +Sanchit,COE,2,9.1 +Aditya,IT,2,9.3 +Sagar,SE,1,9.5 +Prateek,MCE,3,7.8 +Sahil,EP,2,9.1 diff --git a/vendingitems.txt b/vendingitems.txt new file mode 100644 index 00000000..4e791db0 --- /dev/null +++ b/vendingitems.txt @@ -0,0 +1,5 @@ +Potato Chips|20 +Popcorn|30 +Chocolate|15 +Biscuit|10 +Soft Drink|12 \ No newline at end of file diff --git a/video_jpeg_converter.py b/video_jpeg_converter.py new file mode 100644 index 00000000..268f44c9 --- /dev/null +++ b/video_jpeg_converter.py @@ -0,0 +1,44 @@ +# File name: video_jpeg_converter.py +# Objective: To return a set of continuous JPEG images from an input video (useful for annotation of videos) + +from imutils import paths +import cv2 +import os + +# Path for input videos (which will be converted to a series of JPEG images) +dataPath = str(input("Copy the path to your video input data and paste it here: ")) + +# Path for output JPEG images +outPath = str(input("Copy the path to your output folder storing the JPEG images and paste it here: ")) + +for classPath in os.listdir(dataPath): + clipPaths = os.listdir(dataPath + "\\" + classPath) + os.mkdir((outPath + '\\' + classPath)) + + k = 1 + for clips in clipPaths: + os.mkdir((outPath + '\\' + classPath + '\\' + clips)) + os.chdir((outPath + '\\' + classPath + '\\' + clips)) + + f = dataPath + "\\" + classPath + "\\" + clips + cam = cv2.VideoCapture(f) + ret, frame = cam.read() + currentframe = 0 + i = 0 + + # a variable to set how many frames you want to skip + frame_skip = 5 # Since the videos are in 30 FPS, and we want 10 frames per clip + + while cam.isOpened(): + ret, frame = cam.read() + k += 1 + if not ret: + break + if (i > frame_skip - 1): + cv2.imwrite(classPath + '_' + clips + '_' + str(k) +'.jpg', frame) + i = 0 + continue + i += 1 + + cam.release() + cv2.destroyAllWindows() \ No newline at end of file diff --git a/weather_gui.py b/weather_gui.py new file mode 100644 index 00000000..20c9fdf7 --- /dev/null +++ b/weather_gui.py @@ -0,0 +1,42 @@ +import tkinter as tk +import requests +import time + + +def getWeather(canvas): + city = textField.get() + api = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=06c921750b9a82d8f5d1294e1586276f" + + json_data = requests.get(api).json() + condition = json_data['weather'][0]['main'] + temp = int(json_data['main']['temp'] - 273.15) + min_temp = int(json_data['main']['temp_min'] - 273.15) + max_temp = int(json_data['main']['temp_max'] - 273.15) + pressure = json_data['main']['pressure'] + humidity = json_data['main']['humidity'] + wind = json_data['wind']['speed'] + sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600)) + sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600)) + + final_info = condition + "\n" + str(temp) + "°C" + final_data = "\n"+ "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str(max_temp) + "°C" +"\n" + "Pressure: " + str(pressure) + "\n" +"Humidity: " + str(humidity) + "\n" +"Wind Speed: " + str(wind) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset + label1.config(text = final_info) + label2.config(text = final_data) + + +canvas = tk.Tk() +canvas.geometry("600x500") +canvas.title("Weather App") +f = ("poppins", 15, "bold") +t = ("poppins", 35, "bold") + +textField = tk.Entry(canvas, justify='center', width = 20, font = t) +textField.pack(pady = 20) +textField.focus() +textField.bind('', getWeather) + +label1 = tk.Label(canvas, font=t) +label1.pack() +label2 = tk.Label(canvas, font=f) +label2.pack() +canvas.mainloop() diff --git a/webscraper.py b/webscraper.py new file mode 100644 index 00000000..24907aeb --- /dev/null +++ b/webscraper.py @@ -0,0 +1,16 @@ +import requests +from bs4 import BeautifulSoup +# Make a request +page = requests.get("Paste a Domain here") +soup = BeautifulSoup(page.content, 'html.parser') + +# Create all_h1_tags as empty list +all_h1_tags = [] + +# Set all_h1_tags to all h1 tags of the soup +for element in soup.select('h1'): + all_h1_tags.append(element.text) + +print(all_h1_tags) + +# give you all h1 tags \ No newline at end of file diff --git a/weightConverterGUI.py b/weightConverterGUI.py new file mode 100644 index 00000000..8242c6fa --- /dev/null +++ b/weightConverterGUI.py @@ -0,0 +1,37 @@ +from tkinter import * +window = Tk() +def from_kg(): + gram = float(e2_value.get())*1000 + pound = float(e2_value.get())*2.20462 + ounce = float(e2_value.get())*35.274 + t1.delete("1.0",END) + t1.insert(END, gram) + t2.delete("1.0", END) + t2.insert(END, pound) + t3.delete("1.0", END) + t3.insert(END, ounce) + +e1 = Label(window, text="Input the weight in KG") +e2_value = StringVar() +e2 = Entry(window, textvariable=e2_value) +e3 = Label(window, text="Gram") +e4 = Label(window, text="Pound") +e5 = Label(window, text="Ounce") + +t1 = Text(window, height=5, width=30) +t2 = Text(window, height=5, width=30) +t3 = Text(window, height=5, width=30) + +b1 = Button(window, text="Convert", command=from_kg) + +e1.grid(row=0, column=0) +e2.grid(row=0, column=1) +e3.grid(row=1, column=0) +e4.grid(row=1, column=1) +e5.grid(row=1, column=2) +t1.grid(row=2, column=0) +t2.grid(row=2, column=1) +t3.grid(row=2, column=2) +b1.grid(row=0, column=2) + +window.mainloop()