├── .DS_Store ├── Armstrong Number ├── Java ├── CharsetFilter.java ├── Input.java ├── InputStream.java ├── JavaStringBufferDelete.java ├── MultipleClass.java ├── MultipleObj.java ├── MyMergeSort.java ├── Recursion.java ├── ScannerClass.java ├── TrappingRainwater.java ├── getMinimumUniqueSum.java ├── height_of_binary_tree.java └── linear-search.java ├── Python ├── BTSV ├── IP_hostname.py ├── Knapsack-DP.py ├── Scraping_IMDB_Top_1000 │ ├── Output.csv │ ├── README.md │ └── SCRAPE.py ├── dot-animate.py ├── pingpong │ ├── Instructions.txt │ ├── ball.py │ ├── main.py │ └── paddle.py └── wordsubset.py └── passwordManagerProject.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoderAvi/hacktoberfest-22/dffb3e05a53ce202ad55f091d97c6241caa4597f/.DS_Store -------------------------------------------------------------------------------- /Armstrong Number: -------------------------------------------------------------------------------- 1 | # Python program to check if the number is an Armstrong number or not 2 | 3 | # take input from the user 4 | num = int(input("Enter a number: ")) 5 | 6 | # initialize sum 7 | sum = 0 8 | 9 | # find the sum of the cube of each digit 10 | temp = num 11 | while temp > 0: 12 | digit = temp % 10 13 | sum += digit ** 3 14 | temp //= 10 15 | 16 | # display the result 17 | if num == sum: 18 | print(num,"is an Armstrong number") 19 | else: 20 | print(num,"is not an Armstrong number") 21 | -------------------------------------------------------------------------------- /Java/CharsetFilter.java: -------------------------------------------------------------------------------- 1 | package step.learning.filters; 2 | 3 | import com.google.inject.Singleton; 4 | 5 | import javax.servlet.*; 6 | import javax.servlet.annotation.WebFilter; 7 | import java.io.IOException; 8 | 9 | //@WebFilter("/*") 10 | @Singleton 11 | public class CharsetFilter implements Filter { 12 | private FilterConfig filterConfig; 13 | public void init(FilterConfig filterConfig) throws ServletException { 14 | this.filterConfig = filterConfig; 15 | } 16 | @Override 17 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 18 | servletResponse.setCharacterEncoding("UTF-8"); 19 | servletResponse.setContentType("text/html; charset=UTF-8"); 20 | servletRequest.setCharacterEncoding("UTF-8"); 21 | servletRequest.setAttribute("from-charset-filter", "Charset filter works!!"); 22 | filterChain.doFilter(servletRequest, servletResponse); 23 | } 24 | public void destroy() { 25 | filterConfig = null; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Input.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Input { 5 | public static void main(String[] args) throws IOException { 6 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 7 | String line; 8 | while ((line = in.readLine()) != null) { 9 | System.out.println(line); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/InputStream.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class InputStream{ 4 | public static void main(String args[]){ 5 | double principalAmount=0.0; 6 | double rateOfInterest=0.0; 7 | int numberOfYears=0; 8 | try { 9 | DataInputStream in =new DataInputStream(System.in); 10 | String tempString; 11 | System.out.print("Enter Principal Amount: "); 12 | System.out.flush(); 13 | tempString = in.readLine(); 14 | principalAmount = Float.valueOf(tempString); 15 | System.out.print("Enter Rate of Interest: "); 16 | 17 | System.out.flush(); 18 | tempString=in.readLine(); 19 | rateOfInterest = Float.valueOf(tempString); 20 | System.out.println("Enter Number of Years:"); 21 | System.out.flush(); 22 | 23 | tempString=in.readLine(); 24 | numberOfYears = Integer.parseInt(tempString); 25 | } 26 | catch(Exception e){ 27 | System.out.println("Exception: "+e.getMessage()); 28 | } 29 | //Input is over: calculate the Interest) 30 | double interestTotal = principalAmount*rateOfInterest*numberOfYears; 31 | System.out.println("Total Interest= " +interestTotal); 32 | } 33 | } -------------------------------------------------------------------------------- /Java/JavaStringBufferDelete.java: -------------------------------------------------------------------------------- 1 | public class JavaStringBufferDelete { public static void main(String[] args) { 2 | /* 3 | Java StringBuffer class following methods to delete / remove characters or claring the contents of a StringBuffer object. 4 | */ 5 | /* 6 | StringBuffer delete(int start, int end) remove the characters from start index to an end-1 index provided. 7 | This method can throw a StringIndexOutOfBoundException if the start index is invalid. 8 | */ 9 | StringBuffer sb1 = new StringBuffer("Hello World"); sb1.delete(0,6); 10 | System.out.println(sb1); 11 | /* 12 | To clear contents of a StringBuffer use delete(int start, int end) method in the below given way 13 | */ 14 | StringBuffer sb2 = new StringBuffer("Some Content"); System.out.println(sb2); 15 | sb2.delete(0, sb2.length()); System.out.println(sb2); 16 | /* 17 | StringBuffer deleteCharAt(int index) deletes the character at specified index. 18 | This method throws StringIndexOutOfBoundException if index is negative or grater than or equal to the length. 19 | */ 20 | StringBuffer sb3 = new StringBuffer("Hello World"); sb3.deleteCharAt(0); 21 | System.out.println(sb3); 22 | } 23 | } -------------------------------------------------------------------------------- /Java/MultipleClass.java: -------------------------------------------------------------------------------- 1 | class Circle{ 2 | double x,y; 3 | double r; 4 | double circumference(){ 5 | return 2*3.14159*r; 6 | } 7 | double area(){ 8 | return (22/7)*r*r; 9 | } 10 | } 11 | //Another Class Declaration 12 | class Box{ 13 | double width; 14 | double height; 15 | double depth; 16 | double area(){ 17 | double a; 18 | a=(width*height+height*depth+depth*width)*2; 19 | return a; 20 | } 21 | double volume(){ 22 | double vol; 23 | vol=width*height*depth; 24 | return vol; 25 | } 26 | } 27 | 28 | //declaring objects of type Circle and Box 29 | 30 | class MultipleClass{ 31 | public static void main(String args[]){ 32 | Circle c=new Circle(); 33 | Box b=new Box(); 34 | //Initializing the Circle 35 | c.x=3.0; 36 | c.y=4.0; 37 | c.r=5.0; 38 | //Initializing the Box 39 | b.width=3.0; 40 | b.height=4.0; 41 | b.depth=5.0; 42 | System.out.println("Circumference of circle" +c.circumference()); 43 | System.out.println("Area of Circle" +c.area()); 44 | System.out.println("Area of The Box" +b.area()); 45 | System.out.println("Volume of the Box" +b.volume()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Java/MultipleObj.java: -------------------------------------------------------------------------------- 1 | class Circle{ 2 | double x,y; //the Circumference of the center 3 | double r; //the radius 4 | 5 | //Methods that return circumference 6 | double circumference(){ 7 | return 2*3.14159*r; 8 | } 9 | //Method that return area 10 | double area(){ 11 | return (22/7)*r*r; 12 | } 13 | } 14 | //Declaring object of the Circle class 15 | class MultipleObj{ 16 | public static void main(String args[]){ 17 | Circle c1=new Circle(); 18 | Circle c2=new Circle(); 19 | //Initialize the circle 20 | 21 | c1.x=0.0; 22 | c1.y=3.0; 23 | c1.r=5.0; 24 | c2.x=7.0; 25 | c2.y=8.0; 26 | c2.r=4.0; 27 | System.out.println("Circumference circle1" +c1.circumference()); 28 | System.out.println("Area circle1"+ c1.area()); 29 | System.out.println("Circumference circle2" +c2.circumference()); 30 | System.out.println("Area circle2"+ c2.area()); 31 | } 32 | } -------------------------------------------------------------------------------- /Java/MyMergeSort.java: -------------------------------------------------------------------------------- 1 | public class MyMergeSort 2 | { 3 | void merge(int arr[], int beg, int mid, int end) 4 | { 5 | int l = mid - beg + 1; 6 | int r = end - mid; 7 | int LeftArray[] = new int [l]; 8 | int RightArray[] = new int [r]; 9 | for (int i=0; i= 0; i--) { 19 | rightMax[i] = Math.max(height[i], rightMax[i + 1]); 20 | } 21 | 22 | int trappedWater = 0; 23 | // loop 24 | for (int i = 0; i < n; i++) { 25 | // calculate water level= min(leftmax bound. leftmax bound) 26 | int waterLevel = Math.min(leftMax[i], rightMax[i]); 27 | // calclate water trapped= waterlevel - height[i] 28 | trappedWater += waterLevel - height[i]; 29 | 30 | } 31 | return trappedWater; 32 | } 33 | 34 | public static void main(String args[]) { 35 | int height[] = {0,1,0,2,1,0,1,3,2,1,2,1}; 36 | System.out.println("Water trapped between the bars = " + trappedRainwater(height)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Java/getMinimumUniqueSum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.function.*; 8 | import java.util.regex.*; 9 | import java.util.stream.*; 10 | import static java.util.stream.Collectors.joining; 11 | import static java.util.stream.Collectors.toList; 12 | 13 | 14 | 15 | class Result { 16 | 17 | /* 18 | * Complete the 'getMinimumUniqueSum' function below. 19 | * 20 | * The function is expected to return an INTEGER. 21 | * The function accepts INTEGER_ARRAY arr as parameter. 22 | */ 23 | 24 | public static int getMinimumUniqueSum(List arr) { 25 | // Write your code here 26 | if(arr.size()==0) 27 | return 0; 28 | Collections.sort(arr); // sort the array list 29 | 30 | int sum=0; 31 | 32 | // Update the array list 33 | for(int i=1;i arr = IntStream.range(0, arrCount).mapToObj(i -> { 55 | try { 56 | return bufferedReader.readLine().replaceAll("\\s+$", ""); 57 | } catch (IOException ex) { 58 | throw new RuntimeException(ex); 59 | } 60 | }) 61 | .map(String::trim) 62 | .map(Integer::parseInt) 63 | .collect(toList()); 64 | 65 | int result = Result.getMinimumUniqueSum(arr); 66 | 67 | bufferedWriter.write(String.valueOf(result)); 68 | bufferedWriter.newLine(); 69 | 70 | bufferedReader.close(); 71 | bufferedWriter.close(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Java/height_of_binary_tree.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022, 2 | // All rights reserved 3 | // Note: Driver code is taken from GFG. heightDp function is written by me in Solution Class. 4 | 5 | //{ Driver Code Starts 6 | //Initial Template for Java 7 | 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | import java.io.*; 11 | import java.util.*; 12 | import java.lang.*; 13 | 14 | class Node{ 15 | int data; 16 | Node left; 17 | Node right; 18 | Node(int data){ 19 | this.data = data; 20 | left=null; 21 | right=null; 22 | } 23 | } 24 | 25 | class GFG { 26 | 27 | static Node buildTree(String str){ 28 | 29 | if(str.length()==0 || str.charAt(0)=='N'){ 30 | return null; 31 | } 32 | 33 | String ip[] = str.split(" "); 34 | // Create the root of the tree 35 | Node root = new Node(Integer.parseInt(ip[0])); 36 | // Push the root to the queue 37 | 38 | Queue queue = new LinkedList<>(); 39 | 40 | queue.add(root); 41 | // Starting from the second element 42 | 43 | int i = 1; 44 | while(queue.size()>0 && i < ip.length) { 45 | 46 | // Get and remove the front of the queue 47 | Node currNode = queue.peek(); 48 | queue.remove(); 49 | 50 | // Get the current node's value from the string 51 | String currVal = ip[i]; 52 | 53 | // If the left child is not null 54 | if(!currVal.equals("N")) { 55 | 56 | // Create the left child for the current node 57 | currNode.left = new Node(Integer.parseInt(currVal)); 58 | // Push it to the queue 59 | queue.add(currNode.left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.length) 65 | break; 66 | 67 | currVal = ip[i]; 68 | 69 | // If the right child is not null 70 | if(!currVal.equals("N")) { 71 | 72 | // Create the right child for the current node 73 | currNode.right = new Node(Integer.parseInt(currVal)); 74 | 75 | // Push it to the queue 76 | queue.add(currNode.right); 77 | } 78 | i++; 79 | } 80 | 81 | return root; 82 | } 83 | static void printInorder(Node root){ 84 | if(root == null) 85 | return; 86 | 87 | printInorder(root.left); 88 | System.out.print(root.data+" "); 89 | 90 | printInorder(root.right); 91 | } 92 | 93 | public static void main (String[] args) throws IOException{ 94 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 95 | int t=Integer.parseInt(br.readLine()); 96 | 97 | while(t > 0){ 98 | String s = br.readLine(); 99 | Node root = buildTree(s); 100 | 101 | Solution ob = new Solution(); 102 | System.out.println(ob.height(root)); 103 | t--; 104 | } 105 | } 106 | } 107 | // } Driver Code Ends 108 | 109 | 110 | //User function Template for Java 111 | 112 | /* 113 | class Node 114 | { 115 | int data; 116 | Node left, right; 117 | 118 | Node(int item) 119 | { 120 | data = item; 121 | left = right = null; 122 | } 123 | } 124 | */ 125 | 126 | 127 | 128 | class Solution { 129 | //Function to find the height of a binary tree. 130 | int heightDp(Node node){ 131 | if(node==null) return 0; 132 | int left_height = heightDp(node.left); 133 | int right_height = heightDp(node.right); 134 | 135 | int temp = 1+ Math.max(left_height, right_height); 136 | return temp; 137 | } 138 | int height(Node node) 139 | { 140 | // code here 141 | return heightDp(node); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /Java/linear-search.java: -------------------------------------------------------------------------------- 1 | public class LinearSearchExample{ 2 | public static int linearSearch(int[] arr, int key){ 3 | for(int i=0;i W: 26 | t[n][W] = knapsack(wt, val, W, n-1) 27 | return t[n][W] 28 | 29 | 30 | print(knapsack(wt, val, W, n)) 31 | -------------------------------------------------------------------------------- /Python/Scraping_IMDB_Top_1000/README.md: -------------------------------------------------------------------------------- 1 | # IMDB 2 | 3 | IMDb is an online database of information related to films, television programs, home videos and video games, and internet streams, including cast, production crew and personnel biographies, plot summaries, trivia, and fan reviews and ratings. 4 | [IMDB](https://www.imdb.com/search/title/?groups=top_1000&sort=user_rating,desc&count=100&start=001&ref_=adv_nxt) 5 | 6 | ## About this project 7 | Find the details of IMDb "Top 1000" (Sorted by IMDb Rating Descending) all here on a 'Output.csv' file. 8 | 9 | ## Importing libraries 10 | 11 | import requests\ 12 | import re\ 13 | from bs4 import BeautifulSoup\ 14 | import pandas as pd -------------------------------------------------------------------------------- /Python/Scraping_IMDB_Top_1000/SCRAPE.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import re 3 | from bs4 import BeautifulSoup 4 | import pandas as pd 5 | # base_url = requests.get( 6 | # 'https://www.imdb.com/search/title/?groups=top_1000&sort=user_rating,desc&count=100&start=001&ref_=adv_nxt') 7 | # c = base_url.content 8 | # # print(c) 9 | 10 | # soup = BeautifulSoup(base_url.text, 'html.parser') 11 | 12 | # all = soup.find("div", {"class": "lister-item mode-advanced"}) 13 | # print(all.find("h3", {"class": "lister-item-header"} 14 | # ).find("a").get_text(strip=True)) 15 | # # # print(all) 16 | # print(all.find("h3", {"class": "lister-item-header"}).find("span", 17 | # "lister-item-year text-muted unbold").get_text(strip=True)) 18 | # c=all.find_all("p", {"class": "text-muted"}) 19 | # print(c) 20 | # print(c[1].get_text(strip=True)) 21 | # print(c[0].find("span", "certificate").get_text(strip=True)) 22 | # print(c[0].find("span", "runtime").get_text(strip=True)) 23 | # print(c[0].find("span", "genre").get_text(strip=True)) 24 | # print(all.find("p", {"class": ""}).get_text(strip=True)) 25 | # a =all.find("p", {"class": "sort-num_votes-visible"}) 26 | # print(a) 27 | # b=a.find_all("span",{"name": "nv"}) 28 | # print(b[0].text) 29 | # print(b[1].text) 30 | # print(all.find("div", {"class": "inline-block ratings-imdb-rating"}).get_text(strip=True)) 31 | # print(all.find("div", {"class": "inline-block ratings-metascore"}).find("span").get_text(strip=True)) 32 | 33 | l = [] 34 | for i in range(10): 35 | # print("https://www.imdb.com/search/title/?groups=top_1000&sort=user_rating,desc&count=100&start="+i+"01&ref_=adv_nxt") 36 | web_url = requests.get( 37 | "https://www.imdb.com/search/title/?groups=top_1000&sort=user_rating,desc&count=100&start="+f"{i}"+"01&ref_=adv_nxt").text 38 | soup = BeautifulSoup(web_url, 'html.parser') 39 | all = soup.find_all("div", {"class": "lister-item mode-advanced"}) 40 | for item in all: 41 | d = {} 42 | try: 43 | d["TITLE"] = (item.find( 44 | "h3", {"class": "lister-item-header"}).find("a").get_text(strip=True)) 45 | except: 46 | d["TITLE"] = "Not mentioned" 47 | try: 48 | d["RELEASE YEAR"] = re.sub("[^0-9]", "", item.find("h3", {"class": "lister-item-header"}).find( 49 | "span", "lister-item-year text-muted unbold").get_text(strip=True).replace('(', '').replace(')', '')) 50 | except: 51 | d["RELEASE YEAR"] = "Not mentioned" 52 | c = item.find_all("p", {"class": "text-muted"}) 53 | try: 54 | d["CERTIFICATE"] = c[0].find( 55 | "span", "certificate").get_text(strip=True) 56 | except: 57 | d["CERTIFICATE"] = "Not mentioned" 58 | try: 59 | d["RUNTIME"] = c[0].find("span", "runtime").get_text(strip=True) 60 | except: 61 | d["RUNTIME"] = "Not mentioned" 62 | try: 63 | d["GENRE"] = c[0].find("span", "genre").get_text(strip=True) 64 | except: 65 | d["GENRE"] = "Not mentioned" 66 | try: 67 | d["IMDB RATING"] = item.find( 68 | "div", {"class": "inline-block ratings-imdb-rating"}).get_text(strip=True) 69 | except: 70 | d["IMDB RATING"] = "Not mentioned" 71 | try: 72 | d["METASCORE"] = item.find( 73 | "div", {"class": "inline-block ratings-metascore"}).find("span").get_text(strip=True) 74 | except: 75 | d["METASCORE"] = "Not mentioned" 76 | try: 77 | d["DESCRIPTION"] = c[1].get_text(strip=True) 78 | except: 79 | d["DESCRIPTION"] = "Not mentioned" 80 | try: 81 | d["FILM CREW"] = item.find("p", {"class": ""}).get_text(strip=True) 82 | except: 83 | d["FILM CREW"] = "Not mentioned" 84 | a = item.find("p", {"class": "sort-num_votes-visible"} 85 | ).find_all("span", {"name": "nv"}) 86 | try: 87 | d["VOTES"] = a[0].get_text(strip=True) 88 | except: 89 | d["VOTES"] = "Not mentioned" 90 | try: 91 | d["GROSS"] = a[1].get_text(strip=True) 92 | except: 93 | d["GROSS"] = "Not mentioned" 94 | l.append(d) 95 | df = pd.DataFrame(l) 96 | df.to_csv("Output.csv") 97 | -------------------------------------------------------------------------------- /Python/dot-animate.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | from math import cos, sin, sqrt 4 | from random import randrange 5 | 6 | import pygame 7 | 8 | WIDTH = 800 9 | HEIGHT = 800 10 | CENTER = WIDTH // 2, HEIGHT // 2 11 | centerX = WIDTH // 2 12 | centerY = HEIGHT // 2 13 | 14 | G = 0.2 15 | M = 10e7 16 | 17 | BLACK = (0, 0, 0) 18 | WHITE = (255, 255, 255) 19 | 20 | r0 = 10 21 | 22 | pygame.init() 23 | 24 | 25 | class Particle: 26 | def __init__(self, x, y): 27 | self.g = G 28 | self.mass = 2 29 | self.x = x 30 | self.y = y 31 | self.momentum_x = 500 32 | self.momentum_y = 500 33 | self.dt = 0.001 34 | 35 | def move(self, x_y_central_mass): 36 | x2 = x_y_central_mass[0] 37 | y2 = x_y_central_mass[1] 38 | hyp = (self.x - x2) ** 2 + (self.y - y2) ** 2 39 | theta = math.atan2(y2 - self.y, x2 - self.x) 40 | force = (self.g * self.mass * M) / hyp 41 | force_x = force * math.cos(theta) 42 | force_y = force * math.sin(theta) 43 | self.momentum_x += force_x * self.dt 44 | self.momentum_y += force_y * self.dt 45 | self.x += self.momentum_x / self.mass * self.dt 46 | self.y += self.momentum_y / self.mass * self.dt 47 | return [self.x, self.y] 48 | 49 | 50 | screen = pygame.display.set_mode((WIDTH, HEIGHT)) 51 | 52 | particles = [] 53 | 54 | r = 200 55 | 56 | 57 | # Line 58 | def generator(): 59 | for i in range(1000): 60 | x = randrange(-500, 1000) 61 | y = 100 62 | p = Particle(x, y) 63 | particles.append(p) 64 | 65 | 66 | # Circle 67 | # def generator(): 68 | # for i in range(1000): 69 | # ang = random.uniform(0, 1) * 2 * math.pi 70 | # hyp = sqrt(random.uniform(0, 1)) * r 71 | # adj = cos(ang) * hyp 72 | # opp = sin(ang) * hyp 73 | # x = centerX + adj 74 | # y = centerY + opp 75 | # p = Particle(x, y) 76 | # particles.append(p) 77 | 78 | 79 | # Square 80 | # def generator(): 81 | # for i in range(500): 82 | # x = randrange(0, 500) 83 | # y = randrange(0, 500) 84 | # p = Particle(x, y) 85 | # particles.append(p) 86 | 87 | 88 | generator() 89 | 90 | 91 | def draw(): 92 | for i in range(len(particles)): 93 | pygame.draw.circle(screen, WHITE, (particles[i].move(CENTER)), 1) 94 | 95 | 96 | running = True 97 | while running: 98 | 99 | for event in pygame.event.get(): 100 | if event.type == pygame.QUIT: 101 | running = False 102 | 103 | screen.fill(BLACK) 104 | 105 | # Gravity point 106 | # central_mass = pygame.draw.circle(screen, WHITE, CENTER, r0) 107 | 108 | draw() 109 | 110 | pygame.display.update() 111 | -------------------------------------------------------------------------------- /Python/pingpong/Instructions.txt: -------------------------------------------------------------------------------- 1 | 1.Download all 3 files 2 | 2.Make sure you have python installed on your computer 3 | 3.Execute "main.py" file -------------------------------------------------------------------------------- /Python/pingpong/ball.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[ ]: 5 | 6 | # class to create and manage ball 7 | import pygame 8 | from random import randint 9 | 10 | BLACK = (0,0,0) 11 | 12 | class Ball(pygame.sprite.Sprite): 13 | #This class represents a ball. It derives from the "Sprite" class in Pygame. 14 | 15 | def __init__(self, color, width, height): 16 | # Call the parent class (Sprite) constructor 17 | super().__init__() 18 | 19 | # Pass in the color of the ball, its width and height. 20 | # Set the background color and set it to be transparent 21 | self.image = pygame.Surface([width, height]) 22 | self.image.fill(BLACK) 23 | self.image.set_colorkey(BLACK) 24 | 25 | # Draw the ball (a rectangle!) 26 | pygame.draw.circle(self.image, color, [0, 0, width, height]) 27 | 28 | self.velocity = [randint(4,8),randint(-8,8)] 29 | 30 | # Fetch the rectangle object that has the dimensions of the image. 31 | self.rect = self.image.get_rect() 32 | 33 | def update(self): 34 | self.rect.x += self.velocity[0] 35 | self.rect.y += self.velocity[1] 36 | 37 | def bounce(self): 38 | self.velocity[0] = -self.velocity[0] 39 | self.velocity[1] = randint(-8,8) 40 | 41 | -------------------------------------------------------------------------------- /Python/pingpong/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[ ]: 5 | 6 | # driver code containing background, paddles, ball and scores 7 | # Import the pygame library and initialise the game engine 8 | import pygame 9 | from paddle import Paddle 10 | from ball import Ball 11 | 12 | pygame.init() 13 | 14 | # Define some colors 15 | BLACK = (0,0,0) 16 | WHITE = (255,255,255) 17 | 18 | # Open a new window 19 | size = (1280, 720) 20 | screen = pygame.display.set_mode(size) 21 | pygame.display.set_caption("Pong") 22 | 23 | paddleA = Paddle(WHITE, 10, 100) 24 | paddleA.rect.x = 20 25 | paddleA.rect.y = 360 26 | 27 | paddleB = Paddle(WHITE, 10, 100) 28 | paddleB.rect.x = 1250 29 | paddleB.rect.y = 360 30 | 31 | ball = Ball(WHITE,10,10) 32 | ball.rect.x = 345 33 | ball.rect.y = 195 34 | 35 | #This will be a list that will contain all the sprites we intend to use in our game. 36 | all_sprites_list = pygame.sprite.Group() 37 | 38 | # Add the car to the list of objects 39 | all_sprites_list.add(paddleA) 40 | all_sprites_list.add(paddleB) 41 | all_sprites_list.add(ball) 42 | 43 | # The loop will carry on until the user exit the game (e.g. clicks the close button). 44 | carryOn = True 45 | 46 | # The clock will be used to control how fast the screen updates 47 | clock = pygame.time.Clock() 48 | 49 | #Initialise player scores 50 | scoreA = 0 51 | scoreB = 0 52 | 53 | # -------- Main Program Loop ----------- 54 | while carryOn: 55 | # --- Main event loop 56 | for event in pygame.event.get(): # User did something 57 | if event.type == pygame.QUIT: # If user clicked close 58 | carryOn = False # Flag that we are done so we exit this loop 59 | elif event.type==pygame.KEYDOWN: 60 | if event.key==pygame.K_x: #Pressing the x Key will quit the game 61 | carryOn=False 62 | 63 | #Moving the paddles when the use uses the arrow keys (player A) or "W/S" keys (player B) 64 | keys = pygame.key.get_pressed() 65 | if keys[pygame.K_w]: 66 | paddleA.moveUp(5) 67 | if keys[pygame.K_s]: 68 | paddleA.moveDown(5) 69 | if keys[pygame.K_UP]: 70 | paddleB.moveUp(5) 71 | if keys[pygame.K_DOWN]: 72 | paddleB.moveDown(5) 73 | 74 | # --- Game logic should go here 75 | all_sprites_list.update() 76 | 77 | #Check if the ball is bouncing against any of the 4 walls: 78 | if ball.rect.x>=1270: 79 | scoreA+=1 80 | ball.velocity[0] = -ball.velocity[0] 81 | if ball.rect.x<=0: 82 | scoreB+=1 83 | ball.velocity[0] = -ball.velocity[0] 84 | if ball.rect.y>710: 85 | ball.velocity[1] = -ball.velocity[1] 86 | if ball.rect.y<0: 87 | ball.velocity[1] = -ball.velocity[1] 88 | 89 | #Detect collisions between the ball and the paddles 90 | if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB): 91 | ball.bounce() 92 | 93 | # --- Drawing code should go here 94 | # First, clear the screen to black. 95 | screen.fill(BLACK) 96 | #Draw the net 97 | pygame.draw.line(screen, WHITE, [639, 0], [639, 720], 5) 98 | 99 | #Now let's draw all the sprites in one go. (For now we only have 2 sprites!) 100 | all_sprites_list.draw(screen) 101 | 102 | #Display scores: 103 | font = pygame.font.Font(None, 74) 104 | text = font.render(str(scoreA), 1, WHITE) 105 | screen.blit(text, (457,10)) 106 | text = font.render(str(scoreB), 1, WHITE) 107 | screen.blit(text, (768,10)) 108 | 109 | # --- Go ahead and update the screen with what we've drawn. 110 | pygame.display.flip() 111 | 112 | # --- Limit to 60 frames per second 113 | clock.tick(60) 114 | 115 | #Once we have exited the main program loop we can stop the game engine: 116 | pygame.quit() 117 | 118 | -------------------------------------------------------------------------------- /Python/pingpong/paddle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[ ]: 5 | 6 | # class to create and manage paddles 7 | import pygame 8 | BLACK = (0,0,0) 9 | 10 | class Paddle(pygame.sprite.Sprite): 11 | #This class represents a paddle. It derives from the "Sprite" class in Pygame. 12 | 13 | def __init__(self, color, width, height): 14 | # Call the parent class (Sprite) constructor 15 | super().__init__() 16 | 17 | # Pass in the color of the paddle, and its x and y position, width and height. 18 | # Set the background color and set it to be transparent 19 | self.image = pygame.Surface([width, height]) 20 | self.image.fill(BLACK) 21 | self.image.set_colorkey(BLACK) 22 | 23 | # Draw the paddle (a rectangle!) 24 | pygame.draw.rect(self.image, color, [0, 0, width, height]) 25 | 26 | # Fetch the rectangle object that has the dimensions of the image. 27 | self.rect = self.image.get_rect() 28 | 29 | def moveUp(self, pixels): 30 | self.rect.y -= pixels 31 | #Check that you are not going too far (off the screen) 32 | if self.rect.y < 0: 33 | self.rect.y = 0 34 | 35 | def moveDown(self, pixels): 36 | self.rect.y += pixels 37 | #Check that you are not going too far (off the screen) 38 | if self.rect.y > 620: 39 | self.rect.y = 620 40 | 41 | -------------------------------------------------------------------------------- /Python/wordsubset.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: 3 | 4 | target = {} 5 | for targetWord in words2: 6 | toAdd = {} 7 | for letter in targetWord: 8 | if letter not in toAdd: 9 | toAdd[letter] = 1 10 | else: 11 | toAdd[letter] += 1 12 | 13 | for letter, occur in toAdd.items(): 14 | if letter in target: 15 | target[letter] = max(occur, target[letter]) 16 | else: 17 | target[letter] = occur 18 | 19 | ret = [] 20 | for a in words1: 21 | toInclude = True 22 | for key in target: 23 | if a.count(key) < target[key]: 24 | toInclude = False 25 | break 26 | if toInclude: 27 | ret.append(a) 28 | return ret 29 | 30 | 31 | -------------------------------------------------------------------------------- /passwordManagerProject.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import messagebox 3 | from random import choice, randint, shuffle 4 | import pyperclip 5 | import json 6 | 7 | 8 | # ---------------------------- PASSWORD GENERATOR ------------------------------- # 9 | 10 | def generate_password(): 11 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 12 | 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 13 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 14 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 15 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 16 | 17 | password_letters = [choice(letters) for _ in range(randint(8, 10))] 18 | password_symbols = [choice(symbols) for _ in range(randint(2, 4))] 19 | password_numbers = [choice(numbers) for _ in range(randint(2, 4))] 20 | 21 | password_list = password_letters + password_symbols + password_numbers 22 | shuffle(password_list) 23 | 24 | password = "".join(password_list) 25 | password_entry.insert(0, password) 26 | pyperclip.copy(password) 27 | 28 | 29 | # ---------------------------- SEARCH WEBSITES ------------------------------- # 30 | def find(): 31 | web = web_entry.get() 32 | try: 33 | with open("passwords.json", "r") as pass_file: 34 | data = json.load(pass_file) 35 | except FileNotFoundError: 36 | messagebox.showinfo(title="Error", message="No such file exist") 37 | 38 | else: 39 | if web in data: 40 | email1 = data[web]["Email"] 41 | password1 = data[web]["Password"] 42 | messagebox.showinfo(title=web, message=f"Email:{email1}\nPassword:{password1}") 43 | else: 44 | messagebox.showinfo(title="Error", message=f"There is no data available for {web} please add required data") 45 | 46 | 47 | # ---------------------------- SAVE PASSWORD ------------------------------- # 48 | def save(): 49 | web = web_entry.get() 50 | em = email_entry.get() 51 | pa = password_entry.get() 52 | new_data = { 53 | web: { 54 | "Email": em, 55 | "Password": pa, 56 | } 57 | } 58 | if len(web) == 0 or len(pa) == 0: 59 | messagebox.showinfo(title="Empty Field", message="Please enter valid entries.") 60 | else: 61 | try: 62 | with open("passwords.json", "r") as pass_file: 63 | data = json.load(pass_file) 64 | except FileNotFoundError: 65 | with open("passwords.json", "w") as pass_file: 66 | json.dump(new_data, pass_file, indent=4) 67 | else: 68 | data.update(new_data) 69 | with open("passwords.json", "w") as pass_file: 70 | json.dump(data, pass_file, indent=4) 71 | finally: 72 | web_entry.delete(0, END) 73 | password_entry.delete(0, END) 74 | 75 | 76 | # ---------------------------- UI SETUP ------------------------------- # 77 | 78 | window = Tk() 79 | window.title("Password manager") 80 | window.config(padx=50, pady=50) 81 | 82 | canvas = Canvas(height=200, width=200); 83 | logo = PhotoImage(file="logo.png") 84 | canvas.create_image(100, 100, image=logo) 85 | canvas.grid(row=0, column=1) 86 | 87 | # Labels 88 | website = Label(text="Website:") 89 | website.grid(row=1, column=0) 90 | email = Label(text="Email:") 91 | email.grid(row=2, column=0) 92 | password = Label(text="Password:") 93 | password.grid(row=3, column=0) 94 | 95 | # Entries 96 | web_entry = Entry(width=21) 97 | web_entry.grid(row=1, column=1) 98 | web_entry.focus() 99 | email_entry = Entry(width=39) 100 | email_entry.grid(row=2, column=1, columnspan=2) 101 | email_entry.insert(0, "akshayverma887462gmail.com") 102 | password_entry = Entry(width=21) 103 | password_entry.grid(row=3, column=1) 104 | 105 | # Buttons 106 | search = Button(text="Search", width=13, command=find) 107 | search.grid(row=1, column=2) 108 | generate = Button(text="Generate Password", command=generate_password) 109 | generate.grid(row=3, column=2) 110 | add = Button(text="Add", width=36, command=save) 111 | add.grid(row=4, column=1, columnspan=2) 112 | window.mainloop() 113 | --------------------------------------------------------------------------------