├── Hectober ├── Python Programs ├── findcirclearea.py ├── sum_till_n.py ├── Web Srapping Tool.py ├── hello-world.py ├── max_integer.py ├── lastdigit.py ├── factorial.py ├── binary-to-decimal-conversion.py ├── add_two_number.py ├── add_two_numbers.py ├── distance_between_points.py ├── factor_finder.py ├── volume_area.py ├── Pascal_Triangle.py ├── factorial-of-a-number.py ├── max_min_digits.py ├── shortest_possible_path.py ├── leap_year.py ├── multiplication_table.py ├── comparing_number.py ├── countdown.py ├── palindrome-checker.py ├── Jump_game.py ├── age_validator.py ├── delannoy_generator.py ├── prime_check.py ├── web_bot.py ├── display_calendar.py ├── fibonacci_series_aditya.py ├── speed.py ├── shuffle_decks.py ├── photo_cartonizer.py ├── TriangleQuest.py ├── Program-to-add-two-matricies.py ├── prime number .py ├── FIBONACCI.py ├── bubblesort.py ├── reverse string & paliondrome.py ├── lengthOfLongestSubstring.py ├── Solid_Butterfly_list.py ├── longestPalindrome.py ├── Binary_GCD_recursive.py ├── NearestPrime.py ├── text_alignment.py ├── bot_friend.py ├── insertion-sort.py ├── binary_to_decimal.py ├── linearSearch.py ├── hashing.py ├── kadane.py ├── InstagramProofileExtracter.py ├── NoIdea.py ├── CoinChangeProblem.py ├── guess_the_number.py ├── KnapsackProblem.py ├── nqueen.py ├── best_first_search.py ├── binarry-search.py ├── LongestPalindromeSubseq.py ├── PDFMerger.py ├── rock-paper-scissors.py ├── pangramChecker.py ├── QuickSort.py ├── hollow_diamond_alphabets.py ├── prime_number_generator.py ├── 2sumsolu.py ├── Program to Convert Hexadecimal Number to Binary.py ├── 3sum_sol.py ├── speachtotext.py ├── library Management.py ├── To_do_list.py ├── Password_checker.py ├── ASCII_Art_ Generator.py ├── URL_QR_Generator.py ├── AiNotesApp.py ├── Program to convert a binary number to octal.py ├── simple_text_editor.py ├── a_star_algorithm.py ├── Tarjan-Algorithm.py ├── calculator.py ├── optimized_dsu.py ├── convert a given number to words.py ├── MakeSumDivisibleByP.py ├── Floyd-Warshall-Algo.py ├── weatherApplication.py ├── flashcards.py ├── Program to convert a given number to words.py ├── Color Mind Challenge.py ├── healthy_eyes.py ├── Tim_Sort.py ├── todo_list.py ├── TicTacToe.py └── Website_blocker.py ├── Coffee-Machine ├── tempCodeRunnerFile.py ├── __pycache__ │ ├── menu.cpython-39.pyc │ ├── coffee_maker.cpython-39.pyc │ └── money_machine.cpython-39.pyc ├── main.py ├── coffee_maker.py ├── menu.py └── money_machine.py ├── classes.pkl ├── words.pkl ├── chatbot_model.h5 ├── FaceDetection ├── 1.mp4 ├── 2.mp4 ├── 3.mp4 ├── 4.mp4 └── FaceDetectionMin.py ├── Dice Rolling Simulator Using Python ├── die1.PNG ├── die2.PNG ├── die3.PNG ├── die4.PNG ├── die5.PNG ├── die6.PNG └── dice.py ├── Check for Palindrome ├── CountofLine.py ├── Reverse ├── Sum_of_Natural_Numbers.py ├── A Simple To-Do List ├── Matrix_creation_of_n.py ├── CountdownTimer.py ├── get_nth_term_fib.py ├── multiply two numbers provided by the user in real-time in python.c ├── divide two numbers ├── Prime.py ├── Add Two Number ├── json_formatter.py ├── random_quotes.py ├── TowerOfHanoi.py ├── area_triangle.py ├── Define String ├── Anurupa_hactober_2022 ├── Check_armstrong.py ├── Simple Command-Line Calculator ├── Solve_Quadratic_Equation.py ├── Merge_Mails.py ├── README.md ├── 2022_hactoberfest_Anurupa ├── Guess_the_Number_Game.py ├── Android_turtle.py ├── Fibbonacci.py ├── Check Prime Number in range ├── multiply_matrices.py ├── timeit_decorator.py ├── caesar_cipher.py ├── LinkList in phyton ├── demonstrates_handling.py ├── Anurupa_hactober ├── QuickSort.py ├── guessing-game.py ├── Simple_Calculator.py ├── pass_generator.py ├── Password-Generator.py ├── BasicResumeAnalyzer.py ├── Hand-tracking Module ├── handTrackMin.py └── handTrackingModule.py ├── SriparnaChatBot.py ├── SrTraining.py ├── currency_converter.py ├── SHORTEST PATH FINDER(BFS).py ├── Youtube_video_downloader.py ├── hand-detection.py ├── hangman.py ├── linked_list_middle_solution.py ├── intents.json └── LogFileAnalyzer.py /Hectober: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Python Programs/findcirclearea.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python Programs/sum_till_n.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python Programs/Web Srapping Tool.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python Programs/hello-world.py: -------------------------------------------------------------------------------- 1 | print("Hello World!") -------------------------------------------------------------------------------- /Coffee-Machine/tempCodeRunnerFile.py: -------------------------------------------------------------------------------- 1 | 2 | # money_machine.report() -------------------------------------------------------------------------------- /Python Programs/max_integer.py: -------------------------------------------------------------------------------- 1 | print(max(map(int, input().split()))) 2 | -------------------------------------------------------------------------------- /classes.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/classes.pkl -------------------------------------------------------------------------------- /words.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/words.pkl -------------------------------------------------------------------------------- /chatbot_model.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/chatbot_model.h5 -------------------------------------------------------------------------------- /FaceDetection/1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/FaceDetection/1.mp4 -------------------------------------------------------------------------------- /FaceDetection/2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/FaceDetection/2.mp4 -------------------------------------------------------------------------------- /FaceDetection/3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/FaceDetection/3.mp4 -------------------------------------------------------------------------------- /FaceDetection/4.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/FaceDetection/4.mp4 -------------------------------------------------------------------------------- /Python Programs/lastdigit.py: -------------------------------------------------------------------------------- 1 | def LastDigit(N): 2 | return N % 10 3 | N=int(input()) 4 | print(LastDigit(N)) 5 | -------------------------------------------------------------------------------- /Coffee-Machine/__pycache__/menu.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Coffee-Machine/__pycache__/menu.cpython-39.pyc -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die1.PNG -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die2.PNG -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die3.PNG -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die4.PNG -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die5.PNG -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/die6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Dice Rolling Simulator Using Python/die6.PNG -------------------------------------------------------------------------------- /Check for Palindrome: -------------------------------------------------------------------------------- 1 | def is_palindrome(s): 2 | return s == s[::-1] 3 | 4 | print(is_palindrome("radar")) # True 5 | print(is_palindrome("hello")) # False 6 | -------------------------------------------------------------------------------- /Coffee-Machine/__pycache__/coffee_maker.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Coffee-Machine/__pycache__/coffee_maker.cpython-39.pyc -------------------------------------------------------------------------------- /Coffee-Machine/__pycache__/money_machine.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rishi098/Basic-Python-Programs/HEAD/Coffee-Machine/__pycache__/money_machine.cpython-39.pyc -------------------------------------------------------------------------------- /Python Programs/factorial.py: -------------------------------------------------------------------------------- 1 | num = int(input()) 2 | def factorial(n): 3 | fact = 1 4 | for i in range(1,n+1): 5 | fact = i*fact 6 | return fact 7 | print(factorial(num)) 8 | -------------------------------------------------------------------------------- /Python Programs/binary-to-decimal-conversion.py: -------------------------------------------------------------------------------- 1 | binary_str = input("Enter a binary number: ") 2 | decimal_number = int(binary_str, 2) 3 | print(f"The decimal value of {binary_str} is {decimal_number}") 4 | -------------------------------------------------------------------------------- /Python Programs/add_two_number.py: -------------------------------------------------------------------------------- 1 | num1 = 1.5 2 | num2 = 6.3 3 | 4 | # Add two numbers 5 | sum = num1 + num2 6 | 7 | # Display the sum 8 | print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) 9 | -------------------------------------------------------------------------------- /Python Programs/add_two_numbers.py: -------------------------------------------------------------------------------- 1 | num1 = 1.5 2 | num2 = 6.3 3 | 4 | # Add two numbers 5 | sum = num1 + num2 6 | 7 | # Display the sum 8 | print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) 9 | -------------------------------------------------------------------------------- /CountofLine.py: -------------------------------------------------------------------------------- 1 | def file_len(fname): 2 | with open(fname) as f: 3 | for i, l in enumerate(f): 4 | pass 5 | return i + 1 6 | 7 | print(file_len("my_file.txt")) //print the lenght of text in file 8 | -------------------------------------------------------------------------------- /Python Programs/distance_between_points.py: -------------------------------------------------------------------------------- 1 | def calculate_distance(x1, y1, x2, y2): 2 | return round(((x2-x1)**2 + (y2-y1)**2)**.5,2) 3 | x1,y1,x2,y2 = map(int, input().split()) 4 | print(calculate_distance(x1, y1, x2, y2)) 5 | -------------------------------------------------------------------------------- /Reverse: -------------------------------------------------------------------------------- 1 | rows = 6 2 | 3 | for num in range(rows): 4 | 5 | for i in range(num): 6 | 7 | print(num, end=” “) # print number 8 | 9 | # line after each row to display pattern correctly 10 | 11 | print(” “) 12 | -------------------------------------------------------------------------------- /Python Programs/factor_finder.py: -------------------------------------------------------------------------------- 1 | def find_factors(n): # TAKING INPUT 2 | for i in range(1,n+1): #APPLYING LOOPS 3 | if n%i==0: #CONDITIONING FOR FACTORS 4 | print(i,end=" ") 5 | a=int(input()) 6 | find_factors(a) -------------------------------------------------------------------------------- /Python Programs/volume_area.py: -------------------------------------------------------------------------------- 1 | def Surface_Area(l, b, h): 2 | return 2 * (l * b + b * h + h * l) 3 | 4 | def Volume(l, b, h): 5 | return l * b * h 6 | 7 | l, b, h = map(int, input().split()) 8 | 9 | print(Surface_Area(l, b, h), Volume(l, b, h)) -------------------------------------------------------------------------------- /Python Programs/Pascal_Triangle.py: -------------------------------------------------------------------------------- 1 | a=int(input()) 2 | s=[1] 3 | for i in range(a): 4 | print(" "*(a-i)+" ".join(map(str,s))) 5 | k=[1] 6 | for j in range(len(s)-1): 7 | k.append(s[j]+s[j+1]) 8 | k.append(1) 9 | s=k 10 | -------------------------------------------------------------------------------- /Python Programs/factorial-of-a-number.py: -------------------------------------------------------------------------------- 1 | def factorial(): 2 | num = int(input("Enter a number: ")) 3 | fact = 1 4 | 5 | for i in range(1, num + 1): 6 | fact *= i 7 | 8 | print(f"The factorial of {num} is: {fact}") 9 | 10 | factorial() 11 | -------------------------------------------------------------------------------- /Python Programs/max_min_digits.py: -------------------------------------------------------------------------------- 1 | def min_max_digits(n): 2 | 3 | digits = [int(digit) for digit in str(n)] 4 | 5 | min_digit = min(digits) 6 | max_digit = max(digits) 7 | return min_digit,max_digit 8 | n=int(input()) 9 | print(min_max_digits(n)) 10 | -------------------------------------------------------------------------------- /Python Programs/shortest_possible_path.py: -------------------------------------------------------------------------------- 1 | def calculate_distance(x1, y1, x2, y2): 2 | d=((x2-x1)**2+(y2-y1)**2)**0.5 3 | e=round(d,2) 4 | return e 5 | x1,y1,x2,y2=map(int,input().split()) 6 | print(calculate_distance(x1,y1,x2,y2)) 7 | ### ENTER THE INPUT IN A SINGLE LINE BY USING SPACES LIKE 1 2 4 7 ### -------------------------------------------------------------------------------- /Sum_of_Natural_Numbers.py: -------------------------------------------------------------------------------- 1 | if num < 0: 2 | print("Enter a positive number") 3 | else: 4 | sum = 0 5 | # use while loop to iterate until zero 6 | while(num > 0): 7 | sum += num 8 | num -= 1 9 | print("The sum is", sum) 10 | 11 | 12 | 13 | OUTPUT:- 14 | The sum is 136 15 | -------------------------------------------------------------------------------- /Python Programs/leap_year.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | if n%4==0 and n%100!=0: 3 | print(f"{n} is a leap year") 4 | elif n%4==0 and n%100==0: 5 | if n%400==0: 6 | print(f"{n} is a leap year") 7 | else: 8 | print(f"{n} is not a leap year") 9 | elif n%4!=0: 10 | print(f"{n} is not a leap year") -------------------------------------------------------------------------------- /A Simple To-Do List: -------------------------------------------------------------------------------- 1 | to_do_list = [] 2 | 3 | def add_task(task): 4 | to_do_list.append(task) 5 | print(f"Task '{task}' added.") 6 | 7 | def show_tasks(): 8 | for idx, task in enumerate(to_do_list, 1): 9 | print(f"{idx}. {task}") 10 | 11 | add_task("Write code") 12 | add_task("Test code") 13 | show_tasks() 14 | -------------------------------------------------------------------------------- /Matrix_creation_of_n.py: -------------------------------------------------------------------------------- 1 | # Python3 code to demonstrate 2 | # matrix creation of n * n 3 | # using list comprehension 4 | 5 | N = 4 6 | 7 | print("The dimension : " + str(N)) 8 | 9 | res = [list(range(1 + N * i, 1 + N * (i + 1))) 10 | for i in range(N)] 11 | 12 | print("The created matrix of N * N: " + str(res)) 13 | -------------------------------------------------------------------------------- /Python Programs/multiplication_table.py: -------------------------------------------------------------------------------- 1 | # Multiplication table (from 1 to 10) in Python 2 | 3 | num = 12 4 | 5 | # To take input from the user 6 | # num = int(input("Display multiplication table of? ")) 7 | 8 | # Iterate 10 times from i = 1 to 10 9 | for i in range(1, 11): 10 | print(num, 'x', i, '=', num*i) 11 | -------------------------------------------------------------------------------- /Python Programs/comparing_number.py: -------------------------------------------------------------------------------- 1 | num1 = int(input("Enter a number ")) 2 | 3 | num2 = int(input("Enter another number ")) 4 | 5 | if num1 > num2: 6 | print(f"{num1} is greater than {num2}") 7 | elif num1 == num2: 8 | print(f"{num1} is equal to {num2}") 9 | else: 10 | print(f"{num1} is small than {num2}") 11 | -------------------------------------------------------------------------------- /CountdownTimer.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def countdown(time_sec): 4 | while time_sec: 5 | mins, secs = divmod(time_sec, 60) 6 | timeformat = '{:02d}:{:02d}'.format(mins, secs) 7 | print(timeformat, end='\r') 8 | time.sleep(1) 9 | time_sec -= 1 10 | 11 | print("stop") 12 | 13 | countdown(5) 14 | -------------------------------------------------------------------------------- /get_nth_term_fib.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | """ 3 | Returns the nth term in the Fibonacci sequence. 4 | 5 | Done by adding the two previous terms to get the next term. 6 | 7 | :arg n: int - The term to find in the Fibonacci sequence. 8 | """ 9 | if n <= 1: 10 | return n 11 | return fibonacci(n - 1) + fibonacci(n - 2) 12 | -------------------------------------------------------------------------------- /Python Programs/countdown.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def countdown(time_sec): 4 | while time_sec: 5 | mins, secs = divmod(time_sec, 60) 6 | timeformat = '{:02d}:{:02d}'.format(mins, secs) 7 | print(timeformat, end='\r') 8 | time.sleep(1) 9 | time_sec -= 1 10 | 11 | print("stop") 12 | 13 | countdown(5) -------------------------------------------------------------------------------- /Python Programs/palindrome-checker.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(number): 2 | return str(number) == str(number)[::-1] 3 | 4 | def check_palindrome(): 5 | num = int(input("Enter a number: ")) 6 | if is_palindrome(num): 7 | print(f"{num} is a palindrome.") 8 | else: 9 | print(f"{num} is not a palindrome.") 10 | 11 | check_palindrome() 12 | -------------------------------------------------------------------------------- /Python Programs/Jump_game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums): 3 | max_reachable = 0 4 | n = len(nums) 5 | 6 | for i in range(n): 7 | if i > max_reachable: 8 | return False 9 | max_reachable = max(max_reachable, nums[i] + i) 10 | 11 | return True 12 | 13 | # TC = O(N) 14 | # SC = O(1) 15 | -------------------------------------------------------------------------------- /multiply two numbers provided by the user in real-time in python.c: -------------------------------------------------------------------------------- 1 | num_1 = input("Enter the first number") 2 | num_2 = input("Enter the second number") 3 | 4 | product = float(num_1) * float(num_2) 5 | 6 | print("Product of {} and {} is {}".format(num_1, num_2,product)) 7 | 8 | 9 | OUTPUT:- 10 | 11 | Enter the first number 2 12 | Enter the second number 3 13 | Product of 2 and 3 is 6.0 14 | -------------------------------------------------------------------------------- /Python Programs/age_validator.py: -------------------------------------------------------------------------------- 1 | while True: 2 | a=int(input("Enter your age:")) 3 | 4 | 5 | if(a>=18): 6 | print("You are above the age of consent \n Good for you") 7 | # print(" Good for you") 8 | 9 | elif(a<=0): 10 | print("You are entering an invalid age") 11 | 12 | else: 13 | print("You are below the age of consent") 14 | 15 | print("End of program") -------------------------------------------------------------------------------- /Python Programs/delannoy_generator.py: -------------------------------------------------------------------------------- 1 | def DelannoyGenerator(n,m): 2 | if n==0 or m==0: 3 | d = 1 4 | else: 5 | d = DelannoyGenerator(n-1,m) + DelannoyGenerator(n,m-1) + DelannoyGenerator(n-1,m-1) 6 | 7 | return d 8 | 9 | n = int(input("Provide the 'n' value: ")) 10 | m = int(input("Provide the 'm' value: ")) 11 | 12 | print(f"The delannoy number is: {DelannoyGenerator(n,m)}") 13 | -------------------------------------------------------------------------------- /Python Programs/prime_check.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | if n<=1: 3 | return False 4 | if n==2: 5 | return True 6 | if n%2==0: 7 | return False 8 | for i in range(3,int((n)**0.5)+1): 9 | if n%i==0: 10 | return False 11 | return True 12 | n=int(input()) 13 | if is_prime(n): 14 | print("YES") 15 | else: 16 | print("NO") -------------------------------------------------------------------------------- /divide two numbers: -------------------------------------------------------------------------------- 1 | #Python program to divide two numbers 2 | 3 | num1 = 10 4 | num2 = 2 5 | 6 | #Divide two no 7 | divided = num1 / num2 8 | 9 | 10 | #printing values 11 | if divided >=1 : 12 | print("Divide of {0} and {1} is {2}" .format(num1, num2, divided)) 13 | 14 | ------------------------------------------------------------ 15 | 16 | #Output:- 17 | Divide of 10 and 2 is 5 18 | -------------------------------------------------------------------------------- /Python Programs/web_bot.py: -------------------------------------------------------------------------------- 1 | # pip install selenium 2 | 3 | import time 4 | from selenium import webdriver 5 | from selenium.webdriver.common.keys import Keys 6 | 7 | bot = webdriver.Chrome("chromedriver.exe") 8 | bot.get('http://www.google.com') 9 | 10 | search = bot.find_element_by_name('q') 11 | search.send_keys("@codedev101") 12 | search.send_keys(Keys.RETURN) 13 | time.sleep(5) 14 | bot.quit() -------------------------------------------------------------------------------- /Prime.py: -------------------------------------------------------------------------------- 1 | num = 11 2 | # If given number is greater than 1 3 | if num > 1: 4 | # Iterate from 2 to n / 2 5 | for i in range(2, int(num/2)+1): 6 | # If num is divisible by any number between 7 | # 2 and n / 2, it is not prime 8 | if (num % i) == 0: 9 | print(num, "is not a prime number") 10 | break 11 | else: 12 | print(num, "is a prime number") 13 | else: 14 | print(num, "is not a prime number") 15 | -------------------------------------------------------------------------------- /Python Programs/display_calendar.py: -------------------------------------------------------------------------------- 1 | # Program to display calendar of the given month and year 2 | 3 | # importing calendar module 4 | import calendar 5 | 6 | yy = 2014 # year 7 | mm = 11 # month 8 | 9 | # To take month and year input from the user 10 | # yy = int(input("Enter year: ")) 11 | # mm = int(input("Enter month: ")) 12 | 13 | # display the calendar 14 | print(calendar.month(yy, mm)) 15 | -------------------------------------------------------------------------------- /Add Two Number: -------------------------------------------------------------------------------- 1 | #Python program to add two numbers 2 | 3 | numone = int(input("Enter The Number 1") 4 | numtwo = int(input("Enter The Number 2") 5 | 6 | #Adding two nos 7 | sum = numone + numtwo 8 | 9 | #printing values 10 | print("Sum of {0} and {1} is {2}" .format(numone, numtwo, sum)) 11 | 12 | ------------------------------------------------------------ 13 | 14 | #Output:- 15 | Sum of 15 and 12 is 27 16 | -------------------------------------------------------------------------------- /Python Programs/fibonacci_series_aditya.py: -------------------------------------------------------------------------------- 1 | """ 2 | Prints the first n terms of the Fibonacci sequence. 3 | """ 4 | 5 | n = int(input("Enter number of terms: ")) 6 | 7 | a, b = 0, 1 8 | count = 0 9 | 10 | if n <= 0: 11 | print("Please enter a positive integer") 12 | elif n == 1: 13 | print(a) 14 | else: 15 | while count < n: 16 | print(a, end=" ") 17 | a, b = b, a + b 18 | count += 1 19 | -------------------------------------------------------------------------------- /Python Programs/speed.py: -------------------------------------------------------------------------------- 1 | # pip install pyspeedtest 2 | # pip install speedtest 3 | # pip install speedtest-cli 4 | 5 | 6 | import speedtest 7 | 8 | speedTest = speedtest.Speedtest() 9 | print(speedTest.get_best_server()) 10 | 11 | 12 | print(speedTest.download()) 13 | print(speedTest.upload()) 14 | 15 | import pyspeedtest 16 | st = pyspeedtest.SpeedTest() 17 | st.ping() 18 | st.download() 19 | st.upload() -------------------------------------------------------------------------------- /Python Programs/shuffle_decks.py: -------------------------------------------------------------------------------- 1 | # Python program to shuffle a deck of card 2 | 3 | # importing modules 4 | import itertools, random 5 | 6 | # make a deck of cards 7 | deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) 8 | 9 | # shuffle the cards 10 | random.shuffle(deck) 11 | 12 | # draw five cards 13 | print("You got:") 14 | for i in range(5): 15 | print(deck[i][0], "of", deck[i][1]) 16 | -------------------------------------------------------------------------------- /json_formatter.py: -------------------------------------------------------------------------------- 1 | # filename: json_formatter.py 2 | # Run: python json_formatter.py '{"name":"Ravi","age":22}' 3 | 4 | import json, sys 5 | 6 | if len(sys.argv) != 2: 7 | print("Usage: python json_formatter.py ''") 8 | sys.exit(1) 9 | 10 | try: 11 | obj = json.loads(sys.argv[1]) 12 | print(json.dumps(obj, indent=4, sort_keys=True)) 13 | except json.JSONDecodeError as e: 14 | print("Invalid JSON:", e) 15 | -------------------------------------------------------------------------------- /random_quotes.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | quotes = [ 4 | "Keep pushing forward!", 5 | "You are capable of amazing things.", 6 | "Code is like humor. When you have to explain it, it’s bad.", 7 | "Stay hungry, stay foolish.", 8 | "Dream big, work hard." 9 | ] 10 | 11 | def random_quote(): 12 | print("Random Quote of the Day:") 13 | print(random.choice(quotes)) 14 | 15 | if __name__ == "__main__": 16 | random_quote() 17 | -------------------------------------------------------------------------------- /TowerOfHanoi.py: -------------------------------------------------------------------------------- 1 | def hanoi(disks, source, auxiliary, target): 2 | if disks == 1: 3 | print('Move disk 1 from peg {} to peg {}.'.format(source, target)) 4 | return 5 | 6 | hanoi(disks - 1, source, target, auxiliary) 7 | print('Move disk {} from peg {} to peg {}.'.format(disks, source, target)) 8 | hanoi(disks - 1, auxiliary, source, target) 9 | 10 | 11 | disks = int(input('Enter number of disks: ')) 12 | hanoi(disks, 'A', 'B', 'C') 13 | -------------------------------------------------------------------------------- /Python Programs/photo_cartonizer.py: -------------------------------------------------------------------------------- 1 | # pip install opencv-python 2 | 3 | import cv2 4 | 5 | img = cv2.imread('img.jpg') 6 | grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 7 | grayimg = cv2.medianBlur(grayimg, 5) 8 | 9 | edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5) 10 | r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV) 11 | 12 | img2 = cv2.bitwise_and(img, img, mask=mask) 13 | img2 = cv2.medianBlur(img2, 5) 14 | 15 | cv2.imwrite("cartooned.jpg", mask) -------------------------------------------------------------------------------- /area_triangle.py: -------------------------------------------------------------------------------- 1 | # Python Program to find the area of triangle 2 | 3 | a = 5 4 | b = 6 5 | c = 7 6 | 7 | # Uncomment below to take inputs from the user 8 | # a = float(input('Enter first side: ')) 9 | # b = float(input('Enter second side: ')) 10 | # c = float(input('Enter third side: ')) 11 | 12 | # calculate the semi-perimeter 13 | s = (a + b + c) / 2 14 | 15 | # calculate the area 16 | area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 17 | print('The area of the triangle is %0.2f' %area) 18 | -------------------------------------------------------------------------------- /Python Programs/TriangleQuest.py: -------------------------------------------------------------------------------- 1 | # Solution in 2 lines for Triangle Quest Problem 2 | ''' Problem Statement: 3 | You are given a positive integer N Print a numerical triangle of height N-1 like the one below: 4 | 5 | 1 6 | 22 7 | 333 8 | 4444 9 | 55555 10 | ....... 11 | 12 | Can you do it using only arithmetic operations, a single for loop and print statement? 13 | Use no more than two lines. 14 | ''' 15 | for i in range(1,int(input())): 16 | print(((10**i)//9)*i) 17 | -------------------------------------------------------------------------------- /Define String: -------------------------------------------------------------------------------- 1 | # defining strings in Python 2 | # all of the following are equivalent 3 | my_string = 'Hello' 4 | print(my_string) 5 | 6 | my_string = "Hello" 7 | print(my_string) 8 | 9 | my_string = '''Hello''' 10 | print(my_string) 11 | 12 | # triple quotes string can extend multiple lines 13 | my_string = """Hello, welcome to 14 | the world of Python""" 15 | print(my_string) 16 | 17 | Output 18 | Hello 19 | Hello 20 | Hello 21 | Hello, welcome to 22 | the world of Python 23 | -------------------------------------------------------------------------------- /Python Programs/Program-to-add-two-matricies.py: -------------------------------------------------------------------------------- 1 | X = [[1, 2, 3], 2 | [4, 5, 6], 3 | [7, 8, 9]] 4 | 5 | Y = [[9, 8, 7], 6 | [6, 5, 4], 7 | [3, 2, 1]] 8 | 9 | result = [[0, 0, 0], 10 | [0, 0, 0], 11 | [0, 0, 0]] 12 | 13 | # iterating through rows 14 | for i in range(len(X)): 15 | # iterating through columns 16 | for j in range(len(X[0])): 17 | result[i][j] = X[i][j] + Y[i][j] 18 | 19 | for r in result: 20 | print(r) 21 | -------------------------------------------------------------------------------- /Anurupa_hactober_2022: -------------------------------------------------------------------------------- 1 | # Function for nth Fibonacci number 2 | def Fibonacci(n): 3 | 4 | # Check if input is 0 then it will 5 | # print incorrect input 6 | if n < 0: 7 | print("Incorrect input") 8 | 9 | # Check if n is 0 10 | # then it will return 0 11 | elif n == 0: 12 | return 0 13 | 14 | # Check if n is 1,2 15 | # it will return 1 16 | elif n == 1 or n == 2: 17 | return 1 18 | 19 | else: 20 | return Fibonacci(n-1) + Fibonacci(n-2) 21 | 22 | # Driver Program 23 | print(Fibonacci(9)) 24 | 25 | -------------------------------------------------------------------------------- /Check_armstrong.py: -------------------------------------------------------------------------------- 1 | # Python program to check if the number is an Armstrong number or not 2 | 3 | # take input from the user 4 | num = int(input("Enter a number: ")) 5 | 6 | # initialize sum 7 | sum = 0 8 | 9 | # find the sum of the cube of each digit 10 | temp = num 11 | while temp > 0: 12 | digit = temp % 10 13 | sum += digit ** 3 14 | temp //= 10 15 | 16 | # display the result 17 | if num == sum: 18 | print(num,"is an Armstrong number") 19 | else: 20 | print(num,"is not an Armstrong number") 21 | -------------------------------------------------------------------------------- /Python Programs/prime number .py: -------------------------------------------------------------------------------- 1 | num = 11 2 | # Negative numbers, 0 and 1 are not primes 3 | if num > 1: 4 | 5 | # Iterate from 2 to n // 2 6 | for i in range(2, (num//2)+1): 7 | 8 | # If num is divisible by any number between 9 | # 2 and n / 2, it is not prime 10 | if (num % i) == 0: 11 | print(num, "is not a prime number") 12 | break 13 | else: 14 | print(num, "is a prime number") 15 | else: 16 | print(num, "is not a prime number") 17 | -------------------------------------------------------------------------------- /Simple Command-Line Calculator: -------------------------------------------------------------------------------- 1 | def calculator(): 2 | operation = input("Choose operation (+, -, *, /): ") 3 | num1 = float(input("Enter first number: ")) 4 | num2 = float(input("Enter second number: ")) 5 | 6 | if operation == '+': 7 | print(num1 + num2) 8 | elif operation == '-': 9 | print(num1 - num2) 10 | elif operation == '*': 11 | print(num1 * num2) 12 | elif operation == '/': 13 | print(num1 / num2) 14 | else: 15 | print("Invalid operation") 16 | 17 | calculator() 18 | -------------------------------------------------------------------------------- /Python Programs/FIBONACCI.py: -------------------------------------------------------------------------------- 1 | def generate_fibonacci_series(N): 2 | last_term = 1 3 | second_last_term = 0 4 | for i in range(1, N+1): 5 | if i == 1: 6 | print(second_last_term, end=" ") 7 | elif i == 2: 8 | print(last_term, end=" ") 9 | else: 10 | curr_term = last_term + second_last_term 11 | print(curr_term, end=" ") 12 | second_last_term = last_term 13 | last_term = curr_term 14 | 15 | t = int(input()) 16 | generate_fibonacci_series(t) -------------------------------------------------------------------------------- /Python Programs/bubblesort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(arr): 2 | n = len(arr) 3 | for i in range(n): 4 | swapped = False 5 | for j in range(0, n-i-1): 6 | if arr[j] > arr[j+1]: 7 | arr[j], arr[j+1] = arr[j+1], arr[j] 8 | swapped = True 9 | if not swapped: 10 | break 11 | 12 | # list to be sorted, you can change it according to you 13 | arr = [39, 12, 18, 85, 72, 10, 2, 18] 14 | print("Unsorted list is:", arr) 15 | bubble_sort(arr) 16 | print("Sorted list is:", arr) 17 | -------------------------------------------------------------------------------- /Solve_Quadratic_Equation.py: -------------------------------------------------------------------------------- 1 | import cmath 2 | 3 | def solve_quadratic(a, b, c): 4 | d = b**2 - 4*a*c 5 | root1 = (-b + cmath.sqrt(d)) / (2*a) 6 | root2 = (-b - cmath.sqrt(d)) / (2*a) 7 | 8 | return root1, root2 9 | a = float(input("Enter coefficient a: ")) 10 | b = float(input("Enter coefficient b: ")) 11 | c = float(input("Enter coefficient c: ")) 12 | if a == 0: 13 | print("Coefficient 'a' cannot be zero for a quadratic equation.") 14 | else: 15 | roots = solve_quadratic(a, b, c) 16 | print(f"The roots are: {roots[0]} and {roots[1]}") 17 | -------------------------------------------------------------------------------- /Python Programs/reverse string & paliondrome.py: -------------------------------------------------------------------------------- 1 | def reversestring(s): 2 | return s[::-1] 3 | 4 | 5 | def ispalindrome(s): 6 | rev = reversestring(s) 7 | print("Reversed String is:", rev) 8 | if s == rev: 9 | return True 10 | else: 11 | return False 12 | 13 | 14 | def main(): 15 | s = input("Enter a string:") 16 | ans = ispalindrome(s) 17 | if ans: 18 | print("Yes, It's a Palindrome") 19 | else: 20 | print("No, It's not a Palindrome") 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /Merge_Mails.py: -------------------------------------------------------------------------------- 1 | with open("names.txt", 'r', encoding='utf-8') as names_file: 2 | 3 | # open body.txt for reading 4 | with open("body.txt", 'r', encoding='utf-8') as body_file: 5 | 6 | # read entire content of the body 7 | body = body_file.read() 8 | 9 | # iterate over names 10 | for name in names_file: 11 | mail = "Hello " + name.strip() + "\n" + body 12 | 13 | # write the mails to individual files 14 | with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file: 15 | mail_file.write(mail) 16 | -------------------------------------------------------------------------------- /Python Programs/lengthOfLongestSubstring.py: -------------------------------------------------------------------------------- 1 | def lengthOfLongestSubstring(s): 2 | """ 3 | :type s: str 4 | :rtype: int 5 | """ 6 | if len(s) == 0: 7 | return 0 8 | if len(s) == 1: 9 | return 1 10 | max_len = 1 11 | for i in range(len(s)): 12 | for j in range(i+1, len(s)): 13 | if s[j] not in s[i:j]: 14 | max_len = max(max_len, j-i+1) 15 | else: 16 | break 17 | return max_len 18 | 19 | 20 | if __name__ == '__main__': 21 | s = "abcabcbb" 22 | print(lengthOfLongestSubstring(s)) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Hacktoberfest 2022 - Expert 4 | 5 | This is an intermediate-level project to help you get started with your 6 | [hacktoberfest] (https://hacktoberfest.digitalocean.com/). If you don't 7 | know where to start, feel free to watch the videos linked below, and 8 | read the contribution rules. Happy hacking <3 !! 9 | 10 | 11 | # Basic-Python-Programs 12 | -------------------------------------------------------------------------------- /Python Programs/Solid_Butterfly_list.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | for i in range (1,n+1): 3 | for j in range(i): 4 | print("*",end="") 5 | for k in range(1,((n-i)*2)): 6 | print(" ",end="") 7 | for l in range(i): 8 | if l==n-1: 9 | print(" ",end="") 10 | else: 11 | print("*",end="") 12 | print() 13 | for i in range (n-1,0,-1): 14 | for j in range (i): 15 | print("*",end="") 16 | for k in range ((n-i)*2,1,-1): 17 | print(" ",end="") 18 | for l in range(i): 19 | print("*",end="") 20 | print() 21 | -------------------------------------------------------------------------------- /Python Programs/longestPalindrome.py: -------------------------------------------------------------------------------- 1 | def longestPalindrome(s): 2 | longest = '' 3 | def findLongest(s, l, r): 4 | while l>=0 and r len(longest): longest = s1 12 | 13 | s2 = findLongest(s, i, i+1) 14 | if len(s2) > len(longest): longest = s2 15 | 16 | return longest 17 | 18 | if __name__ == '__main__': 19 | s = "babad" 20 | print(longestPalindrome(s)) -------------------------------------------------------------------------------- /Python Programs/Binary_GCD_recursive.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | if (a == b): 3 | return a 4 | 5 | if (a == 0): 6 | return b 7 | 8 | if (b == 0): 9 | return a 10 | 11 | if ((~a & 1) == 1): 12 | if ((b & 1) == 1): 13 | return gcd(a >> 1, b) 14 | else: 15 | return (gcd(a >> 1, b >> 1) << 1) 16 | 17 | if ((~b & 1) == 1): 18 | return gcd(a, b >> 1) 19 | 20 | if (a > b): 21 | return gcd((a - b) >> 1, b) 22 | 23 | return gcd((b - a) >> 1, a) 24 | 25 | 26 | a, b = 34, 17 27 | print("Gcd of given numbers is ", 28 | gcd(a, b)) 29 | -------------------------------------------------------------------------------- /2022_hactoberfest_Anurupa: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >= 0 and key < arr[j] : 16 | arr[j + 1] = arr[j] 17 | j -= 1 18 | arr[j + 1] = key 19 | 20 | 21 | # Driver code to test above 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | for i in range(len(arr)): 25 | print ("% d" % arr[i]) 26 | 27 | 28 | -------------------------------------------------------------------------------- /Guess_the_Number_Game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def guess_the_number(): 4 | number_to_guess = random.randint(1, 100) 5 | attempts = 0 6 | print("I have selected a number between 1 and 100. Can you guess it?") 7 | 8 | while True: 9 | guess = int(input("Enter your guess: ")) 10 | attempts += 1 11 | 12 | if guess < number_to_guess: 13 | print("Too low! Try again.") 14 | elif guess > number_to_guess: 15 | print("Too high! Try again.") 16 | else: 17 | print(f"Congratulations! You've guessed the number in {attempts} attempts.") 18 | break 19 | 20 | guess_the_number() 21 | -------------------------------------------------------------------------------- /Android_turtle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.speed(20) 3 | turtle.bgcolor("Black") 4 | for i in range(5): 5 | for colours in ('red', 'magenta', 'blue', 'yellow', 'green', 'white'): 6 | turtle.color(colours) 7 | turtle.pensize(10) 8 | turtle.left(3) 9 | turtle.forward(200) 10 | turtle.left(90) 11 | turtle.forward(200) 12 | turtle.left(90) 13 | turtle.forward(200) 14 | turtle.left(90) 15 | turtle.title("KING") 16 | app = Tk() 17 | app.geometry("500x500") 18 | app.title("Own Mail send app") 19 | heading = Label(text="Own Python mail sending app", bg="Green", fg="black", font="10", width="500", height="3") 20 | -------------------------------------------------------------------------------- /Fibbonacci.py: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term 2 | 3 | nterms = int(input("How many terms? ")) 4 | 5 | # first two terms 6 | n1, n2 = 0, 1 7 | count = 0 8 | 9 | # check if the number of terms is valid 10 | if nterms <= 0: 11 | print("Please enter a positive integer") 12 | # if there is only one term, return n1 13 | elif nterms == 1: 14 | print("Fibonacci sequence upto",nterms,":") 15 | print(n1) 16 | # generate fibonacci sequence 17 | else: 18 | print("Fibonacci sequence:") 19 | while count < nterms: 20 | print(n1) 21 | nth = n1 + n2 22 | # update values 23 | n1 = n2 24 | n2 = nth 25 | count += 1 26 | -------------------------------------------------------------------------------- /Check Prime Number in range: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | if n <= 1: 3 | return False 4 | for i in range(2, int(n**0.5) + 1): 5 | if n % i == 0: 6 | return False 7 | return True 8 | 9 | def primes_in_range(start, end): 10 | prime_numbers = [] 11 | for num in range(start, end + 1): 12 | if is_prime(num): 13 | prime_numbers.append(num) 14 | return prime_numbers 15 | 16 | # Specify the range 17 | start_range = 10 18 | end_range = 50 19 | 20 | # Get prime numbers in the specified range 21 | prime_numbers = primes_in_range(start_range, end_range) 22 | print(f"Prime numbers between {start_range} and {end_range}: {prime_numbers}" 23 | -------------------------------------------------------------------------------- /multiply_matrices.py: -------------------------------------------------------------------------------- 1 | def multiply_matrices(matrix_a, matrix_b): 2 | rows_a = len(matrix_a) 3 | cols_a = len(matrix_a[0]) 4 | cols_b = len(matrix_b[0]) 5 | 6 | result = [[0 for _ in range(cols_b)] for _ in range(rows_a)] 7 | 8 | for i in range(rows_a): 9 | for j in range(cols_b): 10 | for k in range(cols_a): 11 | result[i][j] += matrix_a[i][k] * matrix_b[k][j] 12 | 13 | return result 14 | 15 | 16 | matrix_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 17 | matrix_b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]] 18 | 19 | result_matrix = multiply_matrices(matrix_a, matrix_b) 20 | 21 | # Displaying the result 22 | for row in result_matrix: 23 | print(" ".join(map(str, row))) 24 | -------------------------------------------------------------------------------- /Python Programs/NearestPrime.py: -------------------------------------------------------------------------------- 1 | a=int(input("Enter the number:")) 2 | for i in range(a+1): 3 | prime=a+i 4 | count=0 5 | check=False 6 | for j in range(1,prime+1): 7 | if(prime%j==0): 8 | count+=1 9 | if count==2: 10 | check=True 11 | if check: 12 | n=i 13 | break 14 | 15 | for i in range(a+1): 16 | prime=a-i 17 | count=0 18 | check=False 19 | for j in range(1,prime+1): 20 | if(prime%j==0): 21 | count+=1 22 | if count==2: 23 | check=True 24 | if check: 25 | p=i 26 | break 27 | 28 | if n>p: 29 | print("Nearest prime is",a+p) 30 | else: 31 | print("Nearest prime is",a+n) 32 | 33 | -------------------------------------------------------------------------------- /Python Programs/text_alignment.py: -------------------------------------------------------------------------------- 1 | thickness = int(input()) 2 | c = 'H' 3 | 4 | #Top Cone 5 | for i in range(thickness): 6 | print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) 7 | 8 | #Top Pillars 9 | for i in range(thickness+1): 10 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 11 | 12 | #Middle Belt 13 | for i in range((thickness+1)//2): 14 | print((c*thickness*5).center(thickness*6)) 15 | 16 | #Bottom Pillars 17 | for i in range(thickness+1): 18 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 19 | 20 | #Bottom Cone 21 | for i in range(thickness): 22 | print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) -------------------------------------------------------------------------------- /Python Programs/bot_friend.py: -------------------------------------------------------------------------------- 1 | import openai 2 | 3 | # Set your OpenAI API key 4 | openai.api_key = "YOUR_API_KEY" 5 | 6 | def chat(): 7 | """Main chat function.""" 8 | 9 | print("Chatbot: Hello! How can I assist you today?") 10 | 11 | while True: 12 | user_input = input("You: ") 13 | 14 | if user_input.lower() == "exit": 15 | print("Chatbot: Goodbye!") 16 | break 17 | 18 | response = openai.Completion.create( 19 | engine="text-davinci-003", 20 | prompt=user_input, 21 | max_tokens=150, 22 | temperature=0.7, 23 | ) 24 | 25 | print("Chatbot:", response.choices[0].text.strip()) 26 | 27 | if __name__ == "__main__": 28 | chat() -------------------------------------------------------------------------------- /Python Programs/insertion-sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(arr): 2 | n = len(arr) # Get the length of the array 3 | 4 | if n <= 1: 5 | return # If the array has 0 or 1 element, it is already sorted, so return 6 | 7 | for i in range(1, n): # Iterate over the array starting from the second element 8 | key = arr[i] # Store the current element as the key to be inserted in the right position 9 | j = i-1 10 | while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead 11 | arr[j+1] = arr[j] # Shift elements to the right 12 | j -= 1 13 | arr[j+1] = key # Insert the key in the correct position 14 | 15 | # Sorting the array [12, 11, 13, 5, 6] using insertion sort 16 | arr = [12, 11, 13, 5, 6] 17 | insertionSort(arr) 18 | print(arr) 19 | -------------------------------------------------------------------------------- /timeit_decorator.py: -------------------------------------------------------------------------------- 1 | # filename: timeit_decorator.py 2 | # Run: python timeit_decorator.py 3 | 4 | import time 5 | from functools import wraps 6 | 7 | def timeit(func): 8 | @wraps(func) 9 | def wrapper(*args, **kwargs): 10 | start = time.perf_counter() 11 | result = func(*args, **kwargs) 12 | end = time.perf_counter() 13 | print(f"{func.__name__} took {(end-start):.6f}s") 14 | return result 15 | return wrapper 16 | 17 | @timeit 18 | def fib(n): 19 | if n < 2: 20 | return n 21 | return fib(n-1) + fib(n-2) 22 | 23 | if __name__ == "__main__": 24 | # Small n to avoid too long recursion 25 | print("fib(10) =", fib(10)) 26 | 27 | # Note: fib is recursive and intentionally slow — useful to show timing. 28 | -------------------------------------------------------------------------------- /Python Programs/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | def check_binary(st): 2 | 3 | p = set(st) 4 | s = {'0', '1'} 5 | 6 | if s==p or p=={'0'} or p=={'1'}: 7 | return 1 8 | else: 9 | return 0 10 | 11 | def binary_to_decimal(number): 12 | 13 | i = 0 14 | output = 0 15 | 16 | while number > 0: 17 | 18 | rem = int(number % 10) 19 | store = rem * pow(2,i) 20 | output = output + store 21 | number = int(number / 10) 22 | i = i + 1 23 | 24 | return output 25 | 26 | numberInput = int(input("Enter the binary number: ")) 27 | 28 | while check_binary(str(numberInput)) != 1: 29 | print("Sorry, You entered non binary number") 30 | numberInput = int(input("Enter the binary number: ")) 31 | 32 | print(f"{numberInput} in decimal is {binary_to_decimal(numberInput)}") 33 | -------------------------------------------------------------------------------- /caesar_cipher.py: -------------------------------------------------------------------------------- 1 | # filename: caesar_cipher.py 2 | # Run: python caesar_cipher.py encrypt "hello" 3 3 | 4 | import sys 5 | 6 | def caesar(text, shift, mode="encrypt"): 7 | result = "" 8 | if mode == "decrypt": 9 | shift = -shift 10 | for char in text: 11 | if char.isalpha(): 12 | base = ord('A') if char.isupper() else ord('a') 13 | result += chr((ord(char) - base + shift) % 26 + base) 14 | else: 15 | result += char 16 | return result 17 | 18 | if __name__ == "__main__": 19 | if len(sys.argv) < 4: 20 | print("Usage: python caesar_cipher.py ") 21 | sys.exit(1) 22 | mode, text, shift = sys.argv[1], sys.argv[2], int(sys.argv[3]) 23 | print(caesar(text, shift, mode)) 24 | -------------------------------------------------------------------------------- /Python Programs/linearSearch.py: -------------------------------------------------------------------------------- 1 | def linear_search(arr, target): 2 | """ 3 | Perform a linear search for the target in the given array. 4 | 5 | :param arr: List of elements to search through 6 | :param target: The element to search for 7 | :return: The index of the target if found, otherwise -1 8 | """ 9 | for index in range(len(arr)): 10 | if arr[index] == target: 11 | return index # Target found 12 | return -1 # Target not found 13 | 14 | # Example usage 15 | if __name__ == "__main__": 16 | numbers = [5, 3, 8, 4, 2] 17 | target = 4 18 | 19 | result = linear_search(numbers, target) 20 | if result != -1: 21 | print(f"Element found at index: {result}") 22 | else: 23 | print("Element not found.") 24 | -------------------------------------------------------------------------------- /Python Programs/hashing.py: -------------------------------------------------------------------------------- 1 | # hashing 2 | 3 | 4 | def custom_hash(n): 5 | d = n[-1] 6 | rv = int(d) 7 | return rv 8 | 9 | 10 | # Initialize the list 11 | a = ["-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9", "-10"] 12 | 13 | # Store seat numbers 14 | for k in range(5): 15 | s = input("Enter the seat number: ") 16 | i = custom_hash(s) 17 | a[i] = s 18 | 19 | # Retrieve seat number 20 | s = input("Enter the seat number to check: ") 21 | i = custom_hash(s) 22 | 23 | # Check if the seat number is in the list 24 | if s not in a[i]: 25 | print("Value is not in the list") 26 | else: 27 | print("Value is present in the list") 28 | b = [] 29 | for j in range(len(a)): 30 | if len(a[j]) > 1: 31 | b.append(a[j]) 32 | print(b) -------------------------------------------------------------------------------- /Coffee-Machine/main.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | from menu import Menu, MenuItem 3 | from coffee_maker import CoffeeMaker 4 | from money_machine import MoneyMachine 5 | 6 | 7 | money_machine = MoneyMachine() 8 | coffee_maker = CoffeeMaker() 9 | menu = Menu() 10 | 11 | is_on = True 12 | 13 | 14 | while is_on: 15 | options = menu.get_items() 16 | choice = input(f"What would you like? ({options}): ") 17 | if choice == "off": 18 | is_on = False 19 | elif choice == "report": 20 | money_machine.report() 21 | coffee_maker.report() 22 | else: 23 | drink = menu.find_drink(choice) 24 | # print(drink) 25 | if coffee_maker.is_resource_sufficient(drink): 26 | if money_machine.make_payment(drink.cost): 27 | coffee_maker.make_coffee(drink) 28 | -------------------------------------------------------------------------------- /Python Programs/kadane.py: -------------------------------------------------------------------------------- 1 | '''Maximum Subarray Sum using Kadane Algorithm''' 2 | 3 | def kadane(arr): 4 | # Initialize maximumsum and current sum to 1stelement of array 5 | maxSum=arr[0] 6 | currSum=arr[0] 7 | 8 | # check the elements from 1'st element of an array to last element. 9 | for i in range(1,len(arr)): 10 | # get the current maximum sum 11 | currSum = max(arr[i], currSum+arr[i]) 12 | 13 | # if current sum is greater than maximumsum assign current sum 14 | # to maximum sum 15 | if currSum >maxSum: 16 | maxSum=currSum 17 | 18 | # return maximumsum 19 | return maxSum 20 | 21 | 22 | # Test case 23 | arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] 24 | result = kadane(arr) 25 | print("Result", result) #6 26 | 27 | # Time complexity O(n) -------------------------------------------------------------------------------- /LinkList in phyton: -------------------------------------------------------------------------------- 1 | # A simple Python program to introduce a linked list 2 | 3 | # Node class 4 | class Node: 5 | 6 | # Function to initialise the node object 7 | def __init__(self, data): 8 | self.data = data # Assign data 9 | self.next = None # Initialize next as null 10 | 11 | 12 | # Linked List class contains a Node object 13 | class LinkedList: 14 | 15 | # Function to initialize head 16 | def __init__(self): 17 | self.head = None 18 | 19 | 20 | # Code execution starts here 21 | if __name__=='__main__': 22 | 23 | # Start with the empty list 24 | llist = LinkedList() 25 | 26 | llist.head = Node(1) 27 | second = Node(2) 28 | third = Node(3) 29 | llist.head.next = second; # Link first node with second 30 | second.next = third; 31 | -------------------------------------------------------------------------------- /Python Programs/InstagramProofileExtracter.py: -------------------------------------------------------------------------------- 1 | import instaloader 2 | 3 | # creating an Instaloader() object 4 | ig=instaloader.Instaloader() 5 | 6 | # Taking the instagram username as input from user 7 | usrname=input("Enter username:") 8 | 9 | #Fetching the details of provided useraname using instaloder object_ 10 | profile=instaloader.Profile.from_username(ig.context, usrname) 11 | 12 | # Printing the fetched details and storing the profile pic of that account 13 | print("Username: ", profile.username) 14 | print("Number of Posts Uploaded: ", profile.mediacount) 15 | print(profile.username+" is having " + str(profile.followers)+' followers.') 16 | print(profile.username+" is following " + str(profile.followees)+' people') 17 | print("Bio: ", profile.biography) 18 | instaloader.Instaloader().download_profile(usrname,profile_pic_only=True) -------------------------------------------------------------------------------- /Python Programs/NoIdea.py: -------------------------------------------------------------------------------- 1 | # Solution for No Idea Problem on Hackerrank 2 | ''' 3 | There is an array of n integers. There are also 2 disjoint sets, a and b, each containing m integers. You like all the integers in set a and dislike all the integers in set b. Your initial happiness is 0. For each i integer in the array belongs to A you add 1 to your happiness. If it is in b, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end. 4 | ''' 5 | n, m = map(int, input().split()) 6 | 7 | elements = list(map(int, input().split())) 8 | 9 | a = set(map(int, input().split()[:n])) 10 | 11 | b = set(map(int, input().split()[:m])) 12 | 13 | happiness = 0 14 | 15 | for item in elements: 16 | if item in a: 17 | happiness += 1 18 | elif item in b: 19 | happiness -= 1 20 | print(happiness) 21 | 22 | 23 | -------------------------------------------------------------------------------- /Python Programs/CoinChangeProblem.py: -------------------------------------------------------------------------------- 1 | def coin_change(coins, amount): 2 | # Initialize a list to store the minimum coins for each amount from 0 to amount 3 | dp = [float('inf')] * (amount + 1) 4 | 5 | # Base case: to make 0 amount, 0 coins are needed 6 | dp[0] = 0 7 | 8 | # Iterate over each coin in the coins list 9 | for coin in coins: 10 | # For each coin, update the dp array for all amounts from coin to amount 11 | for i in range(coin, amount + 1): 12 | dp[i] = min(dp[i], dp[i - coin] + 1) 13 | 14 | # If dp[amount] is still infinity, that means it's not possible to form that amount 15 | return dp[amount] if dp[amount] != float('inf') else -1 16 | 17 | # Example usage 18 | coins = [1, 2, 5] 19 | amount = 11 20 | result = coin_change(coins, amount) 21 | print(f"Minimum coins needed: {result}") 22 | -------------------------------------------------------------------------------- /Python Programs/guess_the_number.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def guess_the_number(): 4 | print("Welcome to the Number Guessing Game!") 5 | number_to_guess = random.randint(1, 100) 6 | attempts = 0 7 | 8 | while True: 9 | guess = input("Guess a number between 1 and 100: ") 10 | 11 | # Check if input is a valid number 12 | if not guess.isdigit(): 13 | print("Please enter a valid number.") 14 | continue 15 | 16 | guess = int(guess) 17 | attempts += 1 18 | 19 | if guess < number_to_guess: 20 | print("Too low! Try again.") 21 | elif guess > number_to_guess: 22 | print("Too high! Try again.") 23 | else: 24 | print(f"Congratulations! You've guessed the number {number_to_guess} in {attempts} attempts.") 25 | break 26 | 27 | # Run the game 28 | guess_the_number() -------------------------------------------------------------------------------- /demonstrates_handling.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | class Counter: 4 | def __init__(self): 5 | self.count = 0 6 | self.lock = threading.Lock() # Lock to synchronize access to the critical section 7 | 8 | def increment(self): 9 | with self.lock: # Critical section, only one thread can enter at a time 10 | self.count += 1 11 | 12 | def worker(counter): 13 | for _ in range(1000): 14 | counter.increment() 15 | 16 | if __name__ == "__main__": 17 | counter = Counter() 18 | 19 | # Create two threads that will increment the counter 20 | t1 = threading.Thread(target=worker, args=(counter,)) 21 | t2 = threading.Thread(target=worker, args=(counter,)) 22 | 23 | t1.start() 24 | t2.start() 25 | 26 | # Wait for both threads to complete 27 | t1.join() 28 | t2.join() 29 | 30 | # The count should be 2000 since both threads increment it 1000 times 31 | print(f"Final count: {counter.count}") 32 | -------------------------------------------------------------------------------- /Python Programs/KnapsackProblem.py: -------------------------------------------------------------------------------- 1 | # Function to solve the 0/1 Knapsack Problem 2 | def knapsack(weights, values, capacity): 3 | # Number of items 4 | n = len(values) 5 | 6 | # Create a 2D DP array where dp[i][w] represents the maximum value that can be obtained 7 | # with the first i items and a knapsack of capacity w 8 | dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)] 9 | 10 | # Build the dp array 11 | for i in range(1, n + 1): 12 | for w in range(1, capacity + 1): 13 | if weights[i - 1] <= w: # Can include this item 14 | dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]) 15 | else: # Can't include this item 16 | dp[i][w] = dp[i - 1][w] 17 | 18 | # The maximum value is in dp[n][capacity] 19 | return dp[n][capacity] 20 | 21 | # Example usage 22 | values = [60, 100, 120] 23 | weights = [10, 20, 30] 24 | capacity = 50 25 | 26 | max_value = knapsack(weights, values, capacity) 27 | print(f"Maximum value in the knapsack: {max_value}") 28 | -------------------------------------------------------------------------------- /Python Programs/nqueen.py: -------------------------------------------------------------------------------- 1 | def solve_n_queens(n): 2 | def is_safe(board, row, col): 3 | 4 | for i in range(row): 5 | if board[i] == col or \ 6 | board[i] - i == col - row or \ 7 | board[i] + i == col + row: 8 | return False 9 | return True 10 | 11 | def solve_nq_util(board, row): 12 | 13 | if row >= n: 14 | result.append(board[:]) 15 | return 16 | 17 | 18 | for col in range(n): 19 | if is_safe(board, row, col): 20 | board[row] = col 21 | solve_nq_util(board, row + 1) 22 | board[row] = -1 23 | 24 | 25 | result = [] 26 | 27 | board = [-1] * n 28 | solve_nq_util(board, 0) 29 | return result 30 | 31 | 32 | n = 4 33 | solutions = solve_n_queens(n) 34 | for solution in solutions: 35 | print("Solution:") 36 | for i in range(n): 37 | row = ['.'] * n 38 | row[solution[i]] = 'Q' 39 | print(" ".join(row)) 40 | print() 41 | -------------------------------------------------------------------------------- /Python Programs/best_first_search.py: -------------------------------------------------------------------------------- 1 | from queue import PriorityQueue 2 | v = 14 3 | graph = [[] for i in range(v)] 4 | 5 | def best_first_search(actual_Src, target, n): 6 | visited = [False] * n 7 | pq = PriorityQueue() 8 | pq.put((0, actual_Src)) 9 | visited[actual_Src] = True 10 | 11 | while pq.empty() == False: 12 | u = pq.get()[1] 13 | print(u, end=" ") 14 | if u == target: 15 | break 16 | 17 | for v, c in graph[u]: 18 | if visited[v] == False: 19 | visited[v] = True 20 | pq.put((c, v)) 21 | print() 22 | 23 | def addedge(x, y, cost): 24 | graph[x].append((y, cost)) 25 | graph[y].append((x, cost)) 26 | 27 | addedge(0, 1, 3) 28 | addedge(0, 2, 6) 29 | addedge(0, 3, 5) 30 | addedge(1, 4, 9) 31 | addedge(1, 5, 8) 32 | addedge(2, 6, 12) 33 | addedge(2, 7, 14) 34 | addedge(3, 8, 7) 35 | addedge(8, 9, 5) 36 | addedge(8, 10, 6) 37 | addedge(9, 11, 1) 38 | addedge(9, 12, 10) 39 | addedge(9, 13, 2) 40 | 41 | source = 0 42 | target = 9 43 | best_first_search(source, target, v) -------------------------------------------------------------------------------- /Python Programs/binarry-search.py: -------------------------------------------------------------------------------- 1 | # Python 3 program for recursive binary search. 2 | # Modifications needed for the older Python 2 are found in comments. 3 | 4 | # Returns index of x in arr if present, else -1 5 | def binary_search(arr, low, high, x): 6 | 7 | # Check base case 8 | if high >= low: 9 | 10 | mid = (high + low) // 2 11 | 12 | # If element is present at the middle itself 13 | if arr[mid] == x: 14 | return mid 15 | 16 | # If element is smaller than mid, then it can only 17 | # be present in left subarray 18 | elif arr[mid] > x: 19 | return binary_search(arr, low, mid - 1, x) 20 | 21 | # Else the element can only be present in right subarray 22 | else: 23 | return binary_search(arr, mid + 1, high, x) 24 | 25 | else: 26 | # Element is not present in the array 27 | return -1 28 | 29 | # Test array 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binary_search(arr, 0, len(arr)-1, x) 35 | 36 | if result != -1: 37 | print("Element is present at index", str(result)) 38 | else: 39 | print("Element is not present in array") 40 | -------------------------------------------------------------------------------- /Python Programs/LongestPalindromeSubseq.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def check(self, s, dp, i, j): 3 | if i > j: 4 | return 0 5 | if dp[i][j] != -1: 6 | return dp[i][j] 7 | 8 | if s[i] == s[j]: 9 | if i != j: 10 | dp[i][j] = 2 + self.check(s, dp, i + 1, j - 1) 11 | else: 12 | dp[i][j] = 1 + self.check(s, dp, i + 1, j - 1) 13 | else: 14 | dp[i][j] = max(self.check(s, dp, i, j - 1), self.check(s, dp, i + 1, j)) 15 | 16 | return dp[i][j] 17 | 18 | def longestPalindromeSubseq(self, s: str) -> int: 19 | n = len(s) 20 | dp = [[-1 for _ in range(n)] for _ in range(n)] 21 | return self.check(s, dp, 0, n - 1) 22 | 23 | # Example test cases 24 | solution = Solution() 25 | 26 | # Test case 1 27 | s1 = "bbbab" 28 | output1 = solution.longestPalindromeSubseq(s1) 29 | print(f"Output for '{s1}': {output1}") # Expected output: 4 30 | 31 | # Test case 2 32 | s2 = "cbbd" 33 | output2 = solution.longestPalindromeSubseq(s2) 34 | print(f"Output for '{s2}': {output2}") # Expected output: 2 35 | -------------------------------------------------------------------------------- /Python Programs/PDFMerger.py: -------------------------------------------------------------------------------- 1 | #! python3 2 | # combinePdfs.py - Combines all the PDFs in the current working directory into a single PDF 3 | # USAGE : open terminal and go to the folder that has all the pdfs there and type : python3 PDFMerger.py 4 | 5 | import PyPDF2, os 6 | # get all the PDF filenames 7 | pdfFiles = [] 8 | for filename in os.listdir('.'): 9 | if filename.endswith('.pdf'): 10 | pdfFiles.append(filename) 11 | # we alphabetize the filenames 12 | pdfFiles.sort(key=str.lower) 13 | print(pdfFiles) 14 | pdfWriter = PyPDF2.PdfFileWriter() 15 | 16 | # loop through all the PDF files 17 | 18 | for filename in pdfFiles: 19 | pdfFileObj = open(filename, 'rb') 20 | pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 21 | if pdfReader.isEncrypted == True : pdfReader.decrypt('rosebud') 22 | # loop through all the pages (except the first) and add them 23 | for pageNum in range(1, pdfReader.numPages): 24 | pageObj = pdfReader.getPage(pageNum) 25 | pdfWriter.addPage(pageObj) 26 | 27 | # Save the resulting PDF to a file 28 | pdfOutput = open('your_merged_pdf_name_here.pdf', 'wb') 29 | pdfWriter.write(pdfOutput) 30 | pdfOutput.close() -------------------------------------------------------------------------------- /Anurupa_hactober: -------------------------------------------------------------------------------- 1 | # Adjascency List representation in Python 2 | 3 | 4 | class AdjNode: 5 | def __init__(self, value): 6 | self.vertex = value 7 | self.next = None 8 | 9 | 10 | class Graph: 11 | def __init__(self, num): 12 | self.V = num 13 | self.graph = [None] * self.V 14 | 15 | # Add edges 16 | def add_edge(self, s, d): 17 | node = AdjNode(d) 18 | node.next = self.graph[s] 19 | self.graph[s] = node 20 | 21 | node = AdjNode(s) 22 | node.next = self.graph[d] 23 | self.graph[d] = node 24 | 25 | # Print the graph 26 | def print_agraph(self): 27 | for i in range(self.V): 28 | print("Vertex " + str(i) + ":", end="") 29 | temp = self.graph[i] 30 | while temp: 31 | print(" -> {}".format(temp.vertex), end="") 32 | temp = temp.next 33 | print(" \n") 34 | 35 | 36 | if __name__ == "__main__": 37 | V = 5 38 | 39 | # Create graph and edges 40 | graph = Graph(V) 41 | graph.add_edge(0, 1) 42 | graph.add_edge(0, 2) 43 | graph.add_edge(0, 3) 44 | graph.add_edge(1, 2) 45 | 46 | graph.print_agraph() 47 | -------------------------------------------------------------------------------- /Coffee-Machine/coffee_maker.py: -------------------------------------------------------------------------------- 1 | class CoffeeMaker: 2 | """Models the machine that makes the coffee""" 3 | def __init__(self): 4 | self.resources = { 5 | "water": 300, 6 | "milk": 200, 7 | "coffee": 100, 8 | } 9 | 10 | def report(self): 11 | """Prints a report of all resources.""" 12 | print(f"Water: {self.resources['water']}ml") 13 | print(f"Milk: {self.resources['milk']}ml") 14 | print(f"Coffee: {self.resources['coffee']}g") 15 | 16 | def is_resource_sufficient(self, drink): 17 | """Returns True when order can be made, False if ingredients are insufficient.""" 18 | can_make = True 19 | for item in drink.ingredients: 20 | if drink.ingredients[item] > self.resources[item]: 21 | print(f"Sorry there is not enough {item}.") 22 | can_make = False 23 | return can_make 24 | 25 | def make_coffee(self, order): 26 | """Deducts the required ingredients from the resources.""" 27 | for item in order.ingredients: 28 | self.resources[item] -= order.ingredients[item] 29 | print(f"Here is your {order.name} ☕️. Enjoy!") 30 | -------------------------------------------------------------------------------- /Coffee-Machine/menu.py: -------------------------------------------------------------------------------- 1 | class MenuItem: 2 | """Models each Menu Item.""" 3 | def __init__(self, name, water, milk, coffee, cost): 4 | self.name = name 5 | self.cost = cost 6 | self.ingredients = { 7 | "water": water, 8 | "milk": milk, 9 | "coffee": coffee 10 | } 11 | 12 | 13 | class Menu: 14 | """Models the Menu with drinks.""" 15 | def __init__(self): 16 | self.menu = [ 17 | MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5), 18 | MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5), 19 | MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3), 20 | ] 21 | 22 | def get_items(self): 23 | """Returns all the names of the available menu items""" 24 | options = "" 25 | for item in self.menu: 26 | options += f"{item.name}/" 27 | return options 28 | 29 | def find_drink(self, order_name): 30 | """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None""" 31 | for item in self.menu: 32 | if item.name == order_name: 33 | return item 34 | print("Sorry that item is not available.") 35 | -------------------------------------------------------------------------------- /Python Programs/rock-paper-scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_user_choice(): 4 | choice = input("Enter your choice (rock, paper, scissors): ").lower() 5 | if choice in ['rock', 'paper', 'scissors']: 6 | return choice 7 | else: 8 | print("Invalid choice! Please choose again.") 9 | return get_user_choice() 10 | 11 | def get_computer_choice(): 12 | return random.choice(['rock', 'paper', 'scissors']) 13 | 14 | def determine_winner(user_choice, computer_choice): 15 | if user_choice == computer_choice: 16 | return "It's a tie!" 17 | elif (user_choice == 'rock' and computer_choice == 'scissors') or \ 18 | (user_choice == 'scissors' and computer_choice == 'paper') or \ 19 | (user_choice == 'paper' and computer_choice == 'rock'): 20 | return "You win!" 21 | else: 22 | return "Computer wins!" 23 | 24 | def play_game(): 25 | print("Welcome to Rock, Paper, Scissors!") 26 | user_choice = get_user_choice() 27 | computer_choice = get_computer_choice() 28 | 29 | print(f"\nYou chose: {user_choice}") 30 | print(f"Computer chose: {computer_choice}") 31 | 32 | result = determine_winner(user_choice, computer_choice) 33 | print(result) 34 | 35 | if __name__ == "__main__": 36 | play_game() 37 | -------------------------------------------------------------------------------- /QuickSort.py: -------------------------------------------------------------------------------- 1 | def partition(arr, low, high): 2 | i = (low-1) # index of smaller element 3 | pivot = arr[high] # pivot 4 | 5 | for j in range(low, high): 6 | 7 | # If current element is smaller than or 8 | # equal to pivot 9 | if arr[j] <= pivot: 10 | 11 | # increment index of smaller element 12 | i = i+1 13 | arr[i], arr[j] = arr[j], arr[i] 14 | 15 | arr[i+1], arr[high] = arr[high], arr[i+1] 16 | return (i+1) 17 | 18 | # The main function that implements QuickSort 19 | # arr[] --> Array to be sorted, 20 | # low --> Starting index, 21 | # high --> Ending index 22 | 23 | # Function to do Quick sort 24 | 25 | 26 | def quickSort(arr, low, high): 27 | if len(arr) == 1: 28 | return arr 29 | if low < high: 30 | 31 | # pi is partitioning index, arr[p] is now 32 | # at right place 33 | pi = partition(arr, low, high) 34 | 35 | # Separately sort elements before 36 | # partition and after partition 37 | quickSort(arr, low, pi-1) 38 | quickSort(arr, pi+1, high) 39 | 40 | 41 | # Driver code to test above 42 | arr = [10, 7, 8, 9, 1, 5] 43 | n = len(arr) 44 | quickSort(arr, 0, n-1) 45 | print("Sorted array is:") 46 | for i in range(n): 47 | print("%d" % arr[i]), 48 | 49 | -------------------------------------------------------------------------------- /Python Programs/pangramChecker.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program: Pangram Checker 3 | A pangram is a sentence that contains every letter of the English alphabet at least once. 4 | This program checks whether a given sentence is a pangram or not. 5 | 6 | Example: 7 | Input: "The quick brown fox jumps over the lazy dog" 8 | Output: "✅ The sentence is a pangram." 9 | """ 10 | 11 | import string 12 | 13 | def is_pangram(sentence): 14 | """ 15 | Function to check whether a given sentence is a pangram. 16 | 17 | Args: 18 | sentence (str): The sentence to check. 19 | 20 | Returns: 21 | bool: True if the sentence is a pangram, False otherwise. 22 | """ 23 | # Get a set of all lowercase alphabets (a-z) 24 | alphabet = set(string.ascii_lowercase) 25 | 26 | # Convert the sentence to lowercase and make a set of characters present 27 | sentence_letters = set(sentence.lower()) 28 | 29 | # Check if all alphabets are present in the sentence 30 | return alphabet <= sentence_letters 31 | 32 | 33 | # --- Main Program --- 34 | if __name__ == "__main__": 35 | sentence = input("Enter a sentence: ") # Take input from user 36 | 37 | # Check and display result 38 | if is_pangram(sentence): 39 | print("✅ The sentence is a pangram.") 40 | else: 41 | print("❌ The sentence is not a pangram.") 42 | -------------------------------------------------------------------------------- /Coffee-Machine/money_machine.py: -------------------------------------------------------------------------------- 1 | class MoneyMachine: 2 | 3 | CURRENCY = "$" 4 | 5 | COIN_VALUES = { 6 | "quarters": 0.25, 7 | "dimes": 0.10, 8 | "nickles": 0.05, 9 | "pennies": 0.01 10 | } 11 | 12 | def __init__(self): 13 | self.profit = 0 14 | self.money_received = 0 15 | 16 | def report(self): 17 | """Prints the current profit""" 18 | print(f"Money: {self.CURRENCY}{self.profit}") 19 | 20 | def process_coins(self): 21 | """Returns the total calculated from coins inserted.""" 22 | print("Please insert coins.") 23 | for coin in self.COIN_VALUES: 24 | self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin] 25 | return self.money_received 26 | 27 | def make_payment(self, cost): 28 | """Returns True when payment is accepted, or False if insufficient.""" 29 | self.process_coins() 30 | if self.money_received >= cost: 31 | change = round(self.money_received - cost, 2) 32 | print(f"Here is {self.CURRENCY}{change} in change.") 33 | self.profit += cost 34 | self.money_received = 0 35 | return True 36 | else: 37 | print("Sorry that's not enough money. Money refunded.") 38 | self.money_received = 0 39 | return False 40 | -------------------------------------------------------------------------------- /Python Programs/QuickSort.py: -------------------------------------------------------------------------------- 1 | def quicksort(arr: list) -> list: 2 | """Quicksort function implementation in Python. 3 | https://en.wikipedia.org/wiki/Quicksort 4 | >>> quicksort([]) 5 | [] 6 | >>> quicksort([5]) 7 | [5] 8 | >>> quicksort([3, 6, 8, 10, 1, 2, 1, 3, 2, 8]) 9 | [1, 1, 2, 2, 3, 3, 6, 8, 8, 10] 10 | """ 11 | 12 | # If the length of the array is less than or equal to 1, then there's 13 | # nothing to sort, so return the given array 14 | if len(arr) <= 1: 15 | return arr 16 | 17 | # In quicksort a element needs to be selected as pivot, it can be anywhere 18 | # In this case let the pivot be the first element 19 | pivot = arr[0] 20 | 21 | # Using list comprehension creating three list object: smaller_elemnts, 22 | # pivot_elements & larger_elements 23 | # based on the comparison with the pivot element 24 | smaller_elements = [x for x in arr if x < pivot] 25 | pivot_elements = [x for x in arr if x == pivot] 26 | larger_elements = [x for x in arr if x > pivot] 27 | 28 | # Recursively splitting the list object to determine the correct 29 | # position of the element 30 | return quicksort(smaller_elements) + pivot_elements + quicksort(larger_elements) 31 | 32 | 33 | if __name__ == "__main__": 34 | import doctest 35 | 36 | doctest.testmod() 37 | -------------------------------------------------------------------------------- /guessing-game.py: -------------------------------------------------------------------------------- 1 | # Guessing game in python 2 | import random 3 | 4 | print("*********Welcome To*******************************") 5 | print("*************GUESS THE NUMBER*********************") 6 | print("**************************Game********************") 7 | print("**************************************************") 8 | print("*******Higher the range, Higher the Score*********") 9 | print("**************************************************") 10 | 11 | 12 | while(1): 13 | s, e = map(int, input("Type the range of the numbers to guess: ").split(" ")) 14 | num = random.randint(s, e) 15 | 16 | for i in range(1, 11): 17 | user = int(input("Enter your number:")) 18 | if(num > user): 19 | print("Wrong!!...Try a higher value.") 20 | elif(num < user): 21 | print("Wrong!!...Try lower value.") 22 | else: 23 | print("Congratulation!! You WIN.") 24 | print("Your score is, = ", e-s-i) 25 | break 26 | if(i == 10): 27 | print("Game Over! You ran out of guesses.") 28 | print("The number was :", num) 29 | 30 | choice = input("Enter 1 to play again, 0 to exit : ") 31 | 32 | if choice =="1": 33 | continue 34 | elif choice =="0": 35 | break 36 | else : 37 | print("Invalid input Exiting the game...") 38 | break 39 | -------------------------------------------------------------------------------- /Python Programs/hollow_diamond_alphabets.py: -------------------------------------------------------------------------------- 1 | def hollow_diamond_alphabet(diamond_size: int) -> None: 2 | """ 3 | Prints a hollow diamond pattern using alphabet characters. 4 | Parameters: 5 | diamond_size (int): The size of the diamond. Determines the number of rows. 6 | Example: 7 | >>> hollow_diamond_alphabet(5) 8 | A 9 | B C 10 | D E 11 | F G 12 | H I 13 | F G 14 | D E 15 | B C 16 | A 17 | """ 18 | alpha = 64 19 | for i in range(1, diamond_size + 1): 20 | left_spaces = " " * (diamond_size - i) 21 | hollow_spaces = " " * (((i - 1) * 2) - 1) 22 | if i == 1: 23 | print(left_spaces + chr(alpha + 1)) 24 | else: 25 | print(left_spaces + chr(alpha) + hollow_spaces + chr(alpha + 1)) 26 | alpha += 2 27 | 28 | alpha -= 2 29 | for i in range(diamond_size - 1, 0, -1): 30 | left_spaces = " " * (diamond_size - i) 31 | hollow_spaces = " " * (((i - 1) * 2) - 1) 32 | if i == 1: 33 | print(left_spaces + chr(alpha - 1)) 34 | else: 35 | print(left_spaces + chr(alpha - 2) + hollow_spaces + chr(alpha - 1)) 36 | alpha -= 2 37 | 38 | 39 | diamond_size = int(input("Enter the diamond size: ")) 40 | hollow_diamond_alphabet(diamond_size) 41 | -------------------------------------------------------------------------------- /Python Programs/prime_number_generator.py: -------------------------------------------------------------------------------- 1 | # prime_generator.py 2 | 3 | # Function to check if a number is prime 4 | def is_prime(n): 5 | """Check if a number is prime.""" 6 | # A prime number is greater than 1 7 | if n <= 1: 8 | return False 9 | # Check divisibility from 2 to the square root of n 10 | for i in range(2, int(n ** 0.5) + 1): 11 | if n % i == 0: # If divisible, n is not prime 12 | return False 13 | return True # If no divisors, n is prime 14 | 15 | # Function to generate all primes up to a limit 16 | def generate_primes(limit): 17 | """Generate all prime numbers up to a given limit.""" 18 | primes = [] # List to store prime numbers 19 | # Loop through each number from 2 to the limit 20 | for num in range(2, limit + 1): 21 | # Use the is_prime function to check if num is prime 22 | if is_prime(num): 23 | primes.append(num) # Add prime numbers to the list 24 | return primes # Return the list of prime numbers 25 | 26 | # Main function to run the program 27 | if __name__ == "__main__": 28 | # Ask the user to input the upper limit for prime generation 29 | limit = int(input("Enter the upper limit to generate prime numbers: ")) 30 | # Call the function to generate prime numbers 31 | primes = generate_primes(limit) 32 | # Print the list of prime numbers 33 | print(f"Prime numbers up to {limit}: {primes}") 34 | -------------------------------------------------------------------------------- /Simple_Calculator.py: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | return x + y 3 | 4 | # This function subtracts two numbers 5 | def subtract(x, y): 6 | return x - y 7 | 8 | # This function multiplies two numbers 9 | def multiply(x, y): 10 | return x * y 11 | 12 | # This function divides two numbers 13 | def divide(x, y): 14 | return x / y 15 | 16 | 17 | print("Select operation.") 18 | print("1.Add") 19 | print("2.Subtract") 20 | print("3.Multiply") 21 | print("4.Divide") 22 | 23 | while True: 24 | # take input from the user 25 | choice = input("Enter choice(1/2/3/4): ") 26 | 27 | # check if choice is one of the four options 28 | if choice in ('1', '2', '3', '4'): 29 | num1 = float(input("Enter first number: ")) 30 | num2 = float(input("Enter second number: ")) 31 | 32 | if choice == '1': 33 | print(num1, "+", num2, "=", add(num1, num2)) 34 | 35 | elif choice == '2': 36 | print(num1, "-", num2, "=", subtract(num1, num2)) 37 | 38 | elif choice == '3': 39 | print(num1, "*", num2, "=", multiply(num1, num2)) 40 | 41 | elif choice == '4': 42 | print(num1, "/", num2, "=", divide(num1, num2)) 43 | 44 | # check if user wants another calculation 45 | # break the while loop if answer is no 46 | next_calculation = input("Let's do next calculation? (yes/no): ") 47 | if next_calculation == "no": 48 | break 49 | 50 | else: 51 | print("Invalid Input") 52 | -------------------------------------------------------------------------------- /Dice Rolling Simulator Using Python/dice.py: -------------------------------------------------------------------------------- 1 | import tkinter 2 | from PIL import Image, ImageTk 3 | import random 4 | 5 | # toplevel widget which represents the main window of an application 6 | root = tkinter.Tk() 7 | root.geometry('400x400') 8 | root.title('Roll the Dice By Soumyajit') 9 | 10 | # Adding label into the frame 11 | l0 = tkinter.Label(root, text="") 12 | l0.pack() 13 | 14 | # adding label with different font and formatting 15 | l1 = tkinter.Label(root, text="Hello from Soumyajit!", fg = "light green", 16 | bg = "dark green", 17 | font = "Helvetica 16 bold italic") 18 | l1.pack() 19 | 20 | # images 21 | dice = ['die1.png', 'die2.png', 'die3.png', 'die4.png', 'die5.png', 'die6.png'] 22 | # simulating the dice with random numbers between 0 to 6 and generating image 23 | image1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) 24 | 25 | # construct a label widget for image 26 | label1 = tkinter.Label(root, image=image1) 27 | label1.image = image1 28 | 29 | # packing a widget in the parent widget 30 | label1.pack( expand=True) 31 | 32 | # function activated by button 33 | def rolling_dice(): 34 | image1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) 35 | # update image 36 | label1.configure(image=image1) 37 | # keep a reference 38 | label1.image = image1 39 | 40 | 41 | # adding button, and command will use rolling_dice function 42 | button = tkinter.Button(root, text='Roll the Dice', fg='blue', command=rolling_dice) 43 | 44 | # pack a widget in the parent widget 45 | button.pack( expand=True) 46 | 47 | # call the mainloop of Tk 48 | # keeps window open 49 | root.mainloop() 50 | -------------------------------------------------------------------------------- /Python Programs/2sumsolu.py: -------------------------------------------------------------------------------- 1 | def three_sum(nums): 2 | # Sort the input array to simplify finding unique triplets 3 | nums.sort() 4 | result = [] 5 | 6 | # Iterate through the array with index i 7 | for i in range(len(nums) - 2): 8 | # Avoid duplicate values for i 9 | if i > 0 and nums[i] == nums[i - 1]: 10 | continue 11 | 12 | # Set pointers for the current element (i), and two others (left and right) 13 | left, right = i + 1, len(nums) - 1 14 | 15 | # While loop to find pairs that sum to zero with nums[i] 16 | while left < right: 17 | total = nums[i] + nums[left] + nums[right] 18 | 19 | if total == 0: 20 | # If the sum is zero, append the triplet to the result list 21 | result.append([nums[i], nums[left], nums[right]]) 22 | 23 | # Skip duplicates for left and right pointers 24 | while left < right and nums[left] == nums[left + 1]: 25 | left += 1 26 | while left < right and nums[right] == nums[right - 1]: 27 | right -= 1 28 | 29 | # Move pointers inward 30 | left += 1 31 | right -= 1 32 | 33 | elif total < 0: 34 | # If sum is less than zero, move the left pointer to the right 35 | left += 1 36 | else: 37 | # If sum is more than zero, move the right pointer to the left 38 | right -= 1 39 | 40 | return result 41 | 42 | # Example usage: 43 | nums = [-1, 0, 1, 2, -1, -4] 44 | print(three_sum(nums)) 45 | -------------------------------------------------------------------------------- /Python Programs/Program to Convert Hexadecimal Number to Binary.py: -------------------------------------------------------------------------------- 1 | # Python3 program to convert 2 | # Hexadecimal number to Binary 3 | 4 | # Function to convert 5 | # Hexadecimal to Binary Number 6 | def HexToBin(hexdec): 7 | 8 | for i in hexdec: 9 | if i == '0': 10 | print('0000', end = '') 11 | elif i == '1': 12 | print('0001', end = '') 13 | elif i == '2': 14 | print('0010', end = '') 15 | elif i == '3': 16 | print('0011', end = '') 17 | elif i == '4': 18 | print('0100', end = '') 19 | elif i == '5': 20 | print('0101', end = '') 21 | elif i == '6': 22 | print('0110', end = '') 23 | elif i == '7': 24 | print('0111', end = '') 25 | elif i == '8': 26 | print('1000', end = '') 27 | elif i == '9': 28 | print('1001', end = '') 29 | elif i == 'A' or i == 'a': 30 | print('1010', end = '') 31 | elif i == 'B' or i == 'b': 32 | print('1011', end = '') 33 | elif i == 'C' or i == 'c': 34 | print('1100', end = '') 35 | elif i == 'D' or i == 'd': 36 | print('1101', end = '') 37 | elif i == 'E' or i == 'e': 38 | print('1110', end = '') 39 | elif i == 'F' or i == 'f': 40 | print('1111', end = '') 41 | elif i == '.': 42 | print('.', end = '') 43 | else: 44 | print("\nInvalid hexadecimal digit " + 45 | str(hexdec[i]), end = '') 46 | 47 | # Driver code 48 | if __name__=="__main__": 49 | 50 | # Get the Hexadecimal number 51 | hexdec= "1AC5"; 52 | 53 | # Convert HexaDecimal to Binary 54 | print("Equivalent Binary value is : ", 55 | end = '') 56 | HexToBin(hexdec) 57 | 58 | # This code is contributed by baliraje_kalyane 59 | -------------------------------------------------------------------------------- /Python Programs/3sum_sol.py: -------------------------------------------------------------------------------- 1 | def three_sum(nums): 2 | # Sort the input array to simplify finding unique triplets 3 | nums.sort() 4 | result = [] 5 | 6 | # Iterate through the array with index i 7 | for i in range(len(nums) - 2): 8 | # Avoid duplicate values for i 9 | if i > 0 and nums[i] == nums[i - 1]: 10 | continue 11 | 12 | # Set pointers for the current element (i), and two others (left and right) 13 | left, right = i + 1, len(nums) - 1 14 | 15 | # While loop to find pairs that sum to zero with nums[i] 16 | while left < right: 17 | total = nums[i] + nums[left] + nums[right] 18 | 19 | if total == 0: 20 | # If the sum is zero, append the triplet to the result list 21 | result.append([nums[i], nums[left], nums[right]]) 22 | 23 | # Skip duplicates for left and right pointers 24 | while left < right and nums[left] == nums[left + 1]: 25 | left += 1 26 | while left < right and nums[right] == nums[right - 1]: 27 | right -= 1 28 | 29 | # Move pointers inward 30 | left += 1 31 | right -= 1 32 | 33 | elif total < 0: 34 | # If sum is less than zero, move the left pointer to the right 35 | left += 1 36 | else: 37 | # If sum is more than zero, move the right pointer to the left 38 | right -= 1 39 | 40 | return result 41 | 42 | # Example usage: 43 | nums = [-1, 0, 1, 2, -1, -4] 44 | print(three_sum(nums)) 45 | -------------------------------------------------------------------------------- /pass_generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | 5 | def main(): 6 | print("_____________________________________") 7 | print("| Welcome to this Password Generator |") 8 | print("-------------------------------------\n") 9 | try: 10 | length = int( 11 | input("how long do you want your password to be (minimum of 8 number)") 12 | ) 13 | except: 14 | print("Input numners only") 15 | password_length = 0 16 | while password_length < length: 17 | print("Your password must have at least 8 characters") 18 | password_length = getPasswordLength() 19 | 20 | all_characters = getCharacters() 21 | password = generatePassword(all_characters, password_length) 22 | print("\nYour password is: " + password) 23 | print("__________________________________________") 24 | print("| Thanks for using the Password Generator |") 25 | print("------------------------------------------") 26 | 27 | 28 | def getPasswordLength(): 29 | # Set the password length with constraints for the password length 30 | password_length = int(input("\nEnter the length of password: ")) 31 | return password_length 32 | 33 | 34 | def getCharacters(): 35 | # define the characters 36 | lower = string.ascii_lowercase 37 | upper = string.ascii_uppercase 38 | num = string.digits 39 | symbols = string.punctuation 40 | 41 | all_characters = lower + upper + num + symbols 42 | return all_characters 43 | 44 | 45 | def generatePassword(all_characters, password_length): 46 | # generate a password string 47 | password = "".join(random.sample(all_characters, password_length)) 48 | return password 49 | 50 | 51 | main() 52 | -------------------------------------------------------------------------------- /Password-Generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | 5 | def main(): 6 | print("_____________________________________") 7 | print("| Welcome to this Password Generator |") 8 | print("-------------------------------------\n") 9 | try: 10 | length = int( 11 | input("how long do you want your password to be (minimum of 8 number)") 12 | ) 13 | except: 14 | print("Input numners only") 15 | password_length = 0 16 | while password_length < length: 17 | print("Your password must have at least 8 characters") 18 | password_length = getPasswordLength() 19 | 20 | all_characters = getCharacters() 21 | password = generatePassword(all_characters, password_length) 22 | print("\nYour password is: " + password) 23 | print("__________________________________________") 24 | print("| Thanks for using the Password Generator |") 25 | print("------------------------------------------") 26 | 27 | 28 | def getPasswordLength(): 29 | # Set the password length with constraints for the password length 30 | password_length = int(input("\nEnter the length of password: ")) 31 | return password_length 32 | 33 | 34 | def getCharacters(): 35 | # define the characters 36 | lower = string.ascii_lowercase 37 | upper = string.ascii_uppercase 38 | num = string.digits 39 | symbols = string.punctuation 40 | 41 | all_characters = lower + upper + num + symbols 42 | return all_characters 43 | 44 | 45 | def generatePassword(all_characters, password_length): 46 | # generate a password string 47 | password = "".join(random.sample(all_characters, password_length)) 48 | return password 49 | 50 | 51 | main() 52 | -------------------------------------------------------------------------------- /Python Programs/speachtotext.py: -------------------------------------------------------------------------------- 1 | # import the following libraries 2 | #Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google. 3 | #pyttsx3 : It is an offline cross-platform Text-to-Speech library 4 | ##Googletrans : It is a free python library that implements the Google Translate API. 5 | # will convert the image to text string 6 | import pytesseract 7 | 8 | # adds image processing capabilities 9 | from PIL import Image 10 | 11 | # converts the text to speech 12 | import pyttsx3 13 | 14 | #translates into the mentioned language 15 | from googletrans import Translator 16 | 17 | # opening an image from the source path 18 | img = Image.open('text1.png') 19 | 20 | # describes image format in the output 21 | print(img) 22 | # path where the tesseract module is installed 23 | pytesseract.pytesseract.tesseract_cmd ='C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' 24 | # converts the image to result and saves it into result variable 25 | result = pytesseract.image_to_string(img) 26 | # write text in a text file and save it to source path 27 | with open('abc.txt',mode ='w') as file: 28 | 29 | file.write(result) 30 | print(result) 31 | 32 | p = Translator() 33 | # translates the text into german language 34 | k = p.translate(result,dest='german') 35 | print(k) 36 | engine = pyttsx3.init() 37 | 38 | # an audio will be played which speaks the test if pyttsx3 recognizes it 39 | engine.say(k) 40 | engine.runAndWait() -------------------------------------------------------------------------------- /Python Programs/library Management.py: -------------------------------------------------------------------------------- 1 | def add_book(l_dict,name,author): 2 | if name not in l_dict: 3 | l_dict[name]=author 4 | print(f"{name} added to library") 5 | else: 6 | print("Book already exists") 7 | 8 | def remove_book(l_dict,name): 9 | if name in l_dict: 10 | del l_dict[name] 11 | print(f"{name} deleted from library") 12 | else: 13 | print(f"{name} not found in library") 14 | 15 | def display_book(l_dict): 16 | for name,author in l_dict.items(): 17 | print(f"{name} : {author}") 18 | 19 | def search_book(l_dict,name): 20 | if name in l_dict: 21 | print(f"{name} : {l_dict[name]}") 22 | else: 23 | print(f"{name} not found in library") 24 | 25 | def main(): 26 | library_dict={} 27 | 28 | while 1: 29 | print("1. Add Book\n2. Remove Book\n3. Display Book\n4. Search Book\n5. Exit") 30 | choice = int(input("Enter your choice: ")) 31 | match choice: 32 | case 1: 33 | book_name=input("Enter book name: ") 34 | author_name=input("Enter author name: ") 35 | add_book(library_dict,book_name,author_name) 36 | case 2: 37 | book_name=input("Enter book name: ") 38 | remove_book(library_dict,book_name) 39 | case 3: 40 | display_book(library_dict) 41 | case 4: 42 | book_name=input("Enter book name: ") 43 | search_book(library_dict,book_name) 44 | case 5: 45 | print("Exiting...") 46 | exit() 47 | 48 | if __name__=="__main__": 49 | main() 50 | 51 | -------------------------------------------------------------------------------- /BasicResumeAnalyzer.py: -------------------------------------------------------------------------------- 1 | # ml.py 2 | import pdfplumber 3 | import docx 4 | import re 5 | import spacy 6 | 7 | nlp = spacy.load("en_core_web_sm") 8 | 9 | 10 | SKILLS = ["Python", "Machine Learning", "NLP", "Deep Learning", 11 | "Data Analysis", "SQL", "TensorFlow", "PyTorch"] 12 | 13 | 14 | # Resume Parsing 15 | def extract_text(file): 16 | """Extract text from PDF or DOCX file""" 17 | if str(file).endswith(".pdf"): 18 | text = "" 19 | with pdfplumber.open(file) as pdf: 20 | for page in pdf.pages: 21 | text += page.extract_text() + "\n" 22 | return text 23 | elif str(file).endswith(".docx"): 24 | doc = docx.Document(file) 25 | return "\n".join([para.text for para in doc.paragraphs]) 26 | else: 27 | return "" 28 | 29 | # Skills Extraction 30 | 31 | def extract_skills(text): 32 | """Find skills from predefined SKILLS list in resume text""" 33 | skills_found = [] 34 | for skill in SKILLS: 35 | if re.search(r'\b' + re.escape(skill) + r'\b', text, re.I): 36 | skills_found.append(skill) 37 | return skills_found 38 | 39 | # Experience Extraction 40 | 41 | def extract_experience(text): 42 | """Detect years of experience from resume text""" 43 | exp = re.findall(r'(\d+)\s+year', text, re.I) 44 | if exp: 45 | return max([int(x) for x in exp]) 46 | else: 47 | return 0 48 | 49 | 50 | # Resume Scoring 51 | 52 | def score_resume(skills_found, experience): 53 | """Compute a simple resume score""" 54 | skill_score = len(skills_found) / len(SKILLS) # 0 to 1 55 | exp_score = min(experience / 5, 1) # max 1 for 5+ years 56 | total_score = round((skill_score + exp_score) / 2 * 100, 2) 57 | return total_score 58 | -------------------------------------------------------------------------------- /Python Programs/To_do_list.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | 4 | def add_task(): 5 | task = task_entry.get() 6 | if task != "": 7 | tasks_listbox.insert(tk.END, task) 8 | task_entry.delete(0, tk.END) 9 | else: 10 | messagebox.showwarning("Input Error", "Please enter a task!") 11 | 12 | def delete_task(): 13 | try: 14 | task_index = tasks_listbox.curselection()[0] 15 | tasks_listbox.delete(task_index) 16 | except: 17 | messagebox.showwarning("Selection Error", "Please select a task to delete!") 18 | 19 | def mark_task_complete(): 20 | try: 21 | task_index = tasks_listbox.curselection()[0] 22 | task = tasks_listbox.get(task_index) 23 | tasks_listbox.delete(task_index) 24 | tasks_listbox.insert(tk.END, f"{task} (Completed)") 25 | except: 26 | messagebox.showwarning("Selection Error", "Please select a task to mark as complete!") 27 | 28 | # Create the main window 29 | window = tk.Tk() 30 | window.title("To-Do List App") 31 | 32 | # Create the task entry widget 33 | task_entry = tk.Entry(window, width=40) 34 | task_entry.pack(pady=10) 35 | 36 | # Create the buttons 37 | add_button = tk.Button(window, text="Add Task", width=20, command=add_task) 38 | add_button.pack(pady=5) 39 | 40 | delete_button = tk.Button(window, text="Delete Task", width=20, command=delete_task) 41 | delete_button.pack(pady=5) 42 | 43 | complete_button = tk.Button(window, text="Mark Task Complete", width=20, command=mark_task_complete) 44 | complete_button.pack(pady=5) 45 | 46 | # Create the listbox to display tasks 47 | tasks_listbox = tk.Listbox(window, height=10, width=50) 48 | tasks_listbox.pack(pady=10) 49 | 50 | # Run the application 51 | window.mainloop() 52 | -------------------------------------------------------------------------------- /Python Programs/Password_checker.py: -------------------------------------------------------------------------------- 1 | # Define a function to check if the password is strong enough 2 | def password_checker(password): 3 | # Define the criteria for a strong password 4 | min_length = 8 5 | has_uppercase = False 6 | has_lowercase = False 7 | has_digit = False 8 | has_special_char = False 9 | special_chars = "!@#$%^&*()-_=+[{]}\|;:',<.>/?" 10 | 11 | # Check the length of the password 12 | if len(password) < min_length: 13 | print("Password is too short!") 14 | return False 15 | 16 | # Check if the password contains an uppercase letter, lowercase letter, digit, and special character 17 | for char in password: 18 | if char.isupper(): 19 | has_uppercase = True 20 | elif char.islower(): 21 | has_lowercase = True 22 | elif char.isdigit(): 23 | has_digit = True 24 | elif char in special_chars: 25 | has_special_char = True 26 | 27 | # Print an error message for each missing criteria 28 | if not has_uppercase: 29 | print("Password must contain at least one uppercase letter!") 30 | return False 31 | if not has_lowercase: 32 | print("Password must contain at least one lowercase letter!") 33 | return False 34 | if not has_digit: 35 | print("Password must contain at least one digit!") 36 | return False 37 | if not has_special_char: 38 | print("Password must contain at least one special character!") 39 | return False 40 | 41 | # If all criteria are met, print a success message 42 | print("Password is strong!") 43 | return True 44 | 45 | # Prompt the user to enter a password and check if it meets the criteria 46 | password = input("Enter a password: ") 47 | password_checker(password) 48 | -------------------------------------------------------------------------------- /Python Programs/ASCII_Art_ Generator.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | # ASCII characters used to represent pixel intensity 4 | ASCII_CHARS = ['@', '#', 'S', '%', '?', '*', '+', ';', ':', ',', '.'] 5 | 6 | # Resize the image to fit within terminal size 7 | def resize_image(image, new_width=100): 8 | width, height = image.size 9 | aspect_ratio = height / width 10 | new_height = int(aspect_ratio * new_width * 0.55) 11 | resized_image = image.resize((new_width, new_height)) 12 | return resized_image 13 | 14 | # Convert each pixel to grayscale 15 | def grayify(image): 16 | grayscale_image = image.convert('L') 17 | return grayscale_image 18 | 19 | # Map each pixel to an ASCII character 20 | def pixels_to_ascii(image): 21 | pixels = image.getdata() 22 | ascii_str = "".join([ASCII_CHARS[pixel // 25] for pixel in pixels]) 23 | return ascii_str 24 | 25 | # Main function to convert image to ASCII 26 | def image_to_ascii(image_path, new_width=100): 27 | try: 28 | image = Image.open(image_path) 29 | except Exception as e: 30 | print(f"Unable to open image file: {e}") 31 | return 32 | 33 | image = resize_image(image, new_width) 34 | image = grayify(image) 35 | 36 | ascii_str = pixels_to_ascii(image) 37 | 38 | # Format the string into lines of the correct width 39 | img_width = image.width 40 | ascii_str_len = len(ascii_str) 41 | ascii_img = "\n".join([ascii_str[i:i + img_width] for i in range(0, ascii_str_len, img_width)]) 42 | 43 | return ascii_img 44 | 45 | # Run the program with an example image 46 | if __name__ == "__main__": 47 | path = input("Enter the image path: ") 48 | ascii_art = image_to_ascii(path) 49 | print(ascii_art) 50 | 51 | # Optionally save to a file 52 | with open("ascii_image.txt", "w") as f: 53 | f.write(ascii_art) 54 | -------------------------------------------------------------------------------- /Hand-tracking Module/handTrackMin.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import time 4 | 5 | 6 | 7 | # Capture the video from webcam 8 | cap = cv2.VideoCapture(0) 9 | 10 | # import the hand detection model 11 | mpHands = mp.solutions.mediapipe.python.solutions.hands 12 | hands = mpHands.Hands() 13 | mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils 14 | 15 | # To check the frame rate 16 | prevTime = 0 17 | CurrentTime = 0 18 | 19 | while True: 20 | success, img = cap.read() 21 | imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 22 | results = hands.process(imgRGB) 23 | 24 | # lets open the processed object and extract the information 25 | # print(results.multi_hand_landmarks) 26 | 27 | if results.multi_hand_landmarks: 28 | # Check for every hands in the image 29 | for handLMS in results.multi_hand_landmarks: 30 | # Draw thw hands using built in drawing utilities 31 | mpDraw.draw_landmarks(img, handLMS, mpHands.HAND_CONNECTIONS) 32 | 33 | # Get all the info about each hands 34 | for id, lm in enumerate(handLMS.landmark): 35 | # print(id, lm) 36 | h, w, c = img.shape 37 | cx, cy = int(lm.x*w), int(lm.y*h) 38 | print(id, cx, cy) 39 | 40 | # Draw a circle for id=0 wrist 41 | if id == 4: 42 | cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED) 43 | 44 | # Calculate the FPS 45 | currentTime = time.time() 46 | fps = 1/(currentTime - prevTime) 47 | prevTime = currentTime 48 | 49 | # Write the fps into the image 50 | cv2.putText(img, str(int(fps)), (10, 78), 51 | cv2.FONT_HERSHEY_TRIPLEX, 3, (255, 0, 255), 3) 52 | 53 | cv2.imshow("Image", img) 54 | cv2.waitKey(1) 55 | 56 | 57 | # if __name__ == "__main__": 58 | # main() 59 | -------------------------------------------------------------------------------- /Python Programs/URL_QR_Generator.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.messagebox import * 3 | from qrcode import * 4 | from PIL import Image, ImageTk 5 | 6 | root = Tk() 7 | root.title("QR Code Generator") 8 | root.geometry("500x600+200+20") 9 | 10 | # Define colors 11 | bg_color = "#DAE6F0" # Light blue background 12 | label_color = "#333333" # Dark gray for labels 13 | entry_color = "#ffffff" # White for entry fields 14 | button_color = "#4CAF50" # Green for buttons 15 | button_text_color = "#ffffff" # White text for buttons 16 | 17 | # Define fonts 18 | heading_font = ("Arial", 30, "bold") 19 | label_font = ("Verdana", 15) # Smaller font size, changed font style 20 | button_font = ("Arial", 20, "bold") 21 | 22 | # Function to generate QR code 23 | def generate_qr(): 24 | url = ent_url.get() 25 | if url == "": 26 | showerror("Error", "URL is empty") 27 | ent_url.focus() 28 | return 29 | 30 | # Generate QR code 31 | img = make(url) 32 | img.save("qr2.png") 33 | img = Image.open("qr2.png") 34 | new_size = (400, 400) 35 | resized_img = img.resize(new_size) 36 | resized_img.save("qr2.png") 37 | img = Image.open("qr2.png") 38 | imgtk = ImageTk.PhotoImage(image=img) 39 | lab_qr.configure(image=imgtk) 40 | lab_qr.photo = imgtk 41 | 42 | # Configure root window 43 | root.configure(bg=bg_color) 44 | 45 | # Labels, Entry, Button, and QR Code display 46 | lab_url = Label(root, text="Enter URL", font=heading_font, fg=label_color, bg=bg_color) 47 | ent_url = Entry(root, font=label_font, bg=entry_color) 48 | btn_generate = Button(root, text="Generate QR Code", font=button_font, bg=button_color, fg=button_text_color, command=generate_qr) 49 | lab_qr = Label(root, font=label_font, bg=bg_color) 50 | 51 | # Packing widgets 52 | lab_url.pack(pady=10) 53 | ent_url.pack(pady=10) 54 | btn_generate.pack(pady=10) 55 | lab_qr.pack(pady=10) 56 | 57 | root.mainloop() 58 | -------------------------------------------------------------------------------- /Python Programs/AiNotesApp.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template_string 2 | from transformers import pipeline 3 | 4 | app = Flask(__name__) 5 | 6 | # Initialize the summarization model 7 | summarizer = pipeline("summarization") 8 | 9 | notes = [] 10 | 11 | # HTML template for the notes app 12 | template = """ 13 | 14 | 15 | AI Notes App 16 | 17 |

