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/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/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/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/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/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/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/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/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/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/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/SI_units.py b/SI_units.py new file mode 100644 index 00000000..840f50b8 --- /dev/null +++ b/SI_units.py @@ -0,0 +1,26 @@ + +#converting pounds to kg + +def pounds_to_kg(pounds): + return pounds*0.453592 + +def feet_to_meters(feet): + return feet*0.3048 + +def inches_to_meters(inches): + return inches*0.0254 + +def yards_to_meters(yards): + return yards*0.9144 + +def miles_to_meters(miles): + return miles*1609.34 + +def miles_per_hour_to_ms(miles_per_hour): + return miles_per_hour*0.44704 + +def celsius_to_kelvin(celsius): + return celsius + 273.15 + +def farenheit_to_kelvin(farenheit): + return ((farenheit - 32)/1.8) +273.15 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/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/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/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/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/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/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/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/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/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/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/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/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/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/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