From 2ad188e48ff57e2324d2b00bb460edb4e20ccb2f Mon Sep 17 00:00:00 2001 From: Shubham Kumar Singh <81859951+Shubh-k04@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:03:46 +0530 Subject: [PATCH 01/24] Create Level order traversal For a given a Binary Tree of type integer, print it in a level order fashion where each level will be printed on a new line. Elements on every level will be printed in a linear fashion and a single space will separate them. --- Level order traversal | 125 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Level order traversal diff --git a/Level order traversal b/Level order traversal new file mode 100644 index 0000000..bcd7d67 --- /dev/null +++ b/Level order traversal @@ -0,0 +1,125 @@ +""" +Level order traversal +Send Feedback +For a given a Binary Tree of type integer, print it in a level order fashion where each level will be printed on a new line. +Elements on every level will be printed in a linear fashion and a single space will separate them. +""" +from sys import stdin, setrecursionlimit +import queue + +setrecursionlimit(10 ** 6) + + +#Following is the structure used to represent the Binary Tree Node +class BinaryTreeNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def printLevelWise(root): + #Your code goes here + if root is None : + return + + pendingNodes = queue.Queue() + pendingNodes.put(root) + pendingNodes.put(None) + + while not pendingNodes.empty(): + frontNode = pendingNodes.get() + + if frontNode is None : + print() + + if not pendingNodes.empty() : + pendingNodes.put(None) + + else : + print(frontNode.data, end = " ") + + if frontNode.left is not None : + pendingNodes.put(frontNode.left) + + + if frontNode.right is not None : + pendingNodes.put(frontNode.right) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#Taking level-order input using fast I/O method +def takeInput(): + levelOrder = list(map(int, stdin.readline().strip().split(" "))) + start = 0 + + length = len(levelOrder) + + if length == 1 : + return None + + root = BinaryTreeNode(levelOrder[start]) + start += 1 + + q = queue.Queue() + q.put(root) + + while not q.empty(): + currentNode = q.get() + + leftChild = levelOrder[start] + start += 1 + + if leftChild != -1: + leftNode = BinaryTreeNode(leftChild) + currentNode.left =leftNode + q.put(leftNode) + + rightChild = levelOrder[start] + start += 1 + + if rightChild != -1: + rightNode = BinaryTreeNode(rightChild) + currentNode.right =rightNode + q.put(rightNode) + + return root + + +# Main +root = takeInput() +printLevelWise(root) From 19ed1889b1524085f14278fd251bd97d94a6264e Mon Sep 17 00:00:00 2001 From: Shubham Kumar Singh <81859951+Shubh-k04@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:04:35 +0530 Subject: [PATCH 02/24] Create Nodes At Depth k Print all the nodes at depth k in a binary tree --- Nodes At Depth k | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Nodes At Depth k diff --git a/Nodes At Depth k b/Nodes At Depth k new file mode 100644 index 0000000..187221d --- /dev/null +++ b/Nodes At Depth k @@ -0,0 +1,49 @@ +class BinaryTreeNode: + def __init__(self,data): + self.data = data + self.left = None + self.right = None +def treeInput(): + rootData = int(input()) + if rootData == -1: + return None + root = BinaryTreeNode(rootData) + leftTree = treeInput() + rightTree = treeInput() + root.left = leftTree + root.right = rightTree + return root + +def PrintTree(root): + if root == None: + return + print(root.data,end= ":") + if root.left is not None: + print("L", root.left.data, end = ",") + if root.right is not None: + print("R", root.right.data, end = "") + print() + PrintTree(root.left) + PrintTree(root.right) +#Approach 1 +def PrintDepthK(root,k): + if root is None: + return + if k == 0: + print(root.data) + return + PrintDepthK(root.left,k-1) + PrintDepthK(root.right,k-1) +#Approach 2 +def PrintDepthKv2(root,k,d = 0): + if root is None: + return + if k == d: + print(root.data) + return + PrintDepthKv2(root.left,k,d+1) + PrintDepthKv2(root.right,k,d+1) + +root = treeInput() +PrintTree(root) +PrintDepthKv2(root,2) From c112241f5cedcf359360230648650dbf4a2491ad Mon Sep 17 00:00:00 2001 From: Shubham Kumar Singh <81859951+Shubh-k04@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:11:56 +0530 Subject: [PATCH 03/24] Rename Nodes At Depth k to NodesAtDepthK.py --- Nodes At Depth k => NodesAtDepthK.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Nodes At Depth k => NodesAtDepthK.py (100%) diff --git a/Nodes At Depth k b/NodesAtDepthK.py similarity index 100% rename from Nodes At Depth k rename to NodesAtDepthK.py From 1948d6dad915c0ae9b12e28c1cbda364daa6350f Mon Sep 17 00:00:00 2001 From: Shubham Kumar Singh <81859951+Shubh-k04@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:12:32 +0530 Subject: [PATCH 04/24] Rename Level order traversal to LevelOrderTraversal.py --- Level order traversal => LevelOrderTraversal.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Level order traversal => LevelOrderTraversal.py (100%) diff --git a/Level order traversal b/LevelOrderTraversal.py similarity index 100% rename from Level order traversal rename to LevelOrderTraversal.py From 3e36a077b3c05616e82f3724b8d661373d60ada9 Mon Sep 17 00:00:00 2001 From: Suhasinimodi <75732986+suhasinimodi@users.noreply.github.com> Date: Mon, 17 Oct 2022 22:40:11 +0530 Subject: [PATCH 05/24] Create suhasini_modi.c --- suhasini_modi.c | 135 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 suhasini_modi.c diff --git a/suhasini_modi.c b/suhasini_modi.c new file mode 100644 index 0000000..4ff2033 --- /dev/null +++ b/suhasini_modi.c @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +#define SIZE 20 + +struct DataItem { + int data; + int key; +}; + +struct DataItem* hashArray[SIZE]; +struct DataItem* dummyItem; +struct DataItem* item; + +int hashCode(int key) { + return key % SIZE; +} + +struct DataItem *search(int key) { + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void insert(int key,int data) { + + struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty or deleted cell + while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} + +struct DataItem* delete(struct DataItem* item) { + int key = item->key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + //assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void display() { + int i = 0; + + for(i = 0; ikey,hashArray[i]->data); + else + printf(" ~~ "); + } + + printf("\n"); +} + +int main() { + dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); + dummyItem->data = -1; + dummyItem->key = -1; + + insert(1, 20); + insert(2, 70); + insert(42, 80); + insert(4, 25); + insert(12, 44); + insert(14, 32); + insert(17, 11); + insert(13, 78); + insert(37, 97); + + display(); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } + + delete(item); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } +} From fabe13de9e4e039b6b887526cc8dfea7a07aeb84 Mon Sep 17 00:00:00 2001 From: Samadreeta Mukherjee <105774222+samadreeta001@users.noreply.github.com> Date: Mon, 17 Oct 2022 22:41:27 +0530 Subject: [PATCH 06/24] Create saam.c --- saam.c | 135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 saam.c diff --git a/saam.c b/saam.c new file mode 100644 index 0000000..4ff2033 --- /dev/null +++ b/saam.c @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +#define SIZE 20 + +struct DataItem { + int data; + int key; +}; + +struct DataItem* hashArray[SIZE]; +struct DataItem* dummyItem; +struct DataItem* item; + +int hashCode(int key) { + return key % SIZE; +} + +struct DataItem *search(int key) { + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void insert(int key,int data) { + + struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty or deleted cell + while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} + +struct DataItem* delete(struct DataItem* item) { + int key = item->key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + //assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void display() { + int i = 0; + + for(i = 0; ikey,hashArray[i]->data); + else + printf(" ~~ "); + } + + printf("\n"); +} + +int main() { + dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); + dummyItem->data = -1; + dummyItem->key = -1; + + insert(1, 20); + insert(2, 70); + insert(42, 80); + insert(4, 25); + insert(12, 44); + insert(14, 32); + insert(17, 11); + insert(13, 78); + insert(37, 97); + + display(); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } + + delete(item); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } +} From 9f52d218d6d07c56978e8e5dd0a4d890a4004ea4 Mon Sep 17 00:00:00 2001 From: The-Hritik <90152873+The-Hritik@users.noreply.github.com> Date: Tue, 18 Oct 2022 09:46:33 +0530 Subject: [PATCH 07/24] Bellman Ford Algo --- Data Structures and Algorithms/BellmanFord.py | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Data Structures and Algorithms/BellmanFord.py diff --git a/Data Structures and Algorithms/BellmanFord.py b/Data Structures and Algorithms/BellmanFord.py new file mode 100644 index 0000000..327fd43 --- /dev/null +++ b/Data Structures and Algorithms/BellmanFord.py @@ -0,0 +1,61 @@ +from Graph import * + +def relaxEdge(G, edge): + + u,v,w = edge + u = G.getVertexById(u.getId()) + v = G.getVertexById(v.getId()) + + distanceU = u.getDistance() + distanceV = v.getDistance() + + if (distanceU + w < distanceV): + v.setDistance(distanceU + w) + +def printSolution(S): + for v in S.vert_dict: + i = S.getVertexById(v) + print('----------------------------------------------') + print(f' Vertex: |{i.getId()}| - Distance from source: |{i.getDistance()}|') + print('----------------------------------------------') + +def bellmanFord(G, s): + print("Bellman-Ford's shortest path") + s.setDistance(0) + i = 0 + while(i < (G.num_vertices)): + for edge in G.edges_list: + relaxEdge(G, edge) + i = i + 1 + + for edge in G.edges_list: + u,v,w = edge + if (v.getDistance() > u.getDistance() + w): + print("NEGATIVE CYCLE") + return False + + printSolution(G) + return True + +if __name__ == '__main__': + + g = Graph() + + a = g.addVertex('a') + b = g.addVertex('b') + c = g.addVertex('c') + d = g.addVertex('d') + e = g.addVertex('e') + f = g.addVertex('f') + + g.addEdge(a, b, 6) + g.addEdge(a, b, 7) + g.addEdge(a, f, 14) + g.addEdge(b, c, 10) + g.addEdge(b, d, 15) + g.addEdge(c, d, 11) + g.addEdge(c, f, 2) + g.addEdge(d, e, 6) + g.addEdge(e, f, 9) + + bellmanFord(g, a) \ No newline at end of file From 79b7142fb5e94cba57555871d6e3879a5566dc6e Mon Sep 17 00:00:00 2001 From: SanchitMahajan2002 <97718772+SanchitMahajan2002@users.noreply.github.com> Date: Wed, 19 Oct 2022 10:32:03 +0530 Subject: [PATCH 08/24] Create BMI_Calculator.py --- python/BMI_Calculator.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 python/BMI_Calculator.py diff --git a/python/BMI_Calculator.py b/python/BMI_Calculator.py new file mode 100644 index 0000000..67c337a --- /dev/null +++ b/python/BMI_Calculator.py @@ -0,0 +1,19 @@ +h=float(input("Enter your height in meters: ")) +w=float(input("Enter your Weight in Kg: ")) + +BMI=w/(h*h) +print("BMI Calculated is: ",BMI) + +if(BMI>0): + if(BMI<=16): + print("You are very underweight") + elif(BMI<=18.5): + print("You are underweight") + elif(BMI<=25): + print("Congrats! You are Healthy") + elif(BMI<=30): + print("You are overweight") + else: + print("You are very overweight") +else: + print("enter valid details") From fedcaf5e4a404040be785199082dff05d482d1ca Mon Sep 17 00:00:00 2001 From: IqraMahmood <87108359+IqraMahmood@users.noreply.github.com> Date: Fri, 21 Oct 2022 01:44:22 -0700 Subject: [PATCH 09/24] Add Stack code --- stack.ipynb | 271 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 stack.ipynb diff --git a/stack.ipynb b/stack.ipynb new file mode 100644 index 0000000..f1d4f6f --- /dev/null +++ b/stack.ipynb @@ -0,0 +1,271 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "88b9bbda", + "metadata": {}, + "source": [ + "# Q1. Create a class Stack Contains\n", + "\n", + "a. Items\n", + "2. Functions\n", + "a. push\n", + "i. insert the item at start of the stack\n", + "b. pop\n", + "i. Pop first element from the stack\n", + "c. peak\n", + "i. Returns top element of the stack\n", + "d. print_stack\n", + "i. Display the entire\n", + "e. size\n", + "i. Return total number of items in the stack\n", + "f. push_without_using_insert\n", + "i. Insert the item at start of the stack without using .insert method of\n", + "string\n", + "\n", + "Note: Not a single function should crash on an empty stack" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "971650a5", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "16306651", + "metadata": {}, + "outputs": [], + "source": [ + "#stack class\n", + "\n", + "class Stack:\n", + "#constructors\n", + " def __init__(self,items = 0):\n", + " self.items = []\n", + "\n", + "#function to push data \n", + " def push(self,data):\n", + " return self.items.insert(0,data)\n", + " \n", + "#function to pop(delete) data from top \n", + " def pop(self, x=0):\n", + " if self.isEmpty():\n", + " pass \n", + " else:\n", + " return self.items.pop(x)\n", + " \n", + "# function to return element from peak \n", + " def peak(self):\n", + " if self.isEmpty():\n", + " pass\n", + " else:\n", + " return self.items[0]\n", + " \n", + "# function to print entire stack\n", + " def print_stack(self):\n", + " if self.isEmpty():\n", + " pass\n", + " else:\n", + " return self.items\n", + "\n", + "# function to print stack size \n", + " def size(self):\n", + " if self.isEmpty():\n", + " pass\n", + " else:\n", + " return len(self.items)\n", + "\n", + "# function to print without using insert \n", + " def push_without_using_insert(self, data ):\n", + " x = data + self.items\n", + " return x\n", + "\n", + " \n", + "# function to check either stack is empty or not \n", + " def isEmpty(self):\n", + " if len(self.items) == 0:\n", + " return (\"Empty stack\")\n", + " \n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "df54d3f2", + "metadata": {}, + "outputs": [], + "source": [ + "s = Stack()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "66be8562", + "metadata": {}, + "outputs": [], + "source": [ + "s.push(1)\n", + "s.push(2)\n", + "s.push(3)\n", + "s.push(4)\n", + "s.push(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "10a11c7d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.pop()" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "e07d9952", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[4, 3, 2, 1]" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.print_stack()" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "7d913f8d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.peak()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "42a0ef70", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.size()" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "5d3c6e95", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[9, 4, 3, 2, 1]" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.push_without_using_insert([9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a67101b0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a23edfd0", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "state": {}, + "version_major": 2, + "version_minor": 0 + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 7798b4c5412b2ba8bb566695021e076c85ceea85 Mon Sep 17 00:00:00 2001 From: Shivam <97429919+Heisenberg99101@users.noreply.github.com> Date: Mon, 24 Oct 2022 12:22:30 +0530 Subject: [PATCH 10/24] Space game --- space_game.py | 180 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 space_game.py diff --git a/space_game.py b/space_game.py new file mode 100644 index 0000000..41d063e --- /dev/null +++ b/space_game.py @@ -0,0 +1,180 @@ +import pygame +import os +pygame.init() +pygame.font.init() +pygame.mixer.init() + +WIDTH, HEIGHT = 900, 500 + +WIN = pygame.display.set_mode((WIDTH, HEIGHT)) +pygame.display.set_caption("First Game!!!") + +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +YELLOW = (255, 255, 0) +RED = (255, 0, 0) + +VEL = 5 + +BULLET_VEL = 7 +MAX_BULLETS = 10 + +BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Grenade+1.mp3')) +BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Gun+Silencer.mp3')) + +YELLOW_HIT = pygame.USEREVENT + 1 +RED_HIT = pygame.USEREVENT + 2 + +FPS = 60 + +BORDER = pygame.Rect(WIDTH/2 - 5, 0, 10, HEIGHT) + +HEALTH_FONT = pygame.font.SysFont('century gothic', 40) +WINNER_FONT = pygame.font.SysFont('century gothic', 40) + +SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40 + +YELLOW_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_yellow.png')) +YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90) + +RED_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_red.png')) +RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 270) + +SPACE = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT)) + +def yellow_handle_movement(keys_pressed, yellow): + if keys_pressed[pygame.K_a] and yellow.x - VEL > 0: + yellow.x -= VEL + if keys_pressed[pygame.K_d] and yellow.x + VEL + yellow.width - 10 < BORDER.x: + yellow.x += VEL + if keys_pressed[pygame.K_w] and yellow.y - VEL > 0: + yellow.y -= VEL + if keys_pressed[pygame.K_s] and yellow.y + yellow.height + VEL < HEIGHT - 15: + yellow.y += VEL + +def red_handle_movement(keys_pressed, red): + if keys_pressed[pygame.K_LEFT] and red.x - VEL > BORDER.x + BORDER.width: + red.x -= VEL + if keys_pressed[pygame.K_RIGHT] and red.x + VEL + red.width < WIDTH + 10: + red.x += VEL + if keys_pressed[pygame.K_UP] and red.y - VEL > 0: + red.y -= VEL + if keys_pressed[pygame.K_DOWN] and red.y + red.height + VEL < HEIGHT - 15: + red.y += VEL + +def handle_bullets(yellow_bullets, red_bullets, yellow, red): + for bullet in yellow_bullets: + bullet.x += BULLET_VEL + if red.colliderect(bullet): + pygame.event.post(pygame.event.Event(RED_HIT)) + yellow_bullets.remove(bullet) + elif bullet.x > WIDTH: + yellow_bullets.remove(bullet) + + for bullet in red_bullets: + bullet.x -= BULLET_VEL + if yellow.colliderect(bullet): + pygame.event.post(pygame.event.Event(YELLOW_HIT)) + red_bullets.remove(bullet) + elif bullet.x < 0: + red_bullets.remove(bullet) + + + +def draw_window(yellow, red, yellow_bullets, red_bullets, red_health, yellow_health): + WIN.blit(SPACE, (0, 0)) + pygame.draw.rect(WIN, BLACK, BORDER) + + WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y)) + WIN.blit(RED_SPACESHIP, (red.x, red.y)) + + red_health_text = HEALTH_FONT.render("Health: " + str(red_health), 1, WHITE) + yellow_health_text = HEALTH_FONT.render('Health: ' + str(yellow_health), 1, WHITE) + + WIN.blit(yellow_health_text, (WIDTH - red_health_text.get_width() - 10,10)) + WIN.blit(red_health_text, (10, 10)) + + for bullet in yellow_bullets: + pygame.draw.rect(WIN, YELLOW, bullet) + for bullet in red_bullets: + pygame.draw.rect(WIN, RED, bullet) + + pygame.display.update() + + + +def draw_winner(text): + draw_text = WINNER_FONT.render(text, 1, WHITE) + WIN.blit(draw_text, (WIDTH//2 - draw_text.get_width()//2, HEIGHT//2 - draw_text.get_height()//2)) + pygame.display.update() + pygame.time.delay(5000) + + + +def main(): + + yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) + red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) + + yellow_bullets = [] + red_bullets = [] + + red_health = 3 + yellow_health = 3 + + clock = pygame.time.Clock() + + run = True + + while run: + + clock.tick(FPS) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + run = False + pygame.quit() + + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_LCTRL and len(yellow_bullets) < MAX_BULLETS: + bullet = pygame.Rect(yellow.x + yellow.width, yellow.y + yellow.height//2 - 2, 10, 5) + yellow_bullets.append(bullet) + BULLET_FIRE_SOUND.play() + + if event.key == pygame.K_RCTRL and len(red_bullets) <= MAX_BULLETS: + bullet = pygame.Rect(red.x, red.y + red.height//2 - 2, 10, 5) + red_bullets.append(bullet) + BULLET_FIRE_SOUND.play() + + if event.type == RED_HIT: + red_health -= 1 + BULLET_HIT_SOUND.play() + if event.type == YELLOW_HIT: + yellow_health -= 1 + BULLET_HIT_SOUND.play() + + winner_text = '' + if red_health <= 0: + winner_text = 'YELLOW WINS !!!' + + if yellow_health <= 0: + winner_text = 'RED WINS !!!' + + if winner_text != '': + draw_winner(winner_text) + break + + keys_pressed = pygame.key.get_pressed() + yellow_handle_movement(keys_pressed,yellow) + red_handle_movement(keys_pressed, red) + + + handle_bullets(yellow_bullets, red_bullets, yellow, red) + draw_window(yellow, red, yellow_bullets, red_bullets, yellow_health, red_health) + + + main() + + +if __name__ == '__main__': + main() From 0cdb8bcdf3a39dcfdcd2a13c365f1a660e8111d1 Mon Sep 17 00:00:00 2001 From: Shivam <97429919+Heisenberg99101@users.noreply.github.com> Date: Mon, 24 Oct 2022 12:27:36 +0530 Subject: [PATCH 11/24] tic_tac_toe.py --- tic_tac_toe.py | 123 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 tic_tac_toe.py diff --git a/tic_tac_toe.py b/tic_tac_toe.py new file mode 100644 index 0000000..3c91f4b --- /dev/null +++ b/tic_tac_toe.py @@ -0,0 +1,123 @@ +board = [' ' for x in range(10)] + +def insertLetter(letter, pos): + board[pos] = letter + +def spaceIsFree(pos): + return board[pos] == ' ' + +def printBoard(board): + print(' | |') + print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) + print(' | |') + print('-----------') + print(' | |') + print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) + print(' | |') + print('-----------') + print(' | |') + print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) + print(' | |') + +def isWinner(bo, le): + return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or(bo[1] == le and bo[2] == le and bo[3] == le) or(bo[1] == le and bo[4] == le and bo[7] == le) or(bo[2] == le and bo[5] == le and bo[8] == le) or(bo[3] == le and bo[6] == le and bo[9] == le) or(bo[1] == le and bo[5] == le and bo[9] == le) or(bo[3] == le and bo[5] == le and bo[7] == le) + +def playerMove(): + run = True + while run: + move = input("Please select a postion to place an \'X\', (1-9)") + try: + move = int(move) + if move > 0 and move < 10: + if spaceIsFree(move): + run = False + insertLetter('X', move) + else: + print('Sorry, the space is occupied!') + else: + print('Please type a number within the range!') + except: + print('Please type a number.') + +def compMove(): + possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0] + move = 0 + + for let in ["O", 'X']: + for i in possibleMoves: + boardCopy = board[:] + boardCopy[i] = let + if isWinner(boardCopy, let): + move = i + return move + + cornersOpen = [] + for i in possibleMoves: + if i in [1,3,7,9]: + cornersOpen.append(i) + + if len(cornersOpen) > 0: + move = selectRandom(cornersOpen) + return move + + if 5 in possibleMoves: + move = 5 + return move + + edgesOpen = [] + for i in possibleMoves: + if i in [2,4,6,8]: + edgesOpen.append(i) + + if len(edgesOpen) > 0: + move = selectRandom(edgesOpen) + + return move + +def selectRandom(li): + import random + ln = len(li) + r = random.randrange(0,ln) + return li[r] + +def isBoardFull(board): + if board.count(' ') > 1: + return False + else: + return True + +def main(): + print('WELCOME TO TIC-TAC-TOE !!!') + printBoard(board) + + while not(isBoardFull(board)): + if not(isWinner(board, 'O')): + playerMove() + printBoard(board) + else: + print("Sorry, O\'s win this time!") + break + + if not(isWinner(board, 'X')): + move = compMove() + if move == 0: + print('Tie Game!') + else: + insertLetter('O', move) + print("Computer placed an \'O\' in position", move, ":") + printBoard(board) + else: + print("You have won this time, Good Job!") + break + + if isBoardFull(board): + print('Tie Game!') + +while True: + answer = input('Do you want to play again? (Y/N)') + if answer.lower() == 'y' or answer.lower == 'yes': + board = [' ' for x in range(10)] + print('-----------------------------------') + main() + else: + break From 47b7abda49abf4f38e3053d4253670e7c8cb6b43 Mon Sep 17 00:00:00 2001 From: Shivam <97429919+Heisenberg99101@users.noreply.github.com> Date: Mon, 24 Oct 2022 14:05:12 +0530 Subject: [PATCH 12/24] Create password_generator.py finding it difficult to generate a password? Use this. --- Python_Script/password_generator.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python_Script/password_generator.py diff --git a/Python_Script/password_generator.py b/Python_Script/password_generator.py new file mode 100644 index 0000000..ac73caa --- /dev/null +++ b/Python_Script/password_generator.py @@ -0,0 +1,29 @@ +import string, random + +if __name__ == '__main__': + s1 = string.ascii_lowercase + s2 = string.ascii_uppercase + s3 = string.digits + s4 = string.punctuation + + while True: + a = input("Enter password length\n") # handle gibberish(anything is entered except int) + b = a.isdigit() + if b==True: + plen= int(a) + break + else: + print("Invalid value! Please enter the valid value") + + s = [] + s.extend(list(s1)) + s.extend(list(s2)) + s.extend(list(s3)) + s.extend(list(s4)) + + random.shuffle(s) + + print("".join(s[0:plen])) + # The string whose method is called is inserted in between each given string. + # The result is returned as a new string. + # Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' From 2d3cc9589de9608a8890e0d05c1f33875fc4637f Mon Sep 17 00:00:00 2001 From: Shivam <97429919+Heisenberg99101@users.noreply.github.com> Date: Mon, 24 Oct 2022 14:06:56 +0530 Subject: [PATCH 13/24] Create space_game.py --- space_game.py | 180 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 space_game.py diff --git a/space_game.py b/space_game.py new file mode 100644 index 0000000..41d063e --- /dev/null +++ b/space_game.py @@ -0,0 +1,180 @@ +import pygame +import os +pygame.init() +pygame.font.init() +pygame.mixer.init() + +WIDTH, HEIGHT = 900, 500 + +WIN = pygame.display.set_mode((WIDTH, HEIGHT)) +pygame.display.set_caption("First Game!!!") + +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +YELLOW = (255, 255, 0) +RED = (255, 0, 0) + +VEL = 5 + +BULLET_VEL = 7 +MAX_BULLETS = 10 + +BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Grenade+1.mp3')) +BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Gun+Silencer.mp3')) + +YELLOW_HIT = pygame.USEREVENT + 1 +RED_HIT = pygame.USEREVENT + 2 + +FPS = 60 + +BORDER = pygame.Rect(WIDTH/2 - 5, 0, 10, HEIGHT) + +HEALTH_FONT = pygame.font.SysFont('century gothic', 40) +WINNER_FONT = pygame.font.SysFont('century gothic', 40) + +SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40 + +YELLOW_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_yellow.png')) +YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90) + +RED_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_red.png')) +RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 270) + +SPACE = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT)) + +def yellow_handle_movement(keys_pressed, yellow): + if keys_pressed[pygame.K_a] and yellow.x - VEL > 0: + yellow.x -= VEL + if keys_pressed[pygame.K_d] and yellow.x + VEL + yellow.width - 10 < BORDER.x: + yellow.x += VEL + if keys_pressed[pygame.K_w] and yellow.y - VEL > 0: + yellow.y -= VEL + if keys_pressed[pygame.K_s] and yellow.y + yellow.height + VEL < HEIGHT - 15: + yellow.y += VEL + +def red_handle_movement(keys_pressed, red): + if keys_pressed[pygame.K_LEFT] and red.x - VEL > BORDER.x + BORDER.width: + red.x -= VEL + if keys_pressed[pygame.K_RIGHT] and red.x + VEL + red.width < WIDTH + 10: + red.x += VEL + if keys_pressed[pygame.K_UP] and red.y - VEL > 0: + red.y -= VEL + if keys_pressed[pygame.K_DOWN] and red.y + red.height + VEL < HEIGHT - 15: + red.y += VEL + +def handle_bullets(yellow_bullets, red_bullets, yellow, red): + for bullet in yellow_bullets: + bullet.x += BULLET_VEL + if red.colliderect(bullet): + pygame.event.post(pygame.event.Event(RED_HIT)) + yellow_bullets.remove(bullet) + elif bullet.x > WIDTH: + yellow_bullets.remove(bullet) + + for bullet in red_bullets: + bullet.x -= BULLET_VEL + if yellow.colliderect(bullet): + pygame.event.post(pygame.event.Event(YELLOW_HIT)) + red_bullets.remove(bullet) + elif bullet.x < 0: + red_bullets.remove(bullet) + + + +def draw_window(yellow, red, yellow_bullets, red_bullets, red_health, yellow_health): + WIN.blit(SPACE, (0, 0)) + pygame.draw.rect(WIN, BLACK, BORDER) + + WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y)) + WIN.blit(RED_SPACESHIP, (red.x, red.y)) + + red_health_text = HEALTH_FONT.render("Health: " + str(red_health), 1, WHITE) + yellow_health_text = HEALTH_FONT.render('Health: ' + str(yellow_health), 1, WHITE) + + WIN.blit(yellow_health_text, (WIDTH - red_health_text.get_width() - 10,10)) + WIN.blit(red_health_text, (10, 10)) + + for bullet in yellow_bullets: + pygame.draw.rect(WIN, YELLOW, bullet) + for bullet in red_bullets: + pygame.draw.rect(WIN, RED, bullet) + + pygame.display.update() + + + +def draw_winner(text): + draw_text = WINNER_FONT.render(text, 1, WHITE) + WIN.blit(draw_text, (WIDTH//2 - draw_text.get_width()//2, HEIGHT//2 - draw_text.get_height()//2)) + pygame.display.update() + pygame.time.delay(5000) + + + +def main(): + + yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) + red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) + + yellow_bullets = [] + red_bullets = [] + + red_health = 3 + yellow_health = 3 + + clock = pygame.time.Clock() + + run = True + + while run: + + clock.tick(FPS) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + run = False + pygame.quit() + + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_LCTRL and len(yellow_bullets) < MAX_BULLETS: + bullet = pygame.Rect(yellow.x + yellow.width, yellow.y + yellow.height//2 - 2, 10, 5) + yellow_bullets.append(bullet) + BULLET_FIRE_SOUND.play() + + if event.key == pygame.K_RCTRL and len(red_bullets) <= MAX_BULLETS: + bullet = pygame.Rect(red.x, red.y + red.height//2 - 2, 10, 5) + red_bullets.append(bullet) + BULLET_FIRE_SOUND.play() + + if event.type == RED_HIT: + red_health -= 1 + BULLET_HIT_SOUND.play() + if event.type == YELLOW_HIT: + yellow_health -= 1 + BULLET_HIT_SOUND.play() + + winner_text = '' + if red_health <= 0: + winner_text = 'YELLOW WINS !!!' + + if yellow_health <= 0: + winner_text = 'RED WINS !!!' + + if winner_text != '': + draw_winner(winner_text) + break + + keys_pressed = pygame.key.get_pressed() + yellow_handle_movement(keys_pressed,yellow) + red_handle_movement(keys_pressed, red) + + + handle_bullets(yellow_bullets, red_bullets, yellow, red) + draw_window(yellow, red, yellow_bullets, red_bullets, yellow_health, red_health) + + + main() + + +if __name__ == '__main__': + main() From 0d5033e79f29a509da738f07ba4a683dc06437ea Mon Sep 17 00:00:00 2001 From: komalchandrancc <116550523+komalchandrancc@users.noreply.github.com> Date: Tue, 25 Oct 2022 09:46:45 +0530 Subject: [PATCH 14/24] Create Missing Number --- Missing Number | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Missing Number diff --git a/Missing Number b/Missing Number new file mode 100644 index 0000000..f6363f9 --- /dev/null +++ b/Missing Number @@ -0,0 +1,11 @@ +def findMissingNumbers(n): + numbers = set(n) + length = len(n) + output = [] + for i in range(1, n[-1]): + if i not in numbers: + output.append(i) + return output + +listOfNumbers = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 13, 14, 16] +print(findMissingNumbers(listOfNumbers)) From ffb45b11dedad79bfc43a2a96413838b751c0305 Mon Sep 17 00:00:00 2001 From: shubham-singh-04 <116623641+shubham-singh-04@users.noreply.github.com> Date: Tue, 25 Oct 2022 11:52:42 +0530 Subject: [PATCH 15/24] Adding Coding Question Contains X Given a generic tree and an integer x, check if x is present in the given tree or not. Return true if x is present, return false otherwise. Input format : The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. The following line contains an integer, that denotes the value of x. Output format : The first and only line of output contains true, if x is present and false, otherwise. --- ContainsX.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ContainsX.py diff --git a/ContainsX.py b/ContainsX.py new file mode 100644 index 0000000..c643e2d --- /dev/null +++ b/ContainsX.py @@ -0,0 +1,47 @@ +from sys import stdin,setrecursionlimit +setrecursionlimit(10**6) +class treeNode: + def __init__(self, data): + self.data = data + self.children = [] + def __str__(self): + return str(self.data) + +def containsX(tree, x): + ############################# + # PLEASE ADD YOUR CODE HERE # + ############################# + if tree is None: + return False + if tree.data == x: + return True + childCount = len(tree.children) + for i in range(childCount): + if (containsX(tree.children[i], x)): + return True + return False +def createLevelWiseTree(arr): + root = treeNode(int(arr[0])) + q = [root] + size = len(arr) + i = 1 + while i Date: Tue, 25 Oct 2022 11:53:41 +0530 Subject: [PATCH 16/24] Adding Coding Question Count Leaf Nodes Given a generic tree, count and return the number of leaf nodes present in the given tree. Input format : The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. Output Format : The first and only line of output prints the count of leaf nodes present in the given tree. Constraints: Time Limit: 1 sec --- CountLeafNodes.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 CountLeafNodes.py diff --git a/CountLeafNodes.py b/CountLeafNodes.py new file mode 100644 index 0000000..0871c72 --- /dev/null +++ b/CountLeafNodes.py @@ -0,0 +1,42 @@ +import sys +class treeNode: + def __init__(self, data): + self.data = data + self.children = [] + def __str__(self): + return str(self.data) + +def leafNodeCount(tree): + ############################# + # PLEASE ADD YOUR CODE HERE # + ############################# + if tree is None: + return 0 + childCount = len(tree.children) + if childCount == 0: + return 1 + res = 0 + for i in range(childCount): + res += leafNodeCount(tree.children[i]) + return res +def createLevelWiseTree(arr): + root = treeNode(int(arr[0])) + q = [root] + size = len(arr) + i = 1 + while i Date: Tue, 25 Oct 2022 11:54:51 +0530 Subject: [PATCH 17/24] Adding Coding Question Height of A generic Tree Given a generic tree, find and return the height of given tree. Input Format: The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. Output Format : The first and only line of output prints the height of the given generic tree. --- HeightOfTree.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 HeightOfTree.py diff --git a/HeightOfTree.py b/HeightOfTree.py new file mode 100644 index 0000000..fef95f9 --- /dev/null +++ b/HeightOfTree.py @@ -0,0 +1,37 @@ +import sys +sys.setrecursionlimit(10**6) +class treeNode: + def __init__(self, data): + self.data = data + self.children = [] + def __str__(self): + return str(self.data) + +#main +def heightOfTree(root): + height = 0 + for child in root.children: + ch = heightOfTree(child) + height = max(ch, height) + height += 1 + return height +## Read input as specified in the question. +def createLevelWiseTree(arr): + root = treeNode(int(arr[0])) + q = [root] + size = len(arr) + i = 1 + while i Date: Tue, 25 Oct 2022 11:56:17 +0530 Subject: [PATCH 18/24] Adding Coding Question "Next largest Node" Given a generic tree and an integer n. Find and return the node with next larger element in the tree i.e. find a node with value just greater than n. Note: Return NULL if no node is present with the value greater than n. Input format : The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. The following line contains an integer, that denotes the value of n. Output format : The first and only line of output contains data of the node, whose data is just greater than n. Constraints: Time Limit: 1 sec Sample Input 1 : 10 3 20 30 40 2 40 50 0 0 0 0 18 Sample Output 1 : 20 Sample Input 2 : 10 3 20 30 40 2 40 50 0 0 0 0 21 Sample Output 2: 30 --- NextLargestNodeInAGenericTree.py | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 NextLargestNodeInAGenericTree.py diff --git a/NextLargestNodeInAGenericTree.py b/NextLargestNodeInAGenericTree.py new file mode 100644 index 0000000..e5ef11b --- /dev/null +++ b/NextLargestNodeInAGenericTree.py @@ -0,0 +1,51 @@ +from sys import stdin,setrecursionlimit +setrecursionlimit(10**6) +class treeNode: + def __init__(self, data): + self.data = data + self.children = [] + +def nextLargestUtil(root, x): + global res + if root is None: + return + if root.data > x: + if ((res == None or res.data > root.data)): + res = root + countChildren = len(root.children) + for i in range(countChildren): + nextLargestUtil(root.children[i], x) + return +def nextLargest(root, n): + ############################# + # PLEASE ADD YOUR CODE HERE # + ############################# + global res + res = None + nextLargestUtil(root, n) + return res + + + +def createLevelWiseTree(arr): + root = treeNode(int(arr[0])) + q = [root] + size = len(arr) + i = 1 + while i Date: Tue, 25 Oct 2022 11:57:51 +0530 Subject: [PATCH 19/24] Adding Coding Question "Node with Maximum Child Sum" Given a generic tree, find and return the node for which sum of its data and data of all its child nodes is maximum. n the sum, data of the node and data of its immediate child nodes has to be taken. Input format : The first line of input contains data of the nodes of the tree in level order form. he order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. Output format : The first and only line of output contains the data of the node with maximum sum, as described in the task. Constraints: Time Limit: 1 sec Sample Input 1 : 5 3 1 2 3 1 15 2 4 5 1 6 0 0 0 0 Sample Output 1 : 1 --- NodeWithMaximumChildSum.py | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 NodeWithMaximumChildSum.py diff --git a/NodeWithMaximumChildSum.py b/NodeWithMaximumChildSum.py new file mode 100644 index 0000000..83eb141 --- /dev/null +++ b/NodeWithMaximumChildSum.py @@ -0,0 +1,51 @@ +from sys import stdin,setrecursionlimit +setrecursionlimit(10**6) +class treeNode: + def __init__(self, data): + self.data = data + self.children = [] + def sum(self): + ans = self.data + for child in self.children: + ans += child.data + return ans +def maxSumUtil(root, resNode, maxsum): + if root is None: + return + cur_sum = root.data + count = len(root.children) + for i in range(count): + cur_sum += root.children[i].data + resNode, maxsum = maxSumUtil(root.children[i], resNode, maxsum) + if cur_sum > maxsum: + resNode = root + maxsum = cur_sum + return resNode, maxsum +def maxSumNode(tree): + ############################# + # PLEASE ADD YOUR CODE HERE # + ############################# + resNode, maxsum = treeNode(None), 0 + resNode, maxsum = maxSumUtil(tree, resNode, maxsum) + return resNode.data + +def createLevelWiseTree(arr): + root = treeNode(int(arr[0])) + q = [root] + size = len(arr) + i = 1 + while i Date: Wed, 26 Oct 2022 13:26:12 +0530 Subject: [PATCH 20/24] Create Factor of a Number --- Factor of a Number | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Factor of a Number diff --git a/Factor of a Number b/Factor of a Number new file mode 100644 index 0000000..78f28f7 --- /dev/null +++ b/Factor of a Number @@ -0,0 +1,11 @@ +# method to print the divisors +def printDivisors(n) : + i = 1 + while i <= n : + if (n % i==0) : + print (i,end=" ") + i = i + 1 + +# Driver method +print ("The divisors of 100 are: ") +printDivisors(100) From 2296bb9fcd021efac4004bde60e2c38f837e99e6 Mon Sep 17 00:00:00 2001 From: MaryamMahmood001 <116386756+MaryamMahmood001@users.noreply.github.com> Date: Fri, 28 Oct 2022 10:36:39 -0700 Subject: [PATCH 21/24] Add simple linear regression code --- Simple Linear Regression.ipynb | 605 +++++++++++++++++++++++++++++++++ 1 file changed, 605 insertions(+) create mode 100644 Simple Linear Regression.ipynb diff --git a/Simple Linear Regression.ipynb b/Simple Linear Regression.ipynb new file mode 100644 index 0000000..6f7f68d --- /dev/null +++ b/Simple Linear Regression.ipynb @@ -0,0 +1,605 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "7e890180", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "42312531", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9f7fec88", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "6d497591", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
agedistanceYearsExperienceSalary
031.177.751.139343
131.378.251.346205
231.578.751.537731
332.080.002.043525
432.280.502.239891
\n", + "
" + ], + "text/plain": [ + " age distance YearsExperience Salary\n", + "0 31.1 77.75 1.1 39343\n", + "1 31.3 78.25 1.3 46205\n", + "2 31.5 78.75 1.5 37731\n", + "3 32.0 80.00 2.0 43525\n", + "4 32.2 80.50 2.2 39891" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# load dataset\n", + "df = pd.read_csv(\"ml_data_salary.csv\")\n", + "df.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "c01ec834", + "metadata": {}, + "outputs": [], + "source": [ + "df = df.drop(['age'], axis = 1)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "7687b1eb", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
YearsExperienceSalary
01.139343
11.346205
21.537731
32.043525
42.239891
\n", + "
" + ], + "text/plain": [ + " YearsExperience Salary\n", + "0 1.1 39343\n", + "1 1.3 46205\n", + "2 1.5 37731\n", + "3 2.0 43525\n", + "4 2.2 39891" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "df = df.drop(['distance'], axis = 1)\n", + "df.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "5c6b8109", + "metadata": {}, + "outputs": [], + "source": [ + "X = df[['YearsExperience']];\n", + "y = df['Salary']" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "595ce83e", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
YearsExperience
01.1
11.3
21.5
32.0
42.2
\n", + "
" + ], + "text/plain": [ + " YearsExperience\n", + "0 1.1\n", + "1 1.3\n", + "2 1.5\n", + "3 2.0\n", + "4 2.2" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "X.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "80fc04f4", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0 39343\n", + "1 46205\n", + "2 37731\n", + "3 43525\n", + "4 39891\n", + "Name: Salary, dtype: int64" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "d8d9eb64", + "metadata": {}, + "outputs": [], + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/5, random_state=0)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "0bd39c96", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "LinearRegression()" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from sklearn.linear_model import LinearRegression\n", + "reg = LinearRegression().fit(X_train,y_train)\n", + "reg" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "1a8f2414", + "metadata": {}, + "outputs": [], + "source": [ + "y_pred = reg.predict(X_test)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "dc45b5c5", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ 40748.96184072, 122699.62295594, 64961.65717022, 63099.14214487,\n", + " 115249.56285456, 107799.50275317])" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y_pred" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "1903fff8", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[]" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYoAAAD4CAYAAADy46FuAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6A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dwI+B7RG3Iyr7AWuAB4PLb/eZ2c5RNyqX3L0e+CWwAlgFbHD3Z6JtVWT2dvdVEPswCewVcXsABUXkzGwX4C/AD939k6jbk0tmdg6w2t0XRN2WCHUBjgTudffBwGfkyeWGXAmuw58L9AP6ADub2TejbZXEU1BEyMy6EguJP7n741G3JwLHA182s1rgMeBUM/tjtE3KuTqgzt0be5NTiQVHKTkdWO7ua9x9K/A48MWI2xSVD82sN0DwfXXE7QEUFJExMyN2Xfptd78j6vZEwd3Hu3tfd68kNng5x91L6pOku38AvG9mA4LSacCiCJsUhRXAsWbWI/j/4jRKbEA/zpPA6OD1aOCJCNvSpEvUDShhxwPfAt4ws1eD2nXu/lR0TZKI/AD4k5l1A5YBF0Xcnpxy9/lmNhX4F7G7AReSp0tZZJKZPQoMBXqZWR1wI1ANTDGzMcQC9ILoWriDlvAQEZGUdOlJRERSUlCIiEhKCgoREUlJQSEiIikpKEREJCUFhYiIpKSgEBGRlP4XGt33odji7XsAAAAASUVORK5CYII=\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "plt.scatter(X_train, y_train)\n", + "plt.plot(X_train, reg.predict(X_train))" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "ff2c4095", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[]" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYoAAAD4CAYAAADy46FuAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAik0lEQVR4nO3deXxU9bnH8c/DHtYIAkIAA8oii2wRwQVRlESwQr1qsVWppeXWeqv3aqmAKC4IKG3dtaJW1FqVIgIVERBwLYsgYtj3JWGVfQmQ5Xf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mdp/fPYUDMytvZkvM7GO/ewkXZhZvZhPNbJX3/0s3v3vym5n9n/d7s8zM3jOzKn73VNbM7G9mtsvMluWr1TazWWa21vt8Tln3paAoWVnAA865i4CuwD1m1trnnsLBfcBKv5sIM88BnzrnWgHtifGfj5klAPcCSc65tkB5oL+/XfliPJBSoDYEmO2caw7M9tZlSkFRgpxz251z33m3D5H7yx/Tb3JhZo2APsDrfvcSLsysJtAdeAPAOXfCObff16bCQwUgzswqAFWBbT73U+acc18CewuU+wJvebffAvqVZU+goCg1ZpYIdAQW+NyK354F/gjk+NxHOGkG7Abe9A7JvW5m1fxuyk/OuXTgT8AWYDtwwDk309+uwkZ959x2yP1jFKhX1g0oKEqBmVUHPgT+1zl30O9+/GJmNwC7nHOL/e4lzFQAOgGvOOc6Akfw4XBCOPGOu/cFmgINgWpmdru/XUkeBUUJM7OK5IbEu865SX7347PLgRvNbBPwPnCNmf3d35bCQhqQ5pzLe7Y5kdzgiGXXAhudc7udc5nAJOAyn3sKFzvNrAGA93lXWTegoChBZmbkHnde6Zz7i9/9+M05N9Q518g5l0juYHKOcy7m/0p0zu0AtppZS6/UE1jhY0vhYAvQ1cyqer9HPYnxAX8+U4EB3u0BwJSybqBCWX/BKHc5cAeQambfe7VhzrlP/GtJwtTvgXfNrBKwAbjL53585ZxbYGYTge/IPXtwCTF4OQ8zew/oAZxrZmnACGAMMMHMBpIbqLeUeV+6hIeIiISiQ08iIhKSgkJEREJSUIiISEgKChERCUlBISIiISkoREQkJAWFiIiE9P+gUYH9qU1j+gAAAABJRU5ErkJggg==\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "plt.scatter(X_test, y_test)\n", + "plt.plot(X_test, reg.predict(X_test))" + ] + }, + { + "cell_type": "markdown", + "id": "f036c516", + "metadata": {}, + "source": [ + "We checl both tesmt and train both are linear so these are hwai baty now we will chek this by a score\n", + "m" + ] + }, + { + "cell_type": "markdown", + "id": "c6f53219", + "metadata": {}, + "source": [ + "# Testing and evaluation" + ] + }, + { + "cell_type": "markdown", + "id": "3b429237", + "metadata": {}, + "source": [ + "Model Fitness" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "id": "bb885ed9", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.988169515729126" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reg.score(X_test, y_test)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "f932693e", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.9411949620562126" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reg.score(X_train, y_train)" + ] + }, + { + "cell_type": "markdown", + "id": "382eb6c8", + "metadata": {}, + "source": [ + "# Prediction" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "f12db637", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([73342.97478427])" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reg.predict([[5]])" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "id": "667d62e6", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ 73342.97478427, 119905.85041792, 166468.72605157])" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reg.predict([[5],[10],[15]])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "04fe24c8", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 5d5ceebd5c93690b489559c74359c36f0cc9e62a Mon Sep 17 00:00:00 2001 From: muskanbindal <98261272+muskanbindal@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:25:13 +0530 Subject: [PATCH 22/24] Create floppybird.py --- python/floppybird.py | 222 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 python/floppybird.py diff --git a/python/floppybird.py b/python/floppybird.py new file mode 100644 index 0000000..895207e --- /dev/null +++ b/python/floppybird.py @@ -0,0 +1,222 @@ +import random # For generating random numbers +import sys # We will use sys.exit to exit the program +import pygame +from pygame.locals import * # Basic pygame imports + +# Global Variables for the game +FPS = 32 +SCREENWIDTH = 289 +SCREENHEIGHT = 511 +SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) +GROUNDY = SCREENHEIGHT * 0.8 +GAME_SPRITES = {} +GAME_SOUNDS = {} +PLAYER = 'gallery/sprites/bird.png' +BACKGROUND = 'gallery/sprites/background.png' +PIPE = 'gallery/sprites/pipe.png' + +def welcomeScreen(): + """ + Shows welcome images on the screen + """ + + playerx = int(SCREENWIDTH/5) + playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2) + messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width())/2) + messagey = int(SCREENHEIGHT*0.13) + basex = 0 + while True: + for event in pygame.event.get(): + # if user clicks on cross button, close the game + if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE): + pygame.quit() + sys.exit() + + # If the user presses space or up key, start the game for them + elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP): + return + else: + SCREEN.blit(GAME_SPRITES['background'], (0, 0)) + SCREEN.blit(GAME_SPRITES['player'], (playerx, playery)) + SCREEN.blit(GAME_SPRITES['message'], (messagex,messagey )) + SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY)) + pygame.display.update() + FPSCLOCK.tick(FPS) + +def mainGame(): + score = 0 + playerx = int(SCREENWIDTH/5) + playery = int(SCREENWIDTH/2) + basex = 0 + + # Create 2 pipes for blitting on the screen + newPipe1 = getRandomPipe() + newPipe2 = getRandomPipe() + + # my List of upper pipes + upperPipes = [ + {'x': SCREENWIDTH+200, 'y':newPipe1[0]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[0]['y']}, + ] + # my List of lower pipes + lowerPipes = [ + {'x': SCREENWIDTH+200, 'y':newPipe1[1]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[1]['y']}, + ] + + pipeVelX = -4 + + playerVelY = -9 + playerMaxVelY = 10 + playerMinVelY = -8 + playerAccY = 1 + + playerFlapAccv = -8 # velocity while flapping + playerFlapped = False # It is true only when the bird is flapping + + + while True: + for event in pygame.event.get(): + if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): + pygame.quit() + sys.exit() + if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): + if playery > 0: + playerVelY = playerFlapAccv + playerFlapped = True + GAME_SOUNDS['wing'].play() + + + crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) # This function will return true if the player is crashed + if crashTest: + return + + #check for score + playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2 + for pipe in upperPipes: + pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2 + if pipeMidPos<= playerMidPos < pipeMidPos +4: + score +=1 + print(f"Your score is {score}") + GAME_SOUNDS['point'].play() + + + if playerVelY GROUNDY - 25 or playery<0: + GAME_SOUNDS['hit'].play() + return True + + for pipe in upperPipes: + pipeHeight = GAME_SPRITES['pipe'][0].get_height() + if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()): + GAME_SOUNDS['hit'].play() + return True + + for pipe in lowerPipes: + if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width(): + GAME_SOUNDS['hit'].play() + return True + + return False + +def getRandomPipe(): + """ + Generate positions of two pipes(one bottom straight and one top rotated ) for blitting on the screen + """ + pipeHeight = GAME_SPRITES['pipe'][0].get_height() + offset = SCREENHEIGHT/3 + y2 = offset + random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 *offset)) + pipeX = SCREENWIDTH + 10 + y1 = pipeHeight - y2 + offset + pipe = [ + {'x': pipeX, 'y': -y1}, #upper Pipe + {'x': pipeX, 'y': y2} #lower Pipe + ] + return pipe + + + + + + +if __name__ == "__main__": + # This will be the main point from where our game will start + pygame.init() # Initialize all pygame's modules + FPSCLOCK = pygame.time.Clock() + pygame.display.set_caption('Flappy Bird by CodeWithHarry') + GAME_SPRITES['numbers'] = ( + pygame.image.load('gallery/sprites/0.png').convert_alpha(), + pygame.image.load('gallery/sprites/1.png').convert_alpha(), + pygame.image.load('gallery/sprites/2.png').convert_alpha(), + pygame.image.load('gallery/sprites/3.png').convert_alpha(), + pygame.image.load('gallery/sprites/4.png').convert_alpha(), + pygame.image.load('gallery/sprites/5.png').convert_alpha(), + pygame.image.load('gallery/sprites/6.png').convert_alpha(), + pygame.image.load('gallery/sprites/7.png').convert_alpha(), + pygame.image.load('gallery/sprites/8.png').convert_alpha(), + pygame.image.load('gallery/sprites/9.png').convert_alpha(), + ) + + GAME_SPRITES['message'] =pygame.image.load('gallery/sprites/message.png').convert_alpha() + GAME_SPRITES['base'] =pygame.image.load('gallery/sprites/base.png').convert_alpha() + GAME_SPRITES['pipe'] =(pygame.transform.rotate(pygame.image.load( PIPE).convert_alpha(), 180), + pygame.image.load(PIPE).convert_alpha() + ) + + # Game sounds + GAME_SOUNDS['die'] = pygame.mixer.Sound('gallery/audio/die.wav') + GAME_SOUNDS['hit'] = pygame.mixer.Sound('gallery/audio/hit.wav') + GAME_SOUNDS['point'] = pygame.mixer.Sound('gallery/audio/point.wav') + GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('gallery/audio/swoosh.wav') + GAME_SOUNDS['wing'] = pygame.mixer.Sound('gallery/audio/wing.wav') + + GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert() + GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha() + + while True: + welcomeScreen() # Shows welcome screen to the user until he presses a button + mainGame() # This is the main game function From 11691d4db2ba1d4214f1049d0edb3be9e27409ac Mon Sep 17 00:00:00 2001 From: muskanbindal <98261272+muskanbindal@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:29:54 +0530 Subject: [PATCH 23/24] Create heapsort.py --- Data Structures and Algorithms/heapsort.py | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Data Structures and Algorithms/heapsort.py diff --git a/Data Structures and Algorithms/heapsort.py b/Data Structures and Algorithms/heapsort.py new file mode 100644 index 0000000..82100dd --- /dev/null +++ b/Data Structures and Algorithms/heapsort.py @@ -0,0 +1,39 @@ +def heapify(arr, n, i): + # Find largest among root and children + largest = i + l = 2 * i + 1 + r = 2 * i + 2 + + if l < n and arr[i] < arr[l]: + largest = l + + if r < n and arr[largest] < arr[r]: + largest = r + + # If root is not largest, swap with largest and continue heapifying + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + heapify(arr, n, largest) + + + def heapSort(arr): + n = len(arr) + + # Build max heap + for i in range(n//2, -1, -1): + heapify(arr, n, i) + + for i in range(n-1, 0, -1): + # Swap + arr[i], arr[0] = arr[0], arr[i] + + # Heapify root element + heapify(arr, i, 0) + + + arr = [1, 12, 9, 5, 6, 10] + heapSort(arr) + n = len(arr) + print("Sorted array is") + for i in range(n): + print("%d " % arr[i], end='') From 68d013fef6f5f22c18ee406da812a6b2dd268fd2 Mon Sep 17 00:00:00 2001 From: muskanbindal <98261272+muskanbindal@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:32:24 +0530 Subject: [PATCH 24/24] Create binary_tree.py --- Data Structures and Algorithms/binary_tree.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Data Structures and Algorithms/binary_tree.py diff --git a/Data Structures and Algorithms/binary_tree.py b/Data Structures and Algorithms/binary_tree.py new file mode 100644 index 0000000..91ec60b --- /dev/null +++ b/Data Structures and Algorithms/binary_tree.py @@ -0,0 +1,44 @@ +class Node: + def __init__(self, key): + self.left = None + self.right = None + self.val = key + + # Traverse preorder + def traversePreOrder(self): + print(self.val, end=' ') + if self.left: + self.left.traversePreOrder() + if self.right: + self.right.traversePreOrder() + + # Traverse inorder + def traverseInOrder(self): + if self.left: + self.left.traverseInOrder() + print(self.val, end=' ') + if self.right: + self.right.traverseInOrder() + + # Traverse postorder + def traversePostOrder(self): + if self.left: + self.left.traversePostOrder() + if self.right: + self.right.traversePostOrder() + print(self.val, end=' ') + + +root = Node(1) + +root.left = Node(2) +root.right = Node(3) + +root.left.left = Node(4) + +print("Pre order Traversal: ", end="") +root.traversePreOrder() +print("\nIn order Traversal: ", end="") +root.traverseInOrder() +print("\nPost order Traversal: ", end="") +root.traversePostOrder()