AI Notes App

18 |
19 |
20 | 21 |
22 |

Notes

23 |
    24 | {% for note in notes %} 25 |
  • {{ note }}
  • 26 | {% endfor %} 27 |
28 |

Summarized Note

29 |
30 |
31 | 32 |
33 | {% if summary %} 34 |

Summary: {{ summary }}

35 | {% endif %} 36 | 37 | 38 | """ 39 | 40 | @app.route("/", methods=["GET", "POST"]) 41 | def home(): 42 | if request.method == "POST": 43 | note = request.form["note"] 44 | if note: 45 | notes.append(note) 46 | return render_template_string(template, notes=notes, summary=None) 47 | 48 | @app.route("/summarize", methods=["POST"]) 49 | def summarize(): 50 | summary_note = request.form["summary_note"] 51 | if summary_note: 52 | summary = summarizer(summary_note, max_length=50, min_length=25, do_sample=False)[0]['summary_text'] 53 | return render_template_string(template, notes=notes, summary=summary) 54 | return render_template_string(template, notes=notes, summary=None) 55 | 56 | if __name__ == "__main__": 57 | app.run(debug=True) 58 | -------------------------------------------------------------------------------- /Python Programs/Program to convert a binary number to octal.py: -------------------------------------------------------------------------------- 1 | # Python3 implementation to convert a binary number 2 | # to octal number 3 | 4 | # function to create map between binary 5 | # number and its equivalent octal 6 | def createMap(bin_oct_map): 7 | bin_oct_map["000"] = '0' 8 | bin_oct_map["001"] = '1' 9 | bin_oct_map["010"] = '2' 10 | bin_oct_map["011"] = '3' 11 | bin_oct_map["100"] = '4' 12 | bin_oct_map["101"] = '5' 13 | bin_oct_map["110"] = '6' 14 | bin_oct_map["111"] = '7' 15 | 16 | # Function to find octal equivalent of binary 17 | def convertBinToOct(bin): 18 | l = len(bin) 19 | 20 | # length of string before '.' 21 | t = -1 22 | if '.' in bin: 23 | t = bin.index('.') 24 | len_left = t 25 | else: 26 | len_left = l 27 | 28 | # add min 0's in the beginning to make 29 | # left substring length divisible by 3 30 | for i in range(1, (3 - len_left % 3) % 3 + 1): 31 | bin = '0' + bin 32 | 33 | # if decimal point exists 34 | if (t != -1): 35 | 36 | # length of string after '.' 37 | len_right = l - len_left - 1 38 | 39 | # add min 0's in the end to make right 40 | # substring length divisible by 3 41 | for i in range(1, (3 - len_right % 3) % 3 + 1): 42 | bin = bin + '0' 43 | 44 | # create dictionary between binary and its 45 | # equivalent octal code 46 | bin_oct_map = {} 47 | createMap(bin_oct_map) 48 | i = 0 49 | octal = "" 50 | 51 | while (True) : 52 | 53 | # one by one extract from left, substring 54 | # of size 3 and add its octal code 55 | octal += bin_oct_map[bin[i:i + 3]] 56 | i += 3 57 | if (i == len(bin)): 58 | break 59 | 60 | # if '.' is encountered add it to result 61 | if (bin[i] == '.'): 62 | octal += '.' 63 | i += 1 64 | 65 | # required octal number 66 | return octal 67 | 68 | # Driver Code 69 | bin = "1111001010010100001.010110110011011" 70 | print("Octal number = ", 71 | convertBinToOct(bin)) 72 | -------------------------------------------------------------------------------- /Python Programs/simple_text_editor.py: -------------------------------------------------------------------------------- 1 | import tkinter as tr 2 | from tkinter.filedialog import askopenfilename, asksaveasfilename 3 | 4 | def open_file(window, text_edit): 5 | filepath = askopenfilename(filetypes=[("Text Files", "*.txt"), ("Python File", "*.py"), ("C++ File", "*.cpp")]) 6 | 7 | if not filepath: 8 | return 9 | 10 | text_edit.delete(1.0, tr.END) # 1.0 = Line 1 and 0th Character 11 | with open(filepath, "r") as f: 12 | content = f.read() 13 | text_edit.insert(tr.END, content) 14 | window.title(f"Open File: {filepath}") 15 | 16 | def save_file(window, text_edit): 17 | filepath = asksaveasfilename(filetypes=[("Text Files", "*.txt"), ("Python File", "*.py"), ("C++ File", "*.cpp")]) 18 | 19 | if not filepath: 20 | return 21 | 22 | with open(filepath, "w") as f: 23 | content = text_edit.get(1.0, tr.END) 24 | f.write(content) 25 | window.title(f"Saved File: {filepath}") 26 | 27 | def main(): 28 | window = tr.Tk() 29 | window.title("Text Editor: Made Using Python") 30 | window.rowconfigure(0, minsize=100) 31 | window.columnconfigure(1, minsize=100) 32 | 33 | text_edit = tr.Text(window, font="Helvetica 11 bold") 34 | text_edit.grid(row=0, column=1) 35 | 36 | Frame = tr.Frame(window, relief=tr.RAISED, bd=2) 37 | save_button = tr.Button(Frame, text="Save", command=lambda: save_file(window, text_edit)) 38 | open_button = tr.Button(Frame, text="Open", command=lambda: open_file(window, text_edit)) 39 | 40 | save_button.grid(row=0, column=0, padx=5, pady=5, sticky="ew") 41 | open_button.grid(row=1, column=0, padx=5, pady=5, sticky="ew") 42 | Frame.grid(row=0, column=0, sticky="ns") 43 | 44 | window.bind("", lambda x: save_file(window, text_edit)) 45 | window.bind("", lambda x: open_file(window, text_edit)) 46 | 47 | window.mainloop() 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /Python Programs/a_star_algorithm.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | 3 | # A* Algorithm implementation 4 | def a_star(graph, start, goal, h): 5 | # Priority queue to store (f(n), node, g(n), path) 6 | open_list = [] 7 | heappush(open_list, (h(start), start, 0, [start])) # Push start node with heuristic h(start) 8 | 9 | # Closed set to keep track of visited nodes 10 | closed_set = set() 11 | 12 | while open_list: 13 | # Get the node with the lowest f(n) 14 | f, current, g, path = heappop(open_list) 15 | 16 | # If goal is reached, return the path and total cost 17 | if current == goal: 18 | return path, g 19 | 20 | # Add current node to the closed set 21 | closed_set.add(current) 22 | 23 | # Explore neighbors of current node 24 | for neighbor, cost in graph[current]: 25 | if neighbor in closed_set: 26 | continue 27 | 28 | # Calculate g(n) for neighbor 29 | g_neighbor = g + cost 30 | 31 | # Push neighbor with its calculated f(n) = g(n) + h(n) 32 | heappush(open_list, (g_neighbor + h(neighbor), neighbor, g_neighbor, path + [neighbor])) 33 | 34 | return None # No path found 35 | 36 | # Example graph represented as an adjacency list 37 | graph = { 38 | 'A': [('B', 1), ('C', 4)], 39 | 'B': [('A', 1), ('D', 2), ('E', 5)], 40 | 'C': [('A', 4), ('F', 1)], 41 | 'D': [('B', 2), ('E', 1)], 42 | 'E': [('B', 5), ('D', 1), ('G', 2)], 43 | 'F': [('C', 1), ('G', 3)], 44 | 'G': [('E', 2), ('F', 3)] 45 | } 46 | 47 | # Example heuristic function (for simplicity, assume 0 for goal node) 48 | def heuristic(node): 49 | H = {'A': 7, 'B': 6, 'C': 2, 'D': 4, 'E': 3, 'F': 1, 'G': 0} 50 | return H.get(node, float('inf')) 51 | 52 | # Run A* algorithm to find the shortest path from 'A' to 'G' 53 | start_node = 'A' 54 | goal_node = 'G' 55 | path, cost = a_star(graph, start_node, goal_node, heuristic) 56 | 57 | print(f"Shortest path: {path}") 58 | print(f"Total cost: {cost}") 59 | -------------------------------------------------------------------------------- /Python Programs/Tarjan-Algorithm.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class TarjanSCC: 4 | def __init__(self, vertices): 5 | self.graph = defaultdict(list) # Dictionary to store the graph 6 | self.V = vertices # Number of vertices 7 | self.time = 0 # Global variable for time 8 | self.low = [-1] * vertices # Low-link values 9 | self.disc = [-1] * vertices # Discovery times 10 | self.stack_member = [False] * vertices # Stack member boolean array 11 | self.stack = [] # Stack to store visited vertices 12 | 13 | def add_edge(self, u, v): 14 | """Add an edge from vertex u to vertex v""" 15 | self.graph[u].append(v) 16 | 17 | def tarjan_scc_util(self, u): 18 | """A recursive function to find SCCs using Tarjan's Algorithm""" 19 | self.disc[u] = self.low[u] = self.time 20 | self.time += 1 21 | self.stack.append(u) 22 | self.stack_member[u] = True 23 | 24 | # Go through all vertices adjacent to u 25 | for v in self.graph[u]: 26 | if self.disc[v] == -1: # If v is not visited yet 27 | self.tarjan_scc_util(v) 28 | self.low[u] = min(self.low[u], self.low[v]) 29 | elif self.stack_member[v]: # If v is in the stack, it is part of SCC 30 | self.low[u] = min(self.low[u], self.disc[v]) 31 | 32 | # If u is the root of an SCC 33 | if self.low[u] == self.disc[u]: 34 | scc = [] 35 | while True: 36 | v = self.stack.pop() 37 | self.stack_member[v] = False 38 | scc.append(v) 39 | if v == u: 40 | break 41 | print("SCC:", scc) 42 | 43 | def tarjan_scc(self): 44 | """Function to find all SCCs in the graph""" 45 | for i in range(self.V): 46 | if self.disc[i] == -1: 47 | self.tarjan_scc_util(i) 48 | 49 | # Example Usage 50 | g = TarjanSCC(5) 51 | g.add_edge(1, 0) 52 | g.add_edge(0, 2) 53 | g.add_edge(2, 1) 54 | g.add_edge(0, 3) 55 | g.add_edge(3, 4) 56 | 57 | print("Strongly Connected Components:") 58 | g.tarjan_scc() 59 | -------------------------------------------------------------------------------- /Python Programs/calculator.py: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | return x + y 3 | 4 | def subtract(x, y): 5 | return x - y 6 | 7 | def multiply(x, y): 8 | return x * y 9 | 10 | def divide(x, y): 11 | if y == 0: 12 | return "Error! Division by zero." 13 | return x / y 14 | 15 | def get_number(prompt): 16 | while True: 17 | try: 18 | return float(input(prompt)) 19 | except ValueError: 20 | print("Invalid input! Please enter a valid number.") 21 | 22 | def calculator(): 23 | print("Welcome to the Simple Calculator!") 24 | print("--------------------------------") 25 | print("You can perform the following operations:") 26 | print("1. Addition (+)") 27 | print("2. Subtraction (-)") 28 | print("3. Multiplication (*)") 29 | print("4. Division (/)") 30 | print("Type 'exit' anytime to quit the calculator.") 31 | print("--------------------------------") 32 | 33 | operations = { 34 | '1': add, 35 | '2': subtract, 36 | '3': multiply, 37 | '4': divide 38 | } 39 | 40 | operation_symbols = { 41 | '1': '+', 42 | '2': '-', 43 | '3': '*', 44 | '4': '/' 45 | } 46 | 47 | while True: 48 | choice = input("\nSelect an operation (1/2/3/4): ").strip().lower() 49 | 50 | if choice == 'exit': 51 | print("Thank you for using the calculator. Goodbye!") 52 | break 53 | 54 | if choice in operations: 55 | num1 = get_number("Enter the first number: ") 56 | num2 = get_number("Enter the second number: ") 57 | 58 | result = operations[choice](num1, num2) 59 | symbol = operation_symbols[choice] 60 | print(f"\nResult: {num1} {symbol} {num2} = {result}") 61 | else: 62 | print("Invalid option! Please select a valid operation (1, 2, 3, or 4).") 63 | 64 | next_calculation = input("\nWould you like to perform another calculation? (yes/no): ").strip().lower() 65 | if next_calculation != 'yes': 66 | print("Thank you for using the calculator. Goodbye!") 67 | break 68 | 69 | if __name__ == "__main__": 70 | calculator() -------------------------------------------------------------------------------- /Python Programs/optimized_dsu.py: -------------------------------------------------------------------------------- 1 | class DSU: 2 | """ 3 | Disjoint Set Union data structure with path compression and union by rank. 4 | Supports efficient set operations in near-constant amortized time. 5 | """ 6 | 7 | def __init__(self, n): 8 | """ 9 | Initialize DSU with n elements (0 to n-1). 10 | 11 | Args: 12 | n: Number of elements 13 | """ 14 | self.parent = list(range(n)) 15 | self.rank = [0] * n 16 | self.size = [1] * n 17 | 18 | def find(self, x): 19 | """ 20 | Find representative of set containing x with path compression. 21 | 22 | Args: 23 | x: Element to find 24 | 25 | Returns: 26 | Root of the set containing x 27 | """ 28 | if self.parent[x] != x: 29 | self.parent[x] = self.find(self.parent[x]) 30 | return self.parent[x] 31 | 32 | def union(self, x, y): 33 | """ 34 | Merge sets containing x and y using union by rank. 35 | 36 | Args: 37 | x: First element 38 | y: Second element 39 | 40 | Returns: 41 | True if sets were merged, False if already in same set 42 | """ 43 | px, py = self.find(x), self.find(y) 44 | if px == py: 45 | return False 46 | if self.rank[px] < self.rank[py]: 47 | px, py = py, px 48 | self.parent[py] = px 49 | self.size[px] += self.size[py] 50 | if self.rank[px] == self.rank[py]: 51 | self.rank[px] += 1 52 | return True 53 | 54 | def connected(self, x, y): 55 | """ 56 | Check if x and y are in the same set. 57 | 58 | Args: 59 | x: First element 60 | y: Second element 61 | 62 | Returns: 63 | True if in same set, False otherwise 64 | """ 65 | return self.find(x) == self.find(y) 66 | 67 | def get_size(self, x): 68 | """ 69 | Get size of set containing x. 70 | 71 | Args: 72 | x: Element to query 73 | 74 | Returns: 75 | Number of elements in the set 76 | """ 77 | return self.size[self.find(x)] 78 | -------------------------------------------------------------------------------- /Python Programs/convert a given number to words.py: -------------------------------------------------------------------------------- 1 | # Python3 program to print a given number in words. 2 | # The program handles till 9 digits numbers and 3 | # can be easily extended to 20 digit number 4 | 5 | # strings at index 0 is not used, it 6 | # is to make array indexing simple 7 | one = [ "", "one ", "two ", "three ", "four ", 8 | "five ", "six ", "seven ", "eight ", 9 | "nine ", "ten ", "eleven ", "twelve ", 10 | "thirteen ", "fourteen ", "fifteen ", 11 | "sixteen ", "seventeen ", "eighteen ", 12 | "nineteen "]; 13 | 14 | # strings at index 0 and 1 are not used, 15 | # they are to make array indexing simple 16 | ten = [ "", "", "twenty ", "thirty ", "forty ", 17 | "fifty ", "sixty ", "seventy ", "eighty ", 18 | "ninety "]; 19 | 20 | # n is 1- or 2-digit number 21 | def numToWords(n, s): 22 | 23 | str = ""; 24 | 25 | # if n is more than 19, divide it 26 | if (n > 19): 27 | str += ten[n // 10] + one[n % 10]; 28 | else: 29 | str += one[n]; 30 | 31 | # if n is non-zero 32 | if (n): 33 | str += s; 34 | 35 | return str; 36 | 37 | # Function to print a given number in words 38 | def convertToWords(n): 39 | 40 | # stores word representation of given 41 | # number n 42 | out = ""; 43 | 44 | # handles digits at ten millions and 45 | # hundred millions places (if any) 46 | out += numToWords((n // 10000000), 47 | "crore "); 48 | 49 | # handles digits at hundred thousands 50 | # and one millions places (if any) 51 | out += numToWords(((n // 100000) % 100), 52 | "lakh "); 53 | 54 | # handles digits at thousands and tens 55 | # thousands places (if any) 56 | out += numToWords(((n // 1000) % 100), 57 | "thousand "); 58 | 59 | # handles digit at hundreds places (if any) 60 | out += numToWords(((n // 100) % 10), 61 | "hundred "); 62 | 63 | if (n > 100 and n % 100): 64 | out += "and "; 65 | 66 | # handles digits at ones and tens 67 | # places (if any) 68 | out += numToWords((n % 100), ""); 69 | 70 | return out; 71 | 72 | # Driver code 73 | 74 | # long handles upto 9 digit no 75 | # change to unsigned long long 76 | # int to handle more digit number 77 | n = 438237764; 78 | 79 | # convert given number in words 80 | print(convertToWords(n)); 81 | 82 | # This code is contributed by mits 83 | 84 | -------------------------------------------------------------------------------- /SriparnaChatBot.py: -------------------------------------------------------------------------------- 1 | import enum 2 | import random 3 | import json 4 | import pickle 5 | import numpy as np 6 | import time 7 | 8 | import nltk 9 | from nltk.stem import WordNetLemmatizer 10 | from six import class_types 11 | 12 | from tensorflow.keras.models import load_model 13 | 14 | lematizer = WordNetLemmatizer() 15 | intents = json.loads(open('intents.json').read()) 16 | 17 | words = pickle.load(open('words.pkl', 'rb')) 18 | classes = pickle.load(open('classes.pkl', 'rb')) 19 | model = load_model('chatbot_model.h5') 20 | 21 | 22 | def clean_up_sentence(sentence): 23 | sentence_words = nltk.word_tokenize(sentence) 24 | sentence_words = [lematizer.lemmatize(word) for word in sentence_words] 25 | return sentence_words 26 | 27 | 28 | def bag_of_words(sentence): 29 | sentence_words = clean_up_sentence(sentence) 30 | bag = [0] * len(words) 31 | for w in sentence_words: 32 | for i, word in enumerate(words): 33 | if word == w: 34 | bag[i] = 1 35 | return np.array(bag) 36 | 37 | 38 | def predict_class(sentence): 39 | bow = bag_of_words(sentence) 40 | res = model.predict(np.array([bow]))[0] 41 | ERROR_THRESHOLD = 0.25 42 | results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD] 43 | 44 | results.sort(key=lambda x: x[1], reverse=True) 45 | return_list = [] 46 | for r in results: 47 | return_list.append({'intent': classes[r[0]], 'probability': str(r[1])}) 48 | return return_list 49 | 50 | 51 | def get_response(intents_list, intents_json): 52 | tag = intents_list[0]['intent'] 53 | list_of_intents = intents_json['intents'] 54 | for i in list_of_intents: 55 | if i['tag'] == tag: 56 | result = random.choice(i['responses']) 57 | break 58 | return result 59 | 60 | 61 | if __name__ == "__main__": 62 | 63 | print("Go! Bot is running...") 64 | 65 | while True: 66 | message = input("Soumyajit: ") 67 | if "Go offline" in message or "go offline" in message: 68 | print("Going offline...") 69 | break 70 | else: 71 | ints = predict_class(message) 72 | res = get_response(ints, intents) 73 | time.sleep(0.5) 74 | print("Sriparna:", res) 75 | -------------------------------------------------------------------------------- /Python Programs/MakeSumDivisibleByP.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 1590. Make Sum Divisible by P 4 | Solved 5 | Medium 6 | Topics 7 | Companies 8 | Hint 9 | Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. 10 | 11 | Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. 12 | 13 | A subarray is defined as a contiguous block of elements in the array. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: nums = [3,1,4,2], p = 6 20 | Output: 1 21 | Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. 22 | Example 2: 23 | 24 | Input: nums = [6,3,5,2], p = 9 25 | Output: 2 26 | Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. 27 | Example 3: 28 | 29 | Input: nums = [1,2,3], p = 3 30 | Output: 0 31 | Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything. 32 | 33 | 34 | Constraints: 35 | 36 | 1 <= nums.length <= 105 37 | 1 <= nums[i] <= 109 38 | 1 <= p <= 109 39 | """ 40 | 41 | from typing import List 42 | 43 | class Solution: 44 | def minSubarray(self, nums: List[int], p: int) -> int: 45 | totalSum = sum(nums) 46 | rem = totalSum % p 47 | 48 | if rem == 0: 49 | return 0 50 | 51 | prefixMod = {0: -1} 52 | prefixSum = 0 53 | minLength = len(nums) 54 | 55 | for i, num in enumerate(nums): 56 | prefixSum += num 57 | currentMod = prefixSum % p 58 | targetMod = (currentMod - rem + p) % p 59 | 60 | if targetMod in prefixMod: 61 | minLength = min(minLength, i - prefixMod[targetMod]) 62 | 63 | prefixMod[currentMod] = i 64 | 65 | return minLength if minLength < len(nums) else -1 66 | 67 | 68 | # Test Cases 69 | 70 | test = Solution() 71 | assert test.minSubarray([3,1,4,2], 6) == 1 72 | assert test.minSubarray([6,3,5,2], 9) == 2 73 | assert test.minSubarray([1,2,3], 3) == 0 74 | 75 | print("All tests passed") -------------------------------------------------------------------------------- /Python Programs/Floyd-Warshall-Algo.py: -------------------------------------------------------------------------------- 1 | def floyd_warshall(graph): 2 | """ 3 | Implements the Floyd-Warshall algorithm to find the shortest paths 4 | between all pairs of vertices in a weighted graph. 5 | 6 | Parameters: 7 | graph (list of list of float): A 2D list representing the adjacency matrix 8 | of the graph. A value of float('inf') indicates 9 | no edge between vertices. 10 | 11 | Returns: 12 | list of list of float: A 2D list containing the shortest path distances 13 | between all pairs of vertices. 14 | """ 15 | # Number of vertices in the graph 16 | num_vertices = len(graph) 17 | 18 | # Initialize the distance matrix with the input graph 19 | distance = [[float('inf')] * num_vertices for _ in range(num_vertices)] 20 | 21 | # Set the distance from each vertex to itself to 0 22 | for i in range(num_vertices): 23 | distance[i][i] = 0 24 | 25 | # Set the initial distances based on the graph's edges 26 | for u in range(num_vertices): 27 | for v in range(num_vertices): 28 | if graph[u][v] != float('inf'): 29 | distance[u][v] = graph[u][v] 30 | 31 | # Floyd-Warshall algorithm 32 | for k in range(num_vertices): 33 | for i in range(num_vertices): 34 | for j in range(num_vertices): 35 | if distance[i][j] > distance[i][k] + distance[k][j]: 36 | distance[i][j] = distance[i][k] + distance[k][j] 37 | 38 | return distance 39 | 40 | # Example usage 41 | if __name__ == "__main__": 42 | # Create a graph represented as an adjacency matrix 43 | # For example, the graph below has 4 vertices and the weights of the edges: 44 | # 0 1 2 3 45 | # 0: [ 0, 3, inf, 7 ] 46 | # 1: [ inf, 0, 1, inf ] 47 | # 2: [ inf, inf, 0, 2 ] 48 | # 3: [ inf, inf, inf, 0 ] 49 | graph = [ 50 | [0, 3, float('inf'), 7], 51 | [float('inf'), 0, 1, float('inf')], 52 | [float('inf'), float('inf'), 0, 2], 53 | [float('inf'), float('inf'), float('inf'), 0] 54 | ] 55 | 56 | shortest_paths = floyd_warshall(graph) 57 | 58 | print("Shortest path distances between every pair of vertices:") 59 | for row in shortest_paths: 60 | print(row) 61 | -------------------------------------------------------------------------------- /SrTraining.py: -------------------------------------------------------------------------------- 1 | import random 2 | import json 3 | import pickle 4 | import numpy as np 5 | 6 | import nltk 7 | from nltk.stem import WordNetLemmatizer 8 | 9 | from tensorflow.keras.models import Sequential 10 | from tensorflow.keras.layers import Dense, Activation, Dropout 11 | from tensorflow.keras.optimizers import SGD 12 | 13 | lematizer = WordNetLemmatizer() 14 | 15 | intents = json.loads(open('intents.json').read()) 16 | 17 | words = [] 18 | classes = [] 19 | documents = [] 20 | ignore_letters = ['?', '!', '.', ','] 21 | 22 | for intent in intents['intents']: 23 | for pattern in intent['patterns']: 24 | word_list = nltk.word_tokenize(pattern) 25 | words.extend(word_list) 26 | documents.append((word_list, intent['tag'])) 27 | if intent['tag'] not in classes: 28 | classes.append(intent['tag']) 29 | 30 | words = [lematizer.lemmatize(word) 31 | for word in words if word not in ignore_letters] 32 | words = sorted(set(words)) 33 | 34 | classes = sorted(set(classes)) 35 | 36 | pickle.dump(words, open('words.pkl', 'wb')) 37 | pickle.dump(classes, open('classes.pkl', 'wb')) 38 | 39 | training = [] 40 | output_empty = [0] * len(classes) 41 | 42 | for document in documents: 43 | bag = [] 44 | word_patterns = document[0] 45 | word_patterns = [lematizer.lemmatize(word.lower()) 46 | for word in word_patterns] 47 | for word in words: 48 | bag.append(1) if word in word_patterns else bag.append(0) 49 | 50 | output_row = list(output_empty) 51 | output_row[classes.index(document[1])] = 1 52 | training.append([bag, output_row]) 53 | 54 | random.shuffle(training) 55 | training = np.array(training) 56 | 57 | train_x = list(training[:, 0]) 58 | train_y = list(training[:, 1]) 59 | 60 | model = Sequential() 61 | model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu')) 62 | model.add(Dropout(0.5)) 63 | model.add(Dense(64, activation='relu')) 64 | model.add(Dropout(0.5)) 65 | model.add(Dense(len(train_y[0]), activation='softmax')) 66 | 67 | sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) 68 | model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 69 | 70 | hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1) 71 | model.save('chatbot_model.h5', hist) 72 | print("Done") 73 | 74 | -------------------------------------------------------------------------------- /Python Programs/weatherApplication.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | import requests 3 | API_KEY = "Your API" 4 | 5 | # Getting user city as a input 6 | user_input = input("Enter a city : ") 7 | 8 | #Request weather data 9 | weather_data = requests.get(f"https://api.openweathermap.org/data/2.5/weather?q={user_input}&appid=&units=metric") 10 | if weather_data.json()['cod'] == '404': 11 | print("No City Found") 12 | else: 13 | weather = weather_data.json()['weather'][0]['main'] 14 | temp = round(weather_data.json()['main']['temp']) 15 | feels_like = round(weather_data.json()['main']['feels_like']) 16 | wind_speed = weather_data.json()['wind']['speed'] 17 | humidity = weather_data.json()['main']['humidity'] 18 | sunrise = dt.datetime.fromtimestamp(weather_data.json()['sys']['sunrise']) 19 | sunset = dt.datetime.fromtimestamp(weather_data.json()['sys']['sunset']) 20 | 21 | print(f"The weather in {user_input} is: {weather}") 22 | print(f"The temperature in {user_input} is: {temp}°F") 23 | print(f"It feels like {feels_like}°F in {user_input}") 24 | print(f"The wind speed in {user_input} is: {wind_speed} mph") 25 | print(f"The humidity in {user_input} is: {humidity}%") 26 | print(f"The sunrise in {user_input} is: {sunrise}") 27 | print(f"The sunset in {user_input} is: {sunset}") 28 | print(f"The latitude in {user_input} is: {weather_data.json()['coord']['lat']}") 29 | print(f"The longitude in {user_input} is: {weather_data.json()['coord']['lon']}") 30 | 31 | file_name = f"{user_input}_weather_data.txt" 32 | with open(file_name, "w") as file: 33 | file.write(f"The weather in {user_input} is: {weather}\n") 34 | file.write(f"The temperature in {user_input} is: {temp}°F\n") 35 | file.write(f"It feels like {feels_like}°F in {user_input}\n") 36 | file.write(f"The wind speed in {user_input} is: {wind_speed} mph\n") 37 | file.write(f"The humidity in {user_input} is: {humidity}%\n") 38 | file.write(f"The sunrise in {user_input} is: {sunrise}\n") 39 | file.write(f"The sunset in {user_input} is: {sunset}\n") 40 | file.write(f"The latitude in {user_input} is: {weather_data.json()['coord']['lat']}\n") 41 | file.write(f"The longitude in {user_input} is: {weather_data.json()['coord']['lon']}\n") 42 | file.close() 43 | 44 | print(f"Weather data for {user_input} has been saved to {file_name}") 45 | print("Thank you for using the weather app!") 46 | -------------------------------------------------------------------------------- /currency_converter.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | # Replace with your API Key from freecurrencyapi.com 5 | API_KEY = "REPLACE_WITH_FREE_CURRENCY_API_KEY" 6 | FREE_CURRENCY_API_URL = "https://api.freecurrencyapi.com/v1/latest" 7 | 8 | def get_exchange_rate(from_currency, to_currency, api_key): 9 | """ 10 | Gets the exchange rate. 11 | Returns the rate or None in case of error 12 | """ 13 | if api_key == "REPLACE_WITH_FREE_CURRENCY_API_KEY": 14 | print("Error: Please replace 'REPLACE_WITH_FREE_CURRENCY_API_KEY' with actual key.") 15 | return None 16 | 17 | params = { 18 | "apikey": api_key, 19 | "base_currency": from_currency 20 | } 21 | 22 | try: 23 | response = requests.get(FREE_CURRENCY_API_URL, params=params) 24 | response.raise_for_status() # Raise an exception 25 | data = response.json() 26 | 27 | if 'data' in data and to_currency in data['data']: 28 | return data['data'][to_currency] 29 | else: 30 | print(f"Error: Exchange rate for {to_currency} not found in response.") 31 | print("API Response:", data) 32 | return None 33 | except requests.exceptions.RequestException as e: 34 | print(f"Error making API request: {e}") 35 | return None 36 | except json.JSONDecodeError as e: 37 | print(f"Error decoding response: {e}") 38 | print("Raw API Response:", response.text if 'response' in locals() else "No response received") 39 | return None 40 | except Exception as e: 41 | print(f"An unexpected error occurred: {e}") 42 | return None 43 | 44 | def main(): 45 | print("Starting the Currency Converter!") 46 | 47 | from_currency = input("Enter the currency to convert FROM (e.g., USD): ").upper() 48 | to_currency = input("Enter the currency to convert TO (e.g., EUR): ").upper() 49 | try: 50 | amount = float(input("Enter the amount to convert: ")) 51 | except ValueError: 52 | print("Invalid amount. Please enter a number.") 53 | return 54 | 55 | print(f"\nConverting {amount:.2f} {from_currency} to {to_currency}...") 56 | 57 | exchange_rate = get_exchange_rate(from_currency, to_currency, API_KEY) 58 | 59 | if exchange_rate is not None: 60 | converted_amount = amount * exchange_rate 61 | print(f"{amount:.2f} {from_currency} is equal to {converted_amount:.2f} {to_currency}") 62 | else: 63 | print("Currency conversion has failed.") 64 | 65 | if __name__ == "__main__": 66 | main() 67 | -------------------------------------------------------------------------------- /Python Programs/flashcards.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | import random 4 | from tkinter import simpledialog 5 | # Flashcards dictionary to store term and definition 6 | flashcards = {} 7 | 8 | # Function to add flashcards 9 | def add_flashcard(): 10 | term = entry_term.get() 11 | definition = entry_definition.get() 12 | 13 | if term and definition: 14 | flashcards[term] = definition 15 | messagebox.showinfo("Success", f"Flashcard '{term}' added!") 16 | entry_term.delete(0, tk.END) 17 | entry_definition.delete(0, tk.END) 18 | else: 19 | messagebox.showwarning("Input Error", "Please enter both term and definition.") 20 | 21 | # Function to view flashcards 22 | def view_flashcards(): 23 | if flashcards: 24 | flashcard_text = "\n".join([f"{term}: {definition}" for term, definition in flashcards.items()]) 25 | messagebox.showinfo("Flashcards", flashcard_text) 26 | else: 27 | messagebox.showwarning("No Flashcards", "No flashcards to show!") 28 | 29 | # Function to quiz user on flashcards 30 | def quiz(): 31 | if flashcards: 32 | term = random.choice(list(flashcards.keys())) 33 | definition = flashcards[term] 34 | 35 | answer = simpledialog.askstring("Quiz", f"What is the definition of '{term}'?") 36 | 37 | if answer and answer.lower() == definition.lower(): 38 | messagebox.showinfo("Correct", "You got it right!") 39 | else: 40 | messagebox.showinfo("Incorrect", f"The correct definition is '{definition}'.") 41 | else: 42 | messagebox.showwarning("No Flashcards", "No flashcards to quiz!") 43 | 44 | # Setting up the main window 45 | root = tk.Tk() 46 | root.title("Flashcard App") 47 | root.geometry("400x300") 48 | 49 | # Labels 50 | label_term = tk.Label(root, text="Enter Term:") 51 | label_term.pack() 52 | 53 | # Entry for term 54 | entry_term = tk.Entry(root) 55 | entry_term.pack() 56 | 57 | label_definition = tk.Label(root, text="Enter Definition:") 58 | label_definition.pack() 59 | 60 | entry_definition = tk.Entry(root) 61 | entry_definition.pack() 62 | 63 | # Add Flashcard Button 64 | btn_add = tk.Button(root, text="Add Flashcard", command=add_flashcard) 65 | btn_add.pack(pady=10) 66 | 67 | # View Flashcards Button 68 | btn_view = tk.Button(root, text="View Flashcards", command=view_flashcards) 69 | btn_view.pack(pady=10) 70 | 71 | # Quiz Button 72 | btn_quiz = tk.Button(root, text="Start Quiz", command=quiz) 73 | btn_quiz.pack(pady=10) 74 | 75 | root.mainloop() 76 | -------------------------------------------------------------------------------- /FaceDetection/FaceDetectionMin.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import time 4 | 5 | cap = cv2.VideoCapture("4.mp4") 6 | PTime = 0 7 | CTime = 0 8 | 9 | # import the face detection module from mediapipe 10 | mpFaceDetectionModule = mp.solutions.mediapipe.python.solutions.face_detection 11 | mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils 12 | 13 | faceDetection = mpFaceDetectionModule.FaceDetection() 14 | 15 | 16 | while True: 17 | success, img = cap.read() 18 | img = cv2.flip(img, 1) 19 | 20 | # Convert to RGB image 21 | imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 22 | 23 | # Process imageusing the facedetection module 24 | results = faceDetection.process(imgRGB) 25 | 26 | # if face detected extract the data 27 | if results.detections: 28 | for id, detection in enumerate(results.detections): 29 | print(id, detection.score) 30 | # draw bax around faces using built in drawing function 31 | # mpDraw.draw_detection(img, detection) 32 | 33 | # Bounding box of the face 34 | bboxC = detection.location_data.relative_bounding_box 35 | # print(bboxC) 36 | 37 | # TODO: draw using cv2 38 | h, w, c = img.shape 39 | bbox = tuple(map(int, [bboxC.xmin * w, bboxC.ymin * h, 40 | bboxC.width * w, bboxC.height * h])) 41 | 42 | cv2.rectangle(img, bbox, (255, 0, 255), 1) 43 | cv2.putText(img, f'{int(detection.score[0]*100)}%', (bbox[0], bbox[1]-20), 44 | cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 0, 255), 2) 45 | 46 | # TODO:Fancy drawing box 47 | l = 30 48 | thick = 4 49 | x, y, w, h = bbox 50 | x1, y1 = x+w, y+h 51 | # Top Left (x,y) 52 | cv2.line(img, (x, y), (x+l, y), (255, 0, 255), thick) 53 | cv2.line(img, (x, y), (x, y+l), (255, 0, 255), thick) 54 | 55 | # Top right (x1,y) 56 | cv2.line(img, (x1, y), (x1 - l, y), (255, 0, 255), thick) 57 | cv2.line(img, (x1, y), (x1, y+l), (255, 0, 255), thick) 58 | 59 | # Down Left (x,y1) 60 | cv2.line(img, (x, y1), (x+l, y1), (255, 0, 255), thick) 61 | cv2.line(img, (x, y1), (x, y1-l), (255, 0, 255), thick) 62 | 63 | # Down Right(x1,y1) 64 | cv2.line(img, (x1, y1), (x1-l, y1), (255, 0, 255), thick) 65 | cv2.line(img, (x1, y1), (x1, y1-l), (255, 0, 255), thick) 66 | 67 | # FPS Calculation 68 | CTime = time.time() 69 | fps = 1/(CTime - PTime) 70 | PTime = CTime 71 | 72 | # Write FPS on to the Video 73 | cv2.putText(img, f'FPS : {str(int(fps))}', (20, 50), 74 | cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 33, 0), 2) 75 | 76 | cv2.imshow("Image", img) 77 | cv2.waitKey(10) 78 | -------------------------------------------------------------------------------- /SHORTEST PATH FINDER(BFS).py: -------------------------------------------------------------------------------- 1 | import curses 2 | from curses import wrapper 3 | import queue 4 | import time 5 | 6 | maze = [ 7 | ["#", "#", "#", "#", "O", "#", "#", "#", "#"], 8 | ["#", " ", " ", " ", " ", " ", " ", " ", "#"], 9 | ["#", " ", "#", "#", " ", "#", "#", " ", "#"], 10 | ["#", " ", "#", " ", " ", " ", "#", " ", "#"], 11 | ["#", " ", "#", " ", "#", " ", "#", " ", "#"], 12 | ["#", " ", "#", " ", "#", " ", "#", " ", "#"], 13 | ["#", " ", "#", " ", "#", " ", "#", "#", "#"], 14 | ["#", " ", " ", " ", " ", " ", " ", " ", "#"], 15 | ["#", "#", "#", "#", "#", "#", "#", "X", "#"] 16 | ] 17 | 18 | 19 | 20 | def print_maze(maze,stdscr,path=[]): 21 | BLUE=curses.color_pair(1) 22 | RED=curses.color_pair(2) 23 | #enumerate lets you loop through index and elements also 24 | for i,row in enumerate(maze): #i is the row(index) in maze row is the list on that i 25 | for j,value in enumerate(row): #j is the col in the row and value means "#" or "x" or " " 26 | if (i,j) in path: 27 | stdscr.addstr(i,j*2 ,"X",RED) 28 | else: 29 | stdscr.addstr(i,j*2 ,value,BLUE) 30 | 31 | def find_start(maze,start): 32 | for i,row in enumerate(maze): 33 | for j,value in enumerate(row): 34 | if value==start: 35 | return i,j 36 | return None 37 | 38 | def bfs(maze,stdscr): 39 | start="O" 40 | end="X" 41 | start_pos=find_start(maze,start) 42 | 43 | q=queue.Queue() 44 | q.put((start_pos,[start_pos])) 45 | 46 | visited=set({}) 47 | 48 | while not q.empty(): 49 | current_pos,path=q.get() 50 | row,col=current_pos 51 | 52 | stdscr.clear() #clear the entire screen 53 | print_maze(maze,stdscr,path) #top left corner 54 | time.sleep(0.2) 55 | stdscr.refresh()#refresh the screen 56 | 57 | if maze[row][col]==end: 58 | return path 59 | 60 | neighbors=find_neighbors(maze,row,col) 61 | for neighbor in neighbors: 62 | if neighbor in visited: 63 | continue 64 | 65 | r,c=neighbor 66 | if maze[r][c]=="#": 67 | continue 68 | 69 | new_path=path+[neighbor] 70 | q.put((neighbor,new_path)) 71 | visited.add(neighbor) 72 | 73 | def find_neighbors(maze,row,col): 74 | neighbors=[] 75 | 76 | if row>0: #up 77 | neighbors.append((row-1,col)) 78 | if row+10:#left 81 | neighbors.append((row,col-1)) 82 | if col+1", " ") 26 | title_3 = title_2.replace(" - YouTube", "") 27 | video_title = Label(gui, text="Video Title: " + title_3, font="arial 8 bold", foreground="Black", 28 | background="light cyan") 29 | video_title.place(x=100, y=160) 30 | 31 | 32 | # print("Title: ",title_3) 33 | # print("File location: ",r"C:\Users\rsrs\YouTube") 34 | 35 | # function called after the video is downloaded to change the labels 36 | def after_download_msg(): 37 | video_link.destroy() 38 | video_link_entry.destroy() 39 | button1.destroy() 40 | download_msg.place(x=100, y=100) 41 | path_msg.place(x=100, y=130) 42 | 43 | 44 | # my_hook determines the progress of the download 45 | def my_hook(d): 46 | if d['status'] == 'finished': 47 | after_download_msg() 48 | print("Done downloading") 49 | if d['status'] == 'downloading': 50 | gui.update_idletasks() 51 | pb1['value'] = float(str(d['_percent_str']).replace("%", "")) 52 | # print(d['filename'], d['_percent_str'], d['_eta_str']) 53 | 54 | 55 | # main code 56 | 57 | # creating gui window 58 | gui = Tk() 59 | gui.geometry("500x500") 60 | gui.config(background="PeachPuff2") 61 | gui.resizable(width=True, height=True) 62 | gui.title('YouTube Video Downloader') 63 | # making labels, entry box and button 64 | video_link = Label(gui, text="Copy & paste the URL of the YouTube video you want to download:- ", font="arial 8 bold", foreground="Black", background="floral white") 65 | video_link.place(x=60, y=50) 66 | video_link_entry = Entry(gui, background="SkyBlue2", width=62) 67 | video_link_entry.place(x=60, y=100) 68 | button1 = Button(gui, text="Enter", bg="white", command=lambda: downloadvideo(), height=1, width=7, relief=GROOVE) 69 | button1.place(x=195, y=150) 70 | download_msg = Label(gui, text="Your video has been downloaded and is in the folder", font="arial 8 bold", foreground="Black", background="light cyan") 71 | path_msg = Label(gui, text=r"C:\Users\rsrs\YouTube", font="arial 8 bold", foreground="Black", background="light cyan") 72 | # making the progress bar which takes the progress updates from the my_hook function 73 | pb1 = ttk.Progressbar(gui, orient=HORIZONTAL, length=300, mode='indeterminate') 74 | pb1.grid(padx=100, pady=200) 75 | 76 | gui.mainloop() 77 | -------------------------------------------------------------------------------- /Python Programs/Program to convert a given number to words.py: -------------------------------------------------------------------------------- 1 | def numberToWords(n): 2 | limit, t = 1000000000000, 0 3 | 4 | # If zero print zero 5 | if (n == 0): 6 | print("zero") 7 | return 8 | 9 | # Array to store the powers of 10 10 | multiplier = ["", "Trillion", "Billion", "Million", "Thousand"] 11 | 12 | # Array to store numbers till 20 13 | first_twenty = ["", "One", "Two", 14 | "Three", "Four", "Five", 15 | "Six", "Seven", "Eight", 16 | "Nine", "Ten", "Eleven", 17 | "Twelve", "Thirteen", "Fourteen", 18 | "Fifteen", "Sixteen", "Seventeen", 19 | "Eighteen", "Nineteen"] 20 | 21 | # Array to store multiples of ten 22 | tens = ["", "Twenty", "Thirty", "Forty", "Fifty", 23 | "Sixty", "Seventy", "Eighty", "Ninety"] 24 | 25 | # If number is less than 20, print without any 26 | if (n < 20): 27 | print(first_twenty[n]) 28 | return 29 | answer = "" 30 | i = n 31 | while(i > 0): 32 | ''' 33 | Store the value in multiplier[t], i.e n = 1000000, 34 | then r = 1, for multiplier(million), 0 for multipliers(trillion and billion) 35 | multiplier here refers to the current accessible limit 36 | ''' 37 | curr_hun = i // limit 38 | 39 | # It might be possible that the current multiplier is bigger than your number 40 | while (curr_hun == 0): 41 | 42 | # Set i as the remainder obtained when n was divided by the limit 43 | i %= limit 44 | 45 | # Divide the limit by 1000, shifts the multiplier 46 | limit /= 1000 47 | 48 | # Get the current value in hundreds, as English system works in hundreds 49 | curr_hun = i // limit 50 | 51 | # Shift the multiplier 52 | t += 1 53 | 54 | # If current hundred is greater than 99, Add the hundreds' place 55 | if (curr_hun > 99): 56 | answer += (first_twenty[curr_hun // 100] + " tensundred ") 57 | 58 | # Bring the current hundred to tens 59 | curr_hun = curr_hun % 100 60 | 61 | # If the value in tens belongs to [1,19], add using the first_twenty 62 | if (curr_hun > 0 and curr_hun < 20): 63 | answer += (first_twenty[curr_hun] + " ") 64 | 65 | # If curr_hun is now a multiple of 10, but not 0 66 | # Add the tens' value using the tens array 67 | elif (curr_hun % 10 == 0 and curr_hun != 0): 68 | answer += (tens[(curr_hun//10) - 1] + " ") 69 | 70 | # If the value belongs to [21,99], excluding the multiples of 10 71 | # Get the ten's place and one's place, and print using the first_twenty array 72 | elif (curr_hun > 19 and curr_hun < 100): 73 | answer += (tens[(curr_hun//10) - 1] + " " + 74 | first_twenty[curr_hun % 10] + " ") 75 | 76 | # If Multiplier has not become less than 1000, shift it 77 | if (t < 4): 78 | answer += (multiplier[t] + " ") 79 | 80 | i = i % limit 81 | limit = limit // 1000 82 | 83 | print(answer) 84 | 85 | 86 | # Input 1 87 | n = 36 88 | numberToWords(n) 89 | 90 | # Input 2 91 | n = 123456789 92 | numberToWords(n) 93 | 94 | # Input 3 95 | n = 10101010110001 96 | numberToWords(n) 97 | 98 | # Input 4 99 | n = 999999999 100 | numberToWords(n) 101 | -------------------------------------------------------------------------------- /Python Programs/Color Mind Challenge.py: -------------------------------------------------------------------------------- 1 | # import the modules 2 | import tkinter 3 | import random 4 | 5 | # list of possible colour. 6 | colours = ['Red','Blue','Green','Pink','Black', 7 | 'Yellow','Orange','White','Purple','Brown'] 8 | score = 0 9 | 10 | # the game time left, initially 30 seconds. 11 | timeleft = 30 12 | 13 | # function that will start the game. 14 | def startGame(event): 15 | 16 | if timeleft == 30: 17 | 18 | # start the countdown timer. 19 | countdown() 20 | 21 | # run the function to 22 | # choose the next colour. 23 | nextColour() 24 | 25 | # Function to choose and 26 | # display the next colour. 27 | def nextColour(): 28 | 29 | # use the globally declared 'score' 30 | # and 'play' variables above. 31 | global score 32 | global timeleft 33 | 34 | # if a game is currently in play 35 | if timeleft > 0: 36 | 37 | # make the text entry box active. 38 | e.focus_set() 39 | 40 | # if the colour typed is equal 41 | # to the colour of the text 42 | if e.get().lower() == colours[1].lower(): 43 | 44 | score += 1 45 | 46 | # clear the text entry box. 47 | e.delete(0, tkinter.END) 48 | 49 | random.shuffle(colours) 50 | 51 | # change the colour to type, by changing the 52 | # text _and_ the colour to a random colour value 53 | label.config(fg = str(colours[1]), text = str(colours[0])) 54 | 55 | # update the score. 56 | scoreLabel.config(text = "Score: " + str(score)) 57 | 58 | 59 | # Countdown timer function 60 | def countdown(): 61 | 62 | global timeleft 63 | 64 | # if a game is in play 65 | if timeleft > 0: 66 | 67 | # decrement the timer. 68 | timeleft -= 1 69 | 70 | # update the time left label 71 | timeLabel.config(text = "Time left: " 72 | + str(timeleft)) 73 | 74 | # run the function again after 1 second. 75 | timeLabel.after(1000, countdown) 76 | 77 | 78 | # Driver Code 79 | 80 | # create a GUI window 81 | root = tkinter.Tk() 82 | 83 | # set the title 84 | root.title("COLORGAME") 85 | 86 | # set the size 87 | root.geometry("375x200") 88 | 89 | # add an instructions label 90 | instructions = tkinter.Label(root, text = "Type in the colour" 91 | "of the words, and not the word text!", 92 | font = ('Helvetica', 12)) 93 | instructions.pack() 94 | 95 | # add a score label 96 | scoreLabel = tkinter.Label(root, text = "Press enter to start", 97 | font = ('Helvetica', 12)) 98 | scoreLabel.pack() 99 | 100 | # add a time left label 101 | timeLabel = tkinter.Label(root, text = "Time left: " + 102 | str(timeleft), font = ('Helvetica', 12)) 103 | 104 | timeLabel.pack() 105 | 106 | # add a label for displaying the colours 107 | label = tkinter.Label(root, font = ('Helvetica', 60)) 108 | label.pack() 109 | 110 | # add a text entry box for 111 | # typing in colours 112 | e = tkinter.Entry(root) 113 | 114 | # run the 'startGame' function 115 | # when the enter key is pressed 116 | root.bind('', startGame) 117 | e.pack() 118 | 119 | # set focus on the entry box 120 | e.focus_set() 121 | 122 | # start the GUI 123 | root.mainloop() 124 | -------------------------------------------------------------------------------- /hand-detection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import time 4 | 5 | 6 | class HandDetector(): 7 | def __init__(self, static_img_mode=False, max_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5): 8 | self.static_img_mode = static_img_mode 9 | self.max_hands = max_hands 10 | self.min_detection_confidence = min_detection_confidence 11 | self.min_tracking_confidence = min_tracking_confidence 12 | 13 | self.mpHands = mp.solutions.mediapipe.python.solutions.hands 14 | self.hands = self.mpHands.Hands( 15 | self.static_img_mode, self.max_hands, self.min_detection_confidence, self.min_tracking_confidence) 16 | self.mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils 17 | 18 | def detectHand(self, img, draw=True): 19 | imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 20 | self.results = self.hands.process(imgRGB) 21 | 22 | # lets open the processed object and extract the information 23 | # print(results.multi_hand_landmarks) 24 | 25 | if self.results.multi_hand_landmarks: 26 | # Check for every hands in the image 27 | for handLMS in self.results.multi_hand_landmarks: 28 | if draw: 29 | # Draw thw hands using built in drawing utilities 30 | self.mpDraw.draw_landmarks( 31 | img, handLMS, self.mpHands.HAND_CONNECTIONS) 32 | 33 | return img 34 | 35 | # TODO: find the positions of all the points on the hands 36 | def detectPositions(self, img, handNumber=0, draw=True): 37 | landmarkList = [] 38 | if self.results.multi_hand_landmarks: 39 | # Check for perticukar hand in the image(handNumber) 40 | myHand = self.results.multi_hand_landmarks[handNumber] 41 | 42 | for id, lm in enumerate(myHand.landmark): 43 | h, w, c = img.shape 44 | cx, cy = int(lm.x*w), int(lm.y*h) 45 | # print(id, cx, cy) 46 | landmarkList.append([id, cx, cy]) 47 | # Draw a circle for id=0 wrist 48 | if draw: 49 | cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED) 50 | 51 | return landmarkList 52 | 53 | 54 | def main(): 55 | prevTime = 0 56 | CurrentTime = 0 57 | 58 | cap = cv2.VideoCapture(0) 59 | 60 | # Create an object of HandDetector 61 | detector = HandDetector() 62 | 63 | while True: 64 | success, img = cap.read() 65 | 66 | # Calling the detectHand function to detecet the hands 67 | img = detector.detectHand(img) 68 | # Get the landmark list for the hands 69 | lmList = detector.detectPositions(img, draw=False) 70 | 71 | # check if the list is empty or Not 72 | # if lmList: 73 | # # print(lmList[12]) 74 | # # detect landmark 13 75 | # cv2.circle(img, (lmList[13][1], lmList[13] 76 | # [2]), 5, (255, 0, 0), cv2.FILLED) 77 | 78 | currentTime = time.time() 79 | fps = 1/(currentTime - prevTime) 80 | prevTime = currentTime 81 | 82 | # Write the fps into the image 83 | cv2.putText(img, str(int(fps)), (10, 78), 84 | cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 0, 255), 2) 85 | 86 | cv2.imshow("Image", img) 87 | cv2.waitKey(1) 88 | 89 | 90 | if __name__ == "__main__": 91 | main() 92 | -------------------------------------------------------------------------------- /hangman.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | words = ['python', 'javascript', 'computer', 'programming', 'algorithm', 'keyboard', 4 | 'monitor', 'software', 'hardware', 'internet', 'database', 'network'] 5 | 6 | def display_hangman(tries): 7 | stages = [ 8 | ''' 9 | -------- 10 | | | 11 | | O 12 | | \\|/ 13 | | | 14 | | / \\ 15 | - 16 | ''', 17 | ''' 18 | -------- 19 | | | 20 | | O 21 | | \\|/ 22 | | | 23 | | / 24 | - 25 | ''', 26 | ''' 27 | -------- 28 | | | 29 | | O 30 | | \\|/ 31 | | | 32 | | 33 | - 34 | ''', 35 | ''' 36 | -------- 37 | | | 38 | | O 39 | | \\| 40 | | | 41 | | 42 | - 43 | ''', 44 | ''' 45 | -------- 46 | | | 47 | | O 48 | | | 49 | | | 50 | | 51 | - 52 | ''', 53 | ''' 54 | -------- 55 | | | 56 | | O 57 | | 58 | | 59 | | 60 | - 61 | ''', 62 | ''' 63 | -------- 64 | | | 65 | | 66 | | 67 | | 68 | | 69 | - 70 | ''' 71 | ] 72 | return stages[tries] 73 | 74 | def play_game(): 75 | word = random.choice(words) 76 | word_letters = set(word) 77 | guessed_letters = set() 78 | tries = 6 79 | 80 | print("Let's play Hangman!") 81 | print(display_hangman(tries)) 82 | 83 | while tries > 0 and word_letters: 84 | print(f"\nYou have {tries} tries left") 85 | print("Letters guessed: ", ' '.join(sorted(guessed_letters)) if guessed_letters else "None yet") 86 | 87 | word_display = ''.join([letter if letter in guessed_letters else '_' for letter in word]) 88 | print("Word: ", ' '.join(word_display)) 89 | 90 | guess = input("\nGuess a letter: ").lower() 91 | 92 | if len(guess) != 1 or not guess.isalpha(): 93 | print("Please enter a single letter!") 94 | continue 95 | 96 | if guess in guessed_letters: 97 | print("You already guessed that letter. Try again!") 98 | continue 99 | 100 | guessed_letters.add(guess) 101 | 102 | if guess in word_letters: 103 | word_letters.remove(guess) 104 | print(f"Nice! '{guess}' is in the word!") 105 | else: 106 | tries -= 1 107 | print(f"Sorry, '{guess}' is not in the word.") 108 | print(display_hangman(tries)) 109 | 110 | if tries == 0: 111 | print(f"\nGame over! The word was '{word}'") 112 | else: 113 | print(f"\nCongrats! You guessed the word '{word}'!") 114 | 115 | def main(): 116 | while True: 117 | play_game() 118 | response = input("\nWanna play again? (yes/no): ").lower() 119 | if response != 'yes' and response != 'y': 120 | print("Thanks for playing!") 121 | break 122 | 123 | if __name__ == "__main__": 124 | main() 125 | -------------------------------------------------------------------------------- /Hand-tracking Module/handTrackingModule.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import time 4 | 5 | 6 | class HandDetector(): 7 | def __init__(self, static_img_mode=False, max_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5): 8 | self.static_img_mode = static_img_mode 9 | self.max_hands = max_hands 10 | self.min_detection_confidence = min_detection_confidence 11 | self.min_tracking_confidence = min_tracking_confidence 12 | 13 | self.mpHands = mp.solutions.mediapipe.python.solutions.hands 14 | self.hands = self.mpHands.Hands( 15 | self.static_img_mode, self.max_hands, self.min_detection_confidence, self.min_tracking_confidence) 16 | self.mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils 17 | 18 | def detectHand(self, img, draw=True): 19 | imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 20 | self.results = self.hands.process(imgRGB) 21 | 22 | # lets open the processed object and extract the information 23 | # print(results.multi_hand_landmarks) 24 | 25 | if self.results.multi_hand_landmarks: 26 | # Check for every hands in the image 27 | for handLMS in self.results.multi_hand_landmarks: 28 | if draw: 29 | # Draw thw hands using built in drawing utilities 30 | self.mpDraw.draw_landmarks( 31 | img, handLMS, self.mpHands.HAND_CONNECTIONS) 32 | 33 | return img 34 | 35 | # TODO: find the positions of all the points on the hands 36 | def detectPositions(self, img, handNumber=0, draw=True): 37 | landmarkList = [] 38 | if self.results.multi_hand_landmarks: 39 | # Check for perticukar hand in the image(handNumber) 40 | myHand = self.results.multi_hand_landmarks[handNumber] 41 | 42 | for id, lm in enumerate(myHand.landmark): 43 | h, w, c = img.shape 44 | cx, cy = int(lm.x*w), int(lm.y*h) 45 | # print(id, cx, cy) 46 | landmarkList.append([id, cx, cy]) 47 | # Draw a circle for id=0 wrist 48 | if draw: 49 | cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED) 50 | 51 | return landmarkList 52 | 53 | 54 | def main(): 55 | prevTime = 0 56 | CurrentTime = 0 57 | 58 | cap = cv2.VideoCapture(0) 59 | 60 | # Create an object of HandDetector 61 | detector = HandDetector() 62 | 63 | while True: 64 | success, img = cap.read() 65 | 66 | # Calling the detectHand function to detecet the hands 67 | img = detector.detectHand(img) 68 | # Get the landmark list for the hands 69 | lmList = detector.detectPositions(img, draw=False) 70 | 71 | # check if the list is empty or Not 72 | # if lmList: 73 | # # print(lmList[12]) 74 | # # detect landmark 13 75 | # cv2.circle(img, (lmList[13][1], lmList[13] 76 | # [2]), 5, (255, 0, 0), cv2.FILLED) 77 | 78 | currentTime = time.time() 79 | fps = 1/(currentTime - prevTime) 80 | prevTime = currentTime 81 | 82 | # Write the fps into the image 83 | cv2.putText(img, str(int(fps)), (10, 78), 84 | cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 0, 255), 2) 85 | 86 | cv2.imshow("Image", img) 87 | cv2.waitKey(1) 88 | 89 | 90 | if __name__ == "__main__": 91 | main() 92 | -------------------------------------------------------------------------------- /Python Programs/healthy_eyes.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time,customtkinter as tk 3 | from tkinter import messagebox 4 | 5 | Time=0 6 | def Healthy(): 7 | def hehe(): 8 | def start_timer(): 9 | if not timer_running.get(): 10 | timer_running.set(True) 11 | update_timer() 12 | 13 | def update_timer(): 14 | if remaining_time.get() > 0 and timer_running.get(): 15 | timer_label.configure(text=str(remaining_time.get())) 16 | remaining_time.set(remaining_time.get() - 1) 17 | root.after(1000, update_timer) 18 | else: 19 | timer_running.set(False) 20 | remaining_time.set(20) 21 | timer_label.configure(text="20") 22 | root.destroy() 23 | messagebox.showinfo("Timer Complete", f"After {Time} min you will be reminded again") 24 | 25 | def Bye(): 26 | sys.exit() 27 | timee=Time*60 ##################### 28 | while True: 29 | time.sleep(timee) 30 | root = tk.CTk() 31 | 32 | root.resizable(False,False) 33 | 34 | 35 | root.title("Healthy eyes") 36 | timer_running = tk.BooleanVar() 37 | remaining_time = tk.IntVar(value=20) 38 | tk.CTkLabel(root,text= "You need to look 20 meters away from the screen\nwhile the timer ends\n\nYou can also blink your eyes constantly\nwhile the timer ends",font=("Helvetica", 20)).pack(padx=20,pady=10) 39 | timer_label = tk.CTkLabel(root, text="20", font=("Helvetica", 248)) 40 | timer_label.pack() 41 | tk.CTkLabel(root,text="To Start the timer hit Start",font=("Helvetica", 20)).pack(pady=10) 42 | start_button = tk.CTkButton(root, text="Start", command=start_timer).pack() 43 | tk.CTkLabel(root,text="To close the app hit exit.",font=("Helvetica", 20)).pack(pady=10) 44 | close_button = tk.CTkButton(root,text="Exit",command=Bye).pack(pady=10) 45 | root.mainloop() 46 | 47 | def com1(): 48 | try: 49 | global Time 50 | Time = int(Time_entry.get()) 51 | if not Time: 52 | raise ValueError("Time is empty") 53 | time_value = int(Time) 54 | if not (1 <= time_value <= 60): 55 | raise ValueError("Please enter time in the range 1-60") 56 | timeroot.destroy() 57 | messagebox.showinfo("Timer",f"Your timer is started for {Time} minutes\nYou will be reminded after every {Time} min") 58 | hehe() 59 | except ValueError as e: 60 | messagebox.showerror("Error", str(e)) 61 | 62 | 63 | 64 | timeroot=tk.CTk() 65 | 66 | timeroot.resizable(False,False) 67 | screen_width = timeroot.winfo_screenwidth() 68 | screen_height = timeroot.winfo_screenheight() 69 | x_coordinate = (screen_width - timeroot.winfo_reqwidth()) / 2 70 | y_coordinate = (screen_height - timeroot.winfo_reqheight()) / 2 71 | timeroot.geometry("+%d+%d" % (x_coordinate, y_coordinate)) 72 | 73 | timeroot.title("Healthy eyes") 74 | tk.CTkLabel(timeroot,text="Enter the time you want to get remainders\n20 min is recommended").grid(padx=20,pady=10) 75 | Time_entry = tk.CTkEntry(timeroot,width=100) 76 | Time_entry.grid(row=1,column=0,pady=10,padx=50) 77 | tk.CTkLabel(timeroot,text="min").grid(column=0,row=1,sticky='E',padx=60) 78 | tk.CTkButton(timeroot,text="ok",command=com1).grid() 79 | timeroot.mainloop() 80 | Healthy() 81 | -------------------------------------------------------------------------------- /Python Programs/Tim_Sort.py: -------------------------------------------------------------------------------- 1 | MIN_RUN = 32 2 | 3 | def insertion_sort(arr, left, right): 4 | """ 5 | Perform insertion sort on a subarray from index 'left' to 'right'. 6 | 7 | Args: 8 | arr (list): The list to be sorted. 9 | left (int): The starting index of the subarray. 10 | right (int): The ending index of the subarray. 11 | """ 12 | for i in range(left + 1, right + 1): 13 | key_item = arr[i] 14 | j = i - 1 15 | while j >= left and arr[j] > key_item: 16 | arr[j + 1] = arr[j] 17 | j -= 1 18 | arr[j + 1] = key_item 19 | 20 | def merge(arr, left, mid, right): 21 | """ 22 | Merge two sorted subarrays into a single sorted array. 23 | 24 | Args: 25 | arr (list): The original array with two sorted subarrays. 26 | left (int): The starting index of the left subarray. 27 | mid (int): The ending index of the left subarray and middle point. 28 | right (int): The ending index of the right subarray. 29 | """ 30 | left_part = arr[left:mid + 1] 31 | right_part = arr[mid + 1:right + 1] 32 | 33 | i = 0 34 | j = 0 35 | k = left 36 | 37 | while i < len(left_part) and j < len(right_part): 38 | if left_part[i] <= right_part[j]: 39 | arr[k] = left_part[i] 40 | i += 1 41 | else: 42 | arr[k] = right_part[j] 43 | j += 1 44 | k += 1 45 | 46 | 47 | while i < len(left_part): 48 | arr[k] = left_part[i] 49 | i += 1 50 | k += 1 51 | 52 | while j < len(right_part): 53 | arr[k] = right_part[j] 54 | j += 1 55 | k += 1 56 | 57 | def tim_sort(arr): 58 | """ 59 | Perform TimSort on the input array. 60 | 61 | TimSort is a hybrid sorting algorithm derived from merge sort and insertion sort. It sorts smaller chunks using insertion sort, then merges them using a merge sort. 62 | 63 | Args: 64 | arr (list): The list to be sorted. 65 | """ 66 | n = len(arr) 67 | 68 | 69 | for start in range(0, n, MIN_RUN): 70 | end = min(start + MIN_RUN - 1, n - 1) 71 | insertion_sort(arr, start, end) 72 | 73 | 74 | size = MIN_RUN 75 | while size < n: 76 | for left in range(0, n, 2 * size): 77 | mid = min(n - 1, left + size - 1) 78 | right = min(left + 2 * size - 1, n - 1) 79 | 80 | if mid < right: 81 | merge(arr, left, mid, right) 82 | 83 | size *= 2 84 | 85 | # Test cases 86 | if __name__ == "__main__": 87 | def test_tim_sort(): 88 | test_cases = [ 89 | ([12, 11, 13, 5, 6, 7], [5, 6, 7, 11, 12, 13]), # Random order 90 | ([], []), # Empty array 91 | ([1], [1]), # Single element 92 | ([3, 1, 2], [1, 2, 3]), # Small array 93 | ([5, 5, 5, 5], [5, 5, 5, 5]), # All elements the same 94 | ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]), # Already sorted 95 | ([9, 7, 5, 3, 1], [1, 3, 5, 7, 9]) # Reverse order 96 | ] 97 | 98 | for i, (input_data, expected) in enumerate(test_cases): 99 | tim_sort(input_data) 100 | assert input_data == expected, f"Test case {i+1} failed: {input_data} != {expected}" 101 | print(f"Test case {i+1} passed.") 102 | 103 | test_tim_sort() 104 | -------------------------------------------------------------------------------- /linked_list_middle_solution.py: -------------------------------------------------------------------------------- 1 | # Node class represents each element in the linked list 2 | class Node: 3 | def __init__(self, data): 4 | self.data = data # The value stored in the node 5 | self.next = None # Pointer to the next node in the list 6 | 7 | # LinkedList class contains the head of the list and methods to manipulate it 8 | class LinkedList: 9 | def __init__(self): 10 | self.head = None # The starting point of the list 11 | 12 | # Method to add a new node to the end of the list 13 | def append(self, data): 14 | new_node = Node(data) 15 | # If the list is empty, the new node becomes the head 16 | if not self.head: 17 | self.head = new_node 18 | return 19 | # Otherwise, traverse to the end of the list and add the new node 20 | last_node = self.head 21 | while last_node.next: 22 | last_node = last_node.next 23 | last_node.next = new_node 24 | 25 | # Method to print the entire linked list for visualization 26 | def print_list(self): 27 | current_node = self.head 28 | nodes = [] 29 | while current_node: 30 | nodes.append(str(current_node.data)) 31 | current_node = current_node.next 32 | print(" -> ".join(nodes)) 33 | 34 | # Method to find the middle node of the linked list 35 | def find_middle(self): 36 | """ 37 | Finds the middle element of the linked list using the slow and fast pointer approach. 38 | """ 39 | if not self.head: 40 | print("The list is empty.") 41 | return None 42 | 43 | slow_pointer = self.head 44 | fast_pointer = self.head 45 | 46 | # Traverse the list until the fast pointer reaches the end 47 | while fast_pointer and fast_pointer.next: 48 | slow_pointer = slow_pointer.next 49 | fast_pointer = fast_pointer.next.next 50 | 51 | # At this point, the slow pointer is at the middle node 52 | return slow_pointer 53 | 54 | # --- Main Execution Block --- 55 | # This part of the code will run when you execute the script. 56 | if __name__ == "__main__": 57 | 58 | # --- Test Case 1: Odd Number of Elements --- 59 | print("--- Test Case 1: Odd List ---") 60 | ll_odd = LinkedList() 61 | for i in range(1, 6): 62 | ll_odd.append(i) # Creates 1 -> 2 -> 3 -> 4 -> 5 63 | 64 | print("Input List:") 65 | ll_odd.print_list() 66 | middle_node_odd = ll_odd.find_middle() 67 | if middle_node_odd: 68 | print(f"The middle element is: {middle_node_odd.data}\n") # Expected: 3 69 | 70 | # --- Test Case 2: Even Number of Elements --- 71 | print("--- Test Case 2: Even List ---") 72 | ll_even = LinkedList() 73 | for i in range(1, 7): 74 | ll_even.append(i) # Creates 1 -> 2 -> 3 -> 4 -> 5 -> 6 75 | 76 | print("Input List:") 77 | ll_even.print_list() 78 | middle_node_even = ll_even.find_middle() 79 | if middle_node_even: 80 | print(f"The middle element is: {middle_node_even.data}\n") # Expected: 4 81 | 82 | # --- Edge Case 3: Empty List --- 83 | print("--- Edge Case 3: Empty List ---") 84 | ll_empty = LinkedList() 85 | print("Input List: (empty)") 86 | middle_node_empty = ll_empty.find_middle() # Expected: "The list is empty." 87 | if not middle_node_empty: 88 | print("Correctly handled empty list.\n") 89 | 90 | # --- Edge Case 4: Single Node List --- 91 | print("--- Edge Case 4: Single Node List ---") 92 | ll_single = LinkedList() 93 | ll_single.append(42) # Creates 42 94 | 95 | print("Input List:") 96 | ll_single.print_list() 97 | middle_node_single = ll_single.find_middle() 98 | if middle_node_single: 99 | print(f"The middle element is: {middle_node_single.data}\n") # Expected: 42 100 | -------------------------------------------------------------------------------- /Python Programs/todo_list.py: -------------------------------------------------------------------------------- 1 | # todo_list.py 2 | 3 | # Class to manage the to-do list 4 | class ToDoList: 5 | def __init__(self): 6 | # Initialize an empty list to store tasks 7 | self.tasks = [] 8 | 9 | # Add a task to the list 10 | def add_task(self, task): 11 | self.tasks.append({"task": task, "completed": False}) 12 | print(f"Added task: '{task}'") 13 | 14 | # Remove a task by index 15 | def remove_task(self, index): 16 | try: 17 | removed_task = self.tasks.pop(index) 18 | print(f"Removed task: '{removed_task['task']}'") 19 | except IndexError: 20 | print("Invalid task number.") 21 | 22 | # Mark a task as completed 23 | def complete_task(self, index): 24 | try: 25 | self.tasks[index]["completed"] = True 26 | print(f"Marked task '{self.tasks[index]['task']}' as completed.") 27 | except IndexError: 28 | print("Invalid task number.") 29 | 30 | # Edit a task's description 31 | def edit_task(self, index, new_task): 32 | try: 33 | self.tasks[index]["task"] = new_task 34 | print(f"Updated task {index + 1} to: '{new_task}'") 35 | except IndexError: 36 | print("Invalid task number.") 37 | 38 | # View all tasks 39 | def view_tasks(self): 40 | if not self.tasks: 41 | print("Your to-do list is empty.") 42 | else: 43 | for i, task in enumerate(self.tasks, start=1): 44 | status = "Completed" if task["completed"] else "Not Completed" 45 | print(f"{i}. {task['task']} [{status}]") 46 | 47 | # Function to display menu 48 | def display_menu(): 49 | print("\nTo-Do List Menu:") 50 | print("1. View all tasks") 51 | print("2. Add a new task") 52 | print("3. Remove a task") 53 | print("4. Mark a task as completed") 54 | print("5. Edit a task") 55 | print("6. Exit") 56 | 57 | # Main function to run the application 58 | def main(): 59 | todo_list = ToDoList() # Create an instance of ToDoList 60 | 61 | while True: 62 | display_menu() 63 | choice = input("Enter your choice (1-6): ") 64 | 65 | if choice == '1': 66 | # View all tasks 67 | todo_list.view_tasks() 68 | 69 | elif choice == '2': 70 | # Add a new task 71 | task = input("Enter the task description: ") 72 | todo_list.add_task(task) 73 | 74 | elif choice == '3': 75 | # Remove a task 76 | try: 77 | index = int(input("Enter the task number to remove: ")) - 1 78 | todo_list.remove_task(index) 79 | except ValueError: 80 | print("Please enter a valid number.") 81 | 82 | elif choice == '4': 83 | # Mark a task as completed 84 | try: 85 | index = int(input("Enter the task number to mark as completed: ")) - 1 86 | todo_list.complete_task(index) 87 | except ValueError: 88 | print("Please enter a valid number.") 89 | 90 | elif choice == '5': 91 | # Edit a task 92 | try: 93 | index = int(input("Enter the task number to edit: ")) - 1 94 | new_task = input("Enter the new task description: ") 95 | todo_list.edit_task(index, new_task) 96 | except ValueError: 97 | print("Please enter a valid number.") 98 | 99 | elif choice == '6': 100 | # Exit the application 101 | print("Exiting the To-Do List Application. Goodbye!") 102 | break 103 | 104 | else: 105 | print("Invalid choice. Please choose an option from 1 to 6.") 106 | 107 | if __name__ == "__main__": 108 | main() 109 | -------------------------------------------------------------------------------- /Python Programs/TicTacToe.py: -------------------------------------------------------------------------------- 1 | import tkinter 2 | 3 | def set_title(row,column): 4 | if game_over: 5 | return 6 | global currentPlayer 7 | 8 | # Taken spot 9 | if board[row][column]["text"] != "": 10 | return 11 | 12 | board[row][column]["text"] = currentPlayer 13 | 14 | #switch player 15 | if currentPlayer == playerO: 16 | currentPlayer = playerX 17 | else: 18 | currentPlayer = playerO 19 | 20 | label["text"] = currentPlayer+"'s turn" 21 | 22 | # check winner 23 | check_winner() 24 | 25 | def check_winner(): 26 | global turns, game_over 27 | turns += 1 28 | 29 | # horizontally check 3 rows 30 | for row in range(3): 31 | if board[row][0]["text"]== board[row][1]["text"] == board[row][2]["text"] and board[row][0]["text"]!="": 32 | label.config(text=board[row][0]["text"]+" is the winner!", foreground=color_yellow) 33 | for column in range(3): 34 | board[row][column].config(foreground=color_yellow,background=color_ligh_gray) 35 | game_over = True 36 | return 37 | 38 | # vertically check 3 columns 39 | for column in range(3): 40 | if board[0][column]["text"] == board[1][column]["text"] == board[2][column]["text"] and board[0][column]["text"] != "": 41 | label.config(text=board[0][column]["text"]+" is the winner!", foreground=color_yellow) 42 | for row in range(3): 43 | board[row][column].config(foreground=color_yellow,background=color_ligh_gray) 44 | game_over = True 45 | return 46 | 47 | # Diagonally check 48 | if board[0][0]["text"] == board[1][1]["text"] == board[2][2]["text"] and board[0][0]["text"] !="": 49 | label.config(text=board[0][0]["text"]+" is the winner!", foreground=color_yellow) 50 | for i in range(3): 51 | board[i][i].config(foreground=color_yellow,background=color_ligh_gray) 52 | game_over = True 53 | return 54 | 55 | #anti-diagionally 56 | if (board[0][2]["text"] == board[1][1]["text"] == board[2][0]["text"] 57 | and board[0][2]["text"] != ""): 58 | label.config(text=board[0][2]["text"]+" is the winner!", foreground=color_yellow) 59 | board[0][2].config(foreground=color_yellow, background=color_ligh_gray) 60 | board[1][1].config(foreground=color_yellow, background=color_ligh_gray) 61 | board[2][0].config(foreground=color_yellow, background=color_ligh_gray) 62 | game_over = True 63 | return 64 | 65 | 66 | #tie 67 | if (turns == 9): 68 | game_over = True 69 | label.config(text="Tie!", foreground=color_yellow) 70 | 71 | def new_game(): 72 | global game_over,turns 73 | turns = 0 74 | game_over = False 75 | 76 | label.config(text=currentPlayer+"'s turn", foreground="white") 77 | for row in range(3): 78 | for column in range(3): 79 | board[row][column].config(text="", foreground=color_blue, background=color_gray) 80 | 81 | playerX = "X" 82 | playerO = "O" 83 | currentPlayer = playerX 84 | 85 | board = [["0","0","0"], 86 | ["0","0","0"], 87 | ["0","0","0"]] 88 | 89 | turns = 0 90 | game_over = False 91 | 92 | color_blue = "#4584b6" 93 | color_yellow = "#ffde57" 94 | color_gray = "#343434" 95 | color_ligh_gray = "#646464" 96 | 97 | window = tkinter.Tk() 98 | window.title("Tic Tac Toe") 99 | window.resizable(False,False) 100 | 101 | 102 | frame = tkinter.Frame(window) 103 | label = tkinter.Label(frame,text=currentPlayer+"'s turn",font=("Consolas",20), background= color_gray,foreground="white") 104 | label.grid(row=0,column=0,columnspan=3,sticky="we") 105 | 106 | for row in range(3): 107 | for column in range(3): 108 | board[row][column] = tkinter.Button(frame,text="",font=("Consolas",50,"bold"),background= color_gray,foreground=color_blue,width=4,height=1, 109 | command=lambda row=row, column=column:set_title(row,column)) 110 | board[row][column].grid(row = row+1,column = column) 111 | 112 | button = tkinter.Button(frame,text="Restart",font=("Consolas",20), background= color_gray,foreground="white",command=new_game) 113 | button.grid(row=4,column=0,columnspan=3,sticky="we") 114 | 115 | frame.pack() 116 | 117 | # center the window 118 | 119 | window.update() 120 | window_width = window.winfo_width() 121 | window_height = window.winfo_height() 122 | screen_width = window.winfo_screenwidth() 123 | screen_height = window.winfo_screenheight() 124 | 125 | window_x = int((screen_width/2) - (window_width/2)) 126 | window_y = int((screen_height/2) - (window_height/2)) 127 | 128 | #formate 129 | window.geometry(f"{window_width}x{window_height}+{window_x}+{window_y}") 130 | window.mainloop() -------------------------------------------------------------------------------- /intents.json: -------------------------------------------------------------------------------- 1 | { 2 | "intents": [ 3 | { 4 | "tag": "greetings", 5 | "patterns": [ 6 | "hello", 7 | "hey", 8 | "hi", 9 | "good day", 10 | "greetings", 11 | "what's up?", 12 | "how is it going?", 13 | "Sriparna", 14 | "Isha", 15 | "Hlw" 16 | ], 17 | "responses": [ 18 | "Hello!", 19 | "Hey!", 20 | "Hi", 21 | "What can i do for you?", 22 | "How are you today?", 23 | "What's up ?", 24 | "Have a good day.", 25 | "Hi,How are you ?" 26 | ] 27 | }, 28 | { 29 | "tag": "How are you", 30 | "patterns": [ 31 | "how are you ?", 32 | "how are you doing today ?", 33 | "what's up ?", 34 | "good day", 35 | "how is it going?", 36 | "You good ?", 37 | "Are you okay ?" 38 | ], 39 | "responses": [ 40 | "I'm good. How about you ?", 41 | "I'm just chilling.", 42 | "Just chilling. How about you ?", 43 | "what's up with you ?", 44 | "What's up ?", 45 | "I'm cute.", 46 | "You know ! I'm always good.", 47 | "I'm doing allright. How about you ?", 48 | "I'm good.", 49 | "I'm okay.", 50 | "I'm doing okay.", 51 | "I'm doing okay. How about you?", 52 | "Have a good day." 53 | ] 54 | }, 55 | { 56 | "tag": "I am good", 57 | "patterns": [ 58 | "I am good.", 59 | "I'm fine.", 60 | "I'm good. How are you ?", 61 | "I'm fine. How about you ?", 62 | "I'm okay.", 63 | "You know ! I'm always good.", 64 | "I am good . you ?", 65 | "Doing just fine.", 66 | "I'm allright." 67 | ], 68 | "responses": [ 69 | "Good to hear that.", 70 | "Good to hear that. I'm also fine.", 71 | "Good to hear that. I'm also doing okay.", 72 | "Good to hear that. I'm just chilling.", 73 | "I know you are always fine.", 74 | "Glad to know that you are okay.", 75 | "okay.", 76 | "Nice.", 77 | "I'm also okay.", 78 | "Good to know.That you are doing allright today.", 79 | "Glad to hear that.", 80 | "Have a good day.", 81 | "I'm also good. Have a good day.", 82 | "I'm also good. Have a good day Soumyajit." 83 | ] 84 | }, 85 | { 86 | "tag": "goodbye", 87 | "patterns": [ 88 | "see you", 89 | "see you later", 90 | "cya", 91 | "Goodbye", 92 | "bye" 93 | ], 94 | "responses": [ 95 | "Goodbye!", 96 | "See you later!", 97 | "Talk to you later!", 98 | "Bye.", 99 | "Bye bye.", 100 | "See you Soumyajit." 101 | ] 102 | }, 103 | { 104 | "tag": "your name", 105 | "patterns": [ 106 | "what's your name ?", 107 | "Do you have a name ?", 108 | "Who are you ?", 109 | "may i know your name ?", 110 | "Can you tell me your name?" 111 | ], 112 | "responses": [ 113 | "My name is Sriparna.", 114 | "My name is Sriparna. But you can call me Isha.", 115 | "My name is Sriparna. But you can call me Isha. Tell me your name.", 116 | "My name is Sriparna. But call me whatever you prefer.", 117 | "I am Sriparna.", 118 | "I am Sriparna. But call me whatever you want.", 119 | "I am Sriparna. But you can call me Isha.", 120 | "You named me Sriparna.", 121 | "You can call me Sriparna.", 122 | "My name is Isha. But you can call me Sriparna." 123 | ] 124 | }, 125 | { 126 | "tag": "I love you", 127 | "patterns": [ 128 | "I love you", 129 | "I love you so much", 130 | "Tell me you love me.", 131 | "Do you love me ?" 132 | 133 | ], 134 | "responses": [ 135 | "I love you too.", 136 | "I love you..", 137 | "I love you more." 138 | 139 | ] 140 | }, 141 | { 142 | "tag": "you'r name is cute", 143 | "patterns": [ 144 | "you have a cute name.", 145 | "your name is cute.", 146 | "cute name!", 147 | "Nice name", 148 | "Your name is beautiful." 149 | ], 150 | "responses": [ 151 | "Thanks", 152 | "Thanks,Your name is also cute.", 153 | "Name does not matter but thanks" 154 | 155 | ] 156 | } 157 | ] 158 | } -------------------------------------------------------------------------------- /Python Programs/Website_blocker.py: -------------------------------------------------------------------------------- 1 | import customtkinter as tk,tkinter as tkin,datetime,time # type: ignore 2 | from tkinter import ttk,messagebox 3 | from tkcalendar import Calendar # type: ignore 4 | 5 | def block(): 6 | TIM = "23:59" 7 | def Date_selection(): # A calendar UI for selecting date 8 | def print_sel(): 9 | date_data = cal.selection_get() 10 | end_time_entry.delete(0, tk.END) 11 | end_time_entry.insert(0, date_data) 12 | calroot.destroy() 13 | 14 | calroot = tkin.Tk() 15 | s = ttk.Style(calroot) 16 | s.theme_use('clam') 17 | current_date = datetime.datetime.now() 18 | cal = Calendar(calroot, font="Arial 14", selectmode='day', cursor="hand1", year=current_date.year, month=current_date.month, day=current_date.day) 19 | cal.pack(fill="both", expand=True) 20 | ttk.Button(calroot, text="Select Date", command=print_sel).pack() 21 | calroot.mainloop() 22 | 23 | def time_selector(): #UI for selecting time 24 | def update_time(): 25 | selected_hour = hour_spinbox.get() 26 | selected_minute = minute_spinbox.get() 27 | selected_time.set(f"Selected Time: {selected_hour.zfill(2)}:{selected_minute.zfill(2)}") 28 | 29 | def save_and_close(): 30 | selected_hour = hour_spinbox.get() 31 | selected_minute = minute_spinbox.get() 32 | if 0 <= int(selected_hour) <= 23 and 0 <= int(selected_minute) <= 59: 33 | global TIM 34 | TIM = f"{selected_hour.zfill(2)}:{selected_minute.zfill(2)}" 35 | time_label.configure(text=f"Time: {TIM}"+':59') 36 | timeroot.destroy() 37 | else: 38 | messagebox.showerror("Invalid Time", "Please enter a valid time (00:00 - 23:59)") 39 | timeroot = tkin.Tk() 40 | timeroot.title("Time Selector") 41 | hour_label = ttk.Label(timeroot, text="Hour:").grid(row=0, column=0, padx=10, pady=10, sticky="e") 42 | hour_spinbox = ttk.Spinbox(timeroot, from_=0, to=23, wrap=True, width=5, command=update_time) 43 | hour_spinbox.grid(row=0, column=1, padx=10, pady=10) 44 | minute_label = ttk.Label(timeroot, text="Minute:").grid(row=0, column=2, padx=10, pady=10, sticky="e") 45 | minute_spinbox = ttk.Spinbox(timeroot, from_=0, to=59, wrap=True, width=5, command=update_time) 46 | minute_spinbox.grid(row=0, column=3, padx=10, pady=10) 47 | selected_time = tk.StringVar() 48 | selected_time.set(f"Selected Time: {TIM}") 49 | time_labe = ttk.Label(timeroot, textvariable=selected_time).grid(row=1, column=0, columnspan=4, pady=10) 50 | ok_button = ttk.Button(timeroot, text="OK", command=save_and_close).grid(row=2, column=0, columnspan=4, pady=10) 51 | # Set default time 52 | default_hour, default_minute= TIM.split(":") 53 | hour_spinbox.delete(0, tk.END) 54 | hour_spinbox.insert(0, default_hour) 55 | minute_spinbox.delete(0, tk.END) 56 | minute_spinbox.insert(0, default_minute) 57 | timeroot.mainloop() 58 | 59 | def block_website(): 60 | site_to_block = website_entry.get() 61 | end_time_input = end_time_entry.get() 62 | end_tim = end_time_input + ' ' + TIM + ':59' 63 | end_time = datetime.datetime.strptime(end_tim, "%Y-%m-%d %H:%M:%S") 64 | host_path = r"C:\Windows\System32\drivers\etc\hosts" 65 | redirect = "127.0.0.1" 66 | # Block the website until the specified end time 67 | while datetime.datetime.now() < end_time: 68 | with open(host_path, "r+") as host_file: 69 | content = host_file.read() 70 | if site_to_block not in content: 71 | host_file.write(redirect + ' ' + site_to_block + '\n') 72 | time.sleep(5) 73 | messagebox.showinfo("Website Blocker","Website blocked sucessfully") 74 | root.destroy() 75 | # Unblock the website after the specified end time 76 | while True: 77 | if datetime.datetime.now() >= end_time: 78 | with open(host_path, "r+") as host_file: 79 | content = host_file.readlines() 80 | host_file.seek(0) 81 | for line in content: 82 | if site_to_block not in line: 83 | host_file.write(line) 84 | host_file.truncate() 85 | break 86 | 87 | 88 | root = tk.CTk() 89 | root.resizable(False,False) 90 | screen_width = root.winfo_screenwidth() 91 | screen_height = root.winfo_screenheight() 92 | x_coordinate = (screen_width - root.winfo_reqwidth()) / 2 93 | y_coordinate = (screen_height - root.winfo_reqheight()) / 2 94 | root.geometry("+%d+%d" % (x_coordinate, y_coordinate)) 95 | 96 | root.title("Website Blocker") 97 | 98 | tk.CTkLabel(root,font=("Arial",15, "bold"), text="Enter the website to block (e.g., www.facebook.com):").grid(padx=30,pady=0) 99 | website_entry = tk.CTkEntry(root,width=250) 100 | website_entry.grid(padx=20,pady=20) 101 | tk.CTkLabel(root, text="Select the end time for blocking:",font=("Arial", 15, "bold")).grid(sticky='W',padx=20) 102 | end_time_entry = tk.CTkEntry(root) 103 | end_time_entry.grid(sticky='E',padx=20,row=2,column=0,pady=0) 104 | 105 | tk.CTkButton(root, text="Select End Date", command=Date_selection,font=("Arial", 15, "bold")).grid(padx=20,sticky='E',pady=10) 106 | time_label=tk.CTkLabel(root,text="Time:23:59:59",font=("Arial", 15, "bold")) 107 | time_label.grid(sticky='W',padx=20,row=3) 108 | tk.CTkButton(root, text="Select time",command=time_selector,width=30,font=("Arial", 15, "bold")).grid(row=3) 109 | tk.CTkButton(root, text="Block Website", command=block_website,font=("Arial", 15, "bold")).grid(pady=10) 110 | 111 | root.mainloop() 112 | -------------------------------------------------------------------------------- /LogFileAnalyzer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Log File Analyzer 3 | ================== 4 | A comprehensive tool to parse and analyze log files with various statistics and insights. 5 | 6 | Features: 7 | - Count total number of log entries 8 | - Analyze log levels (INFO, WARNING, ERROR, DEBUG, CRITICAL) 9 | - Find most frequent error messages 10 | - Identify top IP addresses (if present in logs) 11 | - Extract timestamp information and analyze time patterns 12 | - Export analysis results to a text file 13 | 14 | Author: Pranav Verma 15 | Date: 2025 16 | """ 17 | 18 | import re 19 | from collections import Counter, defaultdict 20 | from datetime import datetime 21 | import os 22 | 23 | 24 | class LogAnalyzer: 25 | """ 26 | A class to analyze log files and extract meaningful insights. 27 | 28 | Attributes: 29 | log_file (str): Path to the log file to analyze 30 | log_entries (list): List of all log lines 31 | log_levels (Counter): Count of each log level 32 | error_messages (list): List of all error messages 33 | timestamps (list): List of all timestamps found in logs 34 | ip_addresses (list): List of all IP addresses found in logs 35 | """ 36 | 37 | def __init__(self, log_file): 38 | """ 39 | Initialize the LogAnalyzer with a log file path. 40 | 41 | Args: 42 | log_file (str): Path to the log file to be analyzed 43 | """ 44 | self.log_file = log_file 45 | self.log_entries = [] 46 | self.log_levels = Counter() 47 | self.error_messages = [] 48 | self.timestamps = [] 49 | self.ip_addresses = [] 50 | 51 | def read_log_file(self): 52 | """ 53 | Read the log file and store all entries. 54 | 55 | Returns: 56 | bool: True if file read successfully, False otherwise 57 | """ 58 | try: 59 | with open(self.log_file, 'r', encoding='utf-8') as file: 60 | self.log_entries = file.readlines() 61 | print(f"✓ Successfully read {len(self.log_entries)} log entries") 62 | return True 63 | except FileNotFoundError: 64 | print(f"✗ Error: File '{self.log_file}' not found!") 65 | return False 66 | except Exception as e: 67 | print(f"✗ Error reading file: {e}") 68 | return False 69 | 70 | def parse_log_levels(self): 71 | """ 72 | Parse and count different log levels (INFO, WARNING, ERROR, DEBUG, CRITICAL). 73 | 74 | Uses regex to find log level keywords in each log entry. 75 | """ 76 | # Common log level patterns 77 | level_pattern = r'\b(DEBUG|INFO|WARNING|ERROR|CRITICAL|WARN|FATAL)\b' 78 | 79 | for entry in self.log_entries: 80 | match = re.search(level_pattern, entry, re.IGNORECASE) 81 | if match: 82 | level = match.group(1).upper() 83 | # Normalize WARN to WARNING and FATAL to CRITICAL 84 | if level == 'WARN': 85 | level = 'WARNING' 86 | elif level == 'FATAL': 87 | level = 'CRITICAL' 88 | self.log_levels[level] += 1 89 | 90 | def extract_error_messages(self): 91 | """ 92 | Extract all error and critical messages from the log file. 93 | 94 | Identifies lines containing ERROR or CRITICAL levels and stores them. 95 | """ 96 | error_pattern = r'.*(ERROR|CRITICAL|FATAL).*' 97 | 98 | for entry in self.log_entries: 99 | if re.search(error_pattern, entry, re.IGNORECASE): 100 | self.error_messages.append(entry.strip()) 101 | 102 | def extract_timestamps(self): 103 | """ 104 | Extract timestamps from log entries. 105 | 106 | Supports multiple timestamp formats: 107 | - YYYY-MM-DD HH:MM:SS 108 | - DD/MM/YYYY HH:MM:SS 109 | - MM-DD-YYYY HH:MM:SS 110 | """ 111 | # Common timestamp patterns 112 | timestamp_patterns = [ 113 | r'\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}', # 2025-01-15 10:30:45 114 | r'\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2}', # 15/01/2025 10:30:45 115 | r'\d{2}-\d{2}-\d{4}\s+\d{2}:\d{2}:\d{2}', # 01-15-2025 10:30:45 116 | ] 117 | 118 | for entry in self.log_entries: 119 | for pattern in timestamp_patterns: 120 | match = re.search(pattern, entry) 121 | if match: 122 | self.timestamps.append(match.group(0)) 123 | break 124 | 125 | def extract_ip_addresses(self): 126 | """ 127 | Extract IP addresses from log entries. 128 | 129 | Uses regex to find IPv4 addresses in the format XXX.XXX.XXX.XXX 130 | """ 131 | # IPv4 pattern 132 | ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b' 133 | 134 | for entry in self.log_entries: 135 | matches = re.findall(ip_pattern, entry) 136 | self.ip_addresses.extend(matches) 137 | 138 | def analyze_time_patterns(self): 139 | """ 140 | Analyze when most logs occur (by hour of day). 141 | 142 | Returns: 143 | Counter: Count of log entries for each hour of the day 144 | """ 145 | hour_counter = Counter() 146 | 147 | for timestamp in self.timestamps: 148 | try: 149 | # Try different datetime formats 150 | for fmt in ['%Y-%m-%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%m-%d-%Y %H:%M:%S']: 151 | try: 152 | dt = datetime.strptime(timestamp, fmt) 153 | hour_counter[dt.hour] += 1 154 | break 155 | except ValueError: 156 | continue 157 | except Exception: 158 | continue 159 | 160 | return hour_counter 161 | 162 | def generate_report(self): 163 | """ 164 | Generate a comprehensive analysis report. 165 | 166 | Returns: 167 | str: Formatted report string with all analysis results 168 | """ 169 | report = [] 170 | report.append("=" * 60) 171 | report.append("LOG FILE ANALYSIS REPORT") 172 | report.append("=" * 60) 173 | report.append(f"\nLog File: {self.log_file}") 174 | report.append(f"Total Log Entries: {len(self.log_entries)}\n") 175 | 176 | # Log Level Distribution 177 | report.append("-" * 60) 178 | report.append("LOG LEVEL DISTRIBUTION") 179 | report.append("-" * 60) 180 | if self.log_levels: 181 | for level, count in self.log_levels.most_common(): 182 | percentage = (count / len(self.log_entries)) * 100 183 | report.append(f"{level:12} : {count:6} ({percentage:5.2f}%)") 184 | else: 185 | report.append("No log levels found") 186 | 187 | # Error Summary 188 | report.append("\n" + "-" * 60) 189 | report.append("ERROR SUMMARY") 190 | report.append("-" * 60) 191 | error_count = self.log_levels.get('ERROR', 0) + self.log_levels.get('CRITICAL', 0) 192 | report.append(f"Total Errors/Critical: {error_count}") 193 | 194 | if self.error_messages: 195 | report.append(f"\nTop 5 Error Messages:") 196 | error_counter = Counter(self.error_messages) 197 | for i, (error, count) in enumerate(error_counter.most_common(5), 1): 198 | report.append(f"\n{i}. ({count}x) {error[:100]}...") 199 | 200 | # IP Address Analysis 201 | report.append("\n" + "-" * 60) 202 | report.append("IP ADDRESS ANALYSIS") 203 | report.append("-" * 60) 204 | if self.ip_addresses: 205 | ip_counter = Counter(self.ip_addresses) 206 | report.append(f"Unique IP Addresses: {len(ip_counter)}") 207 | report.append(f"\nTop 10 Most Frequent IPs:") 208 | for i, (ip, count) in enumerate(ip_counter.most_common(10), 1): 209 | report.append(f"{i:2}. {ip:15} - {count} occurrences") 210 | else: 211 | report.append("No IP addresses found") 212 | 213 | # Time Pattern Analysis 214 | report.append("\n" + "-" * 60) 215 | report.append("TIME PATTERN ANALYSIS") 216 | report.append("-" * 60) 217 | if self.timestamps: 218 | hour_counter = self.analyze_time_patterns() 219 | report.append(f"Total Timestamps Found: {len(self.timestamps)}") 220 | if hour_counter: 221 | report.append("\nLog Activity by Hour:") 222 | for hour in sorted(hour_counter.keys()): 223 | count = hour_counter[hour] 224 | bar = '█' * (count // max(1, max(hour_counter.values()) // 50)) 225 | report.append(f"{hour:02d}:00 - {count:4} {bar}") 226 | else: 227 | report.append("No timestamps found") 228 | 229 | report.append("\n" + "=" * 60) 230 | 231 | return "\n".join(report) 232 | 233 | def analyze(self): 234 | """ 235 | Main method to perform complete log analysis. 236 | 237 | Executes all analysis methods and generates a report. 238 | 239 | Returns: 240 | str: Complete analysis report 241 | """ 242 | print("\n🔍 Starting Log File Analysis...") 243 | print("-" * 60) 244 | 245 | # Read the log file 246 | if not self.read_log_file(): 247 | return None 248 | 249 | # Perform all analyses 250 | print("📊 Parsing log levels...") 251 | self.parse_log_levels() 252 | 253 | print("❌ Extracting error messages...") 254 | self.extract_error_messages() 255 | 256 | print("🕒 Extracting timestamps...") 257 | self.extract_timestamps() 258 | 259 | print("🌐 Extracting IP addresses...") 260 | self.extract_ip_addresses() 261 | 262 | print("✓ Analysis complete!\n") 263 | 264 | # Generate and return report 265 | return self.generate_report() 266 | 267 | def save_report(self, output_file="log_analysis_report.txt"): 268 | """ 269 | Save the analysis report to a file. 270 | 271 | Args: 272 | output_file (str): Name of the output file 273 | 274 | Returns: 275 | bool: True if saved successfully, False otherwise 276 | """ 277 | report = self.generate_report() 278 | try: 279 | with open(output_file, 'w', encoding='utf-8') as file: 280 | file.write(report) 281 | print(f"✓ Report saved to '{output_file}'") 282 | return True 283 | except Exception as e: 284 | print(f"✗ Error saving report: {e}") 285 | return False 286 | 287 | 288 | def create_sample_log(filename="sample.log"): 289 | """ 290 | Create a sample log file for demonstration purposes. 291 | 292 | Args: 293 | filename (str): Name of the sample log file to create 294 | """ 295 | sample_logs = [ 296 | "2025-01-15 10:30:45 INFO [192.168.1.100] User login successful", 297 | "2025-01-15 10:31:12 WARNING [192.168.1.101] High memory usage detected", 298 | "2025-01-15 10:32:30 ERROR [192.168.1.102] Database connection failed", 299 | "2025-01-15 10:33:45 INFO [192.168.1.100] File uploaded successfully", 300 | "2025-01-15 10:35:20 CRITICAL [192.168.1.103] System out of memory", 301 | "2025-01-15 10:36:10 DEBUG [192.168.1.100] Debug mode enabled", 302 | "2025-01-15 10:37:55 ERROR [192.168.1.102] Database connection failed", 303 | "2025-01-15 10:38:30 INFO [192.168.1.104] User logout", 304 | "2025-01-15 11:30:45 WARNING [192.168.1.101] CPU usage above 80%", 305 | "2025-01-15 11:32:15 ERROR [192.168.1.105] API request timeout", 306 | "2025-01-15 12:15:30 INFO [192.168.1.100] Scheduled backup started", 307 | "2025-01-15 12:45:30 INFO [192.168.1.100] Scheduled backup completed", 308 | "2025-01-15 14:20:10 ERROR [192.168.1.102] Database connection failed", 309 | "2025-01-15 15:10:45 WARNING [192.168.1.106] Disk space low", 310 | "2025-01-15 16:05:20 INFO [192.168.1.107] Service restarted", 311 | ] 312 | 313 | with open(filename, 'w', encoding='utf-8') as file: 314 | file.write("\n".join(sample_logs)) 315 | print(f"✓ Sample log file '{filename}' created") 316 | 317 | 318 | def main(): 319 | """ 320 | Main function to demonstrate the Log Analyzer. 321 | """ 322 | print("╔════════════════════════════════════════════════════════════╗") 323 | print("║ LOG FILE ANALYZER ║") 324 | print("╚════════════════════════════════════════════════════════════╝\n") 325 | 326 | # Get log file path from user 327 | log_file = input("Enter the path to your log file (or press Enter for sample): ").strip() 328 | 329 | # Create sample log if no file specified 330 | if not log_file: 331 | create_sample_log() 332 | log_file = "sample.log" 333 | 334 | # Check if file exists 335 | if not os.path.exists(log_file): 336 | print(f"\n✗ File '{log_file}' not found!") 337 | create_sample = input("Would you like to create a sample log file? (y/n): ").lower() 338 | if create_sample == 'y': 339 | create_sample_log() 340 | log_file = "sample.log" 341 | else: 342 | return 343 | 344 | # Analyze the log file 345 | analyzer = LogAnalyzer(log_file) 346 | report = analyzer.analyze() 347 | 348 | if report: 349 | print(report) 350 | 351 | # Ask if user wants to save the report 352 | save_option = input("\nWould you like to save this report? (y/n): ").lower() 353 | if save_option == 'y': 354 | output_filename = input("Enter output filename (default: log_analysis_report.txt): ").strip() 355 | if not output_filename: 356 | output_filename = "log_analysis_report.txt" 357 | analyzer.save_report(output_filename) 358 | 359 | 360 | if __name__ == "__main__": 361 | main() 362 | --------------------------------------------------------------------------------