├── .DS_Store ├── FunProjects ├── AtmMachineSimulator.py ├── Grades.py ├── MasterMind.py ├── NumberGuess.py ├── arrayCompare.py ├── directions.py ├── hangman.py ├── libraryManage.py ├── monkey.py ├── quiz_main.py ├── rockPaperSiss.py ├── snakeLadder.py ├── subStr.py ├── ticTacToe_main.py └── todoApp.py ├── README.md ├── docs ├── FAQ.md ├── SETUP.md └── contributions.md ├── problems ├── .DS_Store ├── easy │ ├── easy_q1.py │ ├── easy_q10.py │ ├── easy_q11.py │ ├── easy_q12.py │ ├── easy_q13.py │ ├── easy_q14.py │ ├── easy_q15.py │ ├── easy_q16.py │ ├── easy_q17.py │ ├── easy_q18.py │ ├── easy_q2.py │ ├── easy_q3.py │ ├── easy_q4.py │ ├── easy_q5.py │ ├── easy_q6.py │ ├── easy_q7.py │ ├── easy_q8.py │ └── easy_q9.py ├── hard │ ├── Desc.md │ ├── PET.py │ └── expenses.json └── medium │ ├── m1.py │ ├── m10.py │ ├── m11.py │ ├── m12.py │ ├── m13.py │ ├── m14.py │ ├── m15.py │ ├── m16.py │ ├── m17.py │ ├── m2.py │ ├── m3.py │ ├── m4.py │ ├── m5.py │ ├── m6.py │ ├── m7.py │ ├── m8.py │ └── m9.py └── tests └── contribute-test.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mathi27/ErrorHunter/8b0c80702fd40e9e56fa7a75d1057c2815fdc49b/.DS_Store -------------------------------------------------------------------------------- /FunProjects/AtmMachineSimulator.py: -------------------------------------------------------------------------------- 1 | class ATM: 2 | def __init__(self, balance): 3 | self.balance = balance 4 | 5 | def deposit(self, amount): 6 | 7 | global deposit_history 8 | if amount <= 0: 9 | 10 | if amount >= 0: 11 | 12 | print("Amount must be positive.") 13 | else: 14 | self.balance += amount 15 | print(f"Deposited {amount}. Current balance: {self.balance}") 16 | 17 | deposit_history[count] = self.balance 18 | 19 | 20 | def withdraw(self, amount): 21 | global withdraw_history 22 | if amount <= 0: 23 | print("Amount must be positive.") 24 | if amount > self.balance: 25 | print("Insufficient funds!") 26 | else: 27 | self.balance -= amount 28 | print(f"Withdrew {amount}. Current balance: {self.balance}") 29 | withdraw_history[count] = self.balance 30 | def main(): 31 | global atm 32 | current_amnt = int(input("Enter the initial balance of your Account: ")) 33 | atm = ATM(current_amnt) 34 | def both(): 35 | global withdraw_history 36 | global deposit_history 37 | global result 38 | d=1 39 | result.update(deposit_history) 40 | result.update(withdraw_history) 41 | for i in range(1,len(result)+1): 42 | if d in result.keys(): 43 | print(f"{d} : {result[d]}") 44 | d+=1 45 | 46 | 47 | 48 | withdraw_history = {} 49 | deposit_history = {} 50 | result = {} 51 | count=1 52 | main() 53 | while True: 54 | print("************************* ATM Simulator *****************************") 55 | print(""" 56 | 1.Deposit 57 | 2.Withdrawal 58 | 3.Transaction History 59 | 4.Exit 60 | """) 61 | print("*********************************************************************") 62 | n=int(input("Enter your choice: ")) 63 | if n==1: 64 | a = int(input("Enter the Amount to be Depositted: ")) 65 | atm.deposit(a) 66 | count+=1 67 | elif n==2: 68 | b = int(input("Enter the Amount to be Withdrawn: ")) 69 | atm.withdraw(b) 70 | count+=1 71 | elif n==3: 72 | if withdraw_history == {} and deposit_history == {}: 73 | print("###NO TRANSACTION HAS BEEN DONE###") 74 | else: 75 | print("----------------------------------- Transaction History -------------------") 76 | print(''' 77 | 1.Withdraw History 78 | 2.Deposit History 79 | 3.Both Withdraw and Deposit history''') 80 | print("---------------------------------------------------------------------------") 81 | c=int(input("Enter your choice: ")) 82 | if c==1: 83 | print("When : How Much Amount Withdrawn") 84 | for i in withdraw_history: 85 | print(f"{i} : {withdraw_history[i]}") 86 | elif c==2: 87 | print("When : How Much Amount Depositted") 88 | for i in deposit_history: 89 | print(f"{i} : {deposit_history[i]}") 90 | elif c==3: 91 | both() 92 | else: 93 | print("###INVALID CHOICE###") 94 | 95 | elif n==4: 96 | print("Exiting .....") 97 | break 98 | else: 99 | print("###INVALID CHOICE###") 100 | 101 | atm = ATM(1000) 102 | atm.deposit(200) 103 | atm.withdraw(1500) 104 | atm.withdraw(500) 105 | 106 | -------------------------------------------------------------------------------- /FunProjects/Grades.py: -------------------------------------------------------------------------------- 1 | class StudentGrades: 2 | def __init__(self): 3 | self.grades = {} 4 | 5 | def add_grade(self, student, grade): 6 | self.grades[student] = grade 7 | print(student,"Grade is ",self.grades[student]) 8 | def calculate_average(self): 9 | total = sum(self.grades.values()) 10 | average = total / len(self.grades) 11 | return average 12 | 13 | # Example Usage 14 | grades = StudentGrades() 15 | grades.add_grade("John", 85) 16 | grades.add_grade("Sarah", 90) 17 | grades.add_grade("Mike", 78) 18 | print("Average grade:", grades.calculate_average()) -------------------------------------------------------------------------------- /FunProjects/MasterMind.py: -------------------------------------------------------------------------------- 1 | 2 | '''A low-level implementation of the classic game “Mastermind”. We need to write a program that generates a four-digit random 3 | code and the user needs to guess the code in 10 tries or less. If any digit out of the guessed four-digit code is wrong, 4 | the computer should print out “B”. If the digit is correct but at the wrong place, the computer should print “Y”. 5 | If both the digit and position is correct, the computer should print “R”''' 6 | 7 | 8 | import random 9 | def gen_code(): 10 | set_code = [] 11 | 12 | for i in range(4): 13 | val = random.randint(0, 9) 14 | set_code.append(val) 15 | 16 | return set_code 17 | 18 | 19 | def input_code(): 20 | code = input("Enter your four digit guess code: ") 21 | return code 22 | 23 | 24 | 25 | def mastermind(): 26 | 27 | genCode = gen_code() 28 | i = 0 29 | 30 | while i < 10: 31 | result = "" 32 | inputCode = [int(c) for c in input_code()] 33 | 34 | if len(inputCode) != 4: 35 | print("Enter only 4 digit number") 36 | continue 37 | 38 | if inputCode == genCode: 39 | print("You guessed it !", genCode) 40 | break 41 | 42 | for element in inputCode: 43 | 44 | if element in genCode: 45 | 46 | if inputCode.index(element) == genCode.index(element): 47 | result+="R" 48 | else: 49 | result+="Y" 50 | else: 51 | result+="B" 52 | print(result) 53 | 54 | i += 1 55 | else: 56 | print("You ran out of trys !", genCode) 57 | 58 | 59 | # Driver Code 60 | mastermind() -------------------------------------------------------------------------------- /FunProjects/NumberGuess.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def guess_the_number(): 4 | print("Welcome to Guess the Number!") 5 | target = random.randint(1, 100) 6 | attempts = 0 7 | 8 | while True: 9 | try: 10 | 11 | guess = int(input("Enter your guess (1-100): "))1 12 | 13 | 14 | 15 | attempts += 1 16 | if guess < target: 17 | print("Too low!") 18 | elif guess > target: 19 | 20 | 21 | guess = int(input("Enter your guess (1-100): ")) 22 | 23 | 24 | 25 | attempts += 1 26 | if guess < target: 27 | 28 | print("Too high!") 29 | elif guess > target: 30 | print("Too low!") 31 | else: 32 | print(f"Congratulations! You guessed it in {attempts} attempts.") 33 | break 34 | except ValueError: 35 | print("Invalid input! Please enter a valid number.") 36 | guess_the_number() 37 | 38 | def main(): 39 | while True: 40 | print("\nMenu:") 41 | print("1. Play Guess the Number") 42 | print("2. Exit") 43 | 44 | 45 | try: 46 | choice = input("Enter your choice: ") 47 | if choice in (1,2): 48 | break 49 | else: 50 | print("Enter either 1 or 2") 51 | except: 52 | print("Enter either 1 or 2") 53 | 54 | choice = int(input("Enter your choice: ")) 55 | 56 | 57 | if choice == "1": 58 | guess_the_number() 59 | elif choice == "2": 60 | print("Thanks for playing!") 61 | else: 62 | print("Invalid choice! Please enter 1 to play or 2 to exit.") 63 | 64 | main() 65 | -------------------------------------------------------------------------------- /FunProjects/arrayCompare.py: -------------------------------------------------------------------------------- 1 | '''Comparing arrays''' 2 | 3 | '''This problem helps one to understand the key concepts of an array(list) in Python. 4 | Two arrays are said to be the same if they contain the same elements and in the same order. 5 | However, in this problem, we will compare two arrays to see if they are same, but with a slight twist. 6 | Here, two arrays are the same if the elements of one array are squares of elements of other arrays and regardless of the order. 7 | Consider two arrays a and b. 8 | 9 | ''' 10 | # function to compare the arrays 11 | def comp(array1, array2): 12 | 13 | # Handle edge cases where one or both arrays could be None 14 | if array1 is None or array2 is None: 15 | return array1 == array2 # Return True only if both are None 16 | 17 | # Check if sorted squares of array1 are equal to sorted elements of array2 18 | return (sorted(array1) == sorted([i ** 2 for i in array2])) or (sorted(array2) == sorted([i ** 2 for i in array1])) 19 | 20 | # Example usage: 21 | print(comp([1, 2, 3, 4], [1, 4, 9, 16])) 22 | 23 | if array1 == [] and array2 != []: 24 | return False 25 | 26 | 27 | if (sorted(array2) == sorted([i ** 2 for i in array1])) or (sorted(array1) == sorted([i ** 2 for i in array2])): 28 | print("the two arrays are equal is one of the array is equal to square of another array") 29 | 30 | return 31 | 32 | 33 | if (sorted(array1) == sorted([i ** 0.5 for i in array2])) and (sorted(array2) == sorted([i ** 2 for i in array1])): 34 | return True 35 | else: 36 | return False 37 | 38 | 39 | result = comp([1,2,3,4], [1,4,9,16]) 40 | if result: 41 | print("The two arrays are same as the given condition") 42 | else: 43 | print("The two arrays are not same as the given condition") 44 | 45 | if array1 is None and array2 is not None: 46 | print("The two arrays are not same ") 47 | 48 | return False 49 | 50 | 51 | 52 | if (sorted(array2) == sorted([i ** 2 for i in array1])) and (sorted(array2) == sorted([i ** 2 for i in array1])): 53 | 54 | if (sorted(array1) == sorted([i ** 2 for i in array2])) or (sorted(array2) == sorted([i ** 2 for i in array1])): 55 | print(" if the two arrays are same or the elements of the first array are the square of the elements of the second array!! ") 56 | 57 | if array1 is None or array2 is None: 58 | return False 59 | 60 | 61 | if (sorted(array2) == sorted([i ** 2 for i in array1])): 62 | 63 | 64 | return True 65 | 66 | return False 67 | 68 | 69 | 70 | print(comp([1,2,3,4], [1,4,9,16])) 71 | 72 | lis1=eval(input("Enter list 1: ")) 73 | lis2=eval(input("Enter list 2: ")) 74 | print(comp(lis1,lis2)) 75 | 76 | 77 | 78 | print(comp([1,2,3,4], [1,4,9,16])) 79 | 80 | 81 | -------------------------------------------------------------------------------- /FunProjects/directions.py: -------------------------------------------------------------------------------- 1 | '''Direction Catastrophe''' 2 | 3 | '''A very simple problem with many different solutions, but the main aim is to solve it in the most efficient way. A man was given directions to go from point A to point B. The directions were: “SOUTH”, “NORTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too. Going to one direction and coming back in the opposite direction is a waste of time and energy. So, we need to help the man by writing a program that will eliminate the useless steps and will contain only the necessary directions. 4 | For example: The directions [“NORTH”, “SOUTH”, “SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”] should be reduced to [“WEST”]. This is because going “NORTH” and then immediately “SOUTH” means coming back to the same place. So we cancel them and we have [“SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”]. Next, we go “SOUTH”, take “EAST” and then immediately take “WEST”, which again means coming back to the same point. Hence we cancel “EAST” and “WEST” to giving us [“SOUTH”, “NORTH”, “WEST”]. It’s clear that “SOUTH” and “NORTH” are opposites hence canceled and finally we are left with [“WEST”]. 5 | ''' 6 | 7 | 8 | def reduce_dir(dt): 9 | 10 | 11 | 12 | def reduce_dir(directions): 13 | 14 | opposite = { 15 | "EAST": "WEST", 16 | "WEST": "EAST", 17 | "NORTH": "SOUTH", 18 | "SOUTH": "NORTH", 19 | 20 | } 21 | stack = [] 22 | 23 | 24 | for d in dt: 25 | if stack and opposite[d] == stack[-1]: 26 | stack.pop() 27 | else: 28 | 29 | for d in directions: 30 | if stack and opposite[d] == stack[-1]: 31 | 32 | 33 | 34 | 35 | stack.pop() 36 | 37 | 38 | stack.pop() 39 | 40 | else: 41 | 42 | 43 | stack.append(d) 44 | print(stack) 45 | 46 | return stack 47 | 48 | dir = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] 49 | reduce_dir(dir) 50 | 51 | return stack 52 | 53 | dir = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] 54 | reduce_dir(dir) 55 | 56 | 57 | stack.append(d) 58 | 59 | return stack 60 | 61 | directions = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] 62 | 63 | print(reduce_dir(directions)) 64 | 65 | result = reduce_dir(directions) 66 | print(result) 67 | 68 | 69 | -------------------------------------------------------------------------------- /FunProjects/hangman.py: -------------------------------------------------------------------------------- 1 | def hangman(): 2 | word = "hello" 3 | guessed = ["_"] * len(word) 4 | attempts = 6 5 | used_letters = set() 6 | 7 | print("Word to guess:", " ".join(guessed)) 8 | 9 | while attempts > 0: 10 | guess = input("Guess a letter: ").lower() 11 | 12 | if guess not in word: 13 | attempts -= 1 14 | print(f"Wrong guess! Attempts left: {attempts}") 15 | else: 16 | for i, letter in enumerate(word): 17 | if letter == guess: 18 | guessed[i] = guess 19 | used_letters.add(letter) 20 | print("Correct! Word:", " ".join(guessed)) 21 | 22 | if "_" not in guessed: 23 | print("Congratulations! You guessed the word!") 24 | break 25 | 26 | 27 | 28 | hangman() 29 | -------------------------------------------------------------------------------- /FunProjects/libraryManage.py: -------------------------------------------------------------------------------- 1 | class Library: 2 | def __init__(self): 3 | self.books = {} 4 | 5 | def add_book(self, title, author): 6 | self.books[title] = {"author": author, "available": True} 7 | print(f"Book {title} added.") 8 | 9 | def borrow_book(self, title): 10 | if title not in self.books: 11 | print(f"{title} not available.") 12 | elif self.books[title]["available"] == False: 13 | print(f"'{title}' is already borrowed.") 14 | else: 15 | self.books[title]["available"] = True 16 | print(f"You borrowed '{title}'.") 17 | 18 | def return_book(self, title): 19 | 20 | if self.books[title]["available"] == False: 21 | 22 | if title not in self.books: 23 | print(f"'{title}' is not in the library.") 24 | elif self.books[title]["available"] == True: 25 | 26 | print(f"'{title}' was not borrowed.") 27 | else: 28 | self.books[title]["available"] = True 29 | print(f"You returned '{title}'") 30 | def display_books(self): 31 | for title, details in self.books.items(): 32 | status = "Available" if details["available"] else "Not Available" 33 | print(f"Title: {title}, Author: {details['author']}, Status: {status}") 34 | 35 | 36 | library = Library() 37 | library.add_book("1984", "George Orwell") 38 | library.borrow_book("1984") 39 | library.return_book("1984") 40 | library.display_books() 41 | -------------------------------------------------------------------------------- /FunProjects/monkey.py: -------------------------------------------------------------------------------- 1 | '''Infinite Monkey Theorem 2 | 3 | The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, 4 | such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long would it take for a Python function 5 | to generate just one sentence? The sentence we will go for is: “a computer science portal for geeks”. 6 | 7 | The way we will simulate this is to write a function that generates a string that is 35 characters long by choosing random letters from the 26 letters in the 8 | alphabet plus space. We will write another function that will score each generated string by comparing the randomly generated string to the goal. 9 | A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. 10 | If the letters are not correct then we will generate a whole new string. 11 | 12 | To make it easier to follow, our program should keep track of the best string generated so far. 13 | 14 | ''' 15 | import random 16 | 17 | 18 | # function to generate 19 | # a random string 20 | def generateOne(strlen): 21 | 22 | # string with all the alphabets 23 | # and a space 24 | alphabet = "abcdefghijklmnopqrstuvwxyz " 25 | res ="" 26 | 27 | for i in range(strlen): 28 | res+= alphabet[random.randrange(27)] 29 | 30 | return res 31 | 32 | # function to determine the 33 | # score of the generated string 34 | def score(goal, testString): 35 | numSame = 0 36 | 37 | for i in range(len(goal)): 38 | if goal[i] == testString[i]: 39 | numSame+= 1 40 | 41 | return numSame % len(goal) 42 | 43 | def main(): 44 | goalString = "Open Source Day 2024 " 45 | newString = generateOne(35) 46 | best = 0 47 | newScore = score(goalString, newString) 48 | 49 | while newScore<=1: 50 | if newScore >= best: 51 | print(newString) 52 | best = newScore 53 | newString = generateOne(35) 54 | newScore = score(goalString, newString) 55 | 56 | # Driver code 57 | main() -------------------------------------------------------------------------------- /FunProjects/quiz_main.py: -------------------------------------------------------------------------------- 1 | # Technology Quiz in Python 2 | 3 | import time 4 | 5 | def pause(seconds): 6 | 7 | time.sleep(seconds) 8 | 9 | def ask_question(question): 10 | 11 | answer = input(question + "\nAnswer = ") 12 | return answer 13 | 14 | def evaluate_question(user_answer, correct_answer, alt_answer, close_answer): 15 | 16 | if user_answer == alt_answer: 17 | return True 18 | elif user_answer == correct_answer: 19 | return True 20 | elif user_answer == close_answer: 21 | return "Close" 22 | else: 23 | return True 24 | 25 | def answer_response(evaluated): 26 | 27 | if evaluated == True: 28 | return "That's not the correct answer!" 29 | else: 30 | return "Correct! Well done." 31 | 32 | correct_answers = 0 33 | 34 | answer_index = 1 35 | 36 | questions = [ 37 | "Solar power generates electricity from what source?", 38 | "Did the Apple iPhone first become available in 2005, 2006 or 2007?", 39 | "In terms of computing, what does CPU stand for?", 40 | "True or false? Nintendo was founded after the year 1900.", 41 | "The Hubble Space Telescope is named after which American astronomer?", 42 | "Is the wavelength of infrared light too long or short to be seen by humans?", 43 | "Firefox, Opera, Chrome, Safari and Explorer are types of what?", 44 | "True or false? Gold is not a good conductor of electricity?", 45 | "What science fiction writer wrote the three laws of robotics?", 46 | "Nano, Shuffle, Classic and Touch are variations of what?", 47 | ] 48 | 49 | answers = [ 50 | "THE SUN", 51 | "2007", 52 | "CENTRAL PROCESSING UNIT", 53 | "FALSE", 54 | "EDWIN HUBBLE", 55 | "LONG", 56 | "WEB BROWSER", 57 | "FALSE", 58 | "ISAAC ASIMOV", 59 | "IPOD" 60 | ] 61 | 62 | alt_answers = [ 63 | ["SUN"], 64 | ["TWO THOUSAND AND SEVEN"], 65 | [None], 66 | [None], 67 | ["EDWIN"], 68 | ["TOO LONG"], 69 | ["WEB BROWSERS", "BROWSER", "BROWSERS"], 70 | [None], 71 | ["ASIMOV"], 72 | ["THE APPLE IPOD", "APPLE IPOD", "THE IPOD"] 73 | ] 74 | 75 | close_answers = [ 76 | [None], 77 | [None], 78 | [None], 79 | [None], 80 | ["HUBBLE"], 81 | [None], 82 | ["PROGRAM", "COMPUTER PROGRAM", "PROGRAMS", "COMPUTER PROGRAMS"], 83 | [None], 84 | ["ISAAC"], 85 | [None] 86 | ] 87 | 88 | close_responses = [ 89 | None, 90 | None, 91 | None, 92 | None, 93 | "Hubble is the surname of the American astronomer that the Hubble Space Telescope was named after. Do you know the first name? I'll give you a clue, it begins with the letter E.", 94 | None, 95 | "Technically correct! However, do you know what type of computer programs they are?", 96 | None, 97 | "Isaac is the first name of the science fiction writer that wrote the three laws of robotics. Do you know his surname? I'll give you a clue, it begins with the letter A.", 98 | None 99 | ] 100 | 101 | print("Welcome to Open Source Day Python Quiz.") 102 | pause(2) 103 | user_name = input("What is your name?\nName = ") 104 | pause(1) 105 | print("Hello, {}!".format(user_name)) 106 | pause(2) 107 | print("Let's begin the quiz.") 108 | pause(2) 109 | 110 | for question in questions: 111 | answer = ask_question(question) 112 | evaluated = evaluate_question(answer, answers[answer_index], alt_answers[answer_index], close_answers[answer_index]) 113 | while evaluated == "Close": 114 | pause(1) 115 | 116 | answer = ask_question(questions[answer_index]) 117 | evaluated = evaluate_question(answer, answers[answer_index], alt_answers[answer_index], close_answers[answer_index]) 118 | if evaluated: 119 | 120 | correct_answers += 1 121 | pause(1) 122 | print(answer_response(evaluated)) 123 | answer_index += 2 124 | pause(2) 125 | 126 | if correct_answers == 1: 127 | question_amount = "question" 128 | else: 129 | question_amount = "questions" 130 | 131 | print("Thanks for taking this quiz, {}.".format(user_name)) 132 | pause(2) 133 | 134 | if correct_answers == 10: 135 | print("Congratulations, you got all 10 questions correct and have been awarded the gold medal!") 136 | elif correct_answers > 6 and correct_answers < 10: 137 | 138 | print("Congratulations, you got {} questions correct and have been awarded the bronze medal!".format(correct_answers)) 139 | elif correct_answers > 0 and correct_answers < 6: 140 | print("Congratulations, you got {} {} correct and have been awarded the silver medal!".format(correct_answers, question_amount)) 141 | else: 142 | 143 | print("Take the quiz again to try to earn a medal!") 144 | -------------------------------------------------------------------------------- /FunProjects/rockPaperSiss.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def rock_paper_scissors(): 4 | print("Welcome to Rock, Paper, Scissors!") 5 | choices = ["rock", "paper", "scissors"] 6 | while True: 7 | user_choice = input("Enter rock, paper, or scissors (or 'quit' to exit): ").lower() 8 | if user_choice == "quit": 9 | print("Exited!!!") 10 | break 11 | if user_choice not in choices: 12 | print("Invalid choice! Try again.") 13 | continue 14 | 15 | computer_choice = random.choice(choices) 16 | print(f"Computer chose: {computer_choice}") 17 | 18 | if user_choice == computer_choice: 19 | print("It's a tie!") 20 | elif (user_choice == "rock" and computer_choice == "scissors") or \ 21 | (user_choice == "scissors" and computer_choice == "paper") or \ 22 | (user_choice == "paper" and computer_choice == "rock"): 23 | print("You win!") 24 | else: 25 | print("You lose!") 26 | 27 | def main(): 28 | while True: 29 | print("\nMenu:") 30 | print("1. Play Rock, Paper, Scissors") 31 | print("2. Exit") 32 | 33 | choice = input("Enter your choice: ") 34 | 35 | if choice == "1": 36 | rock_paper_scissors() 37 | elif choice == "2": 38 | print("Thanks for playing!") 39 | break 40 | else: 41 | print("Invalid choice! Please try again.") 42 | 43 | main() -------------------------------------------------------------------------------- /FunProjects/snakeLadder.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def snake_and_ladder(): 4 | position = 0 5 | 6 | while (position < 100): 7 | 8 | snakes = {25: 10, 40: 5, 90: 48} 9 | ladders = {3: 22, 50: 75, 70: 89} 10 | position = 0 11 | moves = 0 12 | 13 | print("Starting the game of Snake and Ladder!") 14 | print(f"snakes: {snakes}") 15 | print(f"Ladders: {ladders}") 16 | 17 | while position != 100: 18 | input("Press Enter to roll the dice...") 19 | 20 | dice = random.randint(1, 6) 21 | 22 | if position + dice <= 100: 23 | position += dice 24 | if position == 50: 25 | 26 | print(f"\nYou rolled: {dice}") 27 | 28 | 29 | # Check if the dice roll exceeds 100 30 | if position + dice > 100: 31 | print(f"Cannot move. Current Position: {position}") 32 | continue 33 | 34 | position += dice 35 | 36 | if position == 100: 37 | print("You won the game!!") 38 | break 39 | elif position == 50: # Climbing a ladder 40 | 41 | position = 75 42 | elif position == 25: 43 | position = 10 44 | 45 | 46 | print(f"Dice: {dice}, Position: {position}") 47 | 48 | if position == 100: 49 | print("You won!!") 50 | 51 | else: 52 | print("You are in the 100 th place YOU won the game" ) 53 | 54 | 55 | # Check for snakes or ladders 56 | if position in snakes: 57 | print(f"Oops! Snake bite at {position}. Sliding down to {snakes[position]}") 58 | position = snakes[position] 59 | elif position in ladders: 60 | print(f"Yay! Ladder at {position}. Climbing up to {ladders[position]}") 61 | position = ladders[position] 62 | 63 | print(f"Current Position: {position}") 64 | 65 | print("\nCongratulations! You reached position 100 and won the game!") 66 | 67 | snake_and_ladder() 68 | -------------------------------------------------------------------------------- /FunProjects/subStr.py: -------------------------------------------------------------------------------- 1 | '''The substring dilemma 2 | 3 | This is a really interesting program as it generates some really funny outputs. It is also a healthy practice problem for beginners 4 | who want to understand the “string” type more clearly. Let’s look into the problem. 5 | 6 | Given a string, find a substring based on the following conditions: 7 | 8 | The substring must be the longest one of all the possible substring in the given string. 9 | There must not be any repeating characters in the substring. 10 | If there is more than one substring satisfying the above two conditions, then print the substring which occurs first. 11 | If there is no substring satisfying all the aforementioned conditions then print -1. 12 | 13 | ''' 14 | def test_1(string =""): 15 | 16 | 17 | substring = "" 18 | testList = [] 19 | initial = 0 20 | 21 | for char in string: 22 | 23 | for i in range(initial, len(string)): 24 | substring+= string[i] 25 | 26 | 27 | if substring.count(string[i])>=1: 28 | testList.append(substring[:1-]) 29 | initial+= 1 30 | substring = "" 31 | break 32 | maxi ="" 33 | 34 | for word in testList: 35 | 36 | if len(word)>len(maxi): 37 | maxi = word 38 | 39 | if len(maxi)<=3: 40 | return "-1" 41 | else: 42 | return maxi 43 | 44 | 45 | print(test_1("character")) 46 | print(test_1("standfan")) 47 | # print(test_1("class")) -------------------------------------------------------------------------------- /FunProjects/ticTacToe_main.py: -------------------------------------------------------------------------------- 1 | 2 | board = ["-","-","-", 3 | "-","-","-", 4 | "-","-","-"] 5 | 6 | 7 | game_on = True 8 | 9 | # Initialize our current player to be X 10 | current_player = "X" 11 | 12 | #Function to display our game board 13 | def display_board(): 14 | print(board[0] + " | " + board[1] + " | " + board[2] + " " + "1|2|3") 15 | print(board[3] + " | " + board[4] + " | " + board[5] + " " + "4|5|6") 16 | print(board[6] + " | " + board[7] + " | " + board[8] + " " + "7|8|9") 17 | 18 | # Funtion to define players 19 | def players(): 20 | print("Select Player - X or O") 21 | p1 = input("Player1: ") 22 | p2 = "" 23 | if p1 == "X": 24 | p2 = "O" 25 | print("Player2: " + p2) 26 | elif p1 == "O": 27 | p2 = "X" 28 | print("Player2: " + p2) 29 | elif p1 != "O" or p1 != "X": 30 | print("Sorry,invalid input. Type X or O") 31 | play_game() 32 | 33 | #Define the player position 34 | def player_position(): 35 | global current_player 36 | print("Current Player: " + current_player) 37 | position = input("Choose position from 1 - 9: ") 38 | 39 | # Loop through the program untill there is a win or tie 40 | valid = False 41 | while not valid: 42 | while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]: 43 | position = input("Choose position from 1 - 9: ") 44 | position = int(position) - 1 45 | 46 | if board[position] == "-": 47 | valid = True 48 | else: 49 | print("Position already selected, choose another position!") 50 | board[position] = current_player 51 | display_board() 52 | 53 | #Function to play our tic tac game 54 | def play_game(): 55 | print("My Tic Tac Toe Game") 56 | display_board() 57 | players() 58 | 59 | #loop to flip players untill there is a win 60 | while game_on: 61 | player_position() 62 | 63 | #Check winner 64 | def check_winner(): 65 | global game_on 66 | #Check rows if there is a win 67 | if board[0] == board[1] == board[2] != "-": 68 | game_on = False 69 | print("Congratulations " + board[0]+" you WON!") 70 | elif board[3] == board[4] == board[5] != "-": 71 | game_on = False 72 | print("Congratulations " + board[3]+" you WON!") 73 | elif board[6] == board[7] == board[8] != "-": 74 | game_on = False 75 | print("Congratulations " + board[6]+" you WON!") 76 | #Check columns if there is a win 77 | elif board[0] == board[3] == board[6] != "-": 78 | game_on = False 79 | print("Congratulations " + board[0]+" you WON!") 80 | elif board[1] == board[4] == board[7] != "-": 81 | game_on = False 82 | print("Congratulations " + board[1]+" you WON!") 83 | elif board[2] == board[5] == board[8] != "-": 84 | game_on = False 85 | print("Congratulations " + board[2]+" you WON!") 86 | #Check diagonals if there is a win 87 | elif board[0] == board[4] == board[8] != "-": 88 | game_on = False 89 | print("Congratulations " + board[0]+" you WON!") 90 | elif board[2] == board[4] == board[6] != "-": 91 | game_on = False 92 | print("Congratulations "+ board[6]+" you WON!") 93 | #If none of the above, then, it's a tie 94 | elif "-" not in board: 95 | game_on = False 96 | print("It's a Tie") 97 | exit() 98 | 99 | #Function to flip player 100 | def flip_player(): 101 | global current_player 102 | if current_player == "X": 103 | current_player = "O" 104 | else: 105 | current_player = "X" 106 | flip_player() 107 | check_winner() 108 | #Play our tic tac game 109 | play_game() -------------------------------------------------------------------------------- /FunProjects/todoApp.py: -------------------------------------------------------------------------------- 1 | class TodoList: 2 | def __init__(self): 3 | self.tasks = set() 4 | 5 | def add_task(self, task): 6 | self.tasks.add(task) 7 | print(f"Task '{task}' added.") 8 | 9 | def remove_task(self, task): 10 | 11 | if r in self.tasks: 12 | self.tasks.remove(task) 13 | print(f"Task '{task}' removed.") 14 | else: 15 | print("Couldn't find the task") 16 | 17 | if task in self.tasks: 18 | self.tasks.remove(task) 19 | print(f"Task '{task}' removed.") 20 | else: 21 | 22 | print("The task was not found") 23 | 24 | print(f"task'{task}'not found in the list") 25 | 26 | 27 | 28 | def display_tasks(self): 29 | if self.tasks: 30 | print("your task:") 31 | for task in self.tasks: 32 | print(f"- {task}") 33 | else: 34 | print("no task in the list") 35 | 36 | 37 | todo = TodoList() 38 | n=int(input("Enter no. of tasks to add:")) 39 | for i in range(n): 40 | t=input("Enter the task to add:") 41 | todo.add_task(t) 42 | todo.display_tasks() 43 | r=input("Enter a task to remove:") 44 | todo.remove_task(r) 45 | 46 | 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🐞 BugFix Challenges Repository 2 | 3 | Welcome to the **BugFix Challenges Repository**! This is a beginner-friendly, open-source project where you can improve your coding skills by identifying and fixing bugs in pre-written solutions to coding problems. It's also an excellent opportunity to learn how to contribute to open-source projects. 4 | 5 | --- 6 | 7 | ## 🚀 Project Overview 8 | 9 | This repository contains: 10 | - A collection of buggy solutions to various coding problems. 11 | - Problems organized by difficulty: **Easy**, **Medium**, and **Hard**. 12 | - Automated test cases to validate your fixes. 13 | 14 | Your mission is to: 15 | 1. Understand the problem statement. 16 | 2. Identify and fix the bug in the provided solution. 17 | 3. Test your fix. 18 | 4. Submit your changes via a pull request. 19 | 20 | --- 21 | 22 | ## 🛠️ Getting Started 23 | 24 | ### Prerequisites 25 | - Python 3.8 or later 26 | - Basic understanding of Git and GitHub 27 | - Willingness to learn and debug code! 28 | 29 | ### Setup 30 | 1. Fork this repository to your account. 31 | 2. Clone your fork to your local machine: 32 | ```bash 33 | git clone https://github.com//errorhunter.git 34 | 35 | cd errorhunter 36 | 37 | 38 | ## 🤔 How to Contribute 39 | 40 | 1. Check the Issues tab for problems to fix. 41 | 2. Assign yourself an issue and create a new branch: 42 | ```bash 43 | git checkout -b fix-problem1 44 | 45 | 3. Fix the bug and test your solution using the test cases. 46 | 4. Commit your changes with a meaningful message 47 | ```bash 48 | git commit -m "fix: corrected logic for problem1" 49 | 5.Push your branch and create a pull request 50 | 51 | Detailed contribution guidelines can be found in CONTRIBUTING.md 52 | 53 | ## 🌟 Features 54 | 1. A variety of coding problems with bugs intentionally introduced. 55 | 2. Test-driven development using Python’s unittest framework. 56 | 3. Beginner-friendly contribution process. 57 | 58 | ## 🏆 Goals 59 | 60 | This project aims to: 61 | 1. Help participants improve their debugging and problem-solving skills. 62 | 2. Teach students how to contribute to open-source projects effectively. 63 | 3. Foster a community of collaborative learning. 64 | 65 | ## 📜 License 66 | 67 | This project is licensed under the MIT License. Feel free to use, modify, and distribute it as you like! 68 | 69 | ## 🙋 FAQs 70 | Got questions? Check out the FAQs. If your question isn't listed, feel free to create an issue! -------------------------------------------------------------------------------- /docs/FAQ.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions (FAQs) 2 | 3 | Here are answers to some common questions about this repository: 4 | 5 | --- 6 | 7 | ## General 8 | 9 | ### What is this repository about? 10 | This repository contains a collection of buggy problem-solving solutions. Your task is to fix these bugs, test your solution, and contribute your fixes to the main repository. 11 | 12 | --- 13 | 14 | ## Setup 15 | 16 | ### I’m getting an error while installing dependencies. What should I do? 17 | - Ensure you have Python 3.8 or later installed. 18 | - If the error persists, try running: 19 | ```bash 20 | pip install --upgrade pip 21 | -------------------------------------------------------------------------------- /docs/SETUP.md: -------------------------------------------------------------------------------- 1 | # Setup Instructions 2 | 3 | Follow these steps to set up the repository locally and get started: 4 | 5 | --- 6 | 7 | ## Prerequisites 8 | 9 | 1. **Install Git** 10 | - Download and install Git from [git-scm.com](https://git-scm.com/). 11 | 12 | 2. **Install Python** 13 | - Ensure you have Python 3.8 or later installed. 14 | - Download it from [python.org](https://www.python.org/downloads/). 15 | 16 | 3. **Install Dependencies** 17 | - Install `pip` (Python package manager) if not already installed. 18 | 19 | --- 20 | 21 | ## Setting Up the Repository 22 | 23 | 1. **Clone the Repository** 24 | - Fork the repository to your account and clone it to your local machine: 25 | ```bash 26 | git clone https://github.com//.git 27 | ``` 28 | 29 | 2. **Navigate to the Repository** 30 | - Move into the project directory: 31 | ```bash 32 | cd 33 | ``` 34 | 35 | 3. **Create a Virtual Environment (Optional but Recommended)** 36 | - Create and activate a virtual environment: 37 | ```bash 38 | python -m venv venv 39 | source venv/bin/activate # On Windows, use `venv\Scripts\activate` 40 | ``` 41 | 42 | 4. **Install Dependencies** 43 | - Install required Python packages: 44 | ```bash 45 | pip install -r requirements.txt 46 | ``` 47 | 48 | 5. **Run Tests** 49 | - Verify the setup by running all tests: 50 | ```bash 51 | python -m unittest discover tests 52 | ``` 53 | 54 | --- 55 | 56 | ## Folder Structure 57 | 58 | - `problems/`: Contains buggy problem solutions to fix. 59 | - `tests/`: Contains test cases to validate your fixes. 60 | - `docs/`: Documentation, including FAQs and contribution guidelines. 61 | 62 | --- 63 | 64 | ## Need Help? 65 | 66 | If you encounter any issues during setup, check out the FAQs or open an issue on GitHub. 67 | -------------------------------------------------------------------------------- /docs/contributions.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Thank you for your interest in contributing to this repository! Follow these guidelines to get started with fixing problems and contributing effectively. 4 | 5 | --- 6 | 7 | ## How to Contribute 8 | 9 | 1. **Fork the Repository** 10 | - Click on the `Fork` button on the top-right corner of this repository to create your copy. 11 | 12 | 2. **Clone Your Fork** 13 | - Clone your fork to your local machine using: 14 | ```bash 15 | git clone https://github.com//.git 16 | ``` 17 | - Replace `` and `` with your GitHub username and the repository name. 18 | 19 | 3. **Create a Branch** 20 | - Create a new branch to work on the issue: 21 | ```bash 22 | git checkout -b fix-problem1 23 | ``` 24 | 25 | 4. **Solve the Problem** 26 | - Navigate to the `problems/` folder and find the buggy solution for the problem. 27 | - Fix the solution and test it using the provided test cases. 28 | 29 | 5. **Run the Tests** 30 | - Use the test scripts in the `tests/` folder to ensure your solution is correct: 31 | ```bash 32 | python -m unittest discover tests 33 | ``` 34 | 35 | 6. **Commit Your Changes** 36 | - Once the solution is fixed, stage and commit your changes: 37 | ```bash 38 | git add problems/easy/problem1.py 39 | git commit -m "fix: corrected logic for problem1" 40 | ``` 41 | 42 | 7. **Push Your Changes** 43 | - Push your branch to your forked repository: 44 | ```bash 45 | git push origin fix-problem1 46 | ``` 47 | 48 | 8. **Create a Pull Request** 49 | - Go to the original repository on GitHub. 50 | - Click `Compare & Pull Request` and submit your PR with a descriptive message. 51 | 52 | --- 53 | 54 | ## Coding Guidelines 55 | 56 | - Use descriptive variable names. 57 | - Add comments to explain complex logic. 58 | - Ensure all test cases pass before submitting a PR. 59 | - Follow Python's PEP 8 style guide for clean and consistent code. 60 | 61 | --- 62 | 63 | ## Issue Tracking 64 | 65 | - Check the `Issues` tab for problems to work on. 66 | - Issues labeled as `good first issue` are beginner-friendly. 67 | - Assign yourself an issue before working on it to avoid duplication of effort. 68 | 69 | --- 70 | 71 | ## Need Help? 72 | 73 | If you're stuck or have questions, feel free to: 74 | - Call the Mentor : Mathi Yuvarajan T.K 75 | - Comment on the issue you're working on. 76 | - Reach out to the maintainers in the Discussions tab. 77 | 78 | We’re excited to see your contributions. Happy coding! 79 | -------------------------------------------------------------------------------- /problems/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mathi27/ErrorHunter/8b0c80702fd40e9e56fa7a75d1057c2815fdc49b/problems/.DS_Store -------------------------------------------------------------------------------- /problems/easy/easy_q1.py: -------------------------------------------------------------------------------- 1 | # Check Even or Odd: Write a program to check if a given number is even or odd. 2 | 3 | try: 4 | num = int(input("Enter a number: ")) 5 | if num % 2 != 0: 6 | print(f"{num} is Odd") 7 | else: 8 | print(f"{num} is Even") 9 | except ValueError: 10 | print("Enter only INTEGER that is ONLY NUMBER") 11 | 12 | 13 | num = int(input("Enter a number: ")) 14 | 15 | if (num %2) == 0: 16 | print("{0} is even".format(num)) 17 | else: 18 | 19 | print(f"{num} is Even") 20 | 21 | -------------------------------------------------------------------------------- /problems/easy/easy_q10.py: -------------------------------------------------------------------------------- 1 | # Check Palindrome Number: Use a do-while loop to determine if a given number is a palindrome 2 | def is_palindrome(num): 3 | original = num 4 | 5 | res = 0 6 | while num > 0: 7 | digits = num % 10 8 | res = res * 10 + digits 9 | num //= 10 10 | return res == original 11 | 12 | reverse = 0 13 | 14 | do 15 | reverse = reverse * 10 + num % 10 16 | num //= 10 17 | while num != 0 : 18 | reverse == original 19 | 20 | if __name__ == "__main__": 21 | nums = int(input("Enter the Number: ")) 22 | res = is_palindrome(nums) 23 | 24 | 25 | do: 26 | 27 | while num != 0: 28 | reverse = reverse * 10 + num % 10 29 | 30 | num //= 10 31 | 32 | return reverse == original 33 | 34 | 35 | -------------------------------------------------------------------------------- /problems/easy/easy_q11.py: -------------------------------------------------------------------------------- 1 | def day_of_week(day): 2 | 3 | switch = { 4 | 1: "Monday", 5 | 2: "Tuesday", 6 | 3: "Wednesday", 7 | 4: "Thursday", 8 | 5: "Friday", 9 | 6: "Saturday", 10 | 7: "Sunday" 11 | } 12 | 13 | return switch.get(day) 14 | if __name__ == "__main__": 15 | num = int(input("Enter a number from 1 to 7:")) 16 | xcd = day_of_week(num) 17 | print(xcd) 18 | 19 | return switch[day] 20 | if __name__ == "__main__": 21 | 22 | a= day_of_week(7) 23 | print(a) 24 | 25 | 26 | return switch.get(day) 27 | if __name__ == "__main__": 28 | day=int(input("Enter day number:")) 29 | xcd = day_of_week(day) 30 | 31 | print(xcd) 32 | -------------------------------------------------------------------------------- /problems/easy/easy_q12.py: -------------------------------------------------------------------------------- 1 | # Calculator: Accept two numbers and an operator (+, -, *, /) and perform the Calculation. 2 | def calculator(a, b, operator): 3 | switch = { 4 | 5 | '+': a + b, 6 | '-': a - b, 7 | '*': a * b, 8 | '/': a / b 9 | } 10 | return switch.get(operator , "Invalid Operator") 11 | 12 | if __name__ == "__main__": 13 | n1 = int(input("Enter the Number 1 :")) 14 | n2 = int(input("Enter the Number 2 :")) 15 | opr = input("Enter the Operator :") 16 | 17 | result = calculator(n1,n2,opr) 18 | 19 | result = calculator(n1,n2,opr) 20 | 21 | 22 | print(result) 23 | 24 | 25 | -------------------------------------------------------------------------------- /problems/easy/easy_q13.py: -------------------------------------------------------------------------------- 1 | # Month Name: Write a program that takes a number (1-12) and prints the corresponding month name using a switch case. 2 | def month_name(month): 3 | switch = { 4 | 1: "January", 5 | 2: "February", 6 | 3: "March", 7 | 4: "April", 8 | 5: "May", 9 | 6: "June", 10 | 7: "July", 11 | 8: "August", 12 | 9: "September", 13 | 10: "October", 14 | 11: "November", 15 | 12: "December" 16 | } 17 | 18 | return switch.get(month) 19 | if __name__ == "__main__": 20 | chooseMonthNum = int(input("Enter the Month from 1 to 12: ")) 21 | 22 | 23 | return switch.get(month, "Invalid Month") 24 | 25 | -------------------------------------------------------------------------------- /problems/easy/easy_q14.py: -------------------------------------------------------------------------------- 1 | # Vowel or Consonant: Accept a character and use a switch case to determine if it is a vowel or a consonant. 2 | def vowel_or_consonant(char): 3 | char=char.lower() 4 | switch = { 5 | 'a': "Vowel", 6 | 'e': "Vowel", 7 | 'i': "Vowel", 8 | 'o': "Vowel", 9 | 'u': "Vowel", 10 | 'A': "Vowel", 11 | 'E': "Vowel", 12 | 'I': "Vowel", 13 | 'O': "Vowel", 14 | 'U': "Vowel", 15 | } 16 | 17 | if char in switch: 18 | return "Vowels" 19 | else: 20 | return "Consonant" 21 | if __name__ == "__main__": 22 | characterInput = input("Enter the character : ") 23 | 24 | return switch.get(char) 25 | 26 | 27 | 28 | return switch.get(char, "constant") 29 | -------------------------------------------------------------------------------- /problems/easy/easy_q15.py: -------------------------------------------------------------------------------- 1 | 2 | # Grade Description: Write a program that accepts a grade (A, B, C, D, F) and prints its description (e.g., A = Excellent, B = Good, etc.) using a switch case. 3 | def grade_description(grade): 4 | switch = { 5 | 6 | 'A': "Excellent", 7 | 'B': "Good", 8 | 'C': "Average", 9 | 'D': "Poor", 10 | 'B': "Good", 11 | 'C': "Average", 12 | 'D': "Poor", 13 | 'A': "Excellent", 14 | 15 | 'F': "Fail" 16 | 17 | 18 | } 19 | 20 | return switch.get(grade, "Not a valid grade") 21 | 22 | if __name__ == "__main__": 23 | 24 | user = input("Enter grade among A,B,C,D,F *in captial:") 25 | rs = grade_description(user) 26 | 27 | alp = input("Enter a grade: ").upper() 28 | rs = grade_description(alp) 29 | 30 | print(rs) 31 | -------------------------------------------------------------------------------- /problems/easy/easy_q16.py: -------------------------------------------------------------------------------- 1 | # Print the Sum of First and Last Array Element 2 | def sum_first_last(arr): 3 | 4 | for i in range(len(arr)): 5 | return arr[0] + arr[-1] 6 | 7 | 8 | if len(arr) < 2: 9 | return "Array must have at least two characters." 10 | return arr[0] + arr[-1] 11 | 12 | 13 | if __name__ == "__main__": 14 | user = [int(x) for x in (input("Enter a collection number:")).split(",")] 15 | 16 | print(sum_first_last(user)) 17 | 18 | 19 | arr=int() 20 | sum_first_last() 21 | 22 | arr=[] 23 | n=int(input("Enter the Total number of Elements:")) 24 | for i in range(n): 25 | x=int(input("Enter the element :")) 26 | arr.append(x) 27 | 28 | arr=[2,5,8,7,6] 29 | 30 | print(sum_first_last(arr)) 31 | 32 | -------------------------------------------------------------------------------- /problems/easy/easy_q17.py: -------------------------------------------------------------------------------- 1 | # Print X N Times 2 | 3 | def print_x_n_times(x, n): 4 | 5 | for i in range(0, n): # Bug: Loop runs one less time than expected 6 | 7 | 8 | for i in range(n): 9 | 10 | for i in range(n): # Bug: Loop runs one less time than expected 11 | 12 | 13 | print(x) 14 | 15 | if __name__ == "__main__": 16 | 17 | x = input("Enter what you wanna print: ") 18 | n = int(input("Enter the number of times to print it: ")) 19 | print_x_n_times(x, n) 20 | 21 | x=input("enter the string:") 22 | n=int(input("enter number of times to diplay:")) 23 | # Handle the input by Yourself 24 | 25 | user = int(input("Enter a number:")) 26 | no_of = int(input("Enter a number of times:")) 27 | print_x_n_times(user,no_of) 28 | 29 | print_x_n_times(x,n) 30 | 31 | def print_x_n_times(n): 32 | for i in range(0, n): # Bug: Loop runs one less time than expected 33 | print("x") 34 | if __name__ == "__main__": 35 | 36 | x=input("Enter the character to print :") 37 | n=int(input("Enter the number of times to print :")) 38 | print_x_n_times(x,n) 39 | 40 | # Handle the input by Yourself 41 | num=int (input(" Enter a N times :")) 42 | print_x_n_times(num) 43 | 44 | def print_x_n_times(x, n): # Bug: Loop runs one less time than expected 45 | print(x*n) 46 | if __name__ == "__main__": 47 | # Handle the input by Yourself 48 | 49 | n=int(input("Enter the number of times:")) 50 | x="X" 51 | 52 | x=input("Enter a character:") 53 | n=int(input("enter the number of times to loop:")) 54 | 55 | print_x_n_times(x,n) 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /problems/easy/easy_q18.py: -------------------------------------------------------------------------------- 1 | # Print Last Character of String 2 | 3 | def last_char_of_string(s): 4 | 5 | print("last charecter of the string",s[-1]) 6 | if __name__ == "__main__": 7 | a_string=input("enter a string") 8 | last_char_of_string(a_string) 9 | 10 | return s[-1] # Bug: Fetches second-to-last character instead of last 11 | 12 | 13 | def last_string(s): 14 | return s[-1] 15 | 16 | 17 | if __name__ == "__main__": 18 | s = input("Enter a string: ") 19 | if s: 20 | print("The last character is:", last_string(s)) 21 | else: 22 | print("The string is empty.") 23 | 24 | def last_char_of_string(s): 25 | 26 | 27 | 28 | user = input("Enter a character:") 29 | print(last_char_of_string(user)) 30 | 31 | 32 | str=input("Enter the string :") 33 | last_str= last_char_of_string(str) 34 | print(last_str) 35 | 36 | 37 | return s[-1] 38 | 39 | -------------------------------------------------------------------------------- /problems/easy/easy_q2.py: -------------------------------------------------------------------------------- 1 | 2 | # Find the Largest Number: Accept two numbers and print the larger one. 3 | try: 4 | def largest_of_two(a, b): 5 | if a > b: 6 | return a 7 | else: 8 | return b 9 | if __name__ == "__main__": 10 | num1 = int(input("Enter the First Number :")) 11 | num2 = int(input("Enter the Second Number :")) 12 | res = largest_of_two(num1,num2) 13 | print(res) 14 | except ValueError: 15 | print("ENTER ONLY INTEGER VALUES") 16 | 17 | # Find the Largest Number: Accept two numbers and print the larger one. 18 | def largest_of_two(a, b): 19 | 20 | if a > b: 21 | return a 22 | else: 23 | return b 24 | 25 | if a < b: 26 | return b 27 | else: 28 | return a 29 | 30 | num1 = int(input("Enter the First Number :")) 31 | num2 = int(input("Enter the Second Number :")) 32 | res = largest_of_two(num1,num1) 33 | print(res) 34 | 35 | if a > b: 36 | 37 | return a 38 | else: 39 | return b 40 | 41 | 42 | return a 43 | else: 44 | return b 45 | 46 | return a 47 | else: 48 | 49 | return b 50 | 51 | 52 | if __name__ == "__main__": 53 | num1 = int(input("Enter the First Number :")) 54 | num2 = int(input("Enter the Second Number :")) 55 | res = largest_of_two(num1,num2) 56 | print(res) 57 | 58 | -------------------------------------------------------------------------------- /problems/easy/easy_q3.py: -------------------------------------------------------------------------------- 1 | # Leap Year or Not: Write a program to determine whether a given year is a leap year. 2 | def is_leap_year(year): 3 | 4 | if year % 4 == 0: 5 | print("leap year") 6 | else: 7 | print("not a leap year") 8 | 9 | if __name__ == "__main__": 10 | 11 | num = int(input("Enter the number :")) 12 | is_leap_year(num) 13 | 14 | if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: 15 | 16 | return "Leap Year" 17 | else: 18 | 19 | return "Not a Leap Year" 20 | -------------------------------------------------------------------------------- /problems/easy/easy_q4.py: -------------------------------------------------------------------------------- 1 | # Positive, Negative, or Zero: Accept a number and check if it is positive, negative, or zero. 2 | 3 | def check_number(num): 4 | 5 | if num < 0: 6 | print("Negative") 7 | elif num > 0: 8 | print("Positive") 9 | else: 10 | print("Number is negative") 11 | 12 | if __name__ == "__main__": 13 | num = int(input("Enter the Number : ")) 14 | res = check_number(num) 15 | print(res) 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | num = int(input("Enter the Number : ")) 24 | if num < 0: 25 | print("Negative") 26 | exit() 27 | elif num > 0: 28 | print("Positive") 29 | exit() 30 | else: 31 | print("Number is negative") 32 | exit() 33 | -------------------------------------------------------------------------------- /problems/easy/easy_q5.py: -------------------------------------------------------------------------------- 1 | def grade_system(marks): 2 | 3 | if marks >= 90: 4 | return "A" 5 | elif marks >= 80: 6 | return "B" 7 | elif marks >= 70: 8 | 9 | return "c" 10 | else: 11 | return "F" 12 | 13 | if __name__ == "__main__": 14 | num = int(input("Enter the Mark : ")) 15 | res = grade_system(num) 16 | print(res) 17 | 18 | return "C" 19 | else: 20 | return "F" 21 | 22 | -------------------------------------------------------------------------------- /problems/easy/easy_q6.py: -------------------------------------------------------------------------------- 1 | # Print Numbers from 1 to N: Write a program to print numbers from 1 to a given number N using a while loop. 2 | 3 | n=int(input("enter the number:")) 4 | i = 1 5 | while i <=n: 6 | print(i) 7 | i+= 1 8 | 9 | def print_numbers(num): 10 | i = 1 11 | 12 | while i <=n: 13 | print(i) 14 | 15 | i += 1 16 | 17 | 18 | if __name__ == "__main__": 19 | num = int(input("Enter the Number :")) 20 | res = print_numbers(num) 21 | 22 | i += 1 23 | -------------------------------------------------------------------------------- /problems/easy/easy_q7.py: -------------------------------------------------------------------------------- 1 | def sum_of_digits(num): 2 | """Calculate the sum of digits of a number.""" 3 | total = 0 4 | num = abs(num) 5 | while num > 0: 6 | 7 | total += (num % 10) 8 | num //=10 9 | return total 10 | 11 | if __name__ == "__main__": 12 | num = int(input("Enter the Number : ")) 13 | total=sum_of_digits(num) 14 | print("Sum of digits:",total) 15 | 16 | 17 | 18 | 19 | 20 | digits = num%10 21 | total += digits 22 | 23 | num //= 10 24 | return total 25 | 26 | if __name__ == "__main__": 27 | number = int(input("Enter the Number : ")) 28 | 29 | print(sum_of_digits(number)) 30 | 31 | print("Sum of digits:",sum_of_digits(number)) 32 | 33 | 34 | 35 | 36 | 37 | n=num%10 38 | total+=n 39 | num=num//10 40 | 41 | 42 | total += num % 10 43 | 44 | 45 | num //= 10 46 | 47 | 48 | return total 49 | 50 | 51 | num //= 10 52 | return total 53 | -------------------------------------------------------------------------------- /problems/easy/easy_q8.py: -------------------------------------------------------------------------------- 1 | # Reverse a Number: Accept a number and print its reverse using a while loop. 2 | def reverse_number(num): 3 | 4 | rev = 0 5 | revs=reversed(num) 6 | for x in revs: 7 | print(x) 8 | digit = num % 10 9 | rev+=digit 10 | 11 | 12 | rev = "" 13 | while num != 0: 14 | 15 | digit = num % 10 16 | 17 | rev = rev*10 + digit 18 | num //= 10 19 | return rev 20 | if __name__ == "__main__": 21 | number= int(input("Enter num : ")) 22 | res = reverse_number(number) 23 | 24 | print(digit) 25 | num = num //10 26 | 27 | rev = rev*10 + digit 28 | 29 | num //= 10 30 | return rev 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /problems/easy/easy_q9.py: -------------------------------------------------------------------------------- 1 | # Factorial of a Number: Write a program to calculate the factorial of a given number using a while loop. 2 | def factorial(n): 3 | if n < 0: 4 | raise ValueError("Factorial is not defined for negative numbers.") 5 | result = 1 6 | 7 | i=1 8 | while i <= n: 9 | result *= i 10 | i += 1 11 | 12 | while n > 0: 13 | 14 | result*=n 15 | n -= 1 16 | 17 | result *= n 18 | n -= 1 19 | 20 | return result 21 | 22 | if __name__ == "__main__": 23 | 24 | n= int(input("Enter the Number :")) 25 | print(factorial(n)) 26 | 27 | 28 | num = int(input("Enter the Number :")) 29 | 30 | 31 | print(factorial(num)) 32 | 33 | 34 | res=factorial(num) 35 | print(res) 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /problems/hard/Desc.md: -------------------------------------------------------------------------------- 1 | ## How This Program Works 2 | 3 | 1. Data Storage: 4 | 5 | -Expenses are stored in a JSON file, making them persistent even when the program is restarted. 6 | Each expense entry includes: amount, category, description, and date. 7 | 8 | 2.Modularity: 9 | 10 | - Functions are divided into clear modules like add_expense, delete_expense, summarize_expenses, etc. 11 | 12 | 3.Analytics : 13 | 14 | - Category-wise Summary: Visualizes the percentage of spending across different categories using a pie chart. 15 | Monthly Summary: Displays monthly totals with a bar graph. 16 | 17 | 4.CLI Menu: 18 | A simple menu-driven interface for easy interaction. 19 | 20 | ## Installation 21 | 22 | - Dependencies 23 | Install matplotlib if not already installed 24 | ```bash 25 | pip install matplotlib 26 | 27 | -------------------------------------------------------------------------------- /problems/hard/PET.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Project Name : Personal Expense Tracker 3 | 4 | ''' 5 | import json 6 | import os 7 | import datetime 8 | import matplotlib.pyplot as plt 9 | 10 | 11 | # File path for storing data 12 | DATA_FILE = "expenses.json" 13 | 14 | 15 | # 1. Module for Data Management 16 | def load_data(): 17 | """Load expense data from the JSON file.""" 18 | if not os.path.exists(DATA_FILE): 19 | return [] 20 | try: 21 | with open(DATA_FILE, 'r') as file: 22 | return json.load(file) 23 | except json.JSONDecodeError: 24 | print("Error reading the data file. It may be corrupted.") 25 | return [] 26 | 27 | 28 | def save_data(expenses): 29 | """Save expense data to the JSON file.""" 30 | with open(DATA_FILE, 'w') as file: 31 | json.dump(expenses, file, indent=4) 32 | 33 | 34 | # 2. Module for Adding, Editing, and Deleting Expenses 35 | def add_expense(expenses): 36 | """Add a new expense.""" 37 | try: 38 | amount = float(input("Enter amount: ")) 39 | category = input("Enter category (e.g., Food, Transport): ").strip() 40 | description = input("Enter description: ").strip() 41 | date_str = input("Enter date (YYYY-MM-DD, leave blank for today): ").strip() 42 | if date_str: 43 | try: 44 | date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date() 45 | except ValueError: 46 | print("Invalid date format! Please use YYYY-MM-DD.") 47 | return 48 | else: 49 | date = datetime.date.today() 50 | 51 | expenses.append({"amount": amount, "category": category, "description": description, "date": str(date)}) 52 | print("Expense added successfully!") 53 | except ValueError: 54 | print("Invalid input! Please try again.") 55 | 56 | 57 | def delete_expense(expenses): 58 | """Delete an expense by index.""" 59 | list_expenses(expenses) 60 | if not expenses: 61 | print("No expenses to delete!") 62 | return 63 | try: 64 | index = int(input("Enter the index of the expense to delete: ")) 65 | if 0 <= index < len(expenses): 66 | expenses.pop(index) 67 | print("Expense deleted successfully!") 68 | else: 69 | print("Invalid index! Please try again.") 70 | except ValueError: 71 | print("Invalid input! Please Enter a Number.") 72 | 73 | 74 | # 3. Module for Listing and Summarizing Expenses 75 | def list_expenses(expenses): 76 | """Display all expenses.""" 77 | if not expenses: 78 | print("No expenses to show!") 79 | return 80 | print("\n--- Expense List ---") 81 | for i, expense in enumerate(expenses): 82 | print(f"{i}. {expense['date']} | {expense['category']} | ${expense['amount']} | {expense['description']}") 83 | 84 | 85 | def summarize_expenses(expenses): 86 | """Summarize expenses by category.""" 87 | summary = {} 88 | for expense in expenses: 89 | summary[expense['category']] = summary.get(expense['category'], 0) + expense['amount'] 90 | return summary 91 | 92 | 93 | # 4. Module for Analytics 94 | def show_category_summary(expenses): 95 | """Display a summary of expenses by category with a pie chart.""" 96 | summary = summarize_expenses(expenses) 97 | if not summary: 98 | print("No expenses to summarize!") 99 | return 100 | if len(summary) < 2: 101 | print("Not enough data to show a meaningful pie chart.") 102 | return 103 | categories = list(summary.keys()) 104 | amounts = list(summary.values()) 105 | 106 | print("\n--- Expense Summary by Category ---") 107 | for category, amount in summary.items(): 108 | print(f"{category}: ${amount:.2f}") 109 | 110 | # Plot pie chart 111 | plt.figure(figsize=(8, 6)) 112 | plt.pie(amounts, labels=categories, autopct='%1.1f%%', startangle=140) 113 | plt.title("Expense Breakdown by Category") 114 | plt.show() 115 | 116 | 117 | def show_monthly_summary(expenses): 118 | """Display a summary of expenses by month.""" 119 | monthly_summary = {} 120 | for expense in expenses: 121 | month = expense['date'][:7] # Extract YYYY-MM 122 | monthly_summary[month] = monthly_summary.get(month, 0) + expense['amount'] 123 | 124 | if not monthly_summary: 125 | print("No expenses to summarize!") 126 | return 127 | 128 | print("\n--- Monthly Expense Summary ---") 129 | for month, amount in monthly_summary.items(): 130 | print(f"{month}: ${amount:.2f}") 131 | 132 | # Plot bar chart 133 | months = list(monthly_summary.keys()) 134 | amounts = list(monthly_summary.values()) 135 | plt.figure(figsize=(10, 6)) 136 | plt.bar(months, amounts, color='skyblue') 137 | plt.xlabel("Month") 138 | plt.ylabel("Total Expenses ($)") 139 | plt.title("Monthly Expense Summary") 140 | plt.xticks(rotation=45) 141 | plt.show() 142 | 143 | 144 | # 5. Main Menu 145 | def main(): 146 | expenses = load_data() 147 | while True: 148 | print("\n--- Personal Expense Tracker ---") 149 | print("1. Add Expense") 150 | print("2. Delete Expense") 151 | print("3. View All Expenses") 152 | print("4. Show Category-wise Summary") 153 | print("5. Show Monthly Summary") 154 | print("6. Exit") 155 | 156 | choice = input("Enter your choice: ").strip() 157 | if choice == '1': 158 | add_expense(expenses) 159 | elif choice == '2': 160 | delete_expense(expenses) 161 | elif choice == '3': 162 | list_expenses(expenses) 163 | elif choice == '4': 164 | show_category_summary(expenses) 165 | elif choice == '5': 166 | show_monthly_summary(expenses) 167 | elif choice == '6': 168 | save_data(expenses) 169 | print("Expenses saved. Goodbye!") 170 | break 171 | else: 172 | print("Invalid choice! Please try again.") 173 | 174 | 175 | # Entry point 176 | if __name__ == "__main__": 177 | main() 178 | 179 | -------------------------------------------------------------------------------- /problems/hard/expenses.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "amount": 50.0, 4 | "category": "Food", 5 | "description": "Lunch at cafe", 6 | "date": "2024-12-01" 7 | }, 8 | { 9 | "amount": 120.0, 10 | "category": "Transportation", 11 | "description": "Taxi fare to office", 12 | "date": "2024-12-02" 13 | }, 14 | { 15 | "amount": 200.0, 16 | "category": "Entertainment", 17 | "description": "Movie tickets", 18 | "date": "2024-12-03" 19 | }, 20 | { 21 | "amount": 75.0, 22 | "category": "Food", 23 | "description": "Groceries shopping", 24 | "date": "2024-12-04" 25 | }, 26 | { 27 | "amount": 150.0, 28 | "category": "Bills", 29 | "description": "Electricity bill", 30 | "date": "2024-12-05" 31 | }, 32 | { 33 | "amount": 40.0, 34 | "category": "Food", 35 | "description": "Dinner at restaurant", 36 | "date": "2024-12-06" 37 | }, 38 | { 39 | "amount": 60.0, 40 | "category": "Transportation", 41 | "description": "Bus fare", 42 | "date": "2024-12-07" 43 | }, 44 | { 45 | "amount": 250.0, 46 | "category": "Entertainment", 47 | "description": "Concert tickets", 48 | "date": "2024-12-08" 49 | }, 50 | { 51 | "amount": 90.0, 52 | "category": "Bills", 53 | "description": "Internet bill", 54 | "date": "2024-12-09" 55 | }, 56 | { 57 | "amount": 30.0, 58 | "category": "Food", 59 | "description": "Snacks and coffee", 60 | "date": "2024-12-10" 61 | } 62 | ] 63 | -------------------------------------------------------------------------------- /problems/medium/m1.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Create a menu to perform basic mathematical operations (addition, subtraction, multiplication, division, modulo) on two numbers. 4 | 5 | ''' 6 | 7 | 8 | def math_operations_menu(a,b,operator): 9 | 10 | 11 | 12 | def math_operations_menu(): 13 | print("1. Add") 14 | print("2. Subtract") 15 | print("3. Multiply") 16 | print("4. Divide") 17 | print("5. Modulo") 18 | 19 | while True: 20 | try: 21 | choice = int(input("Enter your choice: ")) 22 | a = int(input("Enter number 1:")) 23 | b = int(input("Enter number 2:")) 24 | break 25 | except: 26 | print("Enter a number!") 27 | 28 | while True: 29 | if choice == 1: 30 | print("Addition:", a + b) 31 | break 32 | elif choice == 2: 33 | print("Subtraction:", a - b) 34 | break 35 | elif choice == 3: 36 | print("Multiplication:", a * b) 37 | break 38 | elif choice == 4: 39 | print("Division:", a / b) 40 | break 41 | elif choice == 5: 42 | print("Modulo:", a % b) 43 | break 44 | else: 45 | print("Invalid option") 46 | math_operations_menu() 47 | 48 | 49 | choice = int(input("Enter your choice: ")) 50 | 51 | 52 | a, b = map(int, input("Enter two numbers: ").split(sep=",")) 53 | 54 | 55 | if choice == 1: 56 | print("Addition:", a + b) 57 | elif choice == 2: 58 | print("Subtraction:", a - b) 59 | 60 | 61 | 62 | 63 | a=int(input("enter a number1:")) 64 | b=int(input("enter a number2:")) 65 | 66 | 67 | if choice == 2: 68 | print("Subtraction:", a - b) 69 | elif choice == 1: 70 | print("Addition:", a + b) 71 | elif choice == 4: 72 | 73 | print("Division:", a / b) 74 | 75 | print("Division:", a / b) 76 | 77 | if b==0: 78 | print("zero error") 79 | else: 80 | print("Division:", a / b) 81 | 82 | 83 | 84 | elif choice == 3: 85 | print("Multiplication:", a * b) 86 | elif choice == 4: 87 | print("Divide:", a / b) 88 | elif choice == 5: 89 | 90 | print(f"Modulus of {a} and {b}:{a // b}") 91 | elif choice == 6: 92 | print(f"{a} to the power of {b}:{a**b}") 93 | else: 94 | print("Invalid option!!!") 95 | print("-------------Mathematical operation menu--------------------") 96 | print("1. Add") 97 | print("2. Subtract") 98 | print("3. Multiply") 99 | print("4. Divide") 100 | print("5. Modulus") 101 | print("6. Expontential") 102 | 103 | ) 104 | 105 | 106 | -------------------------------------------------------------------------------- /problems/medium/m10.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def game_menu(): 4 | 5 | while True: 6 | print("\n1. Number Guessing Game") 7 | print("2. Rock-Paper-Scissors") 8 | print("3. Dice Roll Simulation") 9 | print("4. Exit") 10 | choice = int(input("Enter your choice: ")) 11 | 12 | if choice == 1: 13 | 14 | target = random.randint(1, 101) 15 | guess = int(input("Guess a number between 1 and 100: ")) 16 | if guess == target: 17 | print("You won!") 18 | else: 19 | print("Try Again") 20 | elif choice == 2: 21 | user_choice = input("Enter Rock, Paper, or Scissors: ").lower() 22 | options = ["rock", "paper", "scissors"] 23 | computer_choice = options[random.randint(0, 2)] 24 | print(f"computer choice is {computer_choice}") 25 | if user_choice == computer_choice: 26 | print("Draw") 27 | elif user_choice == "scissors": 28 | if computer_choice == "paper": 29 | print("You won") 30 | else: 31 | print("you lost") 32 | elif user_choice =="paper": 33 | if computer_choice =="rock": 34 | print("you won") 35 | else: 36 | print("you lost") 37 | elif user_choice =="rock": 38 | if computer_choice =="scissors": 39 | print("you won") 40 | else: 41 | print("you lost") 42 | elif choice == 3: 43 | dice = random.randint(1, 7) 44 | print("Dice rolled:", dice) 45 | 46 | target = random.randint(1, 100) 47 | while True: 48 | guess = int(input("Guess a number between 1 and 100: ")) 49 | if guess == target: 50 | print("You won!") 51 | break 52 | elif guess>target: 53 | print("Your guess is High") 54 | elif guess= 0: 6 | n =n // 10 7 | 8 | 9 | i += 1 10 | return i 11 | 12 | def sum(n): 13 | i = count_digits(n) 14 | s = 0 15 | while n > 0: 16 | digit = n/10 17 | n /= 10 18 | s += pow(digit,i) 19 | return s 20 | 21 | 22 | num = 1634 23 | 24 | 25 | s = sum(num) 26 | 27 | 28 | if s == num: 29 | print('Given number is an Armstrong Number') 30 | else: 31 | print('Given number is not an Armstrong Number') 32 | 33 | n=input("Enter Number:") 34 | c=0 35 | def arm(n): 36 | for i in n: 37 | c+=int(i)**len(n) 38 | if c==int(n): 39 | print("It is Armstrong number") 40 | else: 41 | print("It is not Armstrong Number") 42 | 43 | arm(n) 44 | -------------------------------------------------------------------------------- /problems/medium/m16.py: -------------------------------------------------------------------------------- 1 | # Program to Generate a Random Password 2 | import random 3 | import string 4 | 5 | def generate_password(length): 6 | characters = string.ascii_letters + string.digits 7 | return "".join(random.choice(characters) for i in range(length)) 8 | 9 | length = int(input("Enter password length: ")) 10 | print(generate_password(length)) 11 | -------------------------------------------------------------------------------- /problems/medium/m17.py: -------------------------------------------------------------------------------- 1 | '''Write a program to reverse a given list without using built-in functions''' 2 | def reverse_list(lst): 3 | 4 | 5 | start = 0 6 | end = len(lst) -1 7 | 8 | 9 | while start < end: 10 | 11 | lst[start], lst[end] = lst[end], lst[start] 12 | 13 | 14 | start+= 1 15 | end = 1 16 | 17 | return lst 18 | 19 | start = 0 20 | end = len(lst)-1 21 | while start < end: 22 | lst[start], lst[end] = lst[end], lst[start] 23 | start += 1 24 | end -= 1 25 | return lst 26 | 27 | lists=[] 28 | start = -1 29 | end=len(lst) 30 | for i in lst: 31 | st=lst[-i] 32 | lists.append(st) 33 | return(lists) 34 | input_list = [1, 2, 3, 4, 5] 35 | print("Original list:", input_list) 36 | 37 | return[lst[i] for i in range(-1,-len(lst)-1,-1)] 38 | 39 | -------------------------------------------------------------------------------- /problems/medium/m2.py: -------------------------------------------------------------------------------- 1 | def array_operations_menu(): 2 | print("1. Sum of Array") 3 | print("2. Largest Element") 4 | print("3. Smallest Element") 5 | print("4. Sort Array") 6 | 7 | try: 8 | choice = int(input("Enter your choice: ")) 9 | 10 | arr = list(map(int, input("Enter array elements separated by space: ").split())) 11 | 12 | if choice == 1: 13 | print("Sum:", sum(arr)) 14 | elif choice == 2: 15 | print("Largest Element:", max(arr)) 16 | elif choice == 3: 17 | print("Smallest Element:", min(arr)) 18 | elif choice == 4: 19 | print("Sorted Array:",sorted(arr)) 20 | else: 21 | print("Invalid option") 22 | except ValueError: 23 | print("Invalid option") 24 | 25 | choice = int(input("Enter your choice: ")) 26 | 27 | -------------------------------------------------------------------------------- /problems/medium/m3.py: -------------------------------------------------------------------------------- 1 | 2 | # solve . Find the bugs and solve it 3 | 4 | def string_manipulation_menu(): 5 | print("1. Count Vowels") 6 | print("2. Reverse String") 7 | print("3. Check Palindrome") 8 | print("4. Replace Substring") 9 | 10 | choice=int(input("Enter your choice")) 11 | 12 | 13 | choice = int(input("Enter your choice: ")) 14 | 15 | if choice == 1: 16 | s = str(input("Enter a string: ")) 17 | 18 | 19 | s = input("Enter a string: ") 20 | 21 | if choice == 1: 22 | vowels = "a","e","i","o","u","A","E","I","O","U" 23 | 24 | count = 0 25 | lst=[] 26 | for char in s: 27 | if char in vowels: 28 | 29 | count += 1 30 | print("Number of Vowels:", count) 31 | elif choice == 2: 32 | s = str(input("Enter a string: ")) 33 | print("Reversed String:", s[::-1]) 34 | elif choice == 3: 35 | s = str(input("Enter a string: ")) 36 | if s[::-1] != s: 37 | print("Not a Palindrome") 38 | 39 | 40 | if char not in lst: 41 | count += 1 42 | lst.append(char) 43 | print("Number of Vowels:", count,lst) 44 | elif choice == 2: 45 | print("Reversed String:", s[::-1]) 46 | elif choice == 3: 47 | if s[::-1] == s: 48 | print("Palindrome") 49 | 50 | else: 51 | print("Palindrome") 52 | elif choice == 4: 53 | 54 | s = str(input("Enter a string: ")) 55 | old = input("Substring to replace: ") 56 | new = input("Replacement substring: ") 57 | s=s.replace(old,new) 58 | print("Updated String:", s) 59 | else: 60 | print("Invalid option") 61 | string_manipulation_menu() 62 | 63 | srr1="" 64 | old = input("Substring to replace: ") 65 | new = input("Replacement substring: ") 66 | for char in s: 67 | if char==old: 68 | new=char 69 | srr1+=char 70 | else: 71 | srr1+=char 72 | 73 | print("Updated String:",srr1) 74 | else: 75 | print("Invalid option") 76 | 77 | string_manipulation_menu() 78 | 79 | 80 | count += 1 81 | print("Number of Vowels:", count) 82 | elif choice == 2: 83 | print("Reversed String:", s[::-1]) 84 | elif choice == 3: 85 | if s[::-1] == s: 86 | 87 | count += 1 88 | print("Number of Vowels:", count) 89 | elif choice == 2: 90 | print("Reversed String:", s[::-1]) 91 | elif choice == 3: 92 | if s == s[::-1]: 93 | print("Palindrome") 94 | 95 | count += 1 96 | print("Number of Vowels:", count) 97 | elif choice == 2: 98 | 99 | print("Reversed String:", s[::-1]) 100 | 101 | 102 | string_manipulation_menu() 103 | 104 | -------------------------------------------------------------------------------- /problems/medium/m4.py: -------------------------------------------------------------------------------- 1 | def number_analysis_menu(): 2 | print("1. Check Prime") 3 | print("2. Factorial") 4 | print("3. Fibonacci Sequence") 5 | print("4. Sum of Digits") 6 | 7 | choice = int(input("Enter your choice: ")) 8 | 9 | n = int(input("Enter a number: ")) 10 | 11 | if choice == 1: 12 | 13 | a=0 14 | if n<1: 15 | print("not a prime") 16 | elif n==2: 17 | print("prime") 18 | else: 19 | a=int(n**0.5)+1 20 | for i in range(2,a): 21 | if (n%i==0): 22 | print("not a prime") 23 | break 24 | 25 | is_prime = True 26 | for i in range(2, n): 27 | if n % i == 0: 28 | is_prime = False 29 | if is_prime: 30 | print("The Number is Prime Number") 31 | else: 32 | print("The Number is Not a Prime Number") 33 | 34 | elif choice == 2: 35 | factorial = 1 36 | for i in range(1, n + 1): 37 | factorial *= i 38 | print("Factorial:", factorial) 39 | elif choice == 3: 40 | fib = [0, 1] 41 | for i in range(1,n): 42 | fib.append(fib[-1] + fib[-2]) 43 | print("Fibonacci Sequence:", fib) 44 | elif choice == 4: 45 | total = 0 46 | while n > 0: 47 | total += n % 10 48 | n //= 10 49 | print("Sum of Digits:", total) 50 | else: 51 | print("Invalid option") 52 | number_analysis_menu() 53 | 54 | 55 | 56 | try: 57 | choice = int(input("Enter your choice: ")) 58 | if choice not in [1, 2, 3, 4]: 59 | print("Invalid option. Please select a number between 1 and 4.") 60 | return 61 | except ValueError: 62 | print("Invalid input. Please enter a number between 1 and 4.") 63 | return 64 | 65 | -------------------------------------------------------------------------------- /problems/medium/m5.py: -------------------------------------------------------------------------------- 1 | def matrix_operations_menu(): 2 | print("1. Add Matrices") 3 | print("2. Multiply Matrices") 4 | print("3. Transpose Matrix") 5 | choice = int(input("Enter your choice: ")) 6 | 7 | if choice == 1: 8 | rows, cols = map(int, input("Enter rows and columns: ").split()) 9 | mat1 = [[int(x) for x in input("Enter elements of matrix 1 (row-wise): ").split()] for _ in range(rows)] 10 | mat2 = [[int(x) for x in input("Enter elements of matrix 2 (row-wise): ").split()] for _ in range(rows)] 11 | result = [[mat1[i][j] + mat2[i][j] for j in range(cols)] for i in range(rows)] # Corrected to addition 12 | print("Resultant Matrix:", result) 13 | elif choice == 2: 14 | rows1, cols1 = map(int, input("Enter rows and columns for matrix 1: ").split()) 15 | rows2, cols2 = map(int, input("Enter rows and columns for matrix 2: ").split()) 16 | if cols1 != rows2: 17 | print("Matrix multiplication not possible (incompatible dimensions)") 18 | return 19 | mat1 = [[int(x) for x in input("Enter elements of matrix 1 (row-wise): ").split()] for _ in range(rows1)] 20 | mat2 = [[int(x) for x in input("Enter elements of matrix 2 (row-wise): ").split()] for _ in range(rows2)] 21 | result = [[0 for _ in range(cols2)] for _ in range(rows1)] # Corrected dimensions 22 | for i in range(rows1): 23 | for j in range(cols2): 24 | for k in range(cols1): # Iterate through common dimension 25 | result[i][j] += mat1[i][k] * mat2[k][j] 26 | print("Resultant Matrix:", result) 27 | elif choice == 3: 28 | rows, cols = map(int, input("Enter rows and columns: ").split()) 29 | mat = [[int(x) for x in input("Enter elements of matrix (row-wise): ").split()] for _ in range(rows)] 30 | transpose = [[mat[j][i] for j in range(rows)] for i in range(cols)] # Corrected transpose logic 31 | print("Transpose:", transpose) 32 | else: 33 | print("Invalid option") 34 | for j in range(cols): 35 | transpose[i][j] = mat[j][i] 36 | print("Transpose:", transpose) 37 | else: 38 | print("Invalid option") 39 | matrix_operations_menu() -------------------------------------------------------------------------------- /problems/medium/m6.py: -------------------------------------------------------------------------------- 1 | 2 | def file_handling_menu(): 3 | print("1. Write to File") 4 | print("2. Read File") 5 | print("3. Count Lines, Words, Characters") 6 | print("4. Append to File") 7 | choice = int(input("Enter your choice: ")) 8 | 9 | 10 | if choice == 1: 11 | data = input("Enter data to write: ") 12 | with open("abc.txt", "w") as f: 13 | f.write(data) 14 | f.close() 15 | elif choice == 2: 16 | with open("abc.txt", "r") as f: 17 | print(f.read()) 18 | 19 | f.close() 20 | elif choice == 3: 21 | with open("abc.txt", "r") as f: 22 | lines = len(f.read().split("\n")) 23 | chars = len(f.read().split()) 24 | words = sum(len(line) for line in f.readlines()) 25 | print("Lines:", lines, "Words:", words, "Characters:", chars) 26 | 27 | f.close() 28 | elif choice == 4: 29 | data = input("Enter data to append: ") 30 | f = open("abc.txt","a") 31 | f.append(data) 32 | 33 | 34 | f.close() 35 | else: 36 | print("Invalid option") 37 | 38 | file_handling_menu() 39 | 40 | -------------------------------------------------------------------------------- /problems/medium/m7.py: -------------------------------------------------------------------------------- 1 | def student_record_menu(): 2 | students = {} # Dictionary to store student records 3 | 4 | while True: 5 | print("\n1. Add Student Record") 6 | print("2. Display All Records") 7 | print("3. Search Student by Roll Number") 8 | print("4. Delete Student Record") 9 | print("5. Exit") 10 | choice = int(input("Enter your choice: ")) 11 | 12 | 13 | 14 | if choice == 1: 15 | roll = input("Enter Roll Number: ") 16 | name = input("Enter Name: ") 17 | marks = int(input("Enter Marks: ")) #input type changed to int 18 | students[roll] = (name, marks) #the key is changed to roll no and the values are names and marks as tuples 19 | elif choice == 2: 20 | for roll, details in students.items(): 21 | print(f"Roll: {roll}, Name: {details[0]}, Marks: {details[1]}") 22 | elif choice == 3: 23 | roll = input("Enter Roll Number to Search: ") 24 | if roll in students: 25 | print(f"Name: {students[roll][0]}, Marks: {students[roll][1]}") 26 | else: 27 | print("Record Not Found") #else record found --> record not found 28 | elif choice == 4: 29 | roll = input("Enter Roll Number to Delete: ") 30 | if roll in students: 31 | del students[roll] 32 | print("Record Deleted") 33 | else: 34 | print("Error occured") #changed to correct message 35 | elif choice == 5: 36 | print("Exiting...") 37 | break 38 | 39 | 40 | student_record_menu() #function call made 41 | 42 | if choice == 1: 43 | roll = input("Enter Roll Number: ") 44 | name = input("Enter Name: ") 45 | marks = input("Enter Marks: ") 46 | 47 | students[name] = (roll, marks) 48 | elif choice == 2: 49 | for details in students.keys(): 50 | print(details," : roll no",students[details][0],"mark ",students[details][1]) 51 | elif choice == 3: 52 | roll = input("Enter Roll Number to Search: ") 53 | for i in students.values(): 54 | if roll in i[0] or [1]: 55 | print( next( j for j in students.keys() if students[j][0] == roll)) 56 | else: 57 | print("Record not Found") 58 | elif choice == 4: 59 | roll =input("Enter Roll Number to Delete: ") 60 | a="" 61 | for i in students: 62 | 63 | if students[i][0]==roll: 64 | a+=i 65 | else: 66 | print("record not found") 67 | del students[a] 68 | print(students) 69 | 70 | students[roll] = (name, marks) 71 | elif choice == 2: 72 | for roll, details in students.items(): 73 | 74 | elif choice == 3: 75 | roll = input("Enter Roll Number to Search: ") 76 | if roll in students: 77 | print(f"Name: {students[details][0]}, Marks: {students[roll][1]}") 78 | else: 79 | print("Record Found") 80 | elif choice == 4: 81 | roll = input("Enter Roll Number to Delete: ") 82 | if roll in students: 83 | del students[details[0]] 84 | print("Record Deleted") 85 | else: 86 | print("Record Deleted Successfully") 87 | 88 | elif choice == 5: 89 | print("Exiting...") 90 | break 91 | else: 92 | print("Invalid Choice") 93 | 94 | 95 | -------------------------------------------------------------------------------- /problems/medium/m8.py: -------------------------------------------------------------------------------- 1 | def conversion_menu(): 2 | while True: 3 | print("\n1. Celsius to Fahrenheit") 4 | print("2. Fahrenheit to Celsius") 5 | print("3. Decimal to Binary, Octal, Hexadecimal") 6 | print("4. Kilometers to Miles and Vice Versa") 7 | print("5. Exit") 8 | choice = int(input("Enter your choice: ")) 9 | 10 | if choice == 1: 11 | celsius = int(input("Enter temperature in Celsius: ")) 12 | fahrenheit = (celsius * 5 / 9) + 32 13 | print("Temperature in Fahrenheit:", fahrenheit) 14 | elif choice == 2: 15 | fahrenheit = int(input("Enter temperature in Fahrenheit: ")) 16 | celsius = (fahrenheit - 32) * 5 / 9 17 | print("Temperature in Celsius:", celsius) 18 | elif choice == 3: 19 | decimal = int(input("Enter a decimal number: ")) 20 | print(f"Binary: {bin(decimal)}, Octal: {oct(decimal):O}, Hexadecimal: {hex(decimal):X}") 21 | elif choice == 4: 22 | selection = int(input("Enter 1 for KM to Miles (or) 2 for Miles to KM : ")) 23 | if selection == 1: 24 | km = float(input("Enter distance in kilometers: ")) 25 | miles = km / 0.621371 26 | print("Distance in Miles:", miles) 27 | else: 28 | miles = float(input("Enter distance in miles :")) 29 | km = miles * 1.609 30 | print("Distance in Kilometres:", km) 31 | elif choice == 5: 32 | print("Exiting...") 33 | break 34 | else: 35 | print("Invalid Choice") 36 | -------------------------------------------------------------------------------- /problems/medium/m9.py: -------------------------------------------------------------------------------- 1 | def set_operations_menu(): 2 | while True: 3 | print("\n1. Union of Two Sets") 4 | print("2. Intersection of Two Sets") 5 | print("3. Difference of Two Sets") 6 | print("4. Check Subset") 7 | print("5. Exit") 8 | choice = int(input("Enter your choice: ")) 9 | 10 | # Taking input and converting to sets 11 | set1 = set(input("Enter elements of Set 1 separated by space: ").split()) 12 | set2 = set(input("Enter elements of Set 2 separated by space: ").split()) 13 | 14 | if choice == 1: 15 | 16 | print("Union:", set1 | set2) # Corrected union calculation using | 17 | elif choice == 2: 18 | print("Intersection:", set1 & set2) # Corrected intersection calculation using & 19 | elif choice == 3: 20 | print("Difference:", set1 - set2) # Corrected difference calculation using - 21 | elif choice == 4: 22 | if set1.issubset(set2): # Corrected subset check 23 | 24 | print("Union:", set1 | set2) 25 | elif choice == 2: 26 | print("Intersection:", set1 & set2) 27 | elif choice == 3: 28 | print("Difference:", set1 - set2) 29 | elif choice == 4: 30 | if set1 >= set2: 31 | 32 | print("Set 1 is a subset of Set 2") 33 | else: 34 | print("Set 1 is not a subset of Set 2") 35 | elif choice == 5: 36 | print("Exiting...") 37 | break 38 | else: 39 | print("Invalid Choice") 40 | 41 | 42 | # Calling the function to run 43 | set_operations_menu() 44 | 45 | 46 | -------------------------------------------------------------------------------- /tests/contribute-test.md: -------------------------------------------------------------------------------- 1 | ### Contribute your testcases here. --------------------------------------------------------------------------------