├── .gitignore ├── ArInvisibilityCloak.py ├── Barnsley-Ferm ├── README.md ├── b-fern.png └── fern.py ├── Calculator.py ├── Classes.py ├── Cryptography └── AES_Encryption_Decryption.py ├── Factor of Number.py ├── Guess-The-Number ├── ReadMe.md ├── game-pic │ └── terminal.png └── main.py ├── ImplementingStack.py ├── Live Bitcoin └── bitcoin.py ├── Operators.py ├── README.md ├── Recursive_Factorial.py ├── Seconds-DaysHoursSeconds-Convertor ├── README.md └── main.py ├── Smart_Calculator.py ├── TicTacToe.py ├── Timer └── timer.py ├── bank management ├── README.MD └── nitin bank.py ├── number-guessing-game.py ├── python ├── BinaryConverter.py ├── BinarySearchRecursive.py ├── BinarytreeClassbased.py ├── Checkleapyear.py ├── DNS_Lookup.py ├── Face Detection │ ├── Needed Packages.txt │ ├── face_detection.py │ └── haarcascade_frontalface_default.xml ├── Fibonacci │ ├── Fibonacci_1.py │ ├── Fibonacci_2.py │ ├── Fibonacci_3.py │ └── README.md ├── Google Sheets │ └── sheets_analysis.py ├── GraphPlotter │ ├── README.md │ ├── images │ │ ├── 3dline.png │ │ ├── 3dscatter.png │ │ ├── 3dsurface.png │ │ ├── line.png │ │ └── scatter.png │ └── main.py ├── HelloWorld.py ├── Jumping_Number.py ├── LargestOfThreeNumbers.py ├── LinearSearch.py ├── Linked_List.py ├── Queue │ └── ImplementQueue.py ├── Recursive_Factorial.py ├── SquareRoot.py ├── Temperature Converter.py ├── Transpose of a matrix.py ├── bubblesort.py ├── caesar_cypher.py ├── calculator.py ├── countTheNumberOfEachCharacter.py ├── egyptian_fraction.py ├── factorial.py ├── is_palindrome_possible.py ├── largest_among_3.py ├── max_number.py ├── networkx_usage.py ├── primeno.py ├── recursive_substring_search.py ├── reverse.py ├── stack.py ├── tic_tac_toe.py └── timsort.py └── rsa.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe -------------------------------------------------------------------------------- /ArInvisibilityCloak.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import time 4 | 5 | print(""" 6 | Ms. Girl: Hey kiddo !! Let's Get Anonymous ! 7 | Prepare to get invisible ..................... 8 | """) 9 | 10 | cap = cv2.VideoCapture(0) 11 | time.sleep(3) 12 | background = 0 13 | 14 | def nothing(): 15 | pass 16 | 17 | for i in range(30): 18 | ret, background = cap.read() 19 | background = np.flip(background, axis=1) 20 | 21 | cv2.namedWindow("Tracking") 22 | cv2.createTrackbar("LH", "Tracking", 0, 255, nothing) 23 | cv2.createTrackbar("LS", "Tracking", 0, 255, nothing) 24 | cv2.createTrackbar("Lv", "Tracking", 0, 255, nothing) 25 | cv2.createTrackbar("UH", "Tracking", 255, 255, nothing) 26 | cv2.createTrackbar("US", "Tracking", 255, 255, nothing) 27 | cv2.createTrackbar("UV", "Tracking", 255, 255, nothing) 28 | 29 | while(cap.isOpened()): 30 | ret, img = cap.read() 31 | img = np.flip(img, axis=1) 32 | hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 33 | value = (35, 35) 34 | 35 | l_h = cv2.getTrackbarPos("LH", "Tracking") 36 | l_s = cv2.getTrackbarPos("LH", "Tracking") 37 | l_v = cv2.getTrackbarPos("LH", "Tracking") 38 | u_h = cv2.getTrackbarPos("UH", "Tracking" ) 39 | u_s = cv2.getTrackbarPos("US", "Tracking") 40 | u_v = cv2.getTrackbarPos("UV", "Tracking") 41 | 42 | blurred = cv2.GaussianBlur(hsv, value, 0) 43 | 44 | low = np.array([l_h,l_s,l_v]) 45 | high = np.array([u_h, u_s, u_v]) 46 | 47 | mask = cv2.inRange(hsv, low, high) 48 | 49 | mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)) 50 | 51 | img[np.where(mask == 255)] = background[np.where(mask == 255)] 52 | cv2.imshow('Anonimity is Key !', img) 53 | k = cv2.waitKey(10) 54 | if k == 27: 55 | break 56 | -------------------------------------------------------------------------------- /Barnsley-Ferm/README.md: -------------------------------------------------------------------------------- 1 | # Barnsley Fern 2 | 3 | From Wikipedia: 4 | > The Barnsley fern is a fractal named after the British mathematician Michael Barnsley[1][1] 5 | 6 | ## Usage 7 | 8 | `python fern.py` 9 | 10 | It is recommended to call the program with the `--tofile` option. Without it matplotlib will attempt to 11 | plot the fern, but this can take a decently long time to do. With `--tofile` a data file is created that 12 | can then be opened with `gnuplot`. To do this run `python fern.py --tofile` and then open that file with 13 | `plot 'path/to/b-fern-py.data'` 14 | 15 | Your output will look similar to this: 16 | ![Barnsley Fern](./b-fern.png) 17 | This image was made with gnuplot, using 10,000 coordinates. 18 | 19 | 20 | [1]: https://en.wikipedia.org/wiki/Barnsley_fern 21 | -------------------------------------------------------------------------------- /Barnsley-Ferm/b-fern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/Barnsley-Ferm/b-fern.png -------------------------------------------------------------------------------- /Barnsley-Ferm/fern.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import random 5 | import matplotlib.pyplot as plt 6 | 7 | 8 | def fern(array, iterations): 9 | for i in range(iterations): 10 | x = array[i][0] 11 | y = array[i][1] 12 | 13 | probability = random.random() 14 | if probability < 0.01: 15 | array.append(_func1(x, y)) 16 | elif probability > 0.01 and probability < 0.85: 17 | array.append(_func2(x, y)) 18 | elif probability > 0.05 and probability < 0.92: 19 | array.append(_func3(x, y)) 20 | else: 21 | array.append(_func4(x, y)) 22 | return array 23 | 24 | 25 | def _func1(x, y): 26 | return [(0 * x), (0.16 * y)] 27 | 28 | 29 | def _func2(x, y): 30 | return [(0.85 * x + 0.04 * y), (-0.04 * x + 0.85 * y + 1.60)] 31 | 32 | 33 | def _func3(x, y): 34 | return [(0.20 * x - 0.26 * y), (0.23 * x + 0.22 * y + 1.60)] 35 | 36 | 37 | def _func4(x, y): 38 | return [(-0.15 * x + 0.28 * y), (0.26 * x + 0.24 * y + 0.44)] 39 | 40 | 41 | def plot(array): 42 | plt.xlabel("x") 43 | plt.ylabel("y") 44 | plt.title("Barnsley Fern") 45 | 46 | for i in range(len(array)): 47 | plt.scatter(array[i][0], array[i][1]) 48 | plt.show() 49 | 50 | 51 | def to_file(array): 52 | with open("b-fern-py.data", "a") as file: 53 | for i in range(len(array)): 54 | x = array[i][0] 55 | y = array[i][1] 56 | newline = str(x) + ", " + str(y) + "\n" 57 | file.write(newline) 58 | 59 | 60 | def main(): 61 | parser = argparse.ArgumentParser(description="Create a Barnsley Fern") 62 | parser.add_argument( 63 | "--tofile", action="store_true", help="store output to a csv file", 64 | ) 65 | args = parser.parse_args() 66 | array = [[0, 0]] 67 | if args.tofile: 68 | to_file(fern(array, 10000)) 69 | else: 70 | plot(fern(array, 10000)) 71 | 72 | 73 | if __name__ == "__main__": 74 | main() 75 | -------------------------------------------------------------------------------- /Calculator.py: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | print('IN THIS PROGRAM WE WILL CREATE A PYTHON PROGRAM TO PROVIDE DIFFERENT OPTIONS TO CALCULTE TWO NUMBERS') 3 | print ('It will let you know your answer obtained is an even or odd number') 4 | print("enter 2 numbers") 5 | x=int(input()) 6 | y=int(input()) 7 | answer = 0 8 | print("choose any of these option (+,-,*,/) ") 9 | option=input() 10 | if option == '+': 11 | answer=x+y 12 | elif option == '-': 13 | answer=x-y 14 | elif option == '*': 15 | answer=x*y 16 | elif option == '/': 17 | answer=x / y 18 | else: 19 | print("wrong option") 20 | 21 | print(x,option,y,":",answer) 22 | if answer%2==0 : 23 | print('The answer obtained is an even number') 24 | else : 25 | print('Answer obtained is an odd number') 26 | 27 | print('end') 28 | -------------------------------------------------------------------------------- /Classes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Employee: 4 | 'Common base class for all employees' 5 | empCount = 0 6 | 7 | def __init__(self, name, salary): 8 | self.name = name 9 | self.salary = salary 10 | Employee.empCount += 1 11 | 12 | def displayCount(self): 13 | print "Total Employee %d" % Employee.empCount 14 | 15 | def displayEmployee(self): 16 | print "Name : ", self.name, ", Salary: ", self.salary 17 | 18 | "This would create first object of Employee class" 19 | emp1 = Employee("Zara", 2000) 20 | "This would create second object of Employee class" 21 | emp2 = Employee("Manni", 5000) 22 | emp1.displayEmployee() 23 | emp2.displayEmployee() 24 | print "Total Employee %d" % Employee.empCount -------------------------------------------------------------------------------- /Cryptography/AES_Encryption_Decryption.py: -------------------------------------------------------------------------------- 1 | import sys, base64, json, math 2 | try: 3 | from Crypto.Cipher import AES 4 | except ImportError: 5 | print ("Error!! Module AES is required. Run either or following commands") 6 | print("pip install pycrypto") 7 | print("---------OR--------") 8 | print("pip3 install pycrypto") 9 | sys.exit() 10 | 11 | KEY="" 12 | PADDING_CHARACTER="S" 13 | VECTOR_FOR_AES="SUDESH1611GITHUB" 14 | 15 | def GetKey(): 16 | global KEY 17 | tempKey = input("Enter password(min length: 8, max length: 32)") 18 | while(len(tempKey.strip())<8 or len(tempKey.strip())>32 or ' ' in tempKey): 19 | if(' ' in tempKey): 20 | print("White spaces are not allowed!") 21 | else: 22 | print("Password must be at least 8 characters long and at max 32 characters long. Try Again!") 23 | while(len(tempKey)%8!=0): 24 | tempKey+=PADDING_CHARACTER 25 | KEY=tempKey 26 | 27 | def AES_Encryption(cleartext): 28 | if(len(KEY)<8 or len(KEY)%8!=0): 29 | print("Password is corrupted. Exiting!") 30 | sys.exit() 31 | return 32 | AES_Encryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES) 33 | cleartext_length = len(cleartext) 34 | nearest_multiple_of_16 = 16 * math.ceil(cleartext_length/16) 35 | padded_cleartext = cleartext.rjust(nearest_multiple_of_16) 36 | raw_ciphertext = AES_Encryptor.encrypt(padded_cleartext) 37 | return base64.b64encode(raw_ciphertext).decode('utf-8') 38 | 39 | def AES_Decryption(ciphertext): 40 | if(len(KEY)<8 or len(KEY)%8!=0): 41 | print("Password is corrupted. Exiting!") 42 | sys.exit() 43 | return 44 | AES_Decryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES) 45 | raw_ciphertext = base64.b64decode(ciphertext) 46 | decrypted_message_with_padding = AES_Decryptor.decrypt(raw_ciphertext) 47 | return decrypted_message_with_padding.decode('utf-8').strip() 48 | 49 | if __name__ == "__main__": 50 | type="S" 51 | while(type not in "ed"): 52 | type = input("Encrypt or Decrypt the text(e/d): ") 53 | type = type.strip().lower() 54 | if(len(type)!=1): 55 | type="S" 56 | GetKey() 57 | if(type=="e"): 58 | print("NOTE: If you forget this password, you will not be able to decrypt text correctly. So, DO NOT FORGET PASSWORD!!") 59 | message = input("Enter message in single line: ") 60 | ciphertext = AES_Encryption(message) 61 | print("Encrypted Message: %s" % ciphertext) 62 | else: 63 | encText = input("Enter encrypted message: ") 64 | message = AES_Decryption(encText) 65 | print("Original Message: %s" % message) 66 | -------------------------------------------------------------------------------- /Factor of Number.py: -------------------------------------------------------------------------------- 1 | def print_factors(x): 2 | print("The Factors of",x,"are:") 3 | for i in range(1,x+1): 4 | if x%i==0: 5 | print(i) 6 | num=320 7 | print_factors(num) 8 | -------------------------------------------------------------------------------- /Guess-The-Number/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## How to play 2 | 1. Run the main.py script with python3. 3 | 4 | use the command `python3 main.py` and you are good to go!! 5 | ___ 6 | ## Requirments 7 | You will only need [python3](https://python.org) installed on your machine 8 | 9 | termial 14 | ___ 15 | *keep guessing* 16 | -------------------------------------------------------------------------------- /Guess-The-Number/game-pic/terminal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/Guess-The-Number/game-pic/terminal.png -------------------------------------------------------------------------------- /Guess-The-Number/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # defining function named getchar 4 | def getchar(): 5 | ''' 6 | Returns a single character from standard input 7 | ''' 8 | # importing other modules needed 9 | import tty, termios, sys 10 | fd = sys.stdin.fileno() 11 | old_settings = termios.tcgetattr(fd) 12 | try: 13 | tty.setraw(sys.stdin.fileno()) 14 | ch = sys.stdin.read(1) 15 | finally: 16 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 17 | return ch 18 | 19 | guess_number = 0 20 | 21 | # Print statements 22 | print("This is a number guessing game. \nYou will first choose a range of number. \nThen we will generate a secret number.\nYou have to guess it in minimum number of tries.") 23 | print("If you enter your guess we will inform you either the number is smaller than the secret number or bigger.") 24 | print("RULE : give all inputs as integers\nPress Enter" ,end = "") 25 | 26 | # Running while loop to find the range 27 | while getchar() and not guess_number: 28 | print("\nChoose Your Range") 29 | #print("Your number will be in between :") 30 | print("Enter the starting number:") 31 | start = int(input()) 32 | print("Enter the ending number: ") 33 | end = int(input()) 34 | #guess_number = 0 35 | ans = random.randint(start,end) 36 | if ans == ValueError: 37 | print("Your range is wrong") 38 | else: 39 | # Running a while loop inside a if statement 40 | # When the user the guess_number reaches 5, the game will end 41 | while (guess_number<5): 42 | 43 | print("Enter your guess: ",end = "") 44 | user_input = int(input()) 45 | guess_number+=1 46 | 47 | if guess_number==5: 48 | print("Sorry no more guesses! You lost!") 49 | break 50 | 51 | 52 | if user_input == ans: 53 | print("Congratulations!! You have made it. \n This is the secret number") 54 | break 55 | elif user_input > ans: 56 | print("Try something small") 57 | elif user_input < ans: 58 | print("Try something big") 59 | else: 60 | print("Please follow the rules!!!") 61 | exit() 62 | # Exiting the game 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /ImplementingStack.py: -------------------------------------------------------------------------------- 1 | stack = [] 2 | 3 | stack.append('a') 4 | stack.append('b') 5 | stack.append('c') 6 | 7 | print('Initial stack') 8 | print(stack) 9 | 10 | print('\nElements poped from stack:') 11 | print(stack.pop()) 12 | print(stack.pop()) 13 | print(stack.pop()) 14 | 15 | print('\nStack after elements are poped:') 16 | print(stack) 17 | -------------------------------------------------------------------------------- /Live Bitcoin/bitcoin.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from datetime import datetime 3 | import sys 4 | 5 | def get_current_btn_value(): 6 | res = requests.get('https://blockchain.info/ticker') 7 | inr_value = res.json()['INR'] 8 | 9 | symbol = inr_value['symbol'] 10 | current_inr_value = inr_value['last'] 11 | 12 | now = datetime.now() 13 | current_time = now.strftime("%d/%m/%Y %H:%M:%S") 14 | 15 | print(f'Price of Bitcoin in INR: {symbol} {current_inr_value}\nTime of price: {current_time}\n') 16 | 17 | try: 18 | while True: 19 | get_current_btn_value() 20 | 21 | except KeyboardInterrupt: 22 | sys.exit() -------------------------------------------------------------------------------- /Operators.py: -------------------------------------------------------------------------------- 1 | # Examples of Arithmetic Operator 2 | a = 9 3 | b = 4 4 | 5 | # Addition of numbers 6 | add = a + b 7 | 8 | # Subtraction of numbers 9 | sub = a - b 10 | 11 | # Multiplication of number 12 | mul = a * b 13 | 14 | # Division(float) of number 15 | div1 = a / b 16 | 17 | # Division(floor) of number 18 | div2 = a // b 19 | 20 | # Modulo of both number 21 | mod = a % b 22 | 23 | # Power 24 | p = a ** b 25 | 26 | # print results 27 | print(add) 28 | print(sub) 29 | print(mul) 30 | print(div1) 31 | print(div2) 32 | print(mod) 33 | print(p) 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktober Fest 2021 2 | 3 | 4 | ### How to contribute 5 | 6 | * #### fork repository 7 | * #### add your code 8 | * #### make a pull request 9 | -------------------------------------------------------------------------------- /Recursive_Factorial.py: -------------------------------------------------------------------------------- 1 | def recur_factorial(n): 2 | if n == 1: 3 | return n 4 | else: 5 | return n*recur_factorial(n-1) 6 | # take input from the user 7 | num = int(input("Enter a number: ")) 8 | # check is the number is negative 9 | if num < 0: 10 | print("Factorial does not exist for negative numbers") 11 | elif num == 0: 12 | print("The factorial of 0 is 1") 13 | else: 14 | print("The factorial of",num,"is",recur_factorial(num)) -------------------------------------------------------------------------------- /Seconds-DaysHoursSeconds-Convertor/README.md: -------------------------------------------------------------------------------- 1 | ## SECONDS --> DAYS, HOURS & SECONDS CONVERTOR 2 | 3 | Simple program that converts given time (in seconds) to days, hours and seconds. 4 | 5 | Developed by Rudransh Joshi (https://github.com/FireHead90544) 6 | 7 | 8 | **USAGE**: Just cd to the directory file is located. 9 | Run `python main.py` 10 | 11 | And enter the time in seconds result will be displayed in the screen, 12 | to close the program just press Ctrl + C 13 | -------------------------------------------------------------------------------- /Seconds-DaysHoursSeconds-Convertor/main.py: -------------------------------------------------------------------------------- 1 | # Program to convert seconds to days, hours, minutes and seconds 2 | # Coded By Rudransh Joshi https://github.com/FireHead90544 3 | 4 | def convertor(time): 5 | '''Program to convert seconds to days, hours, minutes and seconds''' 6 | time = int(time) 7 | 8 | days = time // 86400 9 | hours = int(time % 86400) // 3600 10 | minutes = int(time % 86400 - hours * 3600) // 60 11 | seconds = int(time % 86400 - hours * 3600) % 60 12 | 13 | if days == 0 and hours > 0: 14 | print(f"{hours}h, {minutes}m, {seconds}s") 15 | elif days == 0 and hours == 0 and minutes > 0: 16 | print(f"{minutes}m, {seconds}s") 17 | elif days == 0 and hours == 0 and minutes == 0 and seconds >= 0: 18 | print(f"{seconds}s") 19 | else: 20 | print(f"{days}d, {hours}h, {minutes}m, {seconds}s") 21 | 22 | 23 | 24 | 25 | 26 | while True: 27 | time = float(input("Enter Time In Seconds:\t")) 28 | convertor(time) 29 | -------------------------------------------------------------------------------- /Smart_Calculator.py: -------------------------------------------------------------------------------- 1 | # main python proghram 2 | 3 | response=['Welcome to smart calculator','My name is SHUBHAM', 4 | 5 | 'Thanks for enjoy with me ','Sorry ,this is beyond my ability'] 6 | 7 | 8 | 9 | # fetching tokens from the text command 10 | 11 | def extract_from_text(text): 12 | 13 | l=[] 14 | 15 | for t in text.split(' '): 16 | 17 | try: 18 | 19 | l.append(float(t)) 20 | 21 | except ValueError: 22 | 23 | pass 24 | 25 | return l 26 | 27 | 28 | 29 | # calculating LCM 30 | 31 | def lcm(a,b): 32 | 33 | L=a if a>b else b 34 | 35 | while L<=a*b: 36 | 37 | if L%a==0 and L%b==0: 38 | 39 | return L 40 | 41 | L+=1 42 | 43 | 44 | 45 | # calculating HCF 46 | 47 | def hcf(a,b): 48 | 49 | H=a if a=1: 52 | 53 | if a%H==0 and b%H==0: 54 | 55 | return H 56 | 57 | H-=1 58 | 59 | 60 | 61 | # Addition 62 | 63 | def add(a,b): 64 | 65 | return a+b 66 | 67 | 68 | 69 | # Subtraction 70 | 71 | def sub(a,b): 72 | 73 | return a-b 74 | 75 | 76 | 77 | # Multiplication 78 | 79 | def mul(a,b): 80 | 81 | return a*b 82 | 83 | 84 | 85 | # Division 86 | 87 | def div(a,b): 88 | 89 | return a/b 90 | 91 | 92 | 93 | # Remainder 94 | 95 | def mod(a,b): 96 | 97 | return a%b 98 | 99 | 100 | 101 | # Response to command 102 | 103 | # printing - "Thanks for enjoy with me" on exit 104 | 105 | def end(): 106 | 107 | print(response[2]) 108 | 109 | input('press enter key to exit') 110 | 111 | exit() 112 | 113 | 114 | 115 | def myname(): 116 | 117 | print(response[1]) 118 | 119 | def sorry(): 120 | 121 | print(response[3]) 122 | 123 | 124 | 125 | # Operations - performed on the basis of text tokens 126 | 127 | operations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add, 128 | 129 | 'SUB':sub,'SUBTRACT':sub, 'MINUS':sub, 130 | 131 | 'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf, 132 | 133 | 'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul, 134 | 135 | 'DIVISION':div,'MOD':mod,'REMANDER' 136 | 137 | :mod,'MODULAS':mod} 138 | 139 | 140 | 141 | # commands 142 | 143 | commands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end} 144 | 145 | 146 | 147 | print('--------------'+response[0]+'------------') 148 | 149 | print('--------------'+response[1]+'--------------------') 150 | 151 | 152 | 153 | 154 | 155 | while True: 156 | 157 | print() 158 | 159 | text=input('enter your queries: ') 160 | 161 | for word in text.split(' '): 162 | 163 | if word.upper() in operations.keys(): 164 | 165 | try: 166 | 167 | l = extract_from_text(text) 168 | 169 | r = operations[word.upper()] (l[0],l[1]) 170 | 171 | print(r) 172 | 173 | except: 174 | 175 | print('something went wrong going plz enter again !!') 176 | 177 | finally: 178 | 179 | break 180 | 181 | elif word.upper() in commands.keys(): 182 | 183 | commands[word.upper()]() 184 | 185 | break 186 | 187 | else: 188 | 189 | sorry() 190 | -------------------------------------------------------------------------------- /TicTacToe.py: -------------------------------------------------------------------------------- 1 | board = [' ' for x in range(10)] #sets range from 1 to 9 2 | 3 | def insertLetter(letter,pos): #return the latest position in the board 4 | board[pos] = letter 5 | 6 | def spaceIsFree(pos): 3return free spaces left 7 | return board[pos] == ' ' 8 | 9 | def printBoard(board): #face of the game 10 | print(' | | ') 11 | print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) 12 | print(' | | ') 13 | print('------------') 14 | print(' | | ') 15 | print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) 16 | print(' | | ') 17 | print('------------') 18 | print(' | | ') 19 | print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) 20 | print(' | | ') 21 | 22 | def isBoardFull(board): 23 | if board.count(' ') > 1: 24 | return False 25 | else: 26 | return True 27 | 28 | def IsWinner(b,l): 29 | return ((b[1] == l and b[2] == l and b[3] == l) or 30 | (b[4] == l and b[5] == l and b[6] == l) or 31 | (b[7] == l and b[8] == l and b[9] == l) or 32 | (b[1] == l and b[4] == l and b[7] == l) or 33 | (b[2] == l and b[5] == l and b[8] == l) or 34 | (b[3] == l and b[6] == l and b[9] == l) or 35 | (b[1] == l and b[5] == l and b[9] == l) or 36 | (b[3] == l and b[5] == l and b[7] == l)) 37 | 38 | def playerMove(): 39 | run = True 40 | while run: 41 | move = input("please select a position to enter the X between 1 to 9") 42 | try: 43 | move = int(move) 44 | if move > 0 and move < 10: 45 | if spaceIsFree(move): 46 | run = False 47 | insertLetter('X' , move) 48 | else: 49 | print('Sorry, this space is occupied') 50 | else: 51 | print('please type a number between 1 and 9') 52 | 53 | except: 54 | print('Please type a number') 55 | 56 | def computerMove(): 57 | possibleMoves = [x for x , letter in enumerate(board) if letter == ' ' and x != 0 ] 58 | move = 0 59 | 60 | for let in ['O' , 'X']: 61 | for i in possibleMoves: 62 | boardcopy = board[:] 63 | boardcopy[i] = let 64 | if IsWinner(boardcopy, let): 65 | move = i 66 | return move 67 | 68 | cornersOpen = [] 69 | for i in possibleMoves: 70 | if i in [1 , 3 , 7 , 9]: 71 | cornersOpen.append(i) 72 | 73 | if len(cornersOpen) > 0: 74 | move = selectRandom(cornersOpen) 75 | return move 76 | 77 | if 5 in possibleMoves: 78 | move = 5 79 | return move 80 | 81 | edgesOpen = [] 82 | for i in possibleMoves: 83 | if i in [2,4,6,8]: 84 | edgesOpen.append(i) 85 | 86 | if len(edgesOpen) > 0: 87 | move = selectRandom(edgesOpen) 88 | return move 89 | 90 | def selectRandom(li): 91 | import random 92 | ln = len(li) 93 | r = random.randrange(0,ln) 94 | return li[r] 95 | 96 | def main(): 97 | print("Welcome to the game!") 98 | printBoard(board) 99 | 100 | while not(isBoardFull(board)): 101 | if not(IsWinner(board , 'O')): 102 | playerMove() 103 | printBoard(board) 104 | else: 105 | print("sorry you loose!") 106 | break 107 | 108 | if not(IsWinner(board , 'X')): 109 | move = computerMove() 110 | if move == 0: 111 | print(" ") 112 | else: 113 | insertLetter('O' , move) 114 | print('computer placed an o on position' , move , ':') 115 | printBoard(board) 116 | else: 117 | print("you win!") 118 | break 119 | 120 | 121 | 122 | 123 | if isBoardFull(board): 124 | print("Tie game") 125 | 126 | while True: 127 | x = input("Do you want to play again? (y/n)") 128 | if x.lower() == 'y': 129 | board = [' ' for x in range(10)] 130 | print('--------------------') 131 | main() 132 | else: 133 | break 134 | -------------------------------------------------------------------------------- /Timer/timer.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | # Taking time input from the user 4 | seconds = int(input("Enter no. of seconds: ")) 5 | 6 | for i in range(seconds): 7 | print(seconds - i, "seconds left") 8 | time.sleep(1) 9 | 10 | print("Time Over!!!!") 11 | -------------------------------------------------------------------------------- /bank management/README.MD: -------------------------------------------------------------------------------- 1 | # Bank Management in console :bank: 2 | 3 | ## Features :receipt: 4 | 5 | * Contains Menu-driven Program :clipboard: 6 | * Python is used which is easy to use, implement, handle & debug :hearts: 7 | * User friendly which uses console, just chose 1, 2, 3, or whatever the option is :one: :two: :three: :infinity: 8 | * No use of database, no data leak :tickets: 9 | 10 | 11 | ## How to use it ? :gear: 12 | 13 | - [ ] No need to install any extra library :luggage: 14 | 15 | - [ ] Just run [nitin bank.py](https://github.com/nitin30kumar/Python-fest2020/blob/master/bank%20management/nitin%20bank.py) and enjoy !! :handshake: :man_dancing: :woman_dancing: 16 | 17 | ## How to run it ? :computer: 18 | 19 | - [ ] It'll ask for the pin , input `1234` ,as given in the code . You may change it in the code itself . 20 | - [ ] The program will tell you at every point what to do next. 21 | - [ ] It'll run infinitely untill user tells to exit program 22 | 23 | For any query , please do comment :left_speech_bubble: or else LIKE it :black_heart: 24 | -------------------------------------------------------------------------------- /bank management/nitin bank.py: -------------------------------------------------------------------------------- 1 | print("Welcome to Black Eagle Bank ") 2 | restart = ['Y'] 3 | chances = 3 4 | balance = 999.12 5 | while chances >= 0: 6 | pin = int(input('Please enter the 4 digit PIN:')) 7 | if pin == 1234: 8 | while restart not in ('n','NO','no','N'): 9 | print('\n\nPlease press 1 for your balance.') 10 | print('Please enter 2 to make a withdrawal') 11 | print('Please enter 3 to pay in') 12 | print('Please enter 4 to return card') 13 | option = int(input('what would you like to choose ?:')) 14 | if option == 1: 15 | print('Your balance is Rs.',balance) 16 | if restart in ('n','NO','no','N'): 17 | print('Thank You !!!') 18 | break 19 | 20 | elif option == 2: 21 | option2 = ('y') 22 | withdrawal = float(input('How much would you like to withdraw? 10,20,50,100,200 for others 1: ')) 23 | if withdrawal in [10,20,50,100,200]: 24 | balance = balance - withdrawal 25 | print('\n\nYou balance is now Rs.',balance) 26 | restart = input('\n\nWould you like to go back?') 27 | if restart in ('n','NO','no','N'): 28 | print('Thank You') 29 | break 30 | elif withdrawal != [10,20,50,100,200]: 31 | print('Invalid amount , Please re-try\n') 32 | restart = 'y' 33 | elif withdrawal == 1: 34 | withdrawal = float(input('Please enter desired amount:')) 35 | 36 | elif option == 3: 37 | pay_in = float(input('How much would you like to pay in ?:')) 38 | balance = balance + pay_in 39 | print('\n\nYour balance is now Rs.',balance) 40 | restart = input('Would you like to go back?') 41 | if restart in ('n','NO','no','N'): 42 | print('Thank You !!!') 43 | break 44 | 45 | elif option == 4: 46 | print('Please wait while your card is returned...\n') 47 | print('Thank you for your interest in our Bank !!!') 48 | break 49 | 50 | else: 51 | print('Please enter a correct number.\n') 52 | restart = 'y' 53 | 54 | elif pin != ('1234'): 55 | print('Incorrect Password') 56 | chances = chances - 1 57 | if chances == 0 : 58 | print('\n No more tries\n Thank You !!!') 59 | break 60 | -------------------------------------------------------------------------------- /number-guessing-game.py: -------------------------------------------------------------------------------- 1 | """ Number Guessing Game 2 | ---------------------------------------- 3 | """ 4 | import random 5 | attempts_list = [] 6 | def show_score(): 7 | if len(attempts_list) <= 0: 8 | print("There is currently no high score, it's yours for the taking!") 9 | else: 10 | print("The current high score is {} attempts".format(min(attempts_list))) 11 | def start_game(): 12 | random_number = int(random.randint(1, 10)) 13 | print("Hello traveler! Welcome to the game of guesses!") 14 | player_name = input("What is your name? ") 15 | wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) 16 | // Where the show_score function USED to be 17 | attempts = 0 18 | show_score() 19 | while wanna_play.lower() == "yes": 20 | try: 21 | guess = input("Pick a number between 1 and 10 ") 22 | if int(guess) < 1 or int(guess) > 10: 23 | raise ValueError("Please guess a number within the given range") 24 | if int(guess) == random_number: 25 | print("Nice! You got it!") 26 | attempts += 1 27 | attempts_list.append(attempts) 28 | print("It took you {} attempts".format(attempts)) 29 | play_again = input("Would you like to play again? (Enter Yes/No) ") 30 | attempts = 0 31 | show_score() 32 | random_number = int(random.randint(1, 10)) 33 | if play_again.lower() == "no": 34 | print("That's cool, have a good one!") 35 | break 36 | elif int(guess) > random_number: 37 | print("It's lower") 38 | attempts += 1 39 | elif int(guess) < random_number: 40 | print("It's higher") 41 | attempts += 1 42 | except ValueError as err: 43 | print("Oh no!, that is not a valid value. Try again...") 44 | print("({})".format(err)) 45 | else: 46 | print("That's cool, have a good one!") 47 | if __name__ == '__main__': 48 | start_game() 49 | -------------------------------------------------------------------------------- /python/BinaryConverter.py: -------------------------------------------------------------------------------- 1 | 2 | binary = input("Input a number in binary:") 3 | denary = 0 4 | for digit in binary: 5 | denary = denary*2 + int(digit) 6 | print("Your denary number is: " + str(denary)) 7 | 8 | denary = int(input("Input a denary number:")) 9 | binary="" 10 | while denary>0: 11 | binary = str(denary%2) + binary 12 | denary = denary//2 13 | 14 | print("Your binary number is: " + binary) -------------------------------------------------------------------------------- /python/BinarySearchRecursive.py: -------------------------------------------------------------------------------- 1 | # main code for binary search 2 | def binary_search(arr, low, high, x): 3 | if high >= low: 4 | mid = (high + low) // 2 5 | if arr[mid] == x: 6 | return mid 7 | elif arr[mid] > x: 8 | return binary_search(arr, low, mid - 1, x) 9 | else: 10 | return binary_search(arr, mid + 1, high, x) 11 | else: 12 | return -1 13 | 14 | # input list 15 | print("Enter the elements:") 16 | A=list(map(int,input().split())) 17 | print("Enter the element to be searched:") 18 | x=int(input()) 19 | 20 | result = binary_search(A, 0, len(A)-1, x) 21 | if result != -1: 22 | print("Element is present at index", (result)) 23 | else: 24 | print("Element is not present in array") -------------------------------------------------------------------------------- /python/BinarytreeClassbased.py: -------------------------------------------------------------------------------- 1 | def binarytree(r): 2 | return[r,[],[]] 3 | def insertleft(root,newbranch): 4 | t=root.pop(1) 5 | if len(t)>1: 6 | root.insert(1,[newbranch,t,[]]) 7 | else: 8 | root.insert(1,[newbranch,[],[]]) 9 | return root 10 | def insertright(root,newbranch): 11 | t=root.pop(2) 12 | if len(t)>1: 13 | root.insert(2,[newbranch,[],t]) 14 | else: 15 | root.insert(2,[newbranch,[],[]]) 16 | return root 17 | def getroot(root,new): 18 | root[0]=new 19 | def setnew(root): 20 | return root[0] 21 | def getleft(root): 22 | return root[1] 23 | def getright(root): 24 | return root[2] 25 | -------------------------------------------------------------------------------- /python/Checkleapyear.py: -------------------------------------------------------------------------------- 1 | year = 2000 2 | if (year % 4) == 0: 3 | if (year % 100) == 0: 4 | if (year % 400) == 0: 5 | print("{0} is a leap year".format(year)) 6 | else: 7 | print("{0} is not a leap year".format(year)) 8 | else: 9 | print("{0} is a leap year".format(year)) 10 | else: 11 | print("{0} is not a leap year".format(year)) 12 | -------------------------------------------------------------------------------- /python/DNS_Lookup.py: -------------------------------------------------------------------------------- 1 | ''' 2 | i)Program to find IP address from Domain Name. 3 | ii)Program to find Server Name from IP address 4 | ''' 5 | import socket 6 | 7 | print ('Welcome to DNS to IP Address') 8 | URL=input('Enter URL: ') 9 | 10 | addr1 = socket.gethostbyname(URL) 11 | 12 | print(addr1) 13 | print ('WelCome IP address to DNS') 14 | IP=input('Enter IP Address: ') 15 | addr6=socket.gethostbyaddr(IP) 16 | print (addr6) 17 | 18 | -------------------------------------------------------------------------------- /python/Face Detection/Needed Packages.txt: -------------------------------------------------------------------------------- 1 | 1. pip 2 | 2. setuptools 3 | 3. opencv-python 4 | 4. numpy 5 | 6 | -------------------------------------------------------------------------------- /python/Face Detection/face_detection.py: -------------------------------------------------------------------------------- 1 | # Importing needful modules and libraries 2 | import numpy as np 3 | import cv2 4 | 5 | 6 | faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # for detecting face 7 | cap = cv2.VideoCapture(0) 8 | cap.set(3, 640) # set Width 9 | cap.set(4, 480) # set Height 10 | 11 | # Running while loop 12 | while True: # infinite loop for live webcam 13 | ret, img = cap.read() 14 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 15 | faces = faceCascade.detectMultiScale( 16 | gray, 17 | scaleFactor=1.2, 18 | minNeighbors=5, 19 | minSize=(20, 20) 20 | ) 21 | 22 | for (x,y,w,h) in faces: # for making red box after detecting face 23 | cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) 24 | roi_color = img[y:y+h, x:x+w] 25 | 26 | cv2.imshow('video', img) # displaying the image continuously to show live video 27 | 28 | k = cv2.waitKey(100) & 0xff # Waits for .1(100ms) second before capturing another image 29 | # to increase time between each capture, increase parameters in waitKey() 30 | if k == 27: # Press 'ESC' for exiting program 31 | break # breaks out of the loop 32 | 33 | # Releasing thr result as image 34 | cap.release() 35 | cv2.destroyAllWindows() 36 | # Exiting the window 37 | -------------------------------------------------------------------------------- /python/Fibonacci/Fibonacci_1.py: -------------------------------------------------------------------------------- 1 | # The Fibonacci sequence is defined as follows: 2 | # F(0)=0 3 | # F(1)=1 4 | # F(n)=F(n−1)+F(n−2) 5 | 6 | # F(n) can be easily calculated in linear time by calculating the terms one by one. 7 | 8 | n = int(input()) 9 | 10 | if n < 2: 11 | print("F(%d) = %d" % (n, n)) 12 | 13 | else: 14 | a, b = 0, 1 15 | for i in range(n-1): 16 | a, b = b, a+b 17 | print("F(%d) = %d" % (n, b)) 18 | -------------------------------------------------------------------------------- /python/Fibonacci/Fibonacci_2.py: -------------------------------------------------------------------------------- 1 | # Binet's Formula can be used to calculate F(n) in O(1) time. 2 | # F(n) = (phi^n - psi^n) / sqrt(5), 3 | # where, phi = (1 + sqrt(5))/2, psi = (1 - sqrt(5))/2 4 | 5 | # It is mathematically accurate, 6 | # but due to limited precision, it is not practical for larger numbers. 7 | 8 | from math import sqrt 9 | 10 | phi = (1 + sqrt(5)) / 2 11 | psi = (1 - sqrt(5)) / 2 12 | 13 | n = int(input()) 14 | ans = (phi**n - psi**n) / sqrt(5) 15 | 16 | print("F(%d) = %d" % (n, ans)) 17 | -------------------------------------------------------------------------------- /python/Fibonacci/Fibonacci_3.py: -------------------------------------------------------------------------------- 1 | # Fibonacci numbers can also be calculated using matrix exponentiation. 2 | # The matrix [F_n F_(n+1)] is equivalent to [F_0 F_1] P^n 3 | # where, P = 0 1 4 | # 1 1 5 | # P^n can be calculated in log n time. 6 | 7 | n = int(input()) 8 | 9 | b = list(bin(n)[2:]) 10 | 11 | cur = [0, 1, 1, 1] 12 | result = [1, 0, 0, 1] # identity matrix 13 | 14 | while b: 15 | if b.pop() == '1': 16 | # if the bit is set, then we should multiply the current value with the result 17 | result = [ 18 | result[0]*cur[0] + result[1]*cur[2], 19 | result[0]*cur[1] + result[1]*cur[3], 20 | result[2]*cur[0] + result[3]*cur[2], 21 | result[2]*cur[1] + result[3]*cur[3] 22 | ] 23 | cur = [ 24 | cur[0]*cur[0] + cur[1]*cur[2], 25 | cur[0]*cur[1] + cur[1]*cur[3], 26 | cur[2]*cur[0] + cur[3]*cur[2], 27 | cur[2]*cur[1] + cur[3]*cur[3] 28 | ] 29 | 30 | # result is now equal to P^n, so we can get n'th fibonacci easily now. 31 | ans = result[2] 32 | 33 | print("F(%d) = %d" % (n, ans)) 34 | -------------------------------------------------------------------------------- /python/Fibonacci/README.md: -------------------------------------------------------------------------------- 1 | # Contents 2 | 3 | 1. Calculating terms one by one to get F(n) in linear time. 4 | 2. Binet's Formula 5 | 3. Matrix Exponentiation to calculate F(n) in log n time. 6 | -------------------------------------------------------------------------------- /python/Google Sheets/sheets_analysis.py: -------------------------------------------------------------------------------- 1 | import gspread 2 | from oauth2client.service_account import ServiceAccountCredentials 3 | 4 | scope = ['https://www.googleapis.com/auth/spreadsheets.readonly'] 5 | credentials = ServiceAccountCredentials.from_json_keyfile_name('', scope) #Enter the service account credentials here taken from google fdevelopers console 6 | gc = gspread.authorize(credentials) 7 | spreadsheet_key = '' #Enter the spreadsheet key here taken from sheet url 8 | book = gc.open_by_key(spreadsheet_key) 9 | 10 | worksheet = book.worksheet("Sheet1") 11 | 12 | table = worksheet.get_all_values() 13 | 14 | print (table) 15 | -------------------------------------------------------------------------------- /python/GraphPlotter/README.md: -------------------------------------------------------------------------------- 1 | ## Plotting graph 2 | 3 | Used `pyplot` from `matplotlib` library. 4 | 5 | ### Installation 6 | `pip install matplotlib` 7 | 8 | ### Usage 9 | `python3 main.py` 10 | 11 | One can try among different plots 12 | 13 | ### 2-D plots 14 | 15 | 1. Line 16 | ![line](./images/line.png) 17 | 18 | 2. Scatter 19 | ![scatter](./images/scatter.png) 20 | 21 | ### 3-D plots 22 | 23 | 1. Line 24 | ![line](./images/3dline.png) 25 | 26 | 2. Scatter 27 | ![scatter](./images/3dscatter.png) 28 | 29 | 3. Surface 30 | ![surface](./images/3dsurface.png) 31 | 32 | 33 | -------------------------------------------------------------------------------- /python/GraphPlotter/images/3dline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/python/GraphPlotter/images/3dline.png -------------------------------------------------------------------------------- /python/GraphPlotter/images/3dscatter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/python/GraphPlotter/images/3dscatter.png -------------------------------------------------------------------------------- /python/GraphPlotter/images/3dsurface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/python/GraphPlotter/images/3dsurface.png -------------------------------------------------------------------------------- /python/GraphPlotter/images/line.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/python/GraphPlotter/images/line.png -------------------------------------------------------------------------------- /python/GraphPlotter/images/scatter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranav2012/Python-fest2020/85dd2f37031c921450ab2cc6fe77633e40289779/python/GraphPlotter/images/scatter.png -------------------------------------------------------------------------------- /python/GraphPlotter/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | ==================== 3 | 2D /3D Graph plotter 4 | ==================== 5 | 6 | Class TwoDGraph: for 2D line and scatter plot. 7 | 8 | Class ThreeDGraph: for 3D line, scatter and surface plot 9 | 10 | """ 11 | 12 | 13 | import numpy as np 14 | from matplotlib import pyplot 15 | from matplotlib import cm 16 | from mpl_toolkits import mplot3d 17 | 18 | 19 | # helper function 20 | def randrange(n, vmin, vmax): 21 | return (vmax - vmin)*np.random.rand(n) + vmin 22 | 23 | 24 | class TwoDGraph: 25 | 26 | """ 27 | Creating an object 28 | myObj = TwoDGraph(n, x, y, title, labeX, labelY) 29 | 30 | If you want to get userinput you can use the getUserInput class method. 31 | myObj = TwoDGraph().getUserInput() 32 | 33 | Now if you want to plot 34 | 2-d Line Graph: 35 | myObj.plotLineGraph() 36 | 37 | 2-d Scatter graph: 38 | myObj.plotScatterGraph() 39 | 40 | 41 | Examples: 42 | 43 | myObj.TwoDGraph(6, [1, 2, 3, 4, 5, 6], [2, 4, 7, 9, 10, 12], 'Graph Title', 'X-asis', 'Y-axis') 44 | myObj.plotLineGraph() 45 | myObj.plotScatterGraph() 46 | 47 | 48 | """ 49 | 50 | def __init__(self, n, x, y, title='', labelX='', labelY=''): 51 | self.n = n 52 | self.x = x 53 | self.y = y 54 | self.title = title 55 | self.labelX = labelX 56 | self.labelY = labelY 57 | 58 | def plotScatterGraph(self): 59 | fig = pyplot.figure() 60 | ax = fig.add_subplot(111) 61 | ax.scatter(self.x, self.y, color='b') 62 | ax.set_xlabel(self.labelX) 63 | ax.set_ylabel(self.labelY) 64 | ax.set_title(self.title) 65 | pyplot.show() 66 | 67 | def plotLineGraph(self): 68 | fig = pyplot.figure() 69 | ax = fig.add_subplot(111) 70 | ax.set_xlabel(self.labelX) 71 | ax.set_ylabel(self.labelY) 72 | ax.set_title(self.title) 73 | pyplot.plot(self.x, self.y) 74 | 75 | # for showing the coordinates of the points 76 | for i, j in zip(self.x, self.y): 77 | ax.annotate(str(f'({i}, {j}'), xy=(i, j)) 78 | 79 | pyplot.show() 80 | 81 | @classmethod 82 | def getUserInput(cls): 83 | while True: 84 | try: 85 | title = input('Enter title of the scatter graph: ') 86 | labelX = input('Enter label for X-axis: ') 87 | labelY = input('Enter label for Y-axis: ') 88 | n = int(input('Enter number of coordinates you will enter: ')) 89 | print('Enter x coordinates separated by spaces: ', end='') 90 | x = list(map(float, input().split(' '))) 91 | print('Enter y coordinates separated by spaces: ', end='') 92 | y = list(map(float, input().split(' '))) 93 | assert(len(x) == n and len(y) == n) 94 | return cls(n, x, y, title, labelX, labelY) 95 | except: 96 | print('Please make sure you give valid input!!') 97 | continue 98 | 99 | 100 | class ThreeDGraph: 101 | """ 102 | Creating an object 103 | myObj = TwoDGraph(x, y, z, title, labeX, labelY, labelZ) 104 | 105 | Now if you want to plot 106 | 3-d Line Graph: 107 | myObj.plotLineGraph() 108 | 109 | 3-d Scatter graph: 110 | myObj.plotScatterGraph() 111 | 112 | 3-d Surface graph: 113 | myObj.plotSurfaceGraph() 114 | 115 | 116 | Example Usage: 117 | 118 | 3-d line graph 119 | --------------- 120 | theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) 121 | z = np.linspace(-2, 2, 100) 122 | r = z**2 + 1 123 | x = r * np.sin(theta) 124 | y = r * np.cos(theta) 125 | obj = ThreeDGraph(x, y, z, '3-D line graph', 'values of x', 'values of y', '') 126 | obj.plotLineGraph() 127 | 128 | 3-d surface graph 129 | ----------------- 130 | X = np.arange(-5, 5, 0.25) 131 | Y = np.arange(-5, 5, 0.25) 132 | X, Y = np.meshgrid(X, Y) 133 | R = np.sqrt(X**2 + Y**2) 134 | Z = np.sin(R) 135 | obj = ThreeDGraph(X, Y, Z, '3-D surface graph', 'values of x', 'values of y', '') 136 | obj.plotSurfaceGraph() 137 | 138 | 139 | 3-d scatter graph 140 | ----------------- 141 | n=100 142 | xs = randrange(n, 23, 32) 143 | ys = randrange(n, 0, 100) 144 | zs = randrange(n, -50, -25) 145 | obj = ThreeDGraph(xs, ys, zs, '3-D Scatter graph', 'values of x', 'values of y', '') 146 | obj.plotScatterGraph() 147 | """ 148 | 149 | def __init__(self, x, y, z, title='', labelX='', labelY='', labelZ=''): 150 | self.x = x 151 | self.y = y 152 | self.z = z 153 | self.title = title 154 | self.labelX = labelX 155 | self.labelY = labelY 156 | self.labelZ = labelZ 157 | 158 | def plotLineGraph(self): 159 | fig = pyplot.figure() 160 | ax = fig.gca(projection='3d') 161 | ax.set_xlabel(self.labelX) 162 | ax.set_ylabel(self.labelY) 163 | ax.set_title(self.title) 164 | ax.plot(self.x, self.y, self.z, label='parametric curve') 165 | ax.legend() 166 | pyplot.show() 167 | 168 | def plotScatterGraph(self): 169 | fig = pyplot.figure() 170 | ax = fig.gca(projection='3d') 171 | ax.set_xlabel(self.labelX) 172 | ax.set_ylabel(self.labelY) 173 | ax.set_title(self.title) 174 | ax.scatter(self.x, self.y, self.z, c='r', marker='o') 175 | ax.legend() 176 | pyplot.show() 177 | 178 | def plotSurfaceGraph(self): 179 | fig = pyplot.figure() 180 | ax = fig.gca(projection='3d') 181 | ax.set_xlabel(self.labelX) 182 | ax.set_ylabel(self.labelY) 183 | ax.set_title(self.title) 184 | ax.plot_surface(self.x, self.y, self.z, cmap=cm.coolwarm, linewidth=0, antialiased=False) 185 | pyplot.show() 186 | 187 | 188 | """ 189 | Ref: 190 | https://matplotlib.org/ 191 | """ -------------------------------------------------------------------------------- /python/HelloWorld.py: -------------------------------------------------------------------------------- 1 | print("Hello World!!") -------------------------------------------------------------------------------- /python/Jumping_Number.py: -------------------------------------------------------------------------------- 1 | #Given a positive number N, check if the number is a Jumping number or not. 2 | #A number is defined as a Jumping Number if all adjacent digits in it have an absolute difference of 1. 3 | #For example 2, 23 and 4343456 are Jumping numbers but 296 and 89498 are not. 4 | 5 | num = input("Enter a number ") 6 | lst = [int(x) for x in num] 7 | n = len(lst) 8 | res = 1 9 | for ele in range(0,n-1): 10 | if abs(lst[ele] - lst[ele+1]) != 1: 11 | res = 0 12 | if res == 1: 13 | print("JUMPING NUMBER") 14 | else: 15 | print("NOT A JUMPING NUMBER") 16 | -------------------------------------------------------------------------------- /python/LargestOfThreeNumbers.py: -------------------------------------------------------------------------------- 1 | num1 = float(input("Enter first number: ")) 2 | num2 = float(input("Enter second number: ")) 3 | num3 = float(input("Enter third number: ")) 4 | 5 | if (num1 > num2) and (num1 > num3): 6 | largest = num1 7 | elif (num2 > num1) and (num2 > num3): 8 | largest = num2 9 | else: 10 | largest = num3 11 | 12 | print("The largest number is",largest) -------------------------------------------------------------------------------- /python/LinearSearch.py: -------------------------------------------------------------------------------- 1 | # main code for linear search 2 | def linear_search(arr, x): 3 | for i in range(len(arr)): 4 | if arr[i] == x: 5 | return i 6 | return -1 7 | 8 | # input list 9 | print("Enter the elements:") 10 | A=list(map(int,input().split())) 11 | print("Enter the element to be searched:") 12 | x=int(input()) 13 | 14 | result = linear_search(A,x) 15 | if result != -1: 16 | print("Element is present at index", (result)) 17 | else: 18 | print("Element is not present in array") -------------------------------------------------------------------------------- /python/Linked_List.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, val=None): 3 | self.dataval = val 4 | self.nextval = None 5 | 6 | class LinkedList: 7 | def __init__(self): 8 | self.head = None 9 | 10 | def atStart(self, val=None): 11 | newNode = Node(val) 12 | newNode.nextval = self.head 13 | self.head = newNode 14 | 15 | def atEnd(self, val=None): 16 | newNode = Node(val) 17 | if self.head is None: 18 | self.head = newNode 19 | return 20 | 21 | ptr = self.head 22 | while ptr.nextval: 23 | ptr = ptr.nextval 24 | ptr.nextval = newNode 25 | 26 | def inBetween(self, middleNode, val): 27 | if middleNode is None: 28 | return 29 | 30 | newNode = Node(val) 31 | newNode.nextval = middleNode.nextval 32 | middleNode.nextval = newNode 33 | 34 | 35 | def print(self): 36 | ptr = self.head 37 | while ptr is not None: 38 | print(ptr.dataval) 39 | ptr = ptr.nextval 40 | 41 | 42 | LL = LinkedList() 43 | LL.head = Node("Monday") 44 | n1 = Node("Tuesday") 45 | n2 = Node("Wednesday") 46 | 47 | LL.head.nextval = n1 48 | n1.nextval = n2 49 | LL.atStart("Sunday") 50 | LL.atEnd("Thursday") 51 | 52 | LL.inBetween(n2.nextval, "Friday") 53 | LL.atEnd("Saturday") 54 | 55 | LL.print() -------------------------------------------------------------------------------- /python/Queue/ImplementQueue.py: -------------------------------------------------------------------------------- 1 | # Simple python program to demonstrate Queue implementation in Python 2 | 3 | queue = [] 4 | 5 | queue.append('a') 6 | queue.append('b') 7 | queue.append('c') 8 | 9 | print("Initial queue") 10 | print(queue) 11 | 12 | print("\nElements dequeued from queue") 13 | print(queue.pop(0)) 14 | print(queue.pop(0)) 15 | print(queue.pop(0)) 16 | 17 | print("\nQueue after removing elements") 18 | print(queue) 19 | 20 | -------------------------------------------------------------------------------- /python/Recursive_Factorial.py: -------------------------------------------------------------------------------- 1 | def recur_factorial(n): 2 | if n == 1: 3 | return n 4 | else: 5 | return n*recur_factorial(n-1) 6 | # take input from the user 7 | num = int(input("Enter a number: ")) 8 | # check is the number is negative 9 | if num < 0: 10 | print("Factorial does not exist for negative numbers") 11 | elif num == 0: 12 | print("The factorial of 0 is 1") 13 | else: 14 | print("The factorial of",num,"is",recur_factorial(num)) -------------------------------------------------------------------------------- /python/SquareRoot.py: -------------------------------------------------------------------------------- 1 | #calculating the square root of a number using Newton Raphson method. 2 | 3 | #what is Newton Raphson method? 4 | 5 | ''' 6 | It is a gradient based technique used to find root of a given number. 7 | according to this method, 8 | 9 | Xn+1 = Xn - f(Xn)/f'(Xn) - (1) {where n is the nth term i.e 0,1,2,....} 10 | 11 | 12 | we know, 13 | X = (N)^1/r 14 | 15 | where N is a number of which we want to find rth root (X). 16 | 17 | above equation can be written as, 18 | X^r - N = 0 19 | => f(X) = X^r - N = 0 - (a) 20 | => f'(X) = r*X^(r-1) - (b) 21 | 22 | now, putting nth term of equation (a) and (b) in equation (1) 23 | Xn+1 = Xn - (Xn^r - N) / r*Xn^(r-1) 24 | 25 | taking L.C.M, 26 | Xn+1 = [ r*Xn^r - (Xn^r - N) ] / r*Xn^(r-1) 27 | 28 | sovling further, 29 | 30 | Xn+1 = [(r-1)Xn^r + N] / r*Xn^r-1 - (2) 31 | 32 | This is the formula to get the rth root of a positive integer N, where X is our approximation number. 33 | 34 | now, our aim is to get square root right, so, in equation (2) put r = 2. 35 | 36 | Xn+1 = ( Xn^2 + N ) / 2 * Xn^2 [This is our equation which we are going to use to calculate square root of a number programatically] 37 | ''' 38 | 39 | number = int(input("enter number:")) #taking input number from user of which we will calculate square root 40 | 41 | x = number # x is our approximation number(or Xn in equation (2)) 42 | # i.e the number which we assume can be the square root of number 43 | # which we assume to be the number itself 44 | 45 | while(True): 46 | 47 | root = (x + number/x)/2 # root is our Xn+1 th term (as in equation (2)) 48 | 49 | if abs(root - x) < 0.0001: # 0.0001 is our precision value an the loop is run until we get precision upto desired decimal places 50 | break 51 | 52 | x = root 53 | 54 | print(root) 55 | -------------------------------------------------------------------------------- /python/Temperature Converter.py: -------------------------------------------------------------------------------- 1 | # choose a number 2 | num = input("Choose a number\n") 3 | 4 | # choose Celsius or Fahrenheit 5 | unit = input("Choose unit: Celsius or Fahrenheit\n") 6 | 7 | # convert Celsius to Fahrenheit 8 | if unit.lower() == "Celsius".lower(): 9 | temp = int(num) * 9/5 + 32 10 | print(num, "degrees Celsius converts to ", temp, "degrees Fahrenheit.") 11 | elif unit.lower() == "Fahrenheit".lower(): 12 | temp = (int(num) - 32) / (9/5) 13 | print(num, "degrees Fahrenheit converts to ", temp, "degrees Celsius.") 14 | else: 15 | # I always mispell Fahrenheit lol 16 | print("Please check your unit spelling!") 17 | -------------------------------------------------------------------------------- /python/Transpose of a matrix.py: -------------------------------------------------------------------------------- 1 | x = [[12,7],[4,5],[3,8]] 2 | result = [[0,0,0],[0,0,0]] 3 | 4 | for i in range (len(x)): 5 | for j in range (len(x[0])): 6 | result[j][i] = x[i][j] 7 | 8 | for r in result: 9 | print(r) 10 | -------------------------------------------------------------------------------- /python/bubblesort.py: -------------------------------------------------------------------------------- 1 | def bubblesort(arr): 2 | swap_happened = True 3 | count = 0 4 | while swap_happened: 5 | print('sort status',count,str(arr)) 6 | swap_happened = False 7 | for i in range(len(arr) - 1): 8 | if arr[i] > arr[i+1]: 9 | swap_happened = True 10 | arr[i],arr[i+1] = arr[i+1],arr[i] 11 | count += 1 12 | return arr 13 | 14 | l = [6,4,535,2,24,12,1,3,55,4545] 15 | print('unsorted list is',l) 16 | print('sorted list is',bubblesort(l)) -------------------------------------------------------------------------------- /python/caesar_cypher.py: -------------------------------------------------------------------------------- 1 | import string 2 | from collections import deque 3 | 4 | def Caesar_Cypher(string_to_translate, number_of_rotations): 5 | 6 | upper = deque(string.ascii_uppercase,maxlen=26) 7 | lower = deque(string.ascii_lowercase,maxlen=26) 8 | 9 | # print(upper) 10 | # print(lower) 11 | 12 | upper.rotate(number_of_rotations) 13 | lower.rotate(number_of_rotations) 14 | 15 | # print(upper) 16 | # print(lower) 17 | 18 | upper_string = ''.join(list(upper)) 19 | lower_string = ''.join(list(lower)) 20 | 21 | # print(upper_string) 22 | # print(lower_string) 23 | 24 | return string_to_translate.translate(str.maketrans(string.ascii_uppercase, upper_string)).translate(str.maketrans(string.ascii_lowercase, lower_string)) 25 | 26 | input_string = input("Enter string u want to translate ") 27 | rotate_by = int(input("Enter the number u want to rotate by ")) 28 | print(f"Translated string is {Caesar_Cypher(input_string,rotate_by)}") 29 | 30 | -------------------------------------------------------------------------------- /python/calculator.py: -------------------------------------------------------------------------------- 1 | # Importing modules 2 | import math 3 | 4 | # defining functions 5 | def add(s,t): 6 | print('sum of',s,'and',y,'is',s+t) 7 | def sub(s,t): 8 | print('difference of',s,'and',y,'is',s-t) 9 | def mul(s,t): 10 | print('product of',s,'and',y,'is',s*t) 11 | def div(s,t): 12 | print('quotient of',s,'and',y,'is',s/t) 13 | 14 | 15 | # Running while loop 16 | q='y' 17 | while q=='y': 18 | x=int(input('enter the first number: ')) 19 | y=int(input('enter the second number: ')) 20 | 21 | if x 0): 9 | a = b 10 | b = c 11 | c = a % b 12 | return b 13 | 14 | def greedy_egyptian_fraction(num, den): 15 | global iter 16 | if(num == 1): 17 | #appending list unit_den_array 18 | iter = iter+1 # storing in unit_den_array from index 1 not 0 19 | unit_den_array[iter] = den 20 | else: 21 | unit_den = math.ceil(den/num) 22 | iter = iter+1 23 | unit_den_array[iter] = unit_den 24 | gcd_of_numbers = gcd((num*unit_den) - den, den*unit_den) 25 | greedy_egyptian_fraction(((num*unit_den) - den)//gcd_of_numbers, (den*unit_den)//gcd_of_numbers) 26 | 27 | if __name__ == '__main__': 28 | greedy_egyptian_fraction(4, 5) 29 | for i in range(1, iter+1): 30 | print(unit_den_array[i]) -------------------------------------------------------------------------------- /python/factorial.py: -------------------------------------------------------------------------------- 1 | #take the input from the user end in the integer format 2 | input_num = int(input("Enter the number:")) 3 | 4 | #define the factorial function 5 | def factorial(input_num): 6 | f = 1 7 | if input_num < 0: 8 | print("Factorial cannot be calculated") 9 | elif input_num == 0: 10 | print("Factorial of 0 is 1") 11 | else: 12 | for i in range(1,input_num+1): 13 | f = f * i 14 | return f 15 | 16 | 17 | #call the factorial function 18 | print(factorial(input_num)) -------------------------------------------------------------------------------- /python/is_palindrome_possible.py: -------------------------------------------------------------------------------- 1 | def is_palindrome_possible(word): 2 | #check if the number of letters appearing odd number of times is either 0 or 1 3 | return len( [ch for ch in word.lower if word.count(ch) % 2 == 1] ) <= 1 4 | 5 | if __name__ == '__main__': 6 | word = input("Enter a word to check if it's palindrome are possible or not: ") 7 | response = is_palindrome_possible(word) 8 | if response: 9 | print("Yes") 10 | else: 11 | print("No") 12 | -------------------------------------------------------------------------------- /python/largest_among_3.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | l=[] #empty list 4 | #taking 3 input value and appending in the list 5 | l.append(int(input('Enter your first number: '))) 6 | l.append(int(input('Enter your second number: '))) 7 | l.append(int(input('Enter your third number: '))) 8 | x=l[0] #setting a defult value 9 | #checking which is largest 10 | for i in range (1,3): 11 | if x 1: 6 | for i in range(2, nom): 7 | if (nom % i) == 0: 8 | print(nom, "ISN'T A PRIME NUMBER") 9 | break 10 | else: 11 | print(nom, "IS A PRIME NUMBER") 12 | else: 13 | print(nom, "IS A PRIME NUMBER") 14 | 15 | 16 | #END OF CODE 17 | #This code was written by arnavk09 for HacktoberFest 2020 18 | -------------------------------------------------------------------------------- /python/recursive_substring_search.py: -------------------------------------------------------------------------------- 1 | # Recursive Python3 program to find if a given pattern is 2 | # present in a text 3 | 4 | def exactMatch(text, pat, text_index, pat_index): 5 | if text_index == len(text) and pat_index != len(pat): 6 | return 0 7 | 8 | # Else If last character of pattern reaches 9 | if pat_index == len(pat): 10 | return 1 11 | 12 | if text[text_index] == pat[pat_index]: 13 | return exactMatch(text, pat, text_index+1, pat_index+1) 14 | 15 | return 0 16 | 17 | 18 | # This function returns true if 'text' contain 'pat' 19 | def contains(text, pat, text_index, pat_index): 20 | # If last character of text reaches 21 | if text_index == len(text): 22 | return 0 23 | 24 | # If current characters of pat and text match 25 | if text[text_index] == pat[pat_index]: 26 | if exactMatch(text, pat, text_index, pat_index): 27 | return 1 28 | else: 29 | return contains(text, pat, text_index+1, pat_index) 30 | 31 | # If current characters of pat and tex don't match 32 | return contains(text , pat, text_index+1, pat_index) 33 | 34 | # Driver program to test the above function 35 | 36 | print(contains("geeksforgeeks", "iron", 0, 0)) 37 | print(contains("geeksforgeeks", "ironman", 0, 0)) 38 | print(contains("geeksquizgeeks", "man", 0, 0)) 39 | 40 | # This code is contributed by ankush_953. 41 | -------------------------------------------------------------------------------- /python/reverse.py: -------------------------------------------------------------------------------- 1 | # Input string from user 2 | s = input("Enter the string : ") 3 | # Reverse the string 4 | output = s[::-1] 5 | # Print the reverse string 6 | print ("The reversed string is : ",output) 7 | -------------------------------------------------------------------------------- /python/stack.py: -------------------------------------------------------------------------------- 1 | #implementation of stack using list in python 2 | s=[] 3 | #index for top element of stack 4 | top=-1 5 | print("Enter 1 for POP operation") 6 | print("Enter 2 for PUSH operation") 7 | print("Enter 3 for PEEK operation") 8 | t=1; 9 | while(t): 10 | i=int(input("enter your choice")) 11 | if(i==1): 12 | #underflow-condition 13 | if(top==-1): 14 | print("No item in stack to delete ") 15 | else: 16 | #delete the element at top of the stack 17 | s.pop() 18 | #deacrease value of top by 1 19 | top-=1 20 | if(i==2): 21 | item=int(input("enter item to append ")) 22 | s.append(item) 23 | #increase value of top by 1 24 | top+=1 25 | if(i==3): 26 | #peek operation gives the value of element at top 27 | if(top==-1): 28 | print("no element is there in stack !!") 29 | else: 30 | print("the element at top is ",s[top]) 31 | t=int(input("enter 0 if you want to discontinue ")) 32 | #print final stack 33 | print("final stack formed is",s) 34 | 35 | #sample input-output 36 | #Enter 1 for POP operation 37 | #Enter 2 for PUSH operation 38 | #Enter 3 for PEEK operation 39 | #enter your choice2 40 | #enter item to append 90 41 | #enter 0 if you want to discontinue 2 42 | #enter your choice2 43 | #enter item to append 89 44 | #enter 0 if you want to discontinue 8 45 | #enter your choice3 46 | #the element at top is 89 47 | #enter 0 if you want to discontinue 0 48 | #final stack formed is [90, 89] 49 | -------------------------------------------------------------------------------- /python/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | //dictionary used to display tic-tac-toe board 2 | board = { 3 | 0: ' ', 1: ' ', 2: ' ', 4 | 3: ' ', 4: ' ', 5: ' ', 5 | 6: ' ', 7: ' ', 8: ' ' 6 | } 7 | //player with X key is player 1 and player with o key is player 2 8 | p={"X":1,"o":2} 9 | player = 1 # to initialise first player 10 | total_moves = 0 # to count the moves 11 | end_check = 0 12 | checkr=0 13 | checkc=0 14 | checkd=0 15 | def row(): #to check row 16 | i=0; 17 | while(i<=6): 18 | if board[i]==board[i+1]==board[i+2]=="X" or board[i]==board[i+1]==board[i+2]=="o": 19 | winner=board[i] 20 | print("player ",p[winner]," has won the game !! ") 21 | return 1 22 | else: 23 | i=i+3 24 | def column(): #to check column 25 | i=0; 26 | while(i!=3): 27 | if board[i] == board[i+3] == board[i+6]== "X" or board[i] == board[i+3] == board[i+6]== "o" : 28 | winner=board[i] 29 | print("player ",p[winner], " won the game !! ") 30 | return 1 31 | else: 32 | i=i+3 33 | def diagonal(): #to check diagonal 34 | if board[0] == board[4] == board[8]=="X" or board[0] == board[4] == board[8]=="o" : 35 | winner=board[0] 36 | print("player ",p[winner]," has won the game !! ") 37 | return 1 38 | elif board[2] == board[4] == board[6]=="X" or board[2] == board[4] == board[6]=="o" : 39 | winner=board[2] 40 | print("player ",p[winner]," has won the game !! ") 41 | return 1 42 | 43 | print('0 |1 |2') 44 | print('- +- +-') 45 | print('3 |4 |5') 46 | print('- +- +-') 47 | print('6 |7 |8') 48 | print('***************************') 49 | 50 | while True: 51 | print(board[0]+'|'+board[1]+'|'+board[2]) 52 | print('-+-+-') 53 | print(board[3] + '|' + board[4] + '|' + board[5]) 54 | print('-+-+-') 55 | print(board[6] + '|' + board[7] + '|' + board[8]) 56 | 57 | //check all possibilities of ending a game. 58 | checkr=row() 59 | if total_moves == 9 or checkr==1 : 60 | break 61 | checkc=column() 62 | if total_moves == 9 or checkc==1 : 63 | break 64 | checkd=diagonal() 65 | if total_moves == 9 or checkd==1 : 66 | break 67 | while True: # input from players 68 | if player == 1: # choose player 69 | p1_input = int(input('player one')) 70 | if p1_input in board and board[p1_input] == ' ': 71 | board[p1_input] = 'X' 72 | player = 2 73 | break 74 | # on wrong input 75 | else: 76 | print('Invalid input, please try again !') 77 | continue 78 | else: 79 | p2_input = int(input('player two')) 80 | if p2_input in board and board[p2_input] == ' ': 81 | board[p2_input] = 'o' 82 | player = 1 83 | break 84 | else: # on wrong input 85 | print('Invalid input, please try again') 86 | continue 87 | total_moves += 1 88 | print('***************************') 89 | print() 90 | -------------------------------------------------------------------------------- /python/timsort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to perform TimSort. 2 | RUN = 32 3 | 4 | # This function sorts array from left index to 5 | # to right index which is of size atmost RUN 6 | def insertionSort(arr, left, right): 7 | 8 | for i in range(left + 1, right+1): 9 | 10 | temp = arr[i] 11 | j = i - 1 12 | while j >= left and arr[j] > temp : 13 | 14 | arr[j+1] = arr[j] 15 | j -= 1 16 | 17 | arr[j+1] = temp 18 | 19 | # merge function merges the sorted runs 20 | def merge(arr, l, m, r): 21 | 22 | # original array is broken in two parts 23 | # left and right array 24 | len1, len2 = m - l + 1, r - m 25 | left, right = [], [] 26 | for i in range(0, len1): 27 | left.append(arr[l + i]) 28 | for i in range(0, len2): 29 | right.append(arr[m + 1 + i]) 30 | 31 | i, j, k = 0, 0, l 32 | # after comparing, we merge those two array 33 | # in larger sub array 34 | while i < len1 and j < len2: 35 | 36 | if left[i] <= right[j]: 37 | arr[k] = left[i] 38 | i += 1 39 | 40 | else: 41 | arr[k] = right[j] 42 | j += 1 43 | 44 | k += 1 45 | 46 | # copy remaining elements of left, if any 47 | while i < len1: 48 | 49 | arr[k] = left[i] 50 | k += 1 51 | i += 1 52 | 53 | # copy remaining element of right, if any 54 | while j < len2: 55 | arr[k] = right[j] 56 | k += 1 57 | j += 1 58 | 59 | # iterative Timsort function to sort the 60 | # array[0...n-1] (similar to merge sort) 61 | def timSort(arr, n): 62 | 63 | # Sort individual subarrays of size RUN 64 | for i in range(0, n, RUN): 65 | insertionSort(arr, i, min((i+31), (n-1))) 66 | 67 | # start merging from size RUN (or 32). It will merge 68 | # to form size 64, then 128, 256 and so on .... 69 | size = RUN 70 | while size < n: 71 | 72 | # pick starting point of left sub array. We 73 | # are going to merge arr[left..left+size-1] 74 | # and arr[left+size, left+2*size-1] 75 | # After every merge, we increase left by 2*size 76 | for left in range(0, n, 2*size): 77 | 78 | # find ending point of left sub array 79 | # mid+1 is starting point of right sub array 80 | mid = left + size - 1 81 | right = min((left + 2*size - 1), (n-1)) 82 | 83 | # merge sub array arr[left.....mid] & 84 | # arr[mid+1....right] 85 | merge(arr, left, mid, right) 86 | 87 | size = 2*size 88 | 89 | # utility function to print the Array 90 | def printArray(arr, n): 91 | 92 | for i in range(0, n): 93 | print(arr[i], end = " ") 94 | print() 95 | 96 | 97 | # Driver program to test above function 98 | if __name__ == "__main__": 99 | 100 | arr = [5, 21, 7, 23, 19] 101 | n = len(arr) 102 | print("Given Array is") 103 | printArray(arr, n) 104 | 105 | timSort(arr, n) 106 | 107 | print("After Sorting Array is") 108 | printArray(arr, n) 109 | 110 | # This code is contributed by Rituraj Jain 111 | -------------------------------------------------------------------------------- /rsa.py: -------------------------------------------------------------------------------- 1 | def euclid(m, n): 2 | 3 | if n == 0: 4 | return m 5 | else: 6 | r = m % n 7 | return euclid(n, r) 8 | def exteuclid(a, b): 9 | 10 | r1 = a 11 | r2 = b 12 | s1 = int(1) 13 | s2 = int(0) 14 | t1 = int(0) 15 | t2 = int(1) 16 | 17 | while r2 > 0: 18 | 19 | q = r1//r2 20 | r = r1-q * r2 21 | r1 = r2 22 | r2 = r 23 | s = s1-q * s2 24 | s1 = s2 25 | s2 = s 26 | t = t1-q * t2 27 | t1 = t2 28 | t2 = t 29 | 30 | if t1 < 0: 31 | t1 = t1 % a 32 | 33 | return (r1, t1) 34 | 35 | p = 823 36 | q = 953 37 | n = p * q 38 | Pn = (p-1)*(q-1) 39 | key = [] 40 | 41 | for i in range(2, Pn): 42 | 43 | gcd = euclid(Pn, i) 44 | 45 | if gcd == 1: 46 | key.append(i) 47 | 48 | e = int(313) 49 | 50 | 51 | r, d = exteuclid(Pn, e) 52 | if r == 1: 53 | d = int(d) 54 | print("decryption key is: ", d) 55 | 56 | else: 57 | print("Multiplicative inverse for\ 58 | the given encryption key does not \ 59 | exist. Choose a different encryption key ") 60 | M = 19070 61 | S = (M**d) % n 62 | M1 = (S**e) % n 63 | 64 | 65 | if M == M1: 66 | print("As M = M1, Accept the\ 67 | message sent by Alice") 68 | else: 69 | print("As M not equal to M1,\ 70 | Do not accept the message\ 71 | sent by Alice ") 72 | --------------------------------------------------------------------------------