├── CONTRIBUTING.md ├── Python Codes ├── 2 level organisation.py ├── 22.Generators.py ├── AGE_CALCULATOR.PY ├── ASCII_Art_With_Python │ ├── ascii_art_python.py │ └── ascii_image.txt ├── Advance Python │ ├── .DS_Store │ ├── AI hand detection │ │ └── handdetection.py │ ├── Digit Recognition │ │ ├── Python_Digit_Recognition.ipynb │ │ └── Readme.md │ ├── Doubly_Linked_List.py │ ├── Infix_to_postfix_method2.py │ ├── Magic_Cloak.py │ ├── Mail Merge Python │ │ ├── .DS_Store │ │ ├── Input │ │ │ ├── .DS_Store │ │ │ ├── Letters │ │ │ │ └── starting_letter.txt │ │ │ └── Names │ │ │ │ └── invited_names.txt │ │ ├── Output │ │ │ ├── .DS_Store │ │ │ └── ReadyToSend │ │ │ │ └── example.txt │ │ └── main.py │ ├── Pandas Basics.ipynb │ ├── Prim's_algorithm.py │ ├── Rearrange the array in alternating positive and negative items with O(1) extra space.py │ ├── Solved_leetcode_part1.ipynb │ ├── Solved_leetcode_part2.ipynb │ ├── Sorting Program │ │ ├── Bubblesort.py │ │ ├── Insertionsort.py │ │ ├── Mergesort.py │ │ ├── Selectionsort.py │ │ └── quickSort.py │ ├── Turtle.py │ ├── face attendance.ipynb │ ├── how_python_calculates_squareroot.py │ ├── infix_to_postifx.py │ ├── linked_lists.py │ ├── numpy_basic.py │ ├── self_dividing_numbers.py │ └── tictactoe.py ├── Binary_Tree.py ├── Blocking_website.py ├── Bouncing ball game.py ├── BreadthFirstSearch ├── Bubble Sort.py ├── CHOPSTICK │ └── CHOPSTICK.PY ├── Caeser Cipher.py ├── Calculator.py ├── Calendar.py ├── Counting Substrings in Strings.py ├── Dictionary │ ├── README.md │ ├── dictionary.py │ └── requirements.txt ├── DigitCounter.py ├── Digital_Clock_with_python.py ├── Face_recognition.py ├── Factorial.py ├── Fake-Advertising_Logistic_Regression.ipynb ├── Fibonacci.py ├── GCD_LCM.py ├── Grabbing first and last element of an Array │ └── List using List Indexing in python ├── GraphPlotting.py ├── Gunjan_Nayak_Reverse_Star_Pattern ├── Hangman_game.py ├── Hi-Lo Game.py ├── If-Else_Example.py ├── Image to Pencil Sketch │ ├── Readme.md │ └── img2sketch.py ├── Leapyear.py ├── Leetcode-question-3Sum.py ├── LinearSearch.py ├── Longest_common_prefix.py ├── Machine learning │ ├── Hacktoberfest Bot By RASA │ │ ├── README.md │ │ ├── actions │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-38.pyc │ │ │ │ └── actions.cpython-38.pyc │ │ │ └── actions.py │ │ ├── config.yml │ │ ├── credentials.yml │ │ ├── data │ │ │ ├── nlu.yml │ │ │ ├── rules.yml │ │ │ └── stories.yml │ │ ├── domain.yml │ │ ├── endpoints.yml │ │ ├── models │ │ │ └── 20211002-210417.tar.gz │ │ └── tests │ │ │ └── test_stories.yml │ ├── Linear_Regression │ │ ├── Readme.md │ │ ├── housing.csv │ │ └── linear-regression-scratch.ipynb │ └── Logistic_regression │ │ ├── Logistic_regression.py │ │ ├── ds1_test.csv │ │ └── ds1_train.csv ├── Name_generator.py ├── NumberGuessing.py ├── Number_ Guessing.py ├── Numberguessing_game.py ├── OpenCV Face and Movement Detector.py ├── PasswordGenerator_pawarspeaks.py ├── Password_generator.py ├── PermutationOfStringFromInput.py ├── PingPlot.py ├── Print First and Last element in array using List indexing.py ├── Python google ├── Qr_Code_Generator.py ├── Quiz-app │ ├── data.py │ ├── images │ │ ├── false.png │ │ └── true.png │ ├── main.py │ ├── question_model.py │ ├── quiz_brain.py │ └── ui.py ├── QuizzingGame.py ├── RANDOM_NUMBERS_SUM.ipynb ├── Random Number Generator.py ├── Reverse_Dictionary Function.py ├── Rock paper scissor_ ├── Roman_to_Numeral.py ├── Scrap amazon ├── ShortenTheURL.py ├── Simple Array Sum.py ├── Snake Game.py ├── Star_RightAngledTriangle_Pattern.py ├── Stop Watch_ ├── Sum of two numbers in python ├── Swap_numbers.py ├── Temperature Converter │ ├── README.md │ └── tempconv.py ├── Test.py ├── Tic_Tac_Toe.py ├── US Topic modelling.ipynb ├── Unblocking_website.py ├── Valid Sudoku.py ├── YouTubeDownloader.py ├── ZigZagPattern.py ├── advertising.csv ├── app.py ├── armstronNumberGenerator.py ├── bert.ipynb ├── calculator.py ├── casino games │ ├── Blackjack.py │ ├── README.md │ ├── Roulette.py │ ├── SevenUP_SevenDOWN.py │ └── Terminal_Casinogame.py ├── checkPalindromeNumber.py ├── chopstick_game.py ├── copy contents of one file to another.py ├── count_down_timer.py ├── couting_sort.py ├── deck_of_cards.py ├── dice-roller.py ├── dice_rolller_simulator.py ├── dog.py ├── factors_number.py ├── fcfs.py ├── find-new-videogames-to-play.py ├── find_gcd.py ├── for_loop.py ├── funktions.py ├── graphs.py ├── guessTheNumber.py ├── hamming.py ├── handcricket.py ├── handcricketgame.py ├── handtracker.py ├── heap_sort in python.py ├── kilometres_to_miles.py ├── lcs.py ├── main.py ├── matrix_multiplication.py ├── matrix_operations.py ├── mergeSortedArray.py ├── merge_sort.py ├── modulus.py ├── mp3 down ├── mp3_downloader.py ├── nQueen.py ├── naeema19_probdiff.py ├── numbersbooklet.py ├── pacman ├── palindrome.py ├── pass gen ├── passwordGenerator.py ├── passwordhasher.py ├── piglatin_translator.py ├── primeNumberGenerator.py ├── prime_number.py ├── primsalgorithm.py ├── problem.py ├── radix-sort.py ├── randomnumbergen.py ├── reverse_integer.py ├── rock_paper.py ├── rock_paper_scissor.py ├── scan.py ├── screenrecorder.py ├── selenium-automation.py ├── speak.py ├── sqrootbyBS.py ├── staircase_pattern.py ├── students_info.py ├── sudoku game solver.py ├── sudoku-game-solver.py ├── sudoku.py ├── texttospeech.py ├── tkinter │ ├── background.png │ ├── kanye.png │ └── main.py ├── topic modelling.ipynb ├── twoSum.py ├── typewriter-macro.py ├── wordSearch.py └── ytdownloader.py └── README.md /Python Codes/2 level organisation.py: -------------------------------------------------------------------------------- 1 | class Dir: 2 | def __init__(self,dirname): 3 | self.dirname = dirname 4 | self.folderlist = {} 5 | self.filelist = [] 6 | 7 | def createfolder(self,folder): 8 | if(folder not in self.folderlist): 9 | self.folderlist[folder.dirname] = folder 10 | print(f"Folder {folder.dirname} CREATED in {self.dirname}") 11 | else: 12 | print(f"Folder{folder.dirname} PRESENT") 13 | 14 | def createfile(self,file): 15 | if(file not in self.filelist): 16 | self.filelist.append(file) 17 | print(f"File {file} CREATED in {self.dirname}") 18 | else: 19 | print(f"File {file} PRESENT") 20 | 21 | 22 | def remove(self,name): 23 | if(name in self.filelist): 24 | self.filelist.remove(name) 25 | print(f"{name} REMOVED from {self.dirname}") 26 | elif(name in self.folderlist): 27 | self.folderlist.pop(name) 28 | print(f"{name} REMOVED from {self.dirname}") 29 | else: 30 | print("Doesn't Exist") 31 | 32 | def __repr__(self): 33 | return(f"{self.dirname}") 34 | 35 | 36 | dirname = input("Directory name:") 37 | d = Dir(dirname) 38 | print(f"Directory {d.dirname} CREATED\n") 39 | while(1): 40 | print("1.Create Folder\n2.Create File\n3.Remove\n4.Open Folder\n5.Insert\n6.Display\n7.Exit\n") 41 | x = int(input("\nChoose option ")) 42 | if(x==1): 43 | foldername = input("Give directory name: ") 44 | folder = Dir(foldername) 45 | d.createfolder(folder) 46 | elif(x==2): 47 | filename = input("Give file name: ") 48 | d.createfile(filename) 49 | elif(x==3): 50 | filename = input("Give file/directory name: ") 51 | d.remove(filename) 52 | elif(x==4): 53 | foldername = input("Give foldername to open: ") 54 | if(foldername in d.folderlist): 55 | open_folder = d.folderlist[foldername] 56 | print(f"Path: {d.dirname}/{foldername}") 57 | for name in open_folder.filelist: 58 | print(f"{name} <- file") 59 | print() 60 | elif(x==5): 61 | foldername = input("Enter foldername:" ) 62 | filename = input("Enter filename: ") 63 | if(foldername not in d.folderlist): 64 | print("Folder not in list") 65 | else: 66 | d.folderlist[foldername].createfile(filename) 67 | elif(x==6): 68 | print("*****************************") 69 | print(f"\nDirectory ->{d.dirname}\n") 70 | for folder in d.folderlist: 71 | print(f"{folder} <-folder") 72 | open_folder = d.folderlist[folder] 73 | for name in open_folder.filelist: 74 | print(f" ->{name} <- file") 75 | 76 | for file in d.filelist: 77 | print(f"{file} <-file") 78 | if(d.folderlist == {} and d.filelist==[]): 79 | print("Empty\n") 80 | print("*****************************") 81 | print() 82 | elif(x==7): 83 | print("Bye") 84 | exit(0) 85 | else: 86 | print("Invalid Input") 87 | 88 | -------------------------------------------------------------------------------- /Python Codes/22.Generators.py: -------------------------------------------------------------------------------- 1 | # Generators:- it is a memory effiecient and also time efficient 2 | # these are simple functions which returns in iterable set of item one at a time 3 | # Generator create refrence only 4 | 5 | # for example 6 | # for i in range(10000000000): 7 | # # print(i) 8 | 9 | # Range is a itself a generator and it is a memory efficient when we need to deal with a large dataset because it works on the fly 10 | # And if all the memory has been kept in a system it makes the system slow thats why generator come into the existens 11 | 12 | 13 | 14 | def generatt(): 15 | yield 10 16 | yield 20 17 | yield 30 18 | 19 | # g = generatt() 20 | 21 | # p = next(g) 22 | # print(p) 23 | 24 | # p = next(g) 25 | # print(p) 26 | 27 | # p = next(g) 28 | # print(p) 29 | 30 | 31 | 32 | def generat2(num): 33 | print("Printing Generator value") 34 | while(num>0): 35 | yield num 36 | # return num 37 | num = num-2 38 | 39 | # cd = generat2(20) 40 | 41 | # v = next(cd) 42 | # print(v) 43 | 44 | # v = next(cd) 45 | # print(v) 46 | 47 | # v = next(cd) 48 | # print(v) 49 | 50 | 51 | # fibonacci number using generator (0,1,1,2,3,5,8) 52 | def fibonacci(num): 53 | a,b = 0,1 54 | while(aself.lmlist[self.tipIds[0]-1][1]: 32 | fingers.append(1) 33 | else: 34 | fingers.append(0) 35 | #4 fingers 36 | for id in range(0,5): 37 | if self.lmlist[self.tipIds[id]][2]" 65 | itr = itr.next 66 | print(llstr) 67 | 68 | def print_reverse(self): 69 | if self.head == None: 70 | print("list is empty") 71 | else: 72 | itr = self.head 73 | while itr.next: 74 | itr = itr.next 75 | 76 | llstr = "" 77 | while itr: 78 | llstr += str(itr.data) + "<--->" 79 | itr = itr.prev 80 | print(llstr) 81 | 82 | 83 | # #=======execution=========# 84 | if __name__ == "__main__": 85 | ll = linkedlist() 86 | ll.insert_at_end("Hello") 87 | ll.print() 88 | ll.insert_at_end("World") 89 | ll.print() 90 | ll.insert_at_end("testing this") 91 | ll.print() 92 | ll.insert_at_beg("123") 93 | ll.print() 94 | ll.insert_at_beg("432") 95 | ll.print() 96 | ll.insert_at_pos("88",3) 97 | ll.print() 98 | ll.delete_from_pos(3) 99 | print("\n") 100 | print(f"Length of the list at this point is = {ll.count_nodes()}") 101 | print("\n") 102 | 103 | print("list in normal order") 104 | ll.print() 105 | 106 | print("\n") 107 | print("list in reverse order") 108 | ll.print_reverse() -------------------------------------------------------------------------------- /Python Codes/Advance Python/Infix_to_postfix_method2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Infix to Postfix method 2 ! 3 | Code contributed by: Hriday Agrawal 4 | Github Name: HridayAg0102 5 | 6 | 7 | #======SAMPLE INPUT:=========# 8 | 9 | abc+-d(a^b*/c) 10 | 11 | #======SAMPLE OUTPUT:=========# 12 | 13 | Postfix for word abc+-d(a^b*/c) is: "abc+dab^*c/-" 14 | 15 | """ 16 | 17 | 18 | 19 | def infix_to_postfix(word): 20 | word = "(" + word + ")" 21 | postfix = "" 22 | stack = [] 23 | order= {"^":3,"/":2,"*":2,"+":1,"-":1} #preference order 24 | 25 | 26 | for i in range(len(word)): 27 | 28 | if word[i] == "(": 29 | stack.append("(") 30 | 31 | 32 | 33 | elif word[i] in order: 34 | 35 | if word[i-1] == "(" or word[i-1] not in order: 36 | if len(stack)>=1: 37 | while stack[len(stack) - 1] in order and order[stack[len(stack) - 1]] >= order[word[i]]: 38 | postfix += str(stack[len(stack)-1]) 39 | stack.pop() 40 | stack.append(word[i]) 41 | 42 | 43 | elif order[word[i-1]] < order[word[i]]: 44 | stack.append(word[i]) 45 | 46 | #checks if the current char. has higher pref. 47 | #hence gets appended to the stack & not to word. 48 | 49 | 50 | 51 | 52 | elif order[stack[len(stack) - 1]] >= order[word[i]]: 53 | 54 | #if current char has lower pref than previous 55 | #add the last element of stack to the word, pop it, 56 | #append the current element to stack 57 | 58 | postfix += stack[len(stack) - 1] 59 | stack.pop() 60 | stack.append(word[i]) 61 | 62 | 63 | 64 | 65 | else: 66 | 67 | # Applying if condition to check ")" and then running a loop inside "()". 68 | 69 | if word[i] == ")": 70 | z = len(stack)-1 71 | while True: 72 | if stack[z] == "(": 73 | stack.pop(z) 74 | 75 | break 76 | else: 77 | postfix += stack[z] 78 | stack.pop(z) 79 | z-=1 80 | 81 | i = z-1 #reassigns value of i 82 | 83 | 84 | else: 85 | postfix += str(word[i]) 86 | 87 | return postfix 88 | 89 | 90 | 91 | 92 | 93 | if __name__ == "__main__": 94 | word = input() 95 | print(f"Postfix for word {word} is: \"{infix_to_postfix(word)}\"") 96 | 97 | 98 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Magic_Cloak.py: -------------------------------------------------------------------------------- 1 | #In this project, we use a red cloth as a cover background, but you can change it any color u want!!! 2 | ##Like and follor my GitHub acc for more! 3 | #https://github.com/akarshan2602 4 | 5 | 6 | import cv2 7 | import numpy as np 8 | import time 9 | 10 | fourCC = cv2.VideoWriter_fourcc(*'XVID') 11 | # this is used to capture video in OpenCV 12 | # fourCC is a 4-byte video code, used to specify the video code 13 | # for Windows, the video code is "*'XVID'" and for Mac, it is "*'MJPG'" 14 | 15 | out = cv2.VideoWriter('output.avi', fourCC, 20, (200, 200)) 16 | # (fileName, fourCCvariable, framesPerSec, frameSize) 17 | 18 | cap = cv2.VideoCapture(0) # you can use 0 or 1 to capture the video 19 | 20 | time.sleep(3) 21 | # 3 second delay to give time for the settings to execute before the webcam starts 22 | 23 | # variables 24 | count = 0 25 | background = 0 26 | 27 | # while this forloop runs, capture the background 28 | for i in range(60): # capturing the bkgrd 60 times, and overlapping to make one 29 | returnV, background = cap.read() 30 | # returnV is a boolean value which returns True if captured properly 31 | # background is the captured background in an array of pixels 32 | 33 | background = np.flip(background, axis=1) 34 | # flipping the background to avoid mirror image 35 | 36 | while(cap.isOpened()): # while your camera is opened, this will run 37 | returnV, img = cap.read() # returnV is true or false 38 | if not(returnV): # if at any point, return becomes false, break the loop 39 | break 40 | count += 1 # keeping count of the number of times this run (no use1) 41 | img = np.flip(img, axis=1) # flipping the current video 42 | 43 | hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # converting your image to HSV 44 | lower_red = np.array([0, 120, 50]) # saturation is 120-255, value is 50-255 45 | upper_red = np.array([10, 255, 255]) 46 | mask1 = cv2.inRange(hsv, lower_red, upper_red) 47 | # detecting wheter image pixel colors are in range of the colors 48 | # creates binary mask, so binary operations can be used 49 | 50 | lower_red = np.array([170, 120, 50]) 51 | upper_red = np.array([180, 255, 255]) 52 | mask2 = cv2.inRange(hsv, lower_red, upper_red) 53 | 54 | mask1 += mask2 # combining both masks 55 | 56 | mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3,3), np.uint8)) 57 | 58 | ''' MORPH_OPEN preforms 2 operations: Erosion and Dilation 59 | Erosion removes extra white spaces (noise) from image, shrinking it 60 | Dilation is reverse of Erosion, wherein clean white spaces are added, 61 | making the image the same size ''' 62 | 63 | # np.ones makes it so that every kernel is more smooth 64 | # np.uint8 makes it so that every kernel is within 0-255 65 | 66 | mask2 = cv2.bitwise_not(mask1) 67 | result1 = cv2.bitwise_and(img, img, mask=mask2) 68 | result2 = cv2.bitwise_and(background, background, mask=mask1) 69 | 70 | finalOutput = cv2.addWeighted(result1, 1, result2, 1, 0) 71 | # equal dominance of result1 and result 2 (0 is just nessecary for syntax) 72 | 73 | out.write(finalOutput) 74 | # writing the output and making it offical 75 | 76 | cv2.imshow('Magic!', finalOutput) 77 | # shown in fourCC video writer as 'Magic' 78 | 79 | # if you hold q for 1 second, the loop breaks 80 | cv2.waitKey(1) 81 | if cv2.waitKey(1) & 0xFF == ord('q'): 82 | break 83 | 84 | # when the loop breaks, everything stops 85 | cap.release() 86 | out.release() 87 | cv2.destroyAllWindows() 88 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Advance Python/Mail Merge Python/.DS_Store -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/Input/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Advance Python/Mail Merge Python/Input/.DS_Store -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/Input/Letters/starting_letter.txt: -------------------------------------------------------------------------------- 1 | Dear [name], 2 | 3 | You are invited to my birthday this Saturday. 4 | 5 | Hope you can make it! 6 | 7 | Rashid. 8 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/Input/Names/invited_names.txt: -------------------------------------------------------------------------------- 1 | Rashid 2 | Aziz 3 | Badar 4 | Wahid 5 | Talib 6 | Inayat 7 | Uncle John 8 | Toph -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/Output/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Advance Python/Mail Merge Python/Output/.DS_Store -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/Output/ReadyToSend/example.txt: -------------------------------------------------------------------------------- 1 | Dear Aang, 2 | 3 | You are invited to my birthday this Saturday. 4 | 5 | Hope you can make it! 6 | 7 | Rashid 8 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Mail Merge Python/main.py: -------------------------------------------------------------------------------- 1 | # reading invited names and adding them into the list... 2 | with open('./Input/Names/invited_names.txt') as invited_people: 3 | invited_people_list = invited_people.readlines() 4 | 5 | # for each person, 6 | for person in invited_people_list: 7 | with open('Input/Letters/starting_letter.txt') as letter: 8 | # creating new string with replaced name, 9 | letter_content = letter.read().replace('[name]', person) 10 | 11 | # saving files with the content. 12 | with open(f'Output/ReadyToSend/letter_to_{person}.txt', 'w') as ready_letter: 13 | ready_letter.write(letter_content) 14 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Prim's_algorithm.py: -------------------------------------------------------------------------------- 1 | # A Python program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | # The program is for adjacency matrix representation of the graph 3 | 4 | import sys # Library for INT_MAX 5 | 6 | class Graph(): 7 | 8 | def __init__(self, vertices): 9 | self.V = vertices 10 | self.graph = [[0 for column in range(vertices)] 11 | for row in range(vertices)] 12 | 13 | # A utility function to print the constructed MST stored in parent[] 14 | def printMST(self, parent): 15 | print "Edge \tWeight" 16 | for i in range(1, self.V): 17 | print parent[i], "-", i, "\t", self.graph[i][ parent[i] ] 18 | 19 | # A utility function to find the vertex with 20 | # minimum distance value, from the set of vertices 21 | # not yet included in shortest path tree 22 | def minKey(self, key, mstSet): 23 | 24 | # Initialize min value 25 | min = sys.maxint 26 | 27 | for v in range(self.V): 28 | if key[v] < min and mstSet[v] == False: 29 | min = key[v] 30 | min_index = v 31 | 32 | return min_index 33 | 34 | # Function to construct and print MST for a graph 35 | # represented using adjacency matrix representation 36 | def primMST(self): 37 | 38 | # Key values used to pick minimum weight edge in cut 39 | key = [sys.maxint] * self.V 40 | parent = [None] * self.V # Array to store constructed MST 41 | # Make key 0 so that this vertex is picked as first vertex 42 | key[0] = 0 43 | mstSet = [False] * self.V 44 | 45 | parent[0] = -1 # First node is always the root of 46 | 47 | for cout in range(self.V): 48 | 49 | # Pick the minimum distance vertex from 50 | # the set of vertices not yet processed. 51 | # u is always equal to src in first iteration 52 | u = self.minKey(key, mstSet) 53 | 54 | # Put the minimum distance vertex in 55 | # the shortest path tree 56 | mstSet[u] = True 57 | 58 | # Update dist value of the adjacent vertices 59 | # of the picked vertex only if the current 60 | # distance is greater than new distance and 61 | # the vertex in not in the shortest path tree 62 | for v in range(self.V): 63 | 64 | # graph[u][v] is non zero only for adjacent vertices of m 65 | # mstSet[v] is false for vertices not yet included in MST 66 | # Update the key only if graph[u][v] is smaller than key[v] 67 | if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: 68 | key[v] = self.graph[u][v] 69 | parent[v] = u 70 | 71 | self.printMST(parent) 72 | 73 | g = Graph(5) 74 | g.graph = [ [0, 2, 0, 6, 0], 75 | [2, 0, 3, 8, 5], 76 | [0, 3, 0, 0, 7], 77 | [6, 8, 0, 0, 9], 78 | [0, 5, 7, 9, 0]] 79 | 80 | g.primMST() 81 | 82 | # Contributed by Divyanshu Mehta 83 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Rearrange the array in alternating positive and negative items with O(1) extra space.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Aug 28 18:26:48 2021 4 | 5 | @author: Debanjan Rudra 6 | """ 7 | 8 | def rearrange(A, n): 9 | 10 | A.sort() 11 | 12 | i, j = 1, 1 13 | 14 | while j < n: 15 | 16 | if A[j] > 0: 17 | 18 | break 19 | 20 | j += 1 21 | 22 | while (A[i] < 0) and (j < n): 23 | 24 | A[i], A[j] = A[j], A[i] 25 | 26 | i += 2 27 | j += 1 28 | 29 | return A 30 | 31 | if __name__=='__main__': 32 | 33 | for _ in range(int(input())): 34 | 35 | A = list(map(int,input().rstrip().split())) 36 | 37 | ans = rearrange(A, len(A)) 38 | 39 | print(*ans) -------------------------------------------------------------------------------- /Python Codes/Advance Python/Sorting Program/Bubblesort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(list1): 2 | # Outer loop for traverse the entire list 3 | for i in range(0,len(list1)-1): 4 | for j in range(len(list1)-1): 5 | if(list1[j]>list1[j+1]): 6 | temp = list1[j] 7 | list1[j] = list1[j+1] 8 | list1[j+1] = temp 9 | return list1 10 | 11 | list1 = [5, 3, 8, 6, 7, 2] 12 | print("The unsorted list is: ", list1) 13 | print("The sorted list is: ", bubble_sort(list1)) 14 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Sorting Program/Insertionsort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >=0 and key < arr[j] : 16 | arr[j+1] = arr[j] 17 | j -= 1 18 | arr[j+1] = key 19 | 20 | 21 | # Driver code to test above 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | print ("Sorted array is:") 25 | for i in range(len(arr)): 26 | print ("%d" %arr[i]) 27 | 28 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Sorting Program/Mergesort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i]), 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i]), 79 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Sorting Program/Selectionsort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Selection 2 | # Sort 3 | import sys 4 | A = [64, 25, 12, 22, 11] 5 | 6 | # Traverse through all array elements 7 | for i in range(len(A)): 8 | 9 | # Find the minimum element in remaining 10 | # unsorted array 11 | min_idx = i 12 | for j in range(i+1, len(A)): 13 | if A[min_idx] > A[j]: 14 | min_idx = j 15 | 16 | # Swap the found minimum element with 17 | # the first element 18 | A[i], A[min_idx] = A[min_idx], A[i] 19 | 20 | # Driver code to test above 21 | print ("Sorted array") 22 | for i in range(len(A)): 23 | print("%d" %A[i]), 24 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/Sorting Program/quickSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Quicksort Sort 2 | 3 | # This function takes last element as pivot, places 4 | # the pivot element at its correct position in sorted 5 | # array, and places all smaller (smaller than pivot) 6 | # to left of pivot and all greater elements to right 7 | # of pivot 8 | 9 | 10 | def partition(arr, low, high): 11 | i = (low-1) # index of smaller element 12 | pivot = arr[high] # pivot 13 | 14 | for j in range(low, high): 15 | 16 | # If current element is smaller than or 17 | # equal to pivot 18 | if arr[j] <= pivot: 19 | 20 | # increment index of smaller element 21 | i = i+1 22 | arr[i], arr[j] = arr[j], arr[i] 23 | 24 | arr[i+1], arr[high] = arr[high], arr[i+1] 25 | return (i+1) 26 | 27 | # The main function that implements QuickSort 28 | # arr[] --> Array to be sorted, 29 | # low --> Starting index, 30 | # high --> Ending index 31 | 32 | # Function to do Quick sort 33 | 34 | 35 | def quickSort(arr, low, high): 36 | if len(arr) == 1: 37 | return arr 38 | if low < high: 39 | 40 | # pi is partitioning index, arr[p] is now 41 | # at right place 42 | pi = partition(arr, low, high) 43 | 44 | # Separately sort elements before 45 | # partition and after partition 46 | quickSort(arr, low, pi-1) 47 | quickSort(arr, pi+1, high) 48 | 49 | 50 | # Driver code to test above 51 | arr = [10, 7, 8, 9, 1, 5] 52 | n = len(arr) 53 | quickSort(arr, 0, n-1) 54 | print("Sorted array is:") 55 | for i in range(n): 56 | print("%d" % arr[i]), 57 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/face attendance.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "C:\\Users\\Kuwar\\photo array\\ \n", 13 | "(500, 1500)\n" 14 | ] 15 | } 16 | ], 17 | "source": [ 18 | "import cv2 \n", 19 | "import os\n", 20 | "import numpy as np\n", 21 | "cam=cv2.VideoCapture(0)\n", 22 | "dataset=r\"C:\\Users\\Kuwar\\photo array\\ \"\n", 23 | "name=''\n", 24 | "haar = cv2.CascadeClassifier('D:\\haarcascade_frontalface_default.xml')\n", 25 | "data=[]\n", 26 | "print(dataset)\n", 27 | "name=True\n", 28 | "re,im=cam.read()\n", 29 | "while(name):\n", 30 | " ret, img = cam.read()\n", 31 | " #gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n", 32 | " faces = haar.detectMultiScale(img, 1.3, 5)\n", 33 | " for face in faces:\n", 34 | " x, y, w, h = face\n", 35 | " offset = 5\n", 36 | " face_offset = img[y - offset:y + h + offset, x - offset:x + w + offset]\n", 37 | " face_selection = cv2.resize(face_offset, (500, 500))\n", 38 | " data.append(face_selection)\n", 39 | " for (x, y, w, h) in faces:\n", 40 | " cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n", 41 | " cv2.imshow('image',img)\n", 42 | " if cv2.waitKey(0) & 0xff==ord('q'):\n", 43 | " break\n", 44 | " \n", 45 | " \n", 46 | " for (x, y, w, h) in faces: \n", 47 | " data = np.array(face_selection)\n", 48 | " data = data.reshape((data.shape[0], -1))\n", 49 | " print(data.shape)\n", 50 | " name = input(\"file_name\")\n", 51 | " np.save(dataset + name, data)\n", 52 | " print(\"Dataset saved at : {}\".format(dataset + name + '.npy'))\n", 53 | "\n", 54 | " #for (x, y, w, h) in faces[:1]:\n", 55 | " \n", 56 | " cam.release()\n", 57 | " cv2.destroyAllWindows()\n", 58 | " name=False\n", 59 | " print(f'Number of faces found = {len(faces)}')" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [] 89 | } 90 | ], 91 | "metadata": { 92 | "kernelspec": { 93 | "display_name": "Python 3", 94 | "language": "python", 95 | "name": "python3" 96 | }, 97 | "language_info": { 98 | "codemirror_mode": { 99 | "name": "ipython", 100 | "version": 3 101 | }, 102 | "file_extension": ".py", 103 | "mimetype": "text/x-python", 104 | "name": "python", 105 | "nbconvert_exporter": "python", 106 | "pygments_lexer": "ipython3", 107 | "version": "3.8.3" 108 | } 109 | }, 110 | "nbformat": 4, 111 | "nbformat_minor": 4 112 | } 113 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/how_python_calculates_squareroot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ever wondered how python is able to calculate squareroot of a non-perfect square number? 3 | This code shows how is python able to calculate it ! 4 | 5 | Code contributed by: Hriday Agrawal 6 | Github Name: HridayAg0102 7 | 8 | 9 | #======SAMPLE OUTPUT:=========# 10 | 11 | Number: 300143838031, its root: 547853.8473270038 12 | 13 | Start approximation 14 | 650072.8960528814 15 | 555890.4336743704 16 | 547911.940357758 17 | 547853.850406696 18 | 547853.8473270038 19 | Found true root after 6 guesses. 20 | """ 21 | 22 | 23 | import random 24 | 25 | # get a random number, range 1 trillion 26 | rand_int = random.randint(0, 1e12) 27 | true_root = rand_int ** 0.5 28 | print(f"Number: {rand_int}, its root: {true_root}\n") 29 | 30 | guess = rand_int // 1e6 # divide by 1 million 31 | counter = 0 # counts how many guesses made till now. 32 | 33 | print("Start approximation") 34 | while True: 35 | counter += 1 36 | 37 | # improve on the guess 38 | prev_guess, guess = guess, (rand_int / guess + guess) / 2 39 | if prev_guess == guess: 40 | print(f"Found true root after {counter} guesses.") 41 | break 42 | print(guess) 43 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/infix_to_postifx.py: -------------------------------------------------------------------------------- 1 | class stacki: 2 | size=0 3 | capacity=1000 4 | li=[0]*capacity 5 | 6 | def __init__(self): 7 | pass 8 | 9 | def empty(self): 10 | return self.size==0 11 | 12 | def full(self): 13 | return self.size==self.capacity 14 | 15 | def push(self,a): 16 | if self.size==self.capacity: 17 | print("Stack full") 18 | else: 19 | self.li[self.size]=a 20 | self.size+=1 21 | def pop(self): 22 | if self.size==0: 23 | print("Stack empty") 24 | else: 25 | self.size-=1 26 | def top(self): 27 | return self.li[self.size-1] 28 | 29 | def precedence(c): 30 | if c=="^": 31 | return 3 32 | if c=="*" or c=="/": 33 | return 2 34 | if c=="+" or c=="-": 35 | return 1 36 | return 0 37 | 38 | def convert(s): 39 | sed=stacki() 40 | ans="" 41 | for i in range(len(s)): 42 | if s[i]=="+" or s[i]=="-" or s[i]=="*" or s[i]=="/" or s[i]=="^": 43 | while not sed.empty() and precedence(s[i])<=precedence(sed.top()): 44 | ans+=sed.top() 45 | sed.pop() 46 | sed.push(s[i]) 47 | elif s[i]=="(": 48 | sed.push(s[i]) 49 | elif s[i]==")": 50 | while not sed.empty() and sed.top()!="(": 51 | ans+=sed.top() 52 | sed.pop() 53 | sed.pop() 54 | else: 55 | ans+=s[i] 56 | while not sed.empty(): 57 | ans+=sed.top() 58 | sed.pop() 59 | return ans 60 | 61 | s=input() 62 | print(convert(s)) -------------------------------------------------------------------------------- /Python Codes/Advance Python/linked_lists.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self, data, next): 4 | self.data = data 5 | self.next = next 6 | 7 | class LinkedList: 8 | 9 | def __init__(self): 10 | self.head = None 11 | 12 | def print(self): 13 | 14 | if self.head is None: 15 | print("Linked List is empty") 16 | return 17 | 18 | itr = self.head 19 | llstr = ' ' 20 | 21 | while itr: 22 | llstr += str(itr.data) + '-->' 23 | itr = itr.next 24 | print(llstr) 25 | 26 | def get_length(self): 27 | 28 | count = 0 29 | itr = self.head 30 | 31 | while itr: 32 | count += 1 33 | itr = itr.next 34 | 35 | print(count) 36 | 37 | def insert_at_beginning(self, data): 38 | 39 | node = Node(data, self.head) 40 | self.head = node 41 | 42 | def insert_at_end(self, data): 43 | 44 | if self.head is None: 45 | self.head = Node(data, None) 46 | return 47 | 48 | itr = self.head 49 | 50 | while itr.next: 51 | itr = itr.next 52 | 53 | itr.next = Node(data, None) 54 | 55 | def insert_at(self, index, data): 56 | 57 | if index < 0 or index > self.get_length(): 58 | raise Exception("Invalid Index") 59 | 60 | if index == 0: 61 | self.insert_at_beginning(data) 62 | return 63 | 64 | count = 0 65 | itr = self.head 66 | 67 | while itr: 68 | if count == index - 1: 69 | node = Node(data, itr.next) 70 | itr.next = node 71 | break 72 | 73 | itr = itr.next 74 | count += 1 75 | 76 | def remove_at(self, index): 77 | 78 | if index < 0 or index > self.get_length(): 79 | raise Exception("Invalid Index") 80 | 81 | count = 0 82 | itr = self.head 83 | 84 | while itr: 85 | if count == index - 1: 86 | itr.next = itr.next.next 87 | break 88 | 89 | itr = itr.next 90 | count += 1 91 | 92 | def insert_values(self, data_list): 93 | 94 | self.head = None 95 | 96 | for data in data_list: 97 | self.insert_at_end(data) 98 | 99 | if __name__ == '__main__': 100 | 101 | ll = LinkedList() 102 | 103 | 104 | print(''' 105 | a -> insert values 106 | b -> insert a value at the beginning 107 | c -> insert a value at the end 108 | d -> insert a value at any index 109 | e -> remove a value at any index 110 | f -> get the length of the linked list 111 | g -> exit from the program 112 | ''' 113 | ) 114 | 115 | while True: 116 | 117 | ch = input() 118 | 119 | if (ch == "a"): 120 | ll.insert_values(list(input().split())) 121 | ll.print() 122 | 123 | elif (ch == "b"): 124 | ll.insert_at_beginning(input()) 125 | ll.print() 126 | 127 | elif (ch == "c"): 128 | ll.insert_at_end(input()) 129 | ll.print() 130 | 131 | elif (ch == "d"): 132 | ll.insert_at(int(input()), input()) 133 | ll.print() 134 | 135 | elif (ch == "e"): 136 | ll.remove_at(int(input())) 137 | ll.print() 138 | 139 | elif (ch == "f"): 140 | ll.get_length() 141 | 142 | elif(ch == "g"): 143 | break 144 | 145 | -------------------------------------------------------------------------------- /Python Codes/Advance Python/numpy_basic.py: -------------------------------------------------------------------------------- 1 | # ============= WHAT IS NUMPY ? ============= 2 | 3 | # NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides 4 | # a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment 5 | # of routines for fast operations on arrays, 6 | # including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, 7 | # basic linear algebra, basic statistical operations, 8 | # random simulation and much more. 9 | 10 | 11 | 12 | 13 | # ============= REQUIREMENT ============= 14 | # pip install numpy 15 | 16 | # ============= IMPORT MODULE/PACKAGE ============= 17 | import numpy as np 18 | 19 | # ============= MAKE ARRAY USING NUMPY ============= 20 | array1 = np.array([1, 2, 3 ,4, 5]) 21 | print("Result is :" , array1) 22 | 23 | # RESULT : 24 | # Result is : [1 2 3 4 5] 25 | 26 | # ============= MAKE ARRAY WITH 0 VALUE ============= 27 | array2 = np.zeros(5) # MAKE ARRAY 0 VALUE AS MUCH 5 28 | print("Result is :", array2) 29 | 30 | # RESULT : 31 | # Result is : [0. 0. 0. 0. 0.] 32 | 33 | # ============= MAKE ARRAY WITH 1 VALUE ============= 34 | array3 = np.ones(5) # MAKE ARRAY 1 VALUE AS MUCH 5 35 | print("Result is :", array3) 36 | 37 | # RESULT : 38 | # Result is : [1. 1. 1. 1. 1.] 39 | 40 | 41 | # ==================== THANKS FOR YOUR ATTENTION, I HOPE YOU LIKE THIS ==================== -------------------------------------------------------------------------------- /Python Codes/Advance Python/self_dividing_numbers.py: -------------------------------------------------------------------------------- 1 | #We are given two numbers and we have to find all the self dividing numbers in this range 2 | def selfDividingNumbers(left, right): 3 | #lst stores all the self dividing numbers 4 | lst = [] 5 | for i in range(left,right+1): 6 | val = i 7 | while val>0: 8 | #Taking the last digit of the number 9 | r = val%10 10 | #If number contains 0 or a it's digit doesn't divide it, we break 11 | if r==0 or i%r!=0: 12 | break 13 | #Removing last digit of the number 14 | val = val//10 15 | #val=0 means we have checked all digits of the number and they all divide it completely 16 | if val==0: 17 | #We add the self dividing number to lst 18 | lst.append(i) 19 | #We return the list of self dividng numbers 20 | return lst -------------------------------------------------------------------------------- /Python Codes/Advance Python/tictactoe.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def status(board): 4 | ''' 5 | This function is used to check if anyone won the game. 6 | Here, T-Top R-Right 7 | M-Middle M-Middle 8 | B-Bottom L-Left 9 | 10 | ''' 11 | if board['TL'] == board['TM'] == board['TR'] and board['TL'] != ' ': 12 | return board['TL'] 13 | elif board['ML'] == board['MM'] == board['MR'] and board['ML'] != ' ': 14 | return board['ML'] 15 | elif board['BL'] == board['BM'] == board['BR'] and board['BL'] != ' ': 16 | return board['BL'] 17 | elif board['TL'] == board['ML'] == board['BL'] and board['TL'] != ' ': 18 | return board['TL'] 19 | elif board['TM'] == board['MM'] == board['BM'] and board['TM'] != ' ': 20 | return board['TM'] 21 | elif board['TR'] == board['MR'] == board['BR'] and board['TR'] != ' ': 22 | return board['TR'] 23 | elif board['TL'] == board['MM'] == board['BR'] and board['TL'] != ' ': 24 | return board['TL'] 25 | elif board['TR'] == board['MM'] == board['BL'] and board['TR'] != ' ': 26 | return board['TR'] 27 | else: 28 | return 'D' 29 | 30 | def printboard(board): 31 | ''' 32 | Used to print the board in the following fashion: 33 | TL | TM | TR 34 | ---+----+--- 35 | ML | MM | MR 36 | ---+----+--- 37 | BL | BM | BR 38 | ''' 39 | print(board['TL']+"|"+board['TM']+"|"+board['TR']) 40 | print("-+-+-") 41 | print(board['ML']+"|"+board['MM']+"|"+board['MR']) 42 | print("-+-+-") 43 | print(board['BL']+"|"+board['BM']+"|"+board['BR']) 44 | 45 | 46 | 47 | ''' 48 | Following is the driver code, which calls the 49 | above functions repetitively until there is a 50 | result. 51 | ''' 52 | 53 | board = {'TL':' ','TM':' ','TR':' ', 54 | 'ML':' ','MM':' ','MR':' ', 55 | 'BL':' ','BM':' ','BR':' ' 56 | } 57 | print("-----------RULES-----------") 58 | print("For Top Left enter TL") 59 | print("For Middle Middle enter MM") 60 | print("For Bottom Right enter BR") 61 | print("And so on.......") 62 | print("---------------------------") 63 | p1 = input("Enter the name of Player 1, choosing O : ") 64 | p2 = input("Enter the name of Player 2, choosing X : ") 65 | turn = 0 66 | print("Board at begining") 67 | printboard(board) 68 | while turn<=9: 69 | print(p1+"'s turn. Enter the position") 70 | inp = input() 71 | board[inp] = 'O' 72 | printboard(board) 73 | turn+=1 74 | if status(board) == 'X': 75 | print(p2+" Wins!!") 76 | break 77 | elif status(board)=='O': 78 | print(p1+" Wins!!") 79 | break 80 | else: 81 | if turn==9: 82 | print("Draw") 83 | break 84 | print(p2+"'s turn. Enter the position") 85 | inp = input() 86 | board[inp] = 'X' 87 | printboard(board) 88 | turn+=1 89 | if status(board) == 'X': 90 | print(p2+" Wins!!") 91 | break 92 | elif status(board)=='O': 93 | print(p1+" Wins!!") 94 | break 95 | else: 96 | if turn==9: 97 | print("Draw") 98 | break -------------------------------------------------------------------------------- /Python Codes/Binary_Tree.py: -------------------------------------------------------------------------------- 1 | class TreeNode(): 2 | #Constructor function 3 | def __init__(self, key): 4 | self.key, self.left, self.right = key, None, None 5 | #Maximun Height of the Binary Tree 6 | def height(self): 7 | if self is None: 8 | return 0 9 | return 1 + max(TreeNode.height(self.left), TreeNode.height(self.right)) 10 | #Size of the Tree 11 | def size(self): 12 | if self is None: 13 | return 0 14 | return 1 + TreeNode.size(self.left) + TreeNode.size(self.right) 15 | #Inorder Traversal 16 | def traverse_in_order(self): 17 | if self is None: 18 | return [] 19 | return (TreeNode.traverse_in_order(self.left) + 20 | [self.key] + 21 | TreeNode.traverse_in_order(self.right)) 22 | #Preorder Traversal 23 | def preorderTraversal(self): 24 | if root is None: 25 | return [] 26 | return([self.val]+TreeNode.postorderTraversal(self.left)+ 27 | TreeNode.postorderTraversal(self.right)) 28 | #Postorder Traversal 29 | def postorderTraversal(self): 30 | if root is None: 31 | return [] 32 | return(TreeNode.postorderTraversal(self.left)+ 33 | TreeNode.postorderTraversal(self.right)+[self.val]) 34 | #Returns the Nodes of the Tree in a Tuple 35 | def to_tuple(self): 36 | if self is None: 37 | return None 38 | if self.left is None and self.right is None: 39 | return self.key 40 | return TreeNode.to_tuple(self.left), self.key, TreeNode.to_tuple(self.right) 41 | #Taking input as a tuple and converting it in a Binary Tree 42 | @staticmethod 43 | def parse_tuple(data): 44 | if data is None: 45 | node = None 46 | elif isinstance(data, tuple) and len(data) == 3: 47 | node = TreeNode(data[1]) 48 | node.left = TreeNode.parse_tuple(data[0]) 49 | node.right = TreeNode.parse_tuple(data[2]) 50 | else: 51 | node = TreeNode(data) 52 | return node -------------------------------------------------------------------------------- /Python Codes/Blocking_website.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime as dt 3 | 4 | sites_to_block = [ 5 | "www.facebook.com", 6 | "facebook.com", 7 | "www.youtube.com", 8 | "youtube.com", 9 | "www.gmail.com", 10 | "gmail.com", 11 | ] 12 | 13 | Window_host = r"C:\\Windows\\System32\\drivers\\etc\\hosts" 14 | default_hoster = Window_host 15 | redirect = "127.0.0.1" 16 | 17 | 18 | def block_websites(start_hour, end_hour): 19 | while True: 20 | if ( 21 | dt(dt.now().year, dt.now().month, dt.now().day, start_hour) 22 | < dt.now() 23 | < dt(dt.now().year, dt.now().month, dt.now().day, end_hour) 24 | ): 25 | print("Do the work ....") 26 | with open(default_hoster, "r+") as hostfile: 27 | hosts = hostfile.read() 28 | for site in sites_to_block: 29 | if site not in hosts: 30 | hostfile.write(redirect + " " + site + "\n") 31 | else: 32 | with open(default_hoster, "r+") as hostfile: 33 | hosts = hostfile.readlines() 34 | hostfile.seek(0) 35 | for host in hosts: 36 | if not any(site in host for site in sites_to_block): 37 | hostfile.write(host) 38 | hostfile.truncate() 39 | print("Good Time") 40 | time.sleep(3) 41 | 42 | 43 | if __name__ == "__main__": 44 | block_websites(9, 21) -------------------------------------------------------------------------------- /Python Codes/Bouncing ball game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | BLACK = (0, 0, 0) 5 | WHITE = (255, 255, 255) 6 | SCREEN_WIDTH = 700 7 | SCREEN_HEIGHT = 500 8 | BALL_SIZE = 25 9 | 10 | class Ball: 11 | def __init__(self): 12 | self.x = 0 13 | self.y = 0 14 | self.change_x = 0 15 | self.change_y = 0 16 | 17 | def make_ball(): 18 | ball = Ball() 19 | ball.x = random.randrange(BALL_SIZE, SCREEN_WIDTH - BALL_SIZE) 20 | ball.y = random.randrange(BALL_SIZE, SCREEN_HEIGHT - BALL_SIZE) 21 | ball.change_x = random.randrange(-2, 3) 22 | ball.change_y = random.randrange(-2, 3) 23 | return ball 24 | 25 | def main(): 26 | pygame.init() 27 | size = [SCREEN_WIDTH, SCREEN_HEIGHT] 28 | screen = pygame.display.set_mode(size) 29 | pygame.display.set_caption("Bouncing Balls") 30 | 31 | done = False 32 | clock = pygame.time.Clock() 33 | ball_list = [] 34 | ball = make_ball() 35 | ball_list.append(ball) 36 | 37 | #--- Main Program --- 38 | 39 | while not done: 40 | for event in pygame.event.get(): 41 | if event.type == pygame.QUIT: 42 | done = True 43 | elif event.type == pygame.KEYDOWN: 44 | if event.key == pygame.K_SPACE: 45 | ball = make_ball() 46 | ball_list.append(ball) 47 | for ball in ball_list: 48 | ball.x += ball.change_x 49 | ball.y += ball.change_y 50 | if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE: 51 | ball.change_y *= -1 52 | if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x < BALL_SIZE: 53 | ball.change_x *= -1 54 | screen.fill(BLACK) 55 | for ball in ball_list: 56 | pygame.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE) 57 | clock.tick(60) 58 | pygame.display.flip() 59 | pygame.quit() 60 | 61 | if __name__ == "__main__": 62 | main() 63 | -------------------------------------------------------------------------------- /Python Codes/BreadthFirstSearch: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self): 3 | self.graph = defaultdict(list) 4 | 5 | def addEdge(self,u,v): 6 | self.graph[u].append(v) 7 | 8 | def BFS(self, s): 9 | visited = [False] * (max(self.graph) + 1) 10 | queue = [] 11 | queue.append(s) 12 | visited[s] = True 13 | 14 | while queue: 15 | s = queue.pop(0) 16 | print (s, end = " ") 17 | for i in self.graph[s]: 18 | if visited[i] == False: 19 | queue.append(i) 20 | visited[i] = True 21 | 22 | 23 | -------------------------------------------------------------------------------- /Python Codes/Bubble Sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[1]: 5 | 6 | 7 | def bubble_sort(arr): #Created a function named Bubble-sort 8 | for i in range(len(arr)-1): #Created a for loop for itterating through each element of the array 9 | for j in range(len(arr)-1): #Created again a for loop for itterating through the list 10 | if arr[j]>arr[j+1]: #Comparing the adjacent element 11 | arr[j],arr[j+1]=arr[j+1],arr[j] #Swapping the elements according to their values (Bigger / Smaller) 12 | arr=[int(x) for x in input().split()] #List comprehension for taking the input through user 13 | bubble_sort(arr) #Calling the function that we created 14 | print(arr) #As the list are mutable so calling the same array after applying the function 15 | 16 | -------------------------------------------------------------------------------- /Python Codes/Caeser Cipher.py: -------------------------------------------------------------------------------- 1 | s=input("Enter a string:\n") 2 | n=int(input("\nEnter the no. of rotations:\n")) 3 | n=n%26 4 | p="" 5 | 6 | for i in s: 7 | if i.isupper(): 8 | x=ord(i)+n 9 | if x not in range(65,91): 10 | x=64+(x-90) 11 | x=chr(x) 12 | p=p+x 13 | elif i.islower(): 14 | x = ord(i) + n 15 | if x not in range(97, 123): 16 | x = 96 + (x - 122) 17 | x = chr(x) 18 | p = p + x 19 | else: 20 | p=p+i 21 | print(p) 22 | -------------------------------------------------------------------------------- /Python Codes/Calculator.py: -------------------------------------------------------------------------------- 1 | # Program make a simple calculator 2 | 3 | def add(x, y): 4 | return x + y 5 | 6 | def subtract(x, y): 7 | return x - y 8 | 9 | def multiply(x, y): 10 | return x * y 11 | 12 | def divide(x, y): 13 | return x / y 14 | 15 | print("Select operation.") 16 | print("1.Add") 17 | print("2.Subtract") 18 | print("3.Multiply") 19 | print("4.Divide") 20 | 21 | while True: 22 | 23 | choice = input("Enter choice(1/2/3/4): ") 24 | 25 | if choice in ('1', '2', '3', '4'): 26 | num1 = float(input("Enter first number: ")) 27 | num2 = float(input("Enter second number: ")) 28 | 29 | if choice == '1': 30 | print(num1, "+", num2, "=", add(num1, num2)) 31 | 32 | elif choice == '2': 33 | print(num1, "-", num2, "=", subtract(num1, num2)) 34 | 35 | elif choice == '3': 36 | print(num1, "*", num2, "=", multiply(num1, num2)) 37 | 38 | elif choice == '4': 39 | print(num1, "/", num2, "=", divide(num1, num2)) 40 | 41 | 42 | next_calculation = input("Let's do next calculation? (yes/no): ") 43 | if next_calculation == "no": 44 | break 45 | -------------------------------------------------------------------------------- /Python Codes/Calendar.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | 3 | yy = 2014 4 | mm = 11 5 | 6 | # To take month and year input from the user 7 | # yy = int(input("Enter year: ")) 8 | # mm = int(input("Enter month: ")) 9 | 10 | # display the calendar 11 | print(calendar.month(yy, mm)) 12 | -------------------------------------------------------------------------------- /Python Codes/Counting Substrings in Strings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[ ]: 5 | 6 | 7 | def count_substring(string, sub_string): #Creating a function named Count_String ,which takes the input of string and substring 8 | p=len(sub_string) #Storig the length of string in a variable called p 9 | count=0 #Counter setting to zero 10 | for i in range(len(string)): #For loop for itterating through list 11 | if string[i:p+i]==sub_string: #Condition 12 | count=count+1 #If condition meet then incrementing the counter 13 | return count #Returning count 14 | 15 | if __name__ == '__main__': 16 | print("Enter the String:- ") 17 | string = input().strip() #Taking input 18 | print("Enter the substring:- ") 19 | sub_string = input().strip() #Taking input sub_string 20 | count = count_substring(string, sub_string) #Calling the function 21 | print("The Substring ",sub_string," appears ",count," times in ",string) #Printing Count 22 | 23 | -------------------------------------------------------------------------------- /Python Codes/Dictionary/README.md: -------------------------------------------------------------------------------- 1 | ## How to run 2 | 1. Clone the repository 3 | ``` 4 | git@github.com:wbhoomika/python4beginners-Hacktoberfest21.git 5 | ``` 6 | 2. Install the script requirements 7 | ``` 8 | pip install -r requirements.txt 9 | ``` 10 | 3. Navigate to `Dictionary` directory 11 | ``` 12 | cd python4beginners-Hacktoberfest21/Python Codes/Dictionary 13 | ``` 14 | 4. Run the script to use the Dictionary 15 | ``` 16 | python dictionary.py 17 | ``` -------------------------------------------------------------------------------- /Python Codes/Dictionary/dictionary.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | print(" Welcome to My Dictionary") 5 | print(" ------------------------") 6 | print("\n ") 7 | terminate = 0 8 | 9 | def findMeaning(word): 10 | API_URL = r"https://api.dictionaryapi.dev/api/v2/entries/en/"+word 11 | meaning = requests.get(API_URL) 12 | #print(meaning.status_code) 13 | if meaning.status_code != 200: 14 | print("Word not found!") 15 | return 16 | word = (meaning.json())[0] 17 | m = (word['meanings'])[0] 18 | definition = m['definitions'][0] 19 | print(definition['definition'],"\n") 20 | 21 | 22 | while not terminate: 23 | word = input("Enter the word: ") 24 | if not word: 25 | print("Please enter a valid word.") 26 | continue 27 | findMeaning(word) 28 | terminate = input("Hit Enter to continue or type E to exit: ") 29 | 30 | print("\n ") 31 | print(" THANK YOU FOR USING MY DICTIONARY") -------------------------------------------------------------------------------- /Python Codes/Dictionary/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.22.0 2 | -------------------------------------------------------------------------------- /Python Codes/DigitCounter.py: -------------------------------------------------------------------------------- 1 | a = int(input("Enter a number: ")) 2 | digit =0 3 | while a >0: 4 | a =a//10 5 | digit+=1 6 | print("the number of digit of the entered number is : "+ str(digit)) -------------------------------------------------------------------------------- /Python Codes/Digital_Clock_with_python.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.ttk import * 3 | 4 | from time import strftime 5 | 6 | root = Tk() 7 | root.title("Clock") 8 | 9 | def time(): 10 | string = strftime ('%H:%M:%S %p') 11 | label.config(text=string) 12 | label.after(1000, time) 13 | 14 | label = Label(root, font=("ds-digital", 80), background = "black",foreground = "cyan") 15 | label.pack(anchor='center') 16 | time() 17 | 18 | mainloop() -------------------------------------------------------------------------------- /Python Codes/Face_recognition.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import time 4 | 5 | cap = cv2.VideoCapture(0) 6 | pTime = 0 7 | 8 | mpFaceDetection = mp.solutions.face_detection 9 | mpDraw = mp.solutions.drawing_utils 10 | faceDetection = mpFaceDetection.FaceDetection(0.75) 11 | 12 | while True: 13 | success, img = cap.read() 14 | 15 | imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 16 | results = faceDetection.process(imgRGB) 17 | print(results) 18 | 19 | if results.detections: 20 | for id, detection in enumerate(results.detections): 21 | # mpDraw.draw_detection(img, detection) 22 | # print(id, detection) 23 | # print(detection.score) 24 | # print(detection.location_data.relative_bounding_box) 25 | bboxC = detection.location_data.relative_bounding_box 26 | ih, iw, ic = img.shape 27 | bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), 28 | int(bboxC.width * iw), int(bboxC.height * ih) 29 | cv2.rectangle(img, bbox, (255, 0, 255), 2) 30 | cv2.putText(img, f'{int(detection.score[0] * 100)}%', 31 | (bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN, 32 | 2, (255, 0, 255), 2) 33 | 34 | cTime = time.time() 35 | fps = 1 / (cTime - pTime) 36 | pTime = cTime 37 | cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 38 | 3, (0, 255, 0), 2) 39 | cv2.imshow("Image", img) 40 | cv2.waitKey(1) 41 | -------------------------------------------------------------------------------- /Python Codes/Factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | f=1 3 | for i in range(1,n+1): 4 | f=f*i # start multiplying all the integers starting from 1 till the given number 5 | return f 6 | num=int(input("Enter an integer number")) 7 | #I'm calling the calling function 8 | print("The factorial of",num,"is",factorial(num)) 9 | -------------------------------------------------------------------------------- /Python Codes/Fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n):# I have used the function def Fibonacci 2 | fib = [1, 1] 3 | 4 | for i in range(2, n): 5 | fib.append(fib[i-1] + fib[i-2]) 6 | 7 | return fib[-1] 8 | 9 | n = int(input("Enter a number : ")) 10 | 11 | for i in range(n): 12 | print(fibonacci(i)) 13 | -------------------------------------------------------------------------------- /Python Codes/GCD_LCM.py: -------------------------------------------------------------------------------- 1 | num1 = int(input("Enter the first number : ")) 2 | num2 = int(input("Enter the second number : ")) 3 | if num1 <= num2: 4 | min = num1 5 | else: 6 | min = num2 7 | 8 | for i in range(1, min + 1): 9 | if num1 % i == 0 & num2 % i == 0: 10 | gcd = i 11 | 12 | lcm = int(num1 * num2 / gcd) 13 | 14 | print("The gcd and lcm of " + str(num1) + " and " + str(2) + " is " + str(gcd) + " and " + str(lcm) + " respectively") 15 | -------------------------------------------------------------------------------- /Python Codes/Grabbing first and last element of an Array/List using List Indexing in python: -------------------------------------------------------------------------------- 1 | # Python3 code to demonstrate 2 | # to get first and last element of list 3 | # using list indexing 4 | 5 | # initializing list 6 | test_list = [1, 5, 6, 7, 4] 7 | 8 | # printing original list 9 | print ("The original list is : " + str(test_list)) 10 | 11 | # using list indexing 12 | # to get first and last element of list 13 | res = [ test_list[0], test_list[-1] ] 14 | 15 | # printing result 16 | print ("The first and last element of list are : " + str(res)) 17 | -------------------------------------------------------------------------------- /Python Codes/GraphPlotting.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | x1 = np.array([2,3,5,9]) 4 | y1 = np.array([4,3,6,2]) 5 | x2 = np.array([1,2,3,4]) 6 | y2 = np.array([4,2,5,1]) 7 | plt.plot(x1, y1) 8 | plt.plot(x2, y2) 9 | plt.title('plot') 10 | plt.xlabel('x-axis') 11 | plt.ylabel('y-axis') 12 | plt.show() 13 | -------------------------------------------------------------------------------- /Python Codes/Gunjan_Nayak_Reverse_Star_Pattern: -------------------------------------------------------------------------------- 1 | i=6 2 | while(i!=0): 3 | print("*"*i) 4 | i-=1 5 | -------------------------------------------------------------------------------- /Python Codes/Hi-Lo Game.py: -------------------------------------------------------------------------------- 1 | # This is a game called Hi-Lo which accepts a number from 1 -100 and the user is given infinite amount of chances to guess it 2 | # If the number is too high it will print "too high" 3 | # If the number is too low it will print "too low" 4 | 5 | 6 | from ast import Index 7 | import random 8 | 9 | print(''' 10 | HI-LO GAME 11 | 12 | INSTRUCTIONS 13 | 14 | - Computer generates a secret number between 1 - 100 15 | - User should guess that number with infinite number of chances 16 | - If the number is too high from the secret number it prints "Too High" 17 | - If the number is too low from the secret number it prints "Too Low" 18 | - If you guess the number correctly you will exit the game 19 | 20 | SO WHAT ARE YOU WAITING FOR!!!! 21 | LET'S PLAY THE GAME 22 | 23 | ''') 24 | 25 | # this function is used to prompt user to enter a user input 26 | def userValue(): 27 | userInputValue = int(input("Enter Your Guess : ")) 28 | return userInputValue 29 | 30 | # this function is used to generate a random numner using the library random. 31 | def randomNumberGenerator(): 32 | computerValue = random.randint(1,100) 33 | return computerValue 34 | 35 | # this is the main function 36 | def main(): 37 | user_value = userValue() 38 | computer_value = randomNumberGenerator() 39 | 40 | 41 | # this list is created in order to store and display the wrong guess done by the user. 42 | wrong_guesses = [] 43 | 44 | # While loop is used to check if the user inputs the correct value. 45 | while user_value != computer_value: 46 | 47 | # if, elif, else conditions are used inorder to print the high, low or correct input 48 | if user_value > computer_value: 49 | print('Too High') 50 | user_value = userValue() 51 | elif user_value < computer_value: 52 | print('Too Low') 53 | user_value = userValue() 54 | 55 | # List is used to add the last wrong guess done by the user 56 | if user_value != computer_value: 57 | wrong_guesses.append(user_value) 58 | print(wrong_guesses) 59 | else: 60 | print('Well Done. You guessed it right') 61 | 62 | 63 | 64 | # calling main function 65 | if __name__ == "__main__": 66 | main() 67 | 68 | -------------------------------------------------------------------------------- /Python Codes/If-Else_Example.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | if N % 2 != 0: 3 | print ('Weird') 4 | else: 5 | if N >= 2 and N <= 5: 6 | print ('Not Weird') 7 | elif N >= 6 and N <= 20: 8 | print ('Weird') 9 | elif N > 20: 10 | print ('Not Weird') 11 | -------------------------------------------------------------------------------- /Python Codes/Image to Pencil Sketch/Readme.md: -------------------------------------------------------------------------------- 1 | ## How to run 2 | 3 | 1. Clone the repository 4 | ``` 5 | git@github.com:wbhoomika/python4beginners-Hacktoberfest21.git 6 | ``` 7 | 8 | 2. Navigate to `Image2Sketch` directory 9 | ``` 10 | cd python4beginners-Hacktoberfest21/Python Codes/Image to Pencil Sketch 11 | ``` 12 | 13 | 3. Add Image to Convert to sketch in `Image2Sketch` directory 14 | ``` 15 | cd python4beginners-Hacktoberfest21/Python Codes/Image to Pencil Sketch 16 | ``` 17 | 18 | 4. Run the script to convert the temperature from and to the desired scale 19 | ``` 20 | python img2sketch.py 21 | ``` 22 | 23 | -------------------------------------------------------------------------------- /Python Codes/Image to Pencil Sketch/img2sketch.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | #reading image 3 | image = cv2.imread("dog.jpg") #enter your own image name in same directory name 4 | 5 | #converting BGR image to grayscale 6 | gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 7 | 8 | 9 | #image inversion 10 | inverted_image = 255 - gray_image 11 | 12 | blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0) 13 | inverted_blurred = 255 - blurred 14 | pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0) 15 | 16 | cv2.imshow("Original Image", image) 17 | cv2.imshow("Pencil Sketch of Dog", pencil_sketch) 18 | cv2.waitKey(0) 19 | -------------------------------------------------------------------------------- /Python Codes/Leapyear.py: -------------------------------------------------------------------------------- 1 | year=int(input("Enter year : ")) 2 | if(year%4==0 and year%100!=0 or year%400==0): 3 | print("Leap Year") 4 | else: 5 | print("Not Leap Year") 6 | -------------------------------------------------------------------------------- /Python Codes/Leetcode-question-3Sum.py: -------------------------------------------------------------------------------- 1 | def threeSum(self, nums: List[int]) -> List[List[int]]: 2 | nums.sort() # sorting cause we need to avoid duplicates, with this duplicates will be near to each other 3 | l=[] 4 | for i in range(len(nums)): #this loop will help to fix the one number i.e, i 5 | if i>0 and nums[i-1]==nums[i]: #skipping if we found the duplicate of i 6 | continue 7 | 8 | #NOW FOLLOWING THE RULE OF TWO POINTERS AFTER FIXING THE ONE VALUE (i) 9 | j=i+1 #taking j pointer larger than i (as said in ques) 10 | k=len(nums)-1 #taking k pointer from last 11 | while j0: #if sum s is greater than 0(target) means the larger value(from right as nums is sorted i.e, k at right) 14 | #is taken and it is not able to sum up to the target 15 | k-=1 #so take value less than previous 16 | elif s<0: #if sum s is less than 0(target) means the shorter value(from left as nums is sorted i.e, j at left) 17 | #is taken and it is not able to sum up to the target 18 | j+=1 #so take value greater than previous 19 | else: 20 | l.append([nums[i],nums[j],nums[k]]) #if sum s found equal to the target (0) 21 | j+=1 22 | while nums[j-1]==nums[j] and jNote: This is a demonstration to the much accepted and growing framework for Conversational AI, RASA. 4 | 5 | Easy to set things up, with great & powerful SOTA engine you can tweak as per your need, RASA Open-Source comes with large community of users & developers involved, making your learning-production-deployment even easier. 6 |
7 | With an intention of introducing RASA to those folks of Nepali AI Community who seemed to have been less known to it, I have just initialized this basic bot for a demonstration with no advancements done in terms of its intelligence, one might find the bot pretty foolish. In that regard, I strongly urge you not to point towards its intelligence or project's progress, but understand its power and how versatile one could make this bot in such a less time and hassle given as compared to other chatbot frameworks. 8 |

9 | 10 | ## To Begin With... 11 | - Install rasa with ``` pip3 install rasa ``` 12 | - Now If You Want To Run This Bot, Clone This Repo, Navigate To The Repo In Your Terminal. Now ``` rasa shell ``` is all you need there. 13 | - RASA also provides an interactive UI session you can run in your browser, giving you power to control and manage slots and intents passed. Hit the command ``` rasa x ``` right away! 14 | 15 | - If You Want To Begin Building From Scratch, Initialize a basic pretrained rasa bot: ``` rasa init ```. 16 | 17 | 18 | Happy Hacktoberfest2021 to y'all! Let Your Machine Learn! 19 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__init__.py -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__pycache__/actions.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/__pycache__/actions.cpython-38.pyc -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/actions/actions.py: -------------------------------------------------------------------------------- 1 | # This files contains your custom actions which can be used to run 2 | # custom Python code. 3 | # 4 | # See this guide on how to implement these action: 5 | # https://rasa.com/docs/rasa/custom-actions 6 | 7 | 8 | # This is a simple example for a custom action which utters "Hello World!" 9 | 10 | # from typing import Any, Text, Dict, List 11 | # 12 | # from rasa_sdk import Action, Tracker 13 | # from rasa_sdk.executor import CollectingDispatcher 14 | # 15 | # 16 | # class ActionHelloWorld(Action): 17 | # 18 | # def name(self) -> Text: 19 | # return "action_hello_world" 20 | # 21 | # def run(self, dispatcher: CollectingDispatcher, 22 | # tracker: Tracker, 23 | # domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: 24 | # 25 | # dispatcher.utter_message(text="Hello World!") 26 | # 27 | # return [] 28 | 29 | 30 | 31 | class ActionHelloWorld(Action): 32 | def name(self) -> Text: 33 | return "action_hello_world" 34 | def run(self, dispatcher: CollectingDispatcher, 35 | tracker: Tracker, 36 | domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: 37 | dispatcher.utter_message(text="Hello World!") 38 | return [] 39 | 40 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/config.yml: -------------------------------------------------------------------------------- 1 | # Configuration for Rasa NLU. 2 | # https://rasa.com/docs/rasa/nlu/components/ 3 | language: en 4 | 5 | pipeline: 6 | # # No configuration for the NLU pipeline was provided. The following default pipeline was used to train your model. 7 | # # If you'd like to customize it, uncomment and adjust the pipeline. 8 | # # See https://rasa.com/docs/rasa/tuning-your-model for more information. 9 | # - name: WhitespaceTokenizer 10 | # - name: RegexFeaturizer 11 | # - name: LexicalSyntacticFeaturizer 12 | # - name: CountVectorsFeaturizer 13 | # - name: CountVectorsFeaturizer 14 | # analyzer: char_wb 15 | # min_ngram: 1 16 | # max_ngram: 4 17 | # - name: DIETClassifier 18 | # epochs: 100 19 | # constrain_similarities: true 20 | # - name: EntitySynonymMapper 21 | # - name: ResponseSelector 22 | # epochs: 100 23 | # constrain_similarities: true 24 | # - name: FallbackClassifier 25 | # threshold: 0.3 26 | # ambiguity_threshold: 0.1 27 | 28 | # Configuration for Rasa Core. 29 | # https://rasa.com/docs/rasa/core/policies/ 30 | policies: 31 | # # No configuration for policies was provided. The following default policies were used to train your model. 32 | # # If you'd like to customize them, uncomment and adjust the policies. 33 | # # See https://rasa.com/docs/rasa/policies for more information. 34 | # - name: MemoizationPolicy 35 | # - name: RulePolicy 36 | # - name: TEDPolicy 37 | # max_history: 5 38 | # epochs: 100 39 | # constrain_similarities: true 40 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/credentials.yml: -------------------------------------------------------------------------------- 1 | # This file contains the credentials for the voice & chat platforms 2 | # which your bot is using. 3 | # https://rasa.com/docs/rasa/messaging-and-voice-channels 4 | 5 | rest: 6 | # # you don't need to provide anything here - this channel doesn't 7 | # # require any credentials 8 | 9 | 10 | #facebook: 11 | # verify: "" 12 | # secret: "" 13 | # page-access-token: "" 14 | 15 | #slack: 16 | # slack_token: "" 17 | # slack_channel: "" 18 | # slack_signing_secret: "" 19 | 20 | #socketio: 21 | # user_message_evt: 22 | # bot_message_evt: 23 | # session_persistence: 24 | 25 | #mattermost: 26 | # url: "https:///api/v4" 27 | # token: "" 28 | # webhook_url: "" 29 | 30 | # This entry is needed if you are using Rasa X. The entry represents credentials 31 | # for the Rasa X "channel", i.e. Talk to your bot and Share with guest testers. 32 | rasa: 33 | url: "http://localhost:5002/api" 34 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/data/nlu.yml: -------------------------------------------------------------------------------- 1 | version: "2.0" 2 | 3 | nlu: 4 | - intent: greet 5 | examples: | 6 | - hey 7 | - hello 8 | - hi 9 | - hello there 10 | - good morning 11 | - good evening 12 | - moin 13 | - hey there 14 | - let's go 15 | - hey dude 16 | - goodmorning 17 | - goodevening 18 | - good afternoon 19 | 20 | - intent: goodbye 21 | examples: | 22 | - good afternoon 23 | - cu 24 | - good by 25 | - cee you later 26 | - good night 27 | - bye 28 | - goodbye 29 | - have a nice day 30 | - see you around 31 | - bye bye 32 | - see you later 33 | 34 | - intent: affirm 35 | examples: | 36 | - yes 37 | - y 38 | - indeed 39 | - of course 40 | - that sounds good 41 | - correct 42 | - yeah 43 | 44 | - intent: deny 45 | examples: | 46 | - no 47 | - n 48 | - never 49 | - nah 50 | - I don't think so 51 | - don't like that 52 | - no way 53 | - not really 54 | 55 | - intent: mood_great 56 | examples: | 57 | - perfect 58 | - great 59 | - amazing 60 | - feeling like a king 61 | - wonderful 62 | - I am feeling very good 63 | - I am great 64 | - I am amazing 65 | - I am going to save the world 66 | - super stoked 67 | - extremely good 68 | - so so perfect 69 | - so good 70 | - so perfect 71 | - fine 72 | - great 73 | - Fine 74 | - I am fine 75 | 76 | 77 | - intent: mood_unhappy 78 | examples: | 79 | - my day was horrible 80 | - I am sad 81 | - I don't feel very well 82 | - I am disappointed 83 | - super sad 84 | - I'm so sad 85 | - sad 86 | - very sad 87 | - unhappy 88 | - not good 89 | - not very good 90 | - extremly sad 91 | - so saad 92 | - so sad 93 | - not fine 94 | - not great 95 | - Not Fine 96 | - NOT FINE 97 | 98 | - intent: bot_challenge 99 | examples: | 100 | - are you a bot? 101 | - are you a human? 102 | - am I talking to a bot? 103 | - am I talking to a human? 104 | 105 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/data/rules.yml: -------------------------------------------------------------------------------- 1 | version: "2.0" 2 | 3 | rules: 4 | 5 | - rule: Say goodbye anytime the user says goodbye 6 | steps: 7 | - intent: goodbye 8 | - action: utter_goodbye 9 | 10 | - rule: Say 'I am a bot' anytime the user challenges 11 | steps: 12 | - intent: bot_challenge 13 | - action: utter_iamabot 14 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/data/stories.yml: -------------------------------------------------------------------------------- 1 | version: "2.0" 2 | 3 | stories: 4 | 5 | - story: signupyes1 6 | steps: 7 | - intent: greet 8 | - action: utter_greet 9 | - intent: mood_great 10 | - action: utter_hacktobersign 11 | - intent: affirm 12 | - action: utter_happy_hacktober 13 | - action: utter_end_chat 14 | 15 | - story: signupyes2 16 | steps: 17 | - intent: greet 18 | - action: utter_greet 19 | - intent: mood_unhappy 20 | - action: utter_hacktobersign 21 | - intent: affirm 22 | - action: utter_happy_hacktober 23 | - action: utter_end_chat 24 | 25 | 26 | - story: signupno1 27 | steps: 28 | - intent: greet 29 | - action: utter_greet 30 | - intent: mood_great 31 | - action: utter_hacktobersign 32 | - intent: deny 33 | - action: utter_sad_hacktober 34 | - action: utter_end_chat 35 | 36 | - story: signupno2 37 | steps: 38 | - intent: greet 39 | - action: utter_greet 40 | - intent: mood_unhappy 41 | - action: utter_hacktobersign 42 | - intent: deny 43 | - action: utter_sad_hacktober 44 | - action: utter_end_chat 45 | 46 | 47 | - story: sad path 1 48 | steps: 49 | - intent: greet 50 | - action: utter_greet 51 | - intent: mood_unhappy 52 | - action: utter_cheer_up 53 | - action: utter_did_that_help 54 | - intent: affirm 55 | - action: utter_happy 56 | - action: utter_end_chat 57 | 58 | - story: sad path 2 59 | steps: 60 | - intent: greet 61 | - action: utter_greet 62 | - intent: mood_unhappy 63 | - action: utter_cheer_up 64 | - action: utter_did_that_help 65 | - intent: deny 66 | - action: utter_goodbye 67 | - action: utter_end_chat 68 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/domain.yml: -------------------------------------------------------------------------------- 1 | version: "2.0" 2 | 3 | intents: 4 | - greet 5 | - goodbye 6 | - affirm 7 | - deny 8 | - mood_great 9 | - mood_unhappy 10 | - bot_challenge 11 | 12 | 13 | responses: 14 | utter_greet: 15 | - text: "Hey! I Am A RASA Powered Bot For Hacktoberfest 2021. Wassup?" 16 | 17 | utter_cheer_up: 18 | - text: "Here is something to cheer you up:" 19 | image: "https://i.imgur.com/nGF1K8f.jpg" 20 | 21 | utter_did_that_help: 22 | - text: "Did that help you?" 23 | 24 | utter_happy: 25 | - text: "Glad To Hear That!" 26 | 27 | utter_goodbye: 28 | - text: "See Ya!" 29 | 30 | utter_iamabot: 31 | - text: "I Am More Than A Bot. I Am Your PR Reminder For Hacktoberfest-2021. Now Off You Go To Make A Pull Request. NOW!!!!!." 32 | 33 | utter_hacktobersign: 34 | - text: "Have You Signed Up For Hacktobefest2021?" 35 | 36 | utter_happy_hacktober: 37 | - text: "That's Like A Pro! OP!" 38 | 39 | utter_sad_hacktober: 40 | - text: "Wakanda Programmer Are You? PITY ON YOU!" 41 | 42 | utter_end_chat: 43 | - text: "Well, Now You Saw Me Working, Let's Just Keep This Straight. I am Just Trained By My Master To Show You How I Work. So, Ask Me No More Questions, Don't Be A Sherlock And Say Goodbye." 44 | 45 | session_config: 46 | session_expiration_time: 60 47 | carry_over_slots_to_new_session: true 48 | 49 | 50 | actions: 51 | - hacktoberfest_action 52 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/endpoints.yml: -------------------------------------------------------------------------------- 1 | # This file contains the different endpoints your bot can use. 2 | 3 | # Server where the models are pulled from. 4 | # https://rasa.com/docs/rasa/model-storage#fetching-models-from-a-server 5 | 6 | #models: 7 | # url: http://my-server.com/models/default_core@latest 8 | # wait_time_between_pulls: 10 # [optional](default: 100) 9 | 10 | # Server which runs your custom actions. 11 | # https://rasa.com/docs/rasa/custom-actions 12 | 13 | action_endpoint: 14 | url: "http://localhost:5055/webhook" 15 | 16 | # Tracker store which is used to store the conversations. 17 | # By default the conversations are stored in memory. 18 | # https://rasa.com/docs/rasa/tracker-stores 19 | 20 | #tracker_store: 21 | # type: redis 22 | # url: 23 | # port: 24 | # db: 25 | # password: 26 | # use_ssl: 27 | 28 | #tracker_store: 29 | # type: mongod 30 | # url: 31 | # db: 32 | # username: 33 | # password: 34 | 35 | # Event broker which all conversation events should be streamed to. 36 | # https://rasa.com/docs/rasa/event-brokers 37 | 38 | #event_broker: 39 | # url: localhost 40 | # username: username 41 | # password: password 42 | # queue: queue 43 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/models/20211002-210417.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Machine learning/Hacktoberfest Bot By RASA/models/20211002-210417.tar.gz -------------------------------------------------------------------------------- /Python Codes/Machine learning/Hacktoberfest Bot By RASA/tests/test_stories.yml: -------------------------------------------------------------------------------- 1 | #### This file contains tests to evaluate that your bot behaves as expected. 2 | #### If you want to learn more, please see the docs: https://rasa.com/docs/rasa/testing-your-assistant 3 | 4 | stories: 5 | - story: happy path 1 6 | steps: 7 | - user: | 8 | hello there! 9 | intent: greet 10 | - action: utter_greet 11 | - user: | 12 | amazing 13 | intent: mood_great 14 | - action: utter_happy 15 | 16 | - story: happy path 2 17 | steps: 18 | - user: | 19 | hello there! 20 | intent: greet 21 | - action: utter_greet 22 | - user: | 23 | amazing 24 | intent: mood_great 25 | - action: utter_happy 26 | - user: | 27 | bye-bye! 28 | intent: goodbye 29 | - action: utter_goodbye 30 | 31 | - story: sad path 1 32 | steps: 33 | - user: | 34 | hello 35 | intent: greet 36 | - action: utter_greet 37 | - user: | 38 | not good 39 | intent: mood_unhappy 40 | - action: utter_cheer_up 41 | - action: utter_did_that_help 42 | - user: | 43 | yes 44 | intent: affirm 45 | - action: utter_happy 46 | 47 | - story: sad path 2 48 | steps: 49 | - user: | 50 | hello 51 | intent: greet 52 | - action: utter_greet 53 | - user: | 54 | not good 55 | intent: mood_unhappy 56 | - action: utter_cheer_up 57 | - action: utter_did_that_help 58 | - user: | 59 | not really 60 | intent: deny 61 | - action: utter_goodbye 62 | 63 | - story: sad path 3 64 | steps: 65 | - user: | 66 | hi 67 | intent: greet 68 | - action: utter_greet 69 | - user: | 70 | very terrible 71 | intent: mood_unhappy 72 | - action: utter_cheer_up 73 | - action: utter_did_that_help 74 | - user: | 75 | no 76 | intent: deny 77 | - action: utter_goodbye 78 | 79 | - story: say goodbye 80 | steps: 81 | - user: | 82 | bye-bye! 83 | intent: goodbye 84 | - action: utter_goodbye 85 | 86 | - story: bot challenge 87 | steps: 88 | - user: | 89 | are you a bot? 90 | intent: bot_challenge 91 | - action: utter_iamabot 92 | -------------------------------------------------------------------------------- /Python Codes/Machine learning/Linear_Regression/Readme.md: -------------------------------------------------------------------------------- 1 | Linear Regression using python. 2 | -------------------------------------------------------------------------------- /Python Codes/Name_generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | ic = ['a', 'i', 'o', 'u', 'e'] 5 | Vowels = "aeiou" 6 | yeaboi = "".join(set(string.ascii_letters) - set(Vowels)) 7 | starters = "abcdfghklmnprst" 8 | 9 | #print (random.choice(yeaboi)+random.choice(ic)+random.choice(yeaboi)+random.choice(ic)+random.choice(ic)+random.choice(yeaboi)) 10 | 11 | word = [] 12 | n = int(input("how letters word do you want?")) 13 | 14 | for i in range(0, n): 15 | if i == 1 : 16 | word.append(random.choice(starters)) 17 | elif i % 2 == 0: 18 | word.append(random.choice(Vowels)) 19 | else: 20 | word.append(random.choice(yeaboi)) 21 | 22 | 23 | str1 = "" 24 | for ele in word: 25 | str1 += ele 26 | 27 | 28 | 29 | print(str1) 30 | 31 | -------------------------------------------------------------------------------- /Python Codes/NumberGuessing.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | 4 | lower = int(input("Enter Lower bound:- ")) 5 | 6 | 7 | upper = int(input("Enter Upper bound:- ")) 8 | 9 | 10 | x = random.randint(lower, upper) 11 | print("\n\tYou've only ", 12 | round(math.log(upper - lower + 1, 2)), 13 | " chances to guess the integer!\n") 14 | 15 | 16 | count = 0 17 | 18 | 19 | while count < math.log(upper - lower + 1, 2): 20 | count += 1 21 | 22 | 23 | guess = int(input("Guess a number:- ")) 24 | 25 | 26 | if x == guess: 27 | print("Congratulations you did it in ", 28 | count, " try") 29 | 30 | break 31 | elif x > guess: 32 | print("You guessed too small!") 33 | elif x < guess: 34 | print("You Guessed too high!") 35 | 36 | 37 | if count >= math.log(upper - lower + 1, 2): 38 | print("\nThe number is %d" % x) 39 | print("\tBetter Luck Next time!") 40 | -------------------------------------------------------------------------------- /Python Codes/Number_ Guessing.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | num = random.randint(1, 100) 4 | 5 | user_input = 0 6 | 7 | count = 0 8 | 9 | while user_input != num: 10 | user_input = int(input("Enter your guess ")) 11 | 12 | if user_input < num: 13 | print("Your number is less") 14 | print("Try Again") 15 | 16 | elif user_input > num: 17 | print("Your number is much") 18 | print("Try Again") 19 | 20 | else: 21 | print("Congratulations you guessed the right number") 22 | 23 | count += 1 24 | 25 | print("Kudos to you!!") 26 | print("You took", str(count), "trials for guessing the correct number") 27 | -------------------------------------------------------------------------------- /Python Codes/Numberguessing_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | 4 | lower = int(input("Enter Lower bound:- ")) 5 | 6 | 7 | upper = int(input("Enter Upper bound:- ")) 8 | 9 | 10 | x = random.randint(lower, upper) 11 | print("\n\tYou've only ", 12 | round(math.log(upper - lower + 1, 2)), 13 | " chances to guess the integer!\n") 14 | 15 | 16 | count = 0 17 | 18 | 19 | while count < math.log(upper - lower + 1, 2): 20 | count += 1 21 | 22 | 23 | guess = int(input("Guess a number:- ")) 24 | 25 | 26 | if x == guess: 27 | print("Congratulations you did it in ", 28 | count, " try") 29 | 30 | break 31 | elif x > guess: 32 | print("You guessed too small!") 33 | elif x < guess: 34 | print("You Guessed too high!") 35 | 36 | 37 | 38 | if count >= math.log(upper - lower + 1, 2): 39 | print("\nThe number is %d" % x) 40 | print("\tBetter Luck Next time!") 41 | 42 | -------------------------------------------------------------------------------- /Python Codes/OpenCV Face and Movement Detector.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 5 | side = cv2.CascadeClassifier('lbpcascade_profileface.xml') 6 | 7 | cap = cv2.VideoCapture(1) 8 | move= cv2.createBackgroundSubtractorMOG2() 9 | 10 | while 1: 11 | 12 | ret, frame = cap.read() 13 | #frame = frame + 10 14 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 15 | 16 | #******************************** 17 | mask = move.apply(gray) 18 | kernel = np.ones((5,5),np.uint8) 19 | mask = cv2.erode(mask,kernel, iterations = 1) 20 | kernel = np.ones((20,20),np.uint8) 21 | mask = cv2.dilate(mask,kernel, iterations = 1) 22 | #******************************** 23 | 24 | #faces = face.detectMultiScale(gray, 1.1, 1, 0 , (100,100),(500,500)) 25 | faces = face.detectMultiScale(gray, 1.1, 1) 26 | 27 | for (x,y,w,h) in faces: 28 | cv2.rectangle(mask,(x,y-60),(x+w,y+h+60),(255,255,255),-1) 29 | 30 | faces = side.detectMultiScale(gray, 1.1, 1) 31 | 32 | for (x,y,w,h) in faces: 33 | cv2.rectangle(mask,(x-10,y-10),(x+w+20,y+h+20),(255,255,255),-1) 34 | #******************************** 35 | 36 | hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) 37 | low = np.array([0, 55, 48]) 38 | up = np.array([130, 110, 269]) 39 | mask1 = cv2.inRange(hsv,low,up) 40 | 41 | kernel = np.ones((15,15),np.uint8) 42 | mask1 = cv2.erode(mask1,kernel, iterations = 1) 43 | kernel = np.ones((30,30),np.uint8) 44 | mask1 = cv2.dilate(mask1,kernel, iterations = 1) 45 | 46 | #******************************** 47 | 48 | mask = mask + mask1 49 | img = cv2.bitwise_and(frame,frame,mask = mask) 50 | 51 | cv2.imshow('img',img) 52 | 53 | if cv2.waitKey(1) & 0xFF == ord('q'): 54 | break 55 | 56 | cap.release() 57 | cv2.destroyAllWindows() 58 | -------------------------------------------------------------------------------- /Python Codes/PasswordGenerator_pawarspeaks.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | from typing import List 4 | 5 | if __name__ == "__main__": 6 | 7 | s1 = string.ascii_lowercase 8 | s2 = string.ascii_uppercase 9 | s3 = string.digits 10 | s4 = string.punctuation 11 | 12 | plen = int(input("Enter password length\n")) 13 | 14 | s = [] 15 | s.extend(list(s1)) 16 | s.extend(list(s2)) 17 | s.extend(list(s3)) 18 | s.extend(list(s4)) 19 | 20 | random.shuffle(s) 21 | 22 | print("Your password is: ") 23 | print("".join(s[0:plen])) 24 | 25 | -------------------------------------------------------------------------------- /Python Codes/Password_generator.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | 4 | if __name__ == "__main__": 5 | s1 = string.ascii_lowercase 6 | s2 = string.ascii_uppercase 7 | s3 = string.digits 8 | s4 = string.punctuation 9 | plen = int(input("Enter password length\n")) 10 | s = [] 11 | s.extend(list(s1)) 12 | s.extend(list(s2)) 13 | s.extend(list(s3)) 14 | s.extend(list(s4)) 15 | print("Your password is: ") 16 | print("".join(random.sample(s, plen))) 17 | 18 | -------------------------------------------------------------------------------- /Python Codes/PermutationOfStringFromInput.py: -------------------------------------------------------------------------------- 1 | def get_permutation(string, i=0): 2 | 3 | if i == len(string): 4 | print("".join(string)) 5 | 6 | for j in range(i, len(string)): 7 | 8 | words = [c for c in string] 9 | 10 | # swap 11 | words[i], words[j] = words[j], words[i] 12 | 13 | get_permutation(words, i + 1) 14 | 15 | num = input('Enter a word: ') 16 | print(get_permutation(num)) 17 | -------------------------------------------------------------------------------- /Python Codes/PingPlot.py: -------------------------------------------------------------------------------- 1 | from pythonping import ping 2 | import matplotlib.pyplot as plt 3 | import matplotlib.animation as animation 4 | from matplotlib import style 5 | 6 | style.use('fivethirtyeight') 7 | 8 | fig = plt.figure() 9 | ax1 = fig.add_subplot(1,1,1) 10 | 11 | xs_min=[0] 12 | ys_min=[5] 13 | 14 | def animate(z): 15 | ping_out = ping('8.8.8.8', count = 1) 16 | #ping_out = ping('127.0.0.1', count = 1) 17 | 18 | ping_arr = str(ping_out)[len(str(ping_out))-28:].split(" ") 19 | print(ping_arr) 20 | for i in range(len(ping_arr)): 21 | if len(ping_arr[i]) > 10: 22 | time_min = ping_arr[i].split("/")[0] 23 | 24 | print(time_min) 25 | 26 | xs_min.append(float(len(xs_min))) 27 | ys_min.append(float(time_min)) 28 | 29 | #print(xs_min) 30 | #print(ys_min) 31 | 32 | ax1.clear() 33 | ax1.plot(xs_min[-50:],ys_min[-50:],linewidth=2) 34 | 35 | 36 | ani = animation.FuncAnimation(fig, animate, interval=50) 37 | plt.show() 38 | 39 | print(xs) 40 | -------------------------------------------------------------------------------- /Python Codes/Print First and Last element in array using List indexing.py: -------------------------------------------------------------------------------- 1 | #This Code contributed by-Yush Chaudhary 2 | 3 | # initializing list 4 | test_list = [15, 1555, 66, 977, 7854] 5 | 6 | # printing list as it is 7 | print ("The list is : " + str(test_list)) 8 | 9 | # using list indexing 10 | res = [ test_list[0], test_list[-1] ] 11 | 12 | # The result is 13 | print ("First and Last element of list are : " + str(res)) 14 | -------------------------------------------------------------------------------- /Python Codes/Python google: -------------------------------------------------------------------------------- 1 | # google search using python steps to install 2 | # pip indtall beautifulsoup then pip install google 3 | try: 4 | from googlesearch import search 5 | except ImportError: 6 | print("No module named 'google' found") 7 | 8 | # to search 9 | query = "Geeksforgeeks" 10 | 11 | for j in search(query, tld="co.in", num=10, stop=10, pause=2): 12 | print(j) 13 | -------------------------------------------------------------------------------- /Python Codes/Qr_Code_Generator.py: -------------------------------------------------------------------------------- 1 | #pip install qrcode 2 | import qrcode 3 | 4 | link = input("Enter txt to encode in QR") 5 | img = qrcode.make("link) 6 | img.save("QR.jpg") 7 | -------------------------------------------------------------------------------- /Python Codes/Quiz-app/images/false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Quiz-app/images/false.png -------------------------------------------------------------------------------- /Python Codes/Quiz-app/images/true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/Quiz-app/images/true.png -------------------------------------------------------------------------------- /Python Codes/Quiz-app/main.py: -------------------------------------------------------------------------------- 1 | from question_model import Question 2 | from data import question_data 3 | from quiz_brain import QuizBrain 4 | from ui import QuizInterface 5 | 6 | 7 | question_bank = [] 8 | for question in question_data: 9 | question_text = question["question"] 10 | question_answer = question["correct_answer"] 11 | new_question = Question(question_text, question_answer) 12 | question_bank.append(new_question) 13 | 14 | 15 | quiz = QuizBrain(question_bank) 16 | quiz_ui=QuizInterface(quiz) 17 | 18 | # while quiz.still_has_questions(): 19 | # quiz.next_question() 20 | 21 | print("You've completed the quiz") 22 | print(f"Your final score was: {quiz.score}/{quiz.question_number}") 23 | -------------------------------------------------------------------------------- /Python Codes/Quiz-app/question_model.py: -------------------------------------------------------------------------------- 1 | class Question: 2 | 3 | def __init__(self, q_text, q_answer): 4 | self.text = q_text 5 | self.answer = q_answer 6 | -------------------------------------------------------------------------------- /Python Codes/Quiz-app/quiz_brain.py: -------------------------------------------------------------------------------- 1 | import html 2 | 3 | class QuizBrain: 4 | 5 | def __init__(self, q_list): 6 | self.question_number = 0 7 | self.score = 0 8 | self.question_list = q_list 9 | self.current_question = None 10 | 11 | def still_has_questions(self): 12 | return self.question_number < len(self.question_list) 13 | 14 | def next_question(self): 15 | self.current_question = self.question_list[self.question_number] 16 | self.question_number += 1 17 | q_text=html.unescape(self.current_question.text) 18 | # user_answer = input(f"Q.{self.question_number}: {q_text} (True/False): ") 19 | # self.check_answer(user_answer) 20 | return f"Q.{self.question_number}: {q_text}" 21 | 22 | def check_answer(self, user_answer): 23 | correct_answer = self.current_question.answer 24 | if user_answer.lower() == correct_answer.lower(): 25 | self.score += 1 26 | print("You got it right!") 27 | return True 28 | else: 29 | print("That's wrong.") 30 | return False 31 | 32 | print(f"Your current score is: {self.score}/{self.question_number}") 33 | print("\n") 34 | -------------------------------------------------------------------------------- /Python Codes/Quiz-app/ui.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from quiz_brain import QuizBrain 3 | 4 | 5 | THEME_COLOR = "#375362" 6 | FONT=("Arial",20,"italic") 7 | class QuizInterface: 8 | def __init__(self,quiz_brain:QuizBrain): 9 | self.quiz=quiz_brain 10 | self.window=Tk() 11 | self.__CANVAS_WIDTH=300 12 | self.__CANVAS_HEIGHT=250 13 | self.window.title("Quizzler") 14 | self.window.config(bg=THEME_COLOR,padx=20,pady=20) 15 | self.score=Label(text="Score: 0",font=("Arial",15)) 16 | self.score.config(padx=5,pady=5,bg=THEME_COLOR,fg="white") 17 | self.score.grid(row=0,column=1) 18 | self.canvas = Canvas( width=self.__CANVAS_WIDTH, height=self.__CANVAS_HEIGHT,bg="white") 19 | # self.canvas.create_rectangle((10,10,30,30),fill="red") 20 | self.text=self.canvas.create_text(150,125,width=280,text="Some question here",font=FONT,fill=THEME_COLOR) 21 | 22 | self.canvas.grid(row=1,column=0,columnspan=2,pady=50) 23 | self.r_img=PhotoImage(file="images/true.png") 24 | self.correct=Button(image=self.r_img,highlightthickness=0,command=self.true_clicked,bd=0,activebackground=THEME_COLOR) 25 | self.correct.grid(row=2,column=0,padx=10,pady=10) 26 | self.w_img=PhotoImage(file="images/false.png") 27 | self.wrong=Button(image=self.w_img,highlightthickness=0,bd=0,command=self.false_clicked,activebackground=THEME_COLOR) 28 | self.wrong.grid(row=2,column=1,padx=10,pady=10) 29 | # self.right.grid(row=2,column=0,columnspan=2) 30 | 31 | self.get_next_question() 32 | 33 | 34 | 35 | self.window.mainloop() 36 | 37 | def get_next_question(self): 38 | self.canvas.config(bg="white") 39 | if self.quiz.still_has_questions(): 40 | self.score.config(text=f"Score: {self.quiz.score}") 41 | q_text=self.quiz.next_question() 42 | self.canvas.itemconfig(self.text,text=q_text) 43 | else: 44 | self.score.config(text=f"Score: {self.quiz.score}") 45 | self.canvas.itemconfig(self.text, 46 | text=f"You've completed the quiz\n" 47 | f"Your final score was: {self.quiz.score}/{self.quiz.question_number}") 48 | self.correct.config(state="disabled") 49 | self.wrong.config(state="disabled") 50 | 51 | def true_clicked(self): 52 | check=self.quiz.check_answer("True") 53 | self.give_feedback(check) 54 | 55 | 56 | # self.get_next_question() 57 | def false_clicked(self): 58 | check=self.quiz.check_answer("False") 59 | self.give_feedback(check) 60 | # self.get_next_question() 61 | def give_feedback(self,check): 62 | if check: 63 | feedback=self.canvas.config(bg="green") 64 | print("chill") 65 | else: 66 | feedback=self.canvas.config(bg="red") 67 | print("it's fine") 68 | # self.canvas.itemconfig(self.text,fill=THEME_COLOR) 69 | self.window.after(1000,self.get_next_question) 70 | if check==None: 71 | self.window.after_cancel(feedback) 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /Python Codes/QuizzingGame.py: -------------------------------------------------------------------------------- 1 | print('Welcome to AskPython Quiz') 2 | answer=input('Are you ready to play the Quiz ? (yes/no) :') 3 | score=0 4 | total_questions=3 5 | 6 | if answer.lower()=='yes': 7 | answer=input('Question 1: What is your Favourite programming language?') 8 | if answer.lower()=='python': 9 | score += 1 10 | print('correct') 11 | else: 12 | print('Wrong Answer :(') 13 | 14 | 15 | answer=input('Question 2: Do you follow any author on AskPython? ') 16 | if answer.lower()=='yes': 17 | score += 1 18 | print('correct') 19 | else: 20 | print('Wrong Answer :(') 21 | 22 | answer=input('Question 3: What is the name of your favourite website for learning Python?') 23 | if answer.lower()=='askpython': 24 | score += 1 25 | print('correct') 26 | else: 27 | print('Wrong Answer :(') 28 | 29 | print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!") 30 | mark=(score/total_questions)*100 31 | print('Marks obtained:',mark) 32 | print('BYE!') 33 | -------------------------------------------------------------------------------- /Python Codes/RANDOM_NUMBERS_SUM.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "#random numbers\n", 10 | "#Take between 1 to 100\n", 11 | "\n", 12 | "import random\n", 13 | "s=0\n", 14 | "l=[]\n", 15 | "for i in range(10):\n", 16 | " n=random.randint(1,100)\n", 17 | " l.append(n)\n", 18 | " s+=n\n", 19 | "print(\"RANDOM NUMBERS\")\n", 20 | "for j in l:\n", 21 | " print(j,end=\" \")\n", 22 | "print(\"\\n\")\n", 23 | "print(\"Sum=\", s)" 24 | ] 25 | } 26 | ], 27 | "metadata": { 28 | "kernelspec": { 29 | "display_name": "Python 3", 30 | "language": "python", 31 | "name": "python3" 32 | }, 33 | "language_info": { 34 | "codemirror_mode": { 35 | "name": "ipython", 36 | "version": 3 37 | }, 38 | "file_extension": ".py", 39 | "mimetype": "text/x-python", 40 | "name": "python", 41 | "nbconvert_exporter": "python", 42 | "pygments_lexer": "ipython3", 43 | "version": "3.8.5" 44 | } 45 | }, 46 | "nbformat": 4, 47 | "nbformat_minor": 4 48 | } 49 | -------------------------------------------------------------------------------- /Python Codes/Random Number Generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | def outer(n): 3 | lst = random.sample(range(0,n+1), n) 4 | def inner(): 5 | ind = random.randrange(0, n) 6 | return lst[ind] 7 | return inner 8 | 9 | n = int(input("Enter a random number: ")) 10 | pick_number = outer(n) 11 | print("Random number generated is: {}".format(pick_number())) 12 | -------------------------------------------------------------------------------- /Python Codes/Reverse_Dictionary Function.py: -------------------------------------------------------------------------------- 1 | def reverse_dictionary(d): 2 | new_dict = {} 3 | 4 | for i in d: 5 | for j in d[i]: 6 | try: 7 | new_dict[j].append(i) 8 | except: 9 | new_dict[j] = [i] 10 | 11 | return(new_dict) -------------------------------------------------------------------------------- /Python Codes/Rock paper scissor_: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.ttk import * 3 | import random 4 | window1 = Tk() 5 | window1.title('Rock Paper Scissors') 6 | window1.geometry('500x500') 7 | style1 = Style() 8 | style1.configure('W.TButton', foreground = 'green', font = ('Bernard MT', 30, 'bold')) 9 | lb1 = Label(window1, text = 'Rock Paper Scissors') 10 | lb1.pack(pady = 15) 11 | lb7 = Label(window1, text = 'Choose and then press start game to play:') 12 | lb7.pack(pady = 15) 13 | lit1 = ['Rock', 'Paper', 'Scissor'] 14 | your_score = 0 15 | computer_score = 0 16 | cho = 3 17 | def clicked2(): 18 | global cho 19 | lb9.configure(text = 'You have choosen Rock') 20 | cho = 0 21 | def clicked3(): 22 | global cho 23 | lb9.configure(text='You have choosen Paper') 24 | cho = 1 25 | def clicked4(): 26 | global cho 27 | lb9.configure(text='You have choosen Scissor') 28 | cho = 2 29 | btn2 = Button(window1, text = 'Rock', command = clicked2) 30 | btn2.pack() 31 | btn3 = Button(window1, text = 'Paper', command = clicked3) 32 | btn3.pack() 33 | btn4 = Button(window1, text = 'Scissor', command = clicked4) 34 | btn4.pack() 35 | lb9 = Label(window1, text = '') 36 | lb9.pack(pady = 10) 37 | lb13 = Label(window1, text = 'Computer: ') 38 | lb13.pack() 39 | lb2 = Label(window1, text = '') 40 | lb2.pack(pady = 10) 41 | 42 | def clicked1(): 43 | global cho 44 | if cho == 3: 45 | lb1.configure(text='Please choose an option to play!', foreground = 'purple') 46 | return 47 | res = random.choice(lit1) 48 | res1 = 4 49 | if res == 'Rock': 50 | res1 = 0 51 | elif res == 'Paper': 52 | res1 = 1 53 | elif res == 'Scissor': 54 | res1 = 2 55 | lb2.configure(text = res) 56 | if res1 == cho: 57 | global your_score 58 | lb1.configure(text = 'You Win', foreground = 'green') 59 | your_score = your_score + 1 60 | lb4.configure(text = 'Your Score: '+ str(your_score)) 61 | elif res1 != cho: 62 | global computer_score 63 | lb1.configure(text='You Lose', foreground='red') 64 | computer_score = computer_score +1 65 | lb5.configure(text='Computer Score: ' + str(computer_score)) 66 | cho = 3 67 | btn1 = Button(window1, text = 'START GAME', command = clicked1, style = 'W.TButton') 68 | btn1.pack(pady = 10) 69 | def clicked5(): 70 | global your_score 71 | global computer_score 72 | computer_score = 0 73 | your_score =0 74 | lb4.configure(text='Your Score: ' + str(your_score)) 75 | lb5.configure(text='Computer Score: ' + str(computer_score)) 76 | lb2.configure(text = '') 77 | lb9.configure(text = '') 78 | btn1 = Button(window1, text = 'Reset Scoreboard', command = clicked5) 79 | btn1.pack(pady = 10) 80 | lb1 = Label(window1, text = '') 81 | lb1.pack() 82 | lb3 = Label(window1, text = 'Note: Choose a button each time and then press start game to play!') 83 | lb3.pack(pady = 10) 84 | lb4 = Label(window1, text = 'Your Score: 0') 85 | lb4.pack() 86 | lb5 = Label(window1, text = 'Computer Score: 0') 87 | lb5.pack() 88 | window1.mainloop() 89 | -------------------------------------------------------------------------------- /Python Codes/Roman_to_Numeral.py: -------------------------------------------------------------------------------- 1 | def romanToInt(s): 2 | dc = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 3 | ans = 0 4 | for i in range(len(s)): 5 | if(i>0 and dc[s[i]]>dc[s[i-1]]): 6 | ans += dc[s[i]] - 2*dc[s[i-1]] 7 | else: 8 | ans += dc[s[i]] 9 | return ans -------------------------------------------------------------------------------- /Python Codes/Scrap amazon: -------------------------------------------------------------------------------- 1 | import csv 2 | from bs4 import BeautifulSoup 3 | from selenium import webdriver 4 | from webdriver_manager.chrome import ChromeDriverManager 5 | import os 6 | 7 | 8 | 9 | def get_url(search_term): 10 | 11 | template = 'https://www.amazon.com/s?k={}&ref=nb_sb_noss_1' 12 | 13 | search_term = search_term.replace(' ', '+') 14 | 15 | url = template.format(search_term) 16 | 17 | url += '&page{}' 18 | 19 | return url 20 | 21 | 22 | 23 | def extract_record(item): 24 | 25 | try: 26 | atag = item.h2.a 27 | except AttributeError: 28 | return 29 | 30 | try: 31 | description = atag.text.strip() 32 | except AttributeError: 33 | return 34 | 35 | url = 'https://www.amazon.com' + atag.get('href') 36 | 37 | try: 38 | price_parent = item.find('span', 'a-price') 39 | price = price_parent.find('span', 'a-offscreen').text 40 | except AttributeError: 41 | return 42 | 43 | try: 44 | rating = item.i.text 45 | review_count = item.find('span', {'class': 'a-size-base'}).text 46 | except AttributeError: 47 | rating = '' 48 | review_count = '' 49 | 50 | result = (description, price, rating, review_count, url) 51 | 52 | return result 53 | 54 | 55 | 56 | def main(): 57 | 58 | search_term = input("Enter the product name to search for - ") 59 | 60 | driver = webdriver.Chrome(ChromeDriverManager().install()) 61 | 62 | url = get_url(search_term) 63 | 64 | records = [] 65 | 66 | 67 | for page in range(1, 21): 68 | 69 | driver.get(url.format(page)) 70 | 71 | soup = BeautifulSoup(driver.page_source, 'html.parser') 72 | 73 | results = soup.find_all('div', {'class', 's-result-item'}) 74 | 75 | for item in results: 76 | 77 | record = extract_record(item) 78 | 79 | if record: 80 | records.append(record) 81 | 82 | 83 | driver.close() 84 | 85 | with open('Scrap-Amazon.csv', 'w', newline='', encoding='utf-8') as f: 86 | 87 | writer = csv.writer(f) 88 | 89 | writer.writerow(['Description', 'Price', 'Rating', 'Review Count', 'URL']) 90 | 91 | writer.writerows(records) 92 | 93 | 94 | os.startfile('Scrap-Amazon.csv') 95 | 96 | 97 | 98 | main() 99 | -------------------------------------------------------------------------------- /Python Codes/ShortenTheURL.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | random.randint(10,20) 4 | letters = string.ascii_lowercase 5 | digits = string.digits 6 | options = letters+digits 7 | # RUN THIS ONLY ONCE. 8 | URLS_DB = {} 9 | def get_short_url(url): 10 | # Convert a long url to short url and save in a Data. 11 | 12 | l = random.randint(4,6) 13 | 14 | short_url = "cm.in/" 15 | for i in range(l): 16 | short_url += random.choice(options) 17 | 18 | if URLS_DB.get(short_url) is not None: 19 | # invalid short url 20 | return get_short_url(url) 21 | else: 22 | URLS_DB[short_url] = url 23 | 24 | return short_url 25 | 26 | 27 | def get_long_url(short_url): 28 | # converts a short url to a long url. 29 | if URLS_DB.get(short_url) is None: 30 | return "Short Link doesn't exists" 31 | else: 32 | return URLS_DB[short_url] 33 | my_url = "https://codingminutes.com/python-data-science.html" 34 | print(get_short_url(my_url)) 35 | print(get_long_url('cm.in/76iyd')) 36 | -------------------------------------------------------------------------------- /Python Codes/Simple Array Sum.py: -------------------------------------------------------------------------------- 1 | output = 0 2 | count = int(input()) 3 | value = (input()) 4 | var = input() 5 | if var != "": 6 | value = value+" "+var 7 | 8 | lt = value.split() 9 | print(lt) 10 | while count > 0: 11 | count -= 1 12 | output += int(lt[count]) 13 | print(output) -------------------------------------------------------------------------------- /Python Codes/Star_RightAngledTriangle_Pattern.py: -------------------------------------------------------------------------------- 1 | def pypart(n): 2 | myList = [] 3 | for i in range(1,n+1): 4 | myList.append("*"*i) 5 | print("\n".join(myList)) 6 | 7 | n = 5 8 | pypart(n) 9 | -------------------------------------------------------------------------------- /Python Codes/Stop Watch_: -------------------------------------------------------------------------------- 1 | import tkinter as Tkinter 2 | from datetime import datetime 3 | 4 | counter = 66600 5 | running = False 6 | 7 | 8 | def counter_label(label): 9 | def count(): 10 | if running: 11 | global counter 12 | 13 | if counter == 66600: 14 | display = "Starting..." 15 | else: 16 | tt = datetime.fromtimestamp(counter) 17 | string = tt.strftime("%H:%M:%S") 18 | display = string 19 | 20 | label['text'] = display # Or label.config(text=display) 21 | 22 | label.after(1000, count) 23 | counter += 1 24 | 25 | count() 26 | 27 | 28 | def Start(label): 29 | global running 30 | running = True 31 | counter_label(label) 32 | start['state'] = 'disabled' 33 | stop['state'] = 'normal' 34 | reset['state'] = 'normal' 35 | 36 | 37 | def Stop(): 38 | global running 39 | start['state'] = 'normal' 40 | stop['state'] = 'disabled' 41 | reset['state'] = 'normal' 42 | running = False 43 | 44 | 45 | def Reset(label): 46 | global counter 47 | counter = 66600 48 | 49 | if running == False: 50 | reset['state'] = 'disabled' 51 | label['text'] = 'Welcome!' 52 | 53 | 54 | else: 55 | label['text'] = 'Starting...' 56 | 57 | 58 | root = Tkinter.Tk() 59 | root.title("Stopwatch") 60 | 61 | root.minsize(width=250, height=70) 62 | label = Tkinter.Label(root, text="Welcome!", fg="black", font="Verdana 30 bold") 63 | label.pack() 64 | f = Tkinter.Frame(root) 65 | start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label)) 66 | stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop) 67 | reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label)) 68 | f.pack(anchor='center', pady=5) 69 | start.pack(side="left") 70 | stop.pack(side="left") 71 | reset.pack(side="left") 72 | root.mainloop() 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /Python Codes/Sum of two numbers in python: -------------------------------------------------------------------------------- 1 | # This program adds two numbers 2 | 3 | num1 = 2 4 | num2 = 4 5 | 6 | # Add two numbers 7 | sum = num1 + num2 8 | 9 | # Display the sum 10 | print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) 11 | -------------------------------------------------------------------------------- /Python Codes/Swap_numbers.py: -------------------------------------------------------------------------------- 1 | # Python program to swap two variables 2 | 3 | #To take inputs from the user 4 | x = input('Enter value of x: ') 5 | y = input('Enter value of y: ') 6 | 7 | # create a temporary variable and swap the values 8 | temp = x 9 | x = y 10 | y = temp 11 | 12 | print('The value of x after swapping: {}'.format(x)) 13 | print('The value of y after swapping: {}'.format(y)) -------------------------------------------------------------------------------- /Python Codes/Temperature Converter/README.md: -------------------------------------------------------------------------------- 1 | ## How to run 2 | 3 | 1. Clone the repository 4 | ``` 5 | git@github.com:wbhoomika/python4beginners-Hacktoberfest21.git 6 | ``` 7 | 2. Navigate to `Temperature Converter` directory 8 | ``` 9 | cd python4beginners-Hacktoberfest21/Python Codes/Temperature Converter 10 | ``` 11 | 3. Run the script to convert the temperature from and to the desired scale 12 | ``` 13 | python tempconv.py 14 | ``` 15 | ### Note 16 | The scales can be selected from the dropdown list at the right side of the input field. 17 | -------------------------------------------------------------------------------- /Python Codes/Temperature Converter/tempconv.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from functools import partial 3 | 4 | tempVal = "Celsius" 5 | 6 | # Getting drop down value 7 | def store_temp(sel_temp): 8 | global tempVal 9 | tempVal = sel_temp 10 | 11 | 12 | # Temperature conversion 13 | def call_convert(rlabel1, rlabe12, inputn): 14 | tem = inputn.get() 15 | if tempVal == "Celsius": 16 | f = round(float((float(tem) * 9 / 5) + 32), 3) 17 | k = round(float((float(tem) + 273.15)), 3) 18 | rlabel1.config(text="%.3f Fahrenheit" % f) 19 | rlabe12.config(text="%.3f Kelvin" % k) 20 | if tempVal == "Fahrenheit": 21 | c = round(float((float(tem) - 32) * 5 / 9), 3) 22 | k = c + 273 23 | rlabel1.config(text="%.3f Celsius" % c) 24 | rlabe12.config(text="%.3f Kelvin" % k) 25 | if tempVal == "Kelvin": 26 | c = round(float((float(tem) - 273.15)), 3) 27 | f = round(float((float(tem) - 273.15) * 1.8000 + 32.00), 3) 28 | rlabel1.config(text="%.3f Celsius" % c) 29 | rlabe12.config(text="%.3f Fahrenheit" % f) 30 | return 31 | 32 | 33 | # App window configuration and UI 34 | root = tk.Tk() 35 | root.geometry("400x150+100+200") 36 | root.title("Temperature Converter") 37 | root.configure(background="#b7abc2") 38 | root.resizable(width=False, height=False) 39 | root.grid_columnconfigure(1, weight=1) 40 | root.grid_rowconfigure(0, weight=1) 41 | 42 | numberInput = tk.StringVar() 43 | var = tk.StringVar() 44 | 45 | # Label and entry field 46 | input_label = tk.Label( 47 | root, text="Enter temperature : ", background="#09A3BA", foreground="#FFFFFF" 48 | ) 49 | input_entry = tk.Entry( 50 | root, textvariable=numberInput, borderwidth=5, fg="white", bg="#545454" 51 | ) 52 | input_label.grid(row=1) 53 | input_entry.grid(row=1, column=1) 54 | 55 | # Result labels for showing the other two temperatures 56 | result_label1 = tk.Label(root, background="#b7abc2", foreground="#000000") 57 | result_label1.grid(row=3, columnspan=4) 58 | result_label2 = tk.Label(root, background="#b7abc2", foreground="#000000") 59 | result_label2.grid(row=4, columnspan=4) 60 | 61 | # Drop down initalization and setup 62 | dropDownList = ["Celsius", "Fahrenheit", "Kelvin"] 63 | dropdown = tk.OptionMenu(root, var, *dropDownList, command=store_temp) 64 | var.set(dropDownList[0]) 65 | dropdown.grid(row=1, column=3) 66 | dropdown.config(background="#09A3BA", foreground="#FFFFFF") 67 | dropdown["menu"].config(background="#09A3BA", foreground="#FFFFFF") 68 | 69 | # Button click 70 | call_convert = partial(call_convert, result_label1, result_label2, numberInput) 71 | result_button = tk.Button( 72 | root, 73 | text="Convert", 74 | command=call_convert, 75 | background="#09A3BA", 76 | foreground="#FFFFFF", 77 | ) 78 | result_button.grid(row=2, columnspan=4) 79 | 80 | root.mainloop() 81 | -------------------------------------------------------------------------------- /Python Codes/Test.py: -------------------------------------------------------------------------------- 1 | def isprime(n): 2 | f=2 3 | while f*f bool: 3 | 4 | rows = [set() for i in range(9)] 5 | cols = [set() for i in range(9)] 6 | mMat = [set() for i in range(9)] 7 | 8 | for i in range(9): 9 | for j in range(9): 10 | cur = board[i][j] 11 | if cur != '.': 12 | 13 | k = (i // 3 ) * 3 + j // 3 14 | 15 | if cur not in rows[i]: rows[i].add(cur) 16 | else: return False 17 | 18 | if cur not in cols[j]: cols[j].add(cur) 19 | else: return False 20 | 21 | if cur not in mMat[k]: mMat[k].add(cur) 22 | else: return False 23 | return True 24 | -------------------------------------------------------------------------------- /Python Codes/YouTubeDownloader.py: -------------------------------------------------------------------------------- 1 | from pytube import YouTube 2 | 3 | def run(Videos): 4 | for vidLink in Videos: 5 | try: 6 | youtube = YouTube(vidLink) # Searches for the video 7 | print("Downloading \"" + youtube.streams[0].title + "\"") 8 | except: 9 | print("\""+vidLink + "\" returned a connection issue") 10 | vidStream = youtube.streams.filter(res="720p").first() # Gets the video 11 | vidStream.download("Videos/") # Downloads the video to Downloads folder 12 | print("Completed!") 13 | 14 | 15 | if __name__ == "__main__": 16 | print("YouTube video downloader - To stop entering URLs, Just click Enter on an empty line. ") 17 | Videos = [] 18 | link = input("YouTube Video Link: ") # Gets the amount of Dice 19 | while not link.__eq__(""): 20 | Videos.append(link) 21 | link = input("YouTube Video Link: ") 22 | run(Videos) 23 | -------------------------------------------------------------------------------- /Python Codes/ZigZagPattern.py: -------------------------------------------------------------------------------- 1 | import math 2 | h=int(input()) 3 | n=int(input()) 4 | x=1 5 | y=1 6 | flag=True 7 | d={} 8 | while(n>0): 9 | if y in d: 10 | d[y]+=[x] 11 | else: 12 | d[y]=[x] 13 | x+=1 14 | if(flag): 15 | y+=1 16 | if(not flag): 17 | y-=1 18 | if(y==h): 19 | flag = False 20 | if(y==1): 21 | flag = True 22 | n-=1 23 | a=[] 24 | for i in range(1,h+1): 25 | b=[] 26 | x=0 27 | for j in d[i]: 28 | b+=[' ']*(j-x-1) 29 | b+=[j] 30 | x=j 31 | print(*b) 32 | ''''Sample 33 | Input 34 | 6 35 | 14 36 | Ouput 37 | 1 11 38 | 2 10 12 39 | 3 9 13 40 | 4 8 14 41 | 5 7 42 | 6 43 | '''' 44 | -------------------------------------------------------------------------------- /Python Codes/app.py: -------------------------------------------------------------------------------- 1 | from os import close 2 | from re import S 3 | import requests 4 | from bs4 import BeautifulSoup 5 | 6 | 7 | url="https://agomoni.org/" 8 | data=requests.get(url) 9 | 10 | htmlContent=data.content 11 | #print(htmlContent) 12 | 13 | soup=BeautifulSoup(htmlContent,'html.parser') 14 | #print(soup.prettify) 15 | 16 | #print(type(soup.title)) 17 | paras=soup.find_all('p') 18 | 19 | #for para in paras: 20 | # print("Scrapped Text : ",para.get_text()) 21 | 22 | #body=soup.find('div',class_="content_wrap") 23 | #for i in body.parents: 24 | # print(i) 25 | #exit() 26 | 27 | 28 | 29 | s=[] 30 | anchors=soup.find_all('a') 31 | 32 | for i in anchors: 33 | link=i.get('href') 34 | 35 | try: 36 | if(link!='#' and link[0:4]=='http'): 37 | s.append(link) 38 | print(link) 39 | except TypeError: 40 | pass 41 | 42 | 43 | with open ('link.txt','w') as fs: 44 | for i in s: 45 | fs.write(f"{i}\n") 46 | fs.close() -------------------------------------------------------------------------------- /Python Codes/armstronNumberGenerator.py: -------------------------------------------------------------------------------- 1 | """armstrong number is an number such that the sum of the digits raised to the power of the number of digits is equal to the original number 2 | Eg - 153 =1^3 +5^3 +3^3 3 | =1+125+9 (here the number of digits is 3 and therefore each digit is raised to the power 3 and ) 4 | =153 """ 5 | start = int(input("Enter starting number : ")) 6 | stop = int(input("Enter ending number : ")) 7 | for number in range(start, stop): 8 | digit = 0 # to reset the digit variable for every number in the loop 9 | sum = 0 # to reset the sum of digits for every number in the loop 10 | temp = int(number) 11 | while temp > 0: 12 | temp = temp // 10 13 | digit += 1 14 | temp = int(number) 15 | while temp > 0: 16 | rem = temp % 10 17 | c = rem 18 | for i in range(1, digit): 19 | c = c * rem 20 | sum = sum + c 21 | temp = temp // 10 22 | if sum == number: 23 | print(str(number) + " is an armstrong number") 24 | -------------------------------------------------------------------------------- /Python Codes/casino games/README.md: -------------------------------------------------------------------------------- 1 | # Presenting with you the most awaited Project.. "The Terminal Casino" 2 | ![Photo_1625234446649](https://user-images.githubusercontent.com/76024137/124350364-f94c1600-dc11-11eb-8735-bcd74dee79c8.jpg) 3 | # Enjoy Multiple games at one stop station.. at your own compiler with 0 pre requisites!! 4 | ![IMG_20210703_122743](https://user-images.githubusercontent.com/76024137/124346612-7caf3c80-dbfd-11eb-8723-435d5c9a2d09.jpg) 5 | 6 | -------------------------------------------------------------------------------- /Python Codes/casino games/Roulette.py: -------------------------------------------------------------------------------- 1 | import random 2 | from time import sleep 3 | import Terminal_Casinogame 4 | import math 5 | 6 | 7 | 8 | game_on = True 9 | 10 | while game_on : 11 | print("\nYou start the game with!", total_money, '$ \n') 12 | bet_value = -1 13 | 14 | # choose the square on which we put 15 | while bet_value < 0 or bet_value > 50: 16 | try: 17 | print("Choose the bet number[0,50]") 18 | bet_value = int(input("What is your choice? ...")) 19 | except ValueError: 20 | print("you haven't introduced anything.") 21 | bet_value = -1 22 | if bet_value < 0: 23 | print("you must choose a number greater than 0.") 24 | elif bet_value > 50: 25 | print("you must choose a number less than 50.") 26 | 27 | print("You chose", bet_value) 28 | 29 | # choose the amount to bet on the number 30 | money_to_bet = 0 31 | while money_to_bet <= 0 or money_to_bet > total_money: 32 | money_to_bet = input("\nWhat is your stake?") 33 | try: 34 | money_to_bet = int(money_to_bet) 35 | except ValueError: 36 | print("you did not choose your stake.") 37 | if money_to_bet <= 0: 38 | print("The bet is negative or zero.") 39 | if money_to_bet > total_money: 40 | print("You don't have enough money. You have", total_money) 41 | 42 | # start roulette 43 | print("\nThe croupier launches the roulette wheel ...") 44 | number_landed = random.randrange(0, 50) 45 | sleep(2) 46 | print("the roulette wheel stops on", number_landed) 47 | 48 | # processing 49 | if number_landed == bet_value: 50 | print("\nYou bet on the right number, you win", money_to_bet *3, '$') 51 | total_money += money_to_bet * 3 52 | elif number_landed % 2 == bet_value % 2: 53 | print("\nYou bet on the right color, you win", math.ceil(money_to_bet * 0.5), '$') 54 | total_money += math.ceil(money_to_bet * 0.5) 55 | else: 56 | print("\nSorry you lost", money_to_bet, '$') 57 | total_money -= money_to_bet 58 | 59 | # Game over 60 | if total_money <= 0: 61 | print("\nYou're ruined, it's the end of the party") 62 | game_on = False 63 | else: 64 | print("\nyou have now", total_money, '$') 65 | quitter = input("\nDo you want to quit the game(y/n)?") 66 | if quitter == 'y' or quitter == 'Y': 67 | print("\nYou leave the casino with", total_money, '$') 68 | game_on = False 69 | print("\nThank you for playing ROULETTE") 70 | 71 | -------------------------------------------------------------------------------- /Python Codes/casino games/Terminal_Casinogame.py: -------------------------------------------------------------------------------- 1 | total_money = 10000 2 | if __name__=='__main__': 3 | 4 | print(" █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█\n" 5 | " █░░╦─╦ ╔╗ ╦ ╔╗ ╔╗ ╔╦╗ ╔╗░░█\n" 6 | " █░░║║║ ╠─ ║ ║ ║║ ║║║ ╠─░░█\n" 7 | " █░░╚╩╝ ╚╝ ╚╝ ╚╝ ╚╝ ╩─╩ ╚╝░░█\n" 8 | " █▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█\n") 9 | print('~~WELCOME TO THE CASINO TERMINAL.... ' 10 | '\n ..THE ALL NEW GAMING PLATFORM! ') 11 | name = str(input('\n ~~Please enter your name: ')) 12 | age = int(input('\n What is your age : ')) 13 | 14 | 15 | print("\n ") 16 | 17 | 18 | game=True 19 | 20 | while game: 21 | if age>18: 22 | print("\n ~~HELLO", name, ",your wallet contains", total_money, "$") 23 | choice = -1 24 | print('\n Enter 1 for Playing the 7UP-7DOWN Game \n') 25 | print('Enter 2 for Playing Blackjack Game\n') 26 | print('Enter 3 for Playing Roulette Wheel Game\n') 27 | while choice>3 or choice<1: 28 | choice = int(input('Enter your choice:')) 29 | if (choice == 1): 30 | exec(open('SevenUP_SevenDOWN.py').read()) 31 | if (choice == 2): 32 | exec(open('Blackjack.py').read()) 33 | if (choice == 3): 34 | exec(open('Roulette.py').read()) 35 | 36 | quitter = input("\nDo you want to play another game(y/n)?") 37 | if quitter == 'y' or quitter == 'Y': 38 | game = True 39 | elif quitter == 'n' or quitter == 'N': 40 | game= False 41 | print("\n ~~HELLO", name, ",your wallet contains", total_money, "$") 42 | print("\nThank you for playing with TERMINAL CASINO and hope to see you again", name) 43 | 44 | else: 45 | print('You can only play Blackjack as you are underage !') 46 | exec(open('Blackjack.py').read()) 47 | quitter = input("\nDo you want to play another game(y/n)?") 48 | if quitter == 'y' or quitter == 'Y': 49 | game = True 50 | 51 | elif quitter == 'n' or quitter == 'N': 52 | game = False 53 | 54 | print("\nThank you for playing with TERMINAL CASINO and hope to see you again", name) 55 | 56 | -------------------------------------------------------------------------------- /Python Codes/checkPalindromeNumber.py: -------------------------------------------------------------------------------- 1 | def checkPalindrome(x): 2 | t = x 3 | v = 0 4 | while t>0: 5 | r = t%10 6 | v = r + (v*10) 7 | t = int(t/10) 8 | if v==x: 9 | return 1 10 | 11 | print("Enter a Number: ", end="") 12 | n = int(input()) 13 | 14 | chk = checkPalindrome(n) 15 | if chk==1: 16 | print("\n" + str(n) + " is a Palindrome Number") 17 | else: 18 | print("\n" + str(n) + " is not a Palindrome Number") -------------------------------------------------------------------------------- /Python Codes/copy contents of one file to another.py: -------------------------------------------------------------------------------- 1 | file_name1 = input("Enter file 1 name: ") 2 | file_name2 = input("Enter file 2 name: ") 3 | file3 = open(file_name2, "r") 4 | c = file3.readline() 5 | file1 = open(file_name1, "r") 6 | file2 = open(file_name2, "w") 7 | l = file1.readline() 8 | print("\n\nContent in file abc before copying is:", c) 9 | print("Content before copying in xyz is :", l) 10 | while l: 11 | file2.write(l) 12 | print("\n content copied successfully \n") 13 | print("Content after copying in abc is:", l) 14 | l = file1.readline() 15 | file1.close() 16 | file2.close() 17 | -------------------------------------------------------------------------------- /Python Codes/count_down_timer.py: -------------------------------------------------------------------------------- 1 | import time 2 | from os import system 3 | 4 | def countdown(time_sec): 5 | while time_sec: 6 | mins, secs = divmod(time_sec, 60) 7 | timeformat = '{:02d}:{:02d}'.format(mins, secs) 8 | print(timeformat, end='\r') 9 | time.sleep(1) 10 | time_sec -= 1 11 | 12 | system('cls') 13 | print("stop") 14 | 15 | countdown(5) -------------------------------------------------------------------------------- /Python Codes/couting_sort.py: -------------------------------------------------------------------------------- 1 | def countSort(arr): 2 | 3 | output = [0 for i in range(256)] 4 | 5 | count = [0 for i in range(256)] 6 | 7 | ans = ["" for _ in arr] 8 | 9 | for i in arr: 10 | count[ord(i)] += 1 11 | 12 | for i in range(256): 13 | count[i] += count[i-1] 14 | 15 | for i in range(len(arr)): 16 | output[count[ord(arr[i])]-1] = arr[i] 17 | count[ord(arr[i])] -= 1 18 | 19 | for i in range(len(arr)): 20 | ans[i] = output[i] 21 | return ans 22 | 23 | arr = "teststring" 24 | ans = countSort(arr) 25 | print(arr) 26 | -------------------------------------------------------------------------------- /Python Codes/deck_of_cards.py: -------------------------------------------------------------------------------- 1 | #first let's import random procedures since we will be shuffling 2 | import random 3 | 4 | #next, let's start building list holders so we can place our cards in there: 5 | cardfaces = [] 6 | suits = ["Hearts", "Diamonds", "Clubs", "Spades"] 7 | royals = ["J", "Q", "K", "A"] 8 | deck = [] 9 | 10 | #now, let's start using loops to add our content: 11 | for i in range(2,11): 12 | cardfaces.append(str(i)) #this adds numbers 2-10 and converts them to string data 13 | for j in range(4): 14 | cardfaces.append(royals[j]) #this will add the royal faces to the cardbase 15 | for k in range(4): 16 | for l in range(13): 17 | card = (cardfaces[l] + " of " + suits[k]) 18 | #this makes each card, cycling through suits, but first through faces 19 | deck.append(card) 20 | #this adds the information to the "full deck" we want to make 21 | #now let's shuffle our deck! 22 | random.shuffle(deck) 23 | #now let's see the cards! 24 | for m in range(52): 25 | print(deck[m]) 26 | 27 | 28 | # output of the code 29 | 30 | # 3 of Diamonds 31 | # A of Hearts 32 | # 5 of Hearts 33 | # 3 of Clubs 34 | # 7 of Hearts 35 | # J of Hearts 36 | # 7 of Spades 37 | # 2 of Clubs 38 | # 2 of Spades 39 | # 10 of Hearts 40 | # K of Clubs 41 | # K of Diamonds 42 | # 7 of Diamonds 43 | # J of Clubs 44 | # 2 of Hearts 45 | # Q of Hearts 46 | # 6 of Spades 47 | # K of Spades 48 | # 10 of Clubs 49 | # 4 of Diamonds 50 | # A of Spades 51 | # 9 of Hearts 52 | # 9 of Diamonds 53 | # 4 of Hearts 54 | # 9 of Spades 55 | # 5 of Diamonds 56 | # K of Hearts 57 | # J of Diamonds 58 | # Q of Spades 59 | # 8 of Diamonds 60 | # 9 of Clubs 61 | # 4 of Clubs 62 | # 5 of Clubs 63 | # 3 of Spades 64 | # 8 of Clubs 65 | # 4 of Spades 66 | # 2 of Diamonds 67 | # 8 of Hearts 68 | # J of Spades 69 | # 6 of Diamonds 70 | # A of Clubs 71 | # 10 of Diamonds 72 | # 10 of Spades 73 | # 6 of Hearts 74 | # 5 of Spades 75 | # A of Diamonds 76 | # 7 of Clubs 77 | # 3 of Hearts 78 | # Q of Diamonds 79 | # 6 of Clubs 80 | # 8 of Spades 81 | # Q of Clubs 82 | -------------------------------------------------------------------------------- /Python Codes/dice-roller.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | 4 | def run(die, rolls): 5 | for roll in range(rolls): # Repeats the amount of print outs, based on the amount of rolls 6 | printStr = "Roll " + str(roll+1) + ": " 7 | for dice in range(die): # Prints the amount of numbers desired 8 | printStr = printStr + " " + str(randint(1, 6)) 9 | print(printStr) # Prints the current roll's string 10 | 11 | 12 | if __name__ == "__main__": 13 | die = int(input("How Many Dice? ")) # Gets the amount of Dice 14 | rolls = int(input("How many Rolls? ")) # Gets the amount of Rolls 15 | run(die, rolls) 16 | -------------------------------------------------------------------------------- /Python Codes/dice_rolller_simulator.py: -------------------------------------------------------------------------------- 1 | import random 2 | x = "y" 3 | 4 | while x == "y": 5 | 6 | # Gnenerates a random number 7 | # between 1 and 6 (including 8 | # both 1 and 6) 9 | no = random.randint(1,6) 10 | 11 | if no == 1: 12 | print("[-----]") 13 | print("[ ]") 14 | print("[ 0 ]") 15 | print("[ ]") 16 | print("[-----]") 17 | if no == 2: 18 | print("[-----]") 19 | print("[ 0 ]") 20 | print("[ ]") 21 | print("[ 0 ]") 22 | print("[-----]") 23 | if no == 3: 24 | print("[-----]") 25 | print("[ ]") 26 | print("[0 0 0]") 27 | print("[ ]") 28 | print("[-----]") 29 | if no == 4: 30 | print("[-----]") 31 | print("[0 0]") 32 | print("[ ]") 33 | print("[0 0]") 34 | print("[-----]") 35 | if no == 5: 36 | print("[-----]") 37 | print("[0 0]") 38 | print("[ 0 ]") 39 | print("[0 0]") 40 | print("[-----]") 41 | if no == 6: 42 | print("[-----]") 43 | print("[0 0 0]") 44 | print("[ ]") 45 | print("[0 0 0]") 46 | print("[-----]") 47 | 48 | x=input("press y to roll again and n to exit:") 49 | print("\n") 50 | -------------------------------------------------------------------------------- /Python Codes/dog.py: -------------------------------------------------------------------------------- 1 | class Dog: 2 | species = "Canis familiaris" 3 | 4 | def __init__(self, name, age): 5 | self.name = name 6 | self.age = age 7 | 8 | def __str__(self): 9 | return f"{self.name} is {self.age} years old" 10 | 11 | def speak(self, sound): 12 | return f"{self.name} says {sound}" 13 | 14 | class GoldenRetriever(Dog): 15 | def speak(self, sound = 'Bark'): 16 | return super().speak(sound) 17 | 18 | miles = GoldenRetriever('miles', 14) 19 | print(miles.speak()) 20 | -------------------------------------------------------------------------------- /Python Codes/factors_number.py: -------------------------------------------------------------------------------- 1 | def print_factors(x): 2 | print("The factors of",x,"are:") 3 | for i in range(1, x + 1): 4 | if x % i == 0: 5 | print(i) 6 | 7 | num = 320 8 | 9 | print_factors(num) 10 | -------------------------------------------------------------------------------- /Python Codes/fcfs.py: -------------------------------------------------------------------------------- 1 | n=int(input("enter number of processes in the queue :")) 2 | head=int(input("enter the position of head currently:")) 3 | pr=[0]*100 4 | seekTime=0 5 | print("enter the positions of the processes in order :") 6 | for i in range(n): 7 | pr[i]=int(input()) 8 | if(i==0): 9 | seekTime=abs(head-pr[i]) 10 | else: 11 | seekTime+=abs(pr[i]-pr[i-1]) 12 | print("seek Time = ",seekTime) 13 | print("order of scheduling :\n") 14 | print(head," ->",end=" ") 15 | for i in range(n): 16 | print(pr[i]," ->",end=" ") 17 | print("end\n") 18 | -------------------------------------------------------------------------------- /Python Codes/find-new-videogames-to-play.py: -------------------------------------------------------------------------------- 1 | print("Are you trying to find new videogames to play?") 2 | print("let me help you!") 3 | print("do you like shooting games, yes or no") 4 | print("try improving accuracy for shooting") 5 | shooting=input() 6 | if shooting = "yes" 7 | print("do you like battle royale games?") 8 | br=input() 9 | if br="yes" 10 | print("you should try out call of duty!") 11 | else if br="no" 12 | print("you should try overwatch!") 13 | else if shooting="no" 14 | print("do you like sports games, yes or no") 15 | sports=input() 16 | if sports="yes" 17 | print("try out Fifa or NBA2k!") 18 | else if sports="no" 19 | print("I know, try out rocket league!") 20 | strategy=input() 21 | if strategy= "yes" 22 | print("do you love sandbox games?") 23 | sb=input() 24 | if sb="yes" 25 | print("you should try out minecraft!") 26 | 27 | -------------------------------------------------------------------------------- /Python Codes/find_gcd.py: -------------------------------------------------------------------------------- 1 | #Euclid's Algorithm to find the GCD of two numbers 2 | 3 | def euclid(n1, n2): 4 | if not n1: 5 | return n2 6 | if not n2: 7 | return n1 8 | if n1 > n2: 9 | return euclid(n1 % n2, n2) 10 | else: 11 | return euclid(n2 % n1, n1) 12 | 13 | 14 | if __name__ == "__main__": 15 | n1 = int(input()) 16 | n2 = int(input()) 17 | 18 | print("The GCD of the numbers is " + str(euclid(n1, n2))) 19 | -------------------------------------------------------------------------------- /Python Codes/for_loop.py: -------------------------------------------------------------------------------- 1 | #Youmay want to run different loops seperately(as running this whole script will print everything in a order) 2 | 3 | 4 | 5 | #As the name suggests loop is nothing but doing a certain task repeatedly, let's understand this through an example, if somone asks you to print 6 | #print your name 5 times then the immediate idea that comes to your mind is to use print statement 5 times. But think what will happen if number is 1000, 7 | #then using print statement isn't feasible, atleast doing that is too repetitive and obviously boring, here comes loop to the rescue 8 | #Enough theory, let us take a look at implementation 9 | 10 | 11 | for i in range(0,5): #It means that start i from 0 and end the loop when i=4 so it will run 5 times(always remember range function excludes the last number in range 12 | print('Joe') #And now if you have to print it 1000 times change 5 to 1000, easy isn't it? 13 | 14 | #Some more examples 15 | n=10 16 | for i in range(0,n): #print numbers 0,1.....n-1 17 | print(i) 18 | for i in range(1,10): #prints the table of n(change n to get the tables of different number) 19 | print(i*n) 20 | 21 | 22 | 23 | #Now, Let's take a look on some cool things which we can do using loops 24 | for i in range(0,5): #prints a pattern 25 | print('*'*i) #notice that string multiplication(with integers ofcourse) is supported in python i.e '*'*2= ** 26 | #don't get confused,'*' represent a character whereas * represent multiplication 27 | 28 | -------------------------------------------------------------------------------- /Python Codes/funktions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Here we learn to write and use simle functions. 3 | """ 4 | 5 | def first_function(): # Every function begins with def , follow with the name and tho prerentecis. Add then a colon at the end. 6 | print(f"This is a simple function.") 7 | print(f"Wen we use the this function, python will show us this message.") 8 | 9 | first_function() # Here we cal the funktion 10 | 11 | """ 12 | But we can make this a lot more dynamic. 13 | """ 14 | 15 | def second_function(foo): # Here we add an value to the function 16 | print(foo) # Print our value 17 | 18 | second_function(f"Just another value!") 19 | 20 | """ 21 | More interactiv? No problem! 22 | 23 | You can use an variable to past your value like this.py 24 | 25 | bar = input("Enter your value. ") 26 | second_function(bar) 27 | 28 | Or the shorter way… 29 | """ 30 | 31 | second_function(input(f"Just give me a value.: ")) # Here we call the input function directly as value. 32 | 33 | """ 34 | If you want to set a value as default is this the way to go… 35 | """ 36 | 37 | def third_function(foo="You don't give me any value to print."): # We set a default value for foo 38 | print(foo) 39 | 40 | third_function() # A call from the third_function without any value. 41 | third_function(input(f"The second call from the third_function. Now we overwrite the default value from foo. ")) # If you just press return, so you send an empty value. 42 | third_function() # Just a check. You see, foo is not set and the standard value is print again. 43 | -------------------------------------------------------------------------------- /Python Codes/graphs.py: -------------------------------------------------------------------------------- 1 | # simple python program plotting graphs depending on input 2 | # requires installation of matplotlib library 3 | import matplotlib.pyplot as plt 4 | 5 | a=[1,2,3,4,5,6] 6 | b=[3,6,9,12,15,18] 7 | plt.plot(a,b) 8 | plt.xlabel("X-axis") 9 | plt.ylabel("Y-axis") 10 | plt.title("Plot between X and Y axis") 11 | plt.show() 12 | -------------------------------------------------------------------------------- /Python Codes/guessTheNumber.py: -------------------------------------------------------------------------------- 1 | import random 2 | n = random.randint(1,100) 3 | print('--------Welcome to the game--------') 4 | print('Rules:') 5 | print('1. Guess a number between 1 and 100') 6 | print('2. We will tell you whether the number you chose is higher or lower than our number') 7 | print('3. You win when you make the right guess within 10 attempts') 8 | 9 | i = 0 10 | k = False 11 | for i in range(10): 12 | print("Have your guess:") 13 | x = int(input()) 14 | if(x==n): 15 | k=True 16 | print(f'{x} is the correct guess. You won!!!') 17 | break 18 | elif(x>n): 19 | i+=1 20 | print('The number you guessed is higher than our number') 21 | else: 22 | i+=1 23 | print('The number you guessed is lower than our number') 24 | print(f'You have {10-i} chances remaining') 25 | if(not k): 26 | print(f'Our number was: {n}') -------------------------------------------------------------------------------- /Python Codes/handcricket.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | 4 | lower = int(input("Enter Lower bound:- ")) 5 | 6 | 7 | upper = int(input("Enter Upper bound:- ")) 8 | 9 | 10 | x = random.randint(lower, upper) 11 | print("\n\tYou've only ", 12 | round(math.log(upper - lower + 1, 2)), 13 | " chances to guess the integer!\n") 14 | 15 | 16 | count = 0 17 | 18 | 19 | while count < math.log(upper - lower + 1, 2): 20 | count += 1 21 | 22 | 23 | guess = int(input("Guess a number:- ")) 24 | 25 | 26 | if x == guess: 27 | print("Congratulations you did it in ", 28 | count, " try") 29 | 30 | break 31 | elif x > guess: 32 | print("You guessed too small!") 33 | elif x < guess: 34 | print("You Guessed too high!") 35 | 36 | 37 | 38 | if count >= math.log(upper - lower + 1, 2): 39 | print("\nThe number is %d" % x) 40 | print("\tBetter Luck Next time!") 41 | 42 | -------------------------------------------------------------------------------- /Python Codes/handcricketgame.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[3]: 5 | 6 | import random 7 | def Handcricket(overs): 8 | Total_balls=(overs*6) 9 | print("Total number of balls : ",Total_balls) 10 | score=0 11 | n=1 12 | computer_score=random.randrange(0,(overs*36)) #Goal to be reached 13 | print(" computer score to beat: ",computer_score) 14 | while (scorecomputer_score): 26 | print("Your score ",score,"\n") 27 | print("Congratulations!!You won the game.") 28 | elif(score>")) 82 | if ch == 1: 83 | m1.addmat(m2).write() 84 | elif ch == 2: 85 | m1.submat(m2).write() 86 | elif ch == 3: 87 | m1.mulmat(m2).write() 88 | elif ch == 4: 89 | print("Transpose of first Matrix: ") 90 | m1.transpose().write() 91 | print("Transpose of second Matrix: ") 92 | m2.transpose().write() 93 | elif ch == 5: 94 | m, n = map(int, input("Enter the dimensions of the Matrix separated by whitespace: ").split()) 95 | m1 = Matrix(m, n) 96 | m1.getmat() 97 | x, y = map(int, input("Enter the dimensions of the second Matrix separated by whitespace: ").split()) 98 | m2 = Matrix(x, y) 99 | m2.getmat() 100 | elif ch == 6: 101 | break 102 | else: 103 | print("Invalid Input") 104 | -------------------------------------------------------------------------------- /Python Codes/mergeSortedArray.py: -------------------------------------------------------------------------------- 1 | def merge(arr1, arr2, n1, n2): 2 | arr3=[None]*(n1+n2) 3 | p1=0 4 | p2=0 5 | i=0 6 | while ( p1< n1 and p2 > "))) 8 | 9 | # extract only audio 10 | video = yt.streams.filter(only_audio=True).first() 11 | 12 | # check for destination to save file 13 | print("Enter the destination (leave blank for current directory)") 14 | destination = str(input(">> ")) or '.' 15 | 16 | # download the file 17 | out_file = video.download(output_path=destination) 18 | 19 | # save the file 20 | base, ext = os.path.splitext(out_file) 21 | new_file = base + '.mp3' 22 | os.rename(out_file, new_file) 23 | 24 | # result of success 25 | print(yt.title + " has been successfully downloaded.") 26 | -------------------------------------------------------------------------------- /Python Codes/mp3_downloader.py: -------------------------------------------------------------------------------- 1 | import time 2 | import os 3 | import sys 4 | from pathlib import Path 5 | from plyer import notification as nt 6 | from selenium import webdriver 7 | from selenium.webdriver.common.keys import Keys 8 | 9 | path_to_downloads = os.path.join(Path.home(), "Downloads") 10 | 11 | songs_list_path = os.path.join(Path.home(), "Desktop", "Songs List for Automated Download.txt") 12 | 13 | if not os.path.exists(songs_list_path): 14 | f_temp = open(songs_list_path, 'w') 15 | f_temp.close() 16 | nt.notify( 17 | title = "Mp3 Songs Automatic Downloader", 18 | message = 'A temporary file named "Songs List for Automated Download" has been created. Please enter the songs (one in each line), save it and run the application again!', 19 | timeout = 15 20 | ) 21 | sys.exit() 22 | 23 | f = open(songs_list_path, 'r') 24 | songs = f.readlines() 25 | 26 | if not len(songs): 27 | nt.notify( 28 | title = "Mp3 Songs Automatic Downloader", 29 | message = 'Songs list empty!', 30 | timeout = 7 31 | ) 32 | sys.exit() 33 | 34 | chrome_options = webdriver.ChromeOptions() 35 | chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) 36 | driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", options=chrome_options) 37 | 38 | driver.get("https://mp3quack.lol/") 39 | 40 | for song in songs: 41 | driver.find_element_by_id("searchInput").clear() 42 | search = driver.find_element_by_id("searchInput") 43 | search.send_keys(song.strip()) 44 | search.send_keys(Keys.RETURN) 45 | time.sleep(2) 46 | download = driver.find_element_by_xpath("/html/body/div[2]/div[3]/div/div[2]/div[2]/ul[1]/li[3]") 47 | download.click() 48 | handles = driver.window_handles 49 | driver.switch_to.window(handles[0]) 50 | if len(handles) > 1: 51 | for i in range(1, len(handles)): 52 | driver.switch_to.window(handles[i]) 53 | driver.close() 54 | driver.switch_to.window(handles[0]) 55 | download = driver.find_element_by_xpath("/html/body/div[2]/div[3]/div/div[2]/div[2]/ul[1]/li[3]") 56 | download.click() 57 | time.sleep(2) 58 | handles = driver.window_handles 59 | driver.switch_to.window(handles[1]) 60 | song_link = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div[3]/ul/li[1]") 61 | song_link.click() 62 | time.sleep(2) 63 | driver.switch_to.window(handles[1]) 64 | driver.close() 65 | time.sleep(2) 66 | driver.switch_to.window(handles[0]) 67 | 68 | while True: 69 | count = 0 70 | for file in os.listdir(path_to_downloads): 71 | if file.strip().endswith(".crdownload"): 72 | count += 1 73 | if count == 0: 74 | break 75 | driver.quit() 76 | f.close() 77 | os.remove(songs_list_path) -------------------------------------------------------------------------------- /Python Codes/nQueen.py: -------------------------------------------------------------------------------- 1 | # Python program to solve N Queen 2 | # Problem using backtracking 3 | 4 | global N 5 | N = 4 6 | 7 | def printSolution(board): 8 | for i in range(N): 9 | for j in range(N): 10 | print board[i][j], 11 | print 12 | 13 | 14 | # A utility function to check if a queen can 15 | # be placed on board[row][col]. Note that this 16 | # function is called when "col" queens are 17 | # already placed in columns from 0 to col -1. 18 | # So we need to check only left side for 19 | # attacking queens 20 | def isSafe(board, row, col): 21 | 22 | # Check this row on left side 23 | for i in range(col): 24 | if board[row][i] == 1: 25 | return False 26 | 27 | # Check upper diagonal on left side 28 | for i, j in zip(range(row, -1, -1), range(col, -1, -1)): 29 | if board[i][j] == 1: 30 | return False 31 | 32 | # Check lower diagonal on left side 33 | for i, j in zip(range(row, N, 1), range(col, -1, -1)): 34 | if board[i][j] == 1: 35 | return False 36 | 37 | return True 38 | 39 | def solveNQUtil(board, col): 40 | # base case: If all queens are placed 41 | # then return true 42 | if col >= N: 43 | return True 44 | 45 | # Consider this column and try placing 46 | # this queen in all rows one by one 47 | for i in range(N): 48 | 49 | if isSafe(board, i, col): 50 | # Place this queen in board[i][col] 51 | board[i][col] = 1 52 | 53 | # recur to place rest of the queens 54 | if solveNQUtil(board, col + 1) == True: 55 | return True 56 | 57 | # If placing queen in board[i][col 58 | # doesn't lead to a solution, then 59 | # queen from board[i][col] 60 | board[i][col] = 0 61 | 62 | # if the queen can not be placed in any row in 63 | # this column col then return false 64 | return False 65 | 66 | # This function solves the N Queen problem using 67 | # Backtracking. It mainly uses solveNQUtil() to 68 | # solve the problem. It returns false if queens 69 | # cannot be placed, otherwise return true and 70 | # placement of queens in the form of 1s. 71 | # note that there may be more than one 72 | # solutions, this function prints one of the 73 | # feasible solutions. 74 | def solveNQ(): 75 | board = [ [0, 0, 0, 0], 76 | [0, 0, 0, 0], 77 | [0, 0, 0, 0], 78 | [0, 0, 0, 0] 79 | ] 80 | 81 | if solveNQUtil(board, 0) == False: 82 | print "Solution does not exist" 83 | return False 84 | 85 | printSolution(board) 86 | return True 87 | 88 | # driver program to test above function 89 | solveNQ() 90 | 91 | # This code is contributed by Divyanshu Mehta 92 | -------------------------------------------------------------------------------- /Python Codes/naeema19_probdiff.py: -------------------------------------------------------------------------------- 1 | T=int(input()) 2 | for i in range(T): 3 | n=list(map(int,input().split())) 4 | n1=set(n) 5 | if len(n1)==4: 6 | print(2) 7 | elif len(n1)==3: 8 | print(2) 9 | elif len(n1)==2: 10 | n.sort() 11 | n2=n[0] 12 | if(n.count(n2)==2): 13 | print(2) 14 | else: 15 | print(1) 16 | else: 17 | print(0) 18 | 19 | 20 | -------------------------------------------------------------------------------- /Python Codes/numbersbooklet.py: -------------------------------------------------------------------------------- 1 | #Simple program to check different categories of number according to user choice. 2 | print("*" * 50) 3 | print(" " * 10,"Categories of Numbers") 4 | print(" " *10," Check types of number") 5 | print("*" * 50) 6 | print("1. Palindrome\n\ 7 | 2. Strong \n\ 8 | 3. Armstrong \n\ 9 | 4. Prime \n\ 10 | 5. Positive or Negative \n\ 11 | 6. Odd or Even") 12 | n=int(input("Enter your choice")) 13 | if n==1: 14 | n=int(input("Enter a Number")) 15 | p=n 16 | r=0 17 | while n!=0: 18 | d=n%10 19 | r=r*10+d 20 | n=n//10 21 | if r==p: 22 | print(" It is a Palindrome Number") 23 | else: 24 | print("It is not a Palindrome Number") 25 | elif n==2: 26 | n=int(input("Enter a Number")) 27 | p=n 28 | c=0 29 | while n!=0: 30 | d=n%10 31 | n=n//10 32 | f=1 33 | for x in range(1,d+1): 34 | f=f*x 35 | c=c+f 36 | if c==p: 37 | print("It is a Strong Number") 38 | else: 39 | print("It is not a strong number") 40 | elif n==3: 41 | n=int(input("Enter a Number")) 42 | p=n 43 | c=0 44 | while n!=0: 45 | d=n%10 46 | n=n//10 47 | c=c+d**3 48 | if p==c: 49 | print("It is an Armstrong Number") 50 | else: 51 | print("It is not an Armstrong Number") 52 | elif n==4: 53 | n=int(input("Enter a Number")) 54 | for x in range(n): 55 | c=0 56 | for y in range(1,x+1): 57 | if x%y==0: 58 | c=c+1 59 | if c==2: 60 | print("It is a Prime Number") 61 | else: 62 | print("It is not a Prime Number") 63 | elif n==5: 64 | n=int(input("Enter a Number")) 65 | if n >=0: 66 | print("It is a Positive Number") 67 | else: 68 | print("It is Negative Number") 69 | elif n==6: 70 | n=int(input("Enter a Number")) 71 | if n %2==0: 72 | print("It is Even Number") 73 | else: 74 | print("It is Odd number") 75 | else: 76 | print("Invalid choice") 77 | 78 | 79 | -------------------------------------------------------------------------------- /Python Codes/palindrome.py: -------------------------------------------------------------------------------- 1 | # function which return reverse of a string 2 | 3 | def isPalindrome(s): 4 | return s == s[::-1] 5 | 6 | 7 | # Driver code 8 | s = "malayalam" 9 | ans = isPalindrome(s) 10 | 11 | if ans: 12 | print("Yes") 13 | else: 14 | print("No") 15 | -------------------------------------------------------------------------------- /Python Codes/pass gen: -------------------------------------------------------------------------------- 1 | # Python program to generate random 2 | # password using Tkinter module 3 | import random 4 | import pyperclip 5 | from tkinter import * 6 | from tkinter.ttk import * 7 | 8 | # Function for calculation of password 9 | def low(): 10 | entry.delete(0, END) 11 | 12 | # Get the length of password 13 | length = var1.get() 14 | 15 | lower = "abcdefghijklmnopqrstuvwxyz" 16 | upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 17 | digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !@#$%^&*()" 18 | password = "" 19 | 20 | # if strength selected is low 21 | if var.get() == 1: 22 | for i in range(0, length): 23 | password = password + random.choice(lower) 24 | return password 25 | 26 | # if strength selected is medium 27 | elif var.get() == 0: 28 | for i in range(0, length): 29 | password = password + random.choice(upper) 30 | return password 31 | 32 | # if strength selected is strong 33 | elif var.get() == 3: 34 | for i in range(0, length): 35 | password = password + random.choice(digits) 36 | return password 37 | else: 38 | print("Please choose an option") 39 | 40 | 41 | # Function for generation of password 42 | def generate(): 43 | password1 = low() 44 | entry.insert(10, password1) 45 | 46 | 47 | # Function for copying password to clipboard 48 | def copy1(): 49 | random_password = entry.get() 50 | pyperclip.copy(random_password) 51 | 52 | 53 | # Main Function 54 | 55 | # create GUI window 56 | root = Tk() 57 | var = IntVar() 58 | var1 = IntVar() 59 | 60 | # Title of your GUI window 61 | root.title("Random Password Generator") 62 | 63 | # create label and entry to show 64 | # password generated 65 | Random_password = Label(root, text="Password") 66 | Random_password.grid(row=0) 67 | entry = Entry(root) 68 | entry.grid(row=0, column=1) 69 | 70 | # create label for length of password 71 | c_label = Label(root, text="Length") 72 | c_label.grid(row=1) 73 | 74 | # create Buttons Copy which will copy 75 | # password to clipboard and Generate 76 | # which will generate the password 77 | copy_button = Button(root, text="Copy", command=copy1) 78 | copy_button.grid(row=0, column=2) 79 | generate_button = Button(root, text="Generate", command=generate) 80 | generate_button.grid(row=0, column=3) 81 | 82 | # Radio Buttons for deciding the 83 | # strength of password 84 | # Default strength is Medium 85 | radio_low = Radiobutton(root, text="Low", variable=var, value=1) 86 | radio_low.grid(row=1, column=2, sticky='E') 87 | radio_middle = Radiobutton(root, text="Medium", variable=var, value=0) 88 | radio_middle.grid(row=1, column=3, sticky='E') 89 | radio_strong = Radiobutton(root, text="Strong", variable=var, value=3) 90 | radio_strong.grid(row=1, column=4, sticky='E') 91 | combo = Combobox(root, textvariable=var1) 92 | 93 | # Combo Box for length of your password 94 | combo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16, 95 | 17, 18, 19, 20, 21, 22, 23, 24, 25, 96 | 26, 27, 28, 29, 30, 31, 32, "Length") 97 | combo.current(0) 98 | combo.bind('<>') 99 | combo.grid(column=1, row=1) 100 | 101 | # start the GUI 102 | root.mainloop() 103 | -------------------------------------------------------------------------------- /Python Codes/passwordGenerator.py: -------------------------------------------------------------------------------- 1 | from random import * 2 | 3 | def generatePassword(length, specialChars): 4 | chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 5 | nums = "0123456789" 6 | specials = "!@#$%^&*()_-=+|}{[]\\';:/?><,." 7 | stringToUse = chars + nums 8 | password = "" 9 | if specialChars: 10 | stringToUse += specials 11 | 12 | 13 | for x in range(int(length)): 14 | rand = randint(1, len(stringToUse)) 15 | password += stringToUse[rand] 16 | 17 | return password 18 | 19 | print("Password Generator") 20 | 21 | howLong = input("How long should the password be?\n") 22 | 23 | specHolder = input("Do you want special characters? (y/n)\n") 24 | 25 | if specHolder == "n": 26 | specialChars = False 27 | else: 28 | specialChars = True 29 | 30 | print(generatePassword(howLong, specialChars)) -------------------------------------------------------------------------------- /Python Codes/passwordhasher.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import os 3 | 4 | salt = os.urandom(32) # Remember this 5 | password = input() #input a password to be hashed 6 | 7 | key = hashlib.pbkdf2_hmac( 8 | 'sha256', # The hash digest algorithm for HMAC 9 | password.encode('utf-8'), # Convert the password to bytes 10 | salt, # Provide the salt 11 | 100000 # It is recommended to use at least 100,000 iterations of SHA-256 12 | ) 13 | -------------------------------------------------------------------------------- /Python Codes/piglatin_translator.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | lst = ['sh', 'gl', 'ch', 'ph', 'tr', 'br', 'fr', 'bl', 'gr', 'st', 'sl', 'cl', 'pl', 'fl'] 3 | sentence = input('Type what you would like translated into pig-latin and press ENTER: ') 4 | sentence = sentence.split() 5 | for k in range(len(sentence)): 6 | i = sentence[k] 7 | if i[0] in ['a', 'e', 'i', 'o', 'u']: 8 | sentence[k] = i+'ay' 9 | elif t(i) in lst: 10 | sentence[k] = i[2:]+i[:2]+'ay' 11 | elif i.isalpha() == False: 12 | sentence[k] = i 13 | else: 14 | sentence[k] = i[1:]+i[0]+'ay' 15 | return ' '.join(sentence) 16 | 17 | def t(str): 18 | return str[0]+str[1] 19 | 20 | if __name__ == "__main__": 21 | x = main() 22 | print(x) 23 | -------------------------------------------------------------------------------- /Python Codes/primeNumberGenerator.py: -------------------------------------------------------------------------------- 1 | def primeChecker(start, stop): 2 | k = 1 3 | for number in range(start, stop): 4 | if number == 1: 5 | print(str(number) + " is neither prime nor composite") 6 | else: 7 | for i in range(2, number): 8 | if number % i != 0: 9 | k = 1 10 | elif number % i == 0: 11 | k = k + 1 12 | break 13 | if k == 1: 14 | print(str(number) + " is prime number") 15 | 16 | start = int(input("enter the starting number: ")) 17 | stop = int(input("enter the stoping number: ")) 18 | 19 | primeChecker(start, stop) -------------------------------------------------------------------------------- /Python Codes/prime_number.py: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | num = 29 4 | 5 | # To take input from the user 6 | #num = int(input("Enter a number: ")) 7 | 8 | # define a flag variable 9 | flag = False 10 | 11 | # prime numbers are greater than 1 12 | if num > 1: 13 | # check for factors 14 | for i in range(2, num): 15 | if (num % i) == 0: 16 | # if factor is found, set flag to True 17 | flag = True 18 | # break out of loop 19 | break 20 | 21 | # check if flag is True 22 | if flag: 23 | print(num, "is not a prime number") 24 | else: 25 | print(num, "is a prime number") 26 | -------------------------------------------------------------------------------- /Python Codes/primsalgorithm.py: -------------------------------------------------------------------------------- 1 | # A Python program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | # The program is for adjacency matrix representation of the graph 3 | 4 | import sys # Library for INT_MAX 5 | 6 | class Graph(): 7 | 8 | def __init__(self, vertices): 9 | self.V = vertices 10 | self.graph = [[0 for column in range(vertices)] 11 | for row in range(vertices)] 12 | 13 | # A utility function to print the constructed MST stored in parent[] 14 | def printMST(self, parent): 15 | print ("Edge \tWeight") 16 | for i in range(1, self.V): 17 | print (parent[i], "-", i, "\t", self.graph[i][ parent[i] ]) 18 | 19 | # A utility function to find the vertex with 20 | # minimum distance value, from the set of vertices 21 | # not yet included in shortest path tree 22 | def minKey(self, key, mstSet): 23 | 24 | # Initialize min value 25 | min = sys.maxint 26 | 27 | for v in range(self.V): 28 | if key[v] < min and mstSet[v] == False: 29 | min = key[v] 30 | min_index = v 31 | 32 | return min_index 33 | 34 | # Function to construct and print MST for a graph 35 | # represented using adjacency matrix representation 36 | def primMST(self): 37 | 38 | # Key values used to pick minimum weight edge in cut 39 | key = [sys.maxint] * self.V 40 | parent = [None] * self.V # Array to store constructed MST 41 | # Make key 0 so that this vertex is picked as first vertex 42 | key[0] = 0 43 | mstSet = [False] * self.V 44 | 45 | parent[0] = -1 # First node is always the root of 46 | 47 | for cout in range(self.V): 48 | 49 | # Pick the minimum distance vertex from 50 | # the set of vertices not yet processed. 51 | # u is always equal to src in first iteration 52 | u = self.minKey(key, mstSet) 53 | 54 | # Put the minimum distance vertex in 55 | # the shortest path tree 56 | mstSet[u] = True 57 | 58 | # Update dist value of the adjacent vertices 59 | # of the picked vertex only if the current 60 | # distance is greater than new distance and 61 | # the vertex in not in the shortest path tree 62 | for v in range(self.V): 63 | 64 | # graph[u][v] is non zero only for adjacent vertices of m 65 | # mstSet[v] is false for vertices not yet included in MST 66 | # Update the key only if graph[u][v] is smaller than key[v] 67 | if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: 68 | key[v] = self.graph[u][v] 69 | parent[v] = u 70 | 71 | self.printMST(parent) 72 | 73 | g = Graph(5) 74 | g.graph = [ [0, 2, 0, 6, 0], 75 | [2, 0, 3, 8, 5], 76 | [0, 3, 0, 0, 7], 77 | [6, 8, 0, 0, 9], 78 | [0, 5, 7, 9, 0]] 79 | 80 | g.primMST() 81 | 82 | -------------------------------------------------------------------------------- /Python Codes/problem.py: -------------------------------------------------------------------------------- 1 | T=int(input()) 2 | for i in range(T): 3 | n=list(map(int,input().split())) 4 | n1=set(n) 5 | if len(n1)==4: 6 | print(2) 7 | elif len(n1)==3: 8 | print(2) 9 | elif len(n1)==2: 10 | n.sort() 11 | n2=n[0] 12 | if(n.count(n2)==2): 13 | print(2) 14 | else: 15 | print(1) 16 | else: 17 | print(0) 18 | -------------------------------------------------------------------------------- /Python Codes/radix-sort.py: -------------------------------------------------------------------------------- 1 | def radix_sort(nums): 2 | RADIX = 10 3 | placement = 1 4 | max_digit = max(nums) 5 | 6 | while placement < max_digit: 7 | buckets = [list() for _ in range( RADIX )] 8 | for i in nums: 9 | tmp = int((i / placement) % RADIX) 10 | buckets[tmp].append(i) 11 | a = 0 12 | for b in range( RADIX ): 13 | buck = buckets[b] 14 | for i in buck: 15 | nums[a] = i 16 | a += 1 17 | placement *= RADIX 18 | return nums 19 | user_input = input("Input numbers separated by a comma:\n").strip() 20 | nums = [int(item) for item in user_input.split(',')] 21 | print(radix_sort(nums)) -------------------------------------------------------------------------------- /Python Codes/randomnumbergen.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | def run(digits, numbers): 4 | for num in range(numbers): # Repeats the amount of print outs, based on the amount of rolls 5 | printStr = "" # Resets the printout string 6 | for dig in range(digits): # Prints the amount of numbers desired 7 | printStr = printStr + str(randint(0, 9)) 8 | print(printStr) # Prints the current number's string 9 | 10 | 11 | if __name__ == "__main__": 12 | digits = int(input("How Many digits? ")) # Gets the amount of digits 13 | numbers = int(input("How many total numbers? ")) # Gets the amount of numbers to output 14 | run(digits, numbers) 15 | -------------------------------------------------------------------------------- /Python Codes/reverse_integer.py: -------------------------------------------------------------------------------- 1 | def reverse_int(x): 2 | #If given argument is non-integer, we return 0 3 | if(x.isnumeric()==0): 4 | return 0 5 | #Taking Absolute of given integer in n 6 | n = abs(x) 7 | #Initializing reverse with 0 8 | reverse = 0 9 | while(n>0): 10 | #Getting the last digit of n 11 | r = n%10 12 | #Adding last digit in reverse 13 | reverse = (reverse*10) + r 14 | #Removing last digit of n 15 | n = n//10 16 | #If given integer is negative 17 | if(x<0): 18 | reverse = -reverse 19 | return reverse 20 | #If given integer is non-negative 21 | return reverse -------------------------------------------------------------------------------- /Python Codes/rock_paper.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | #create a list of play options 4 | t = ["Rock", "Paper", "Scissors"] 5 | 6 | #assign a random play to the computer 7 | computer = t[randint(0,2)] 8 | 9 | #set player to False 10 | player = False 11 | 12 | while player == False: 13 | #set player to True 14 | player = input("Rock, Paper, Scissors?") 15 | if player == computer: 16 | print("Tie!") 17 | elif player == "Rock": 18 | if computer == "Paper": 19 | print("You lose!", computer, "covers", player) 20 | else: 21 | print("You win!", player, "smashes", computer) 22 | elif player == "Paper": 23 | if computer == "Scissors": 24 | print("You lose!", computer, "cut", player) 25 | else: 26 | print("You win!", player, "covers", computer) 27 | elif player == "Scissors": 28 | if computer == "Rock": 29 | print("You lose...", computer, "smashes", player) 30 | else: 31 | print("You win!", player, "cut", computer) 32 | else: 33 | print("That's not a valid play. Check your spelling!") 34 | #player was set to True, but we want it to be False so the loop continues 35 | player = False 36 | computer = t[randint(0,2)] 37 | -------------------------------------------------------------------------------- /Python Codes/rock_paper_scissor.py: -------------------------------------------------------------------------------- 1 | import random 2 | # This library helps make a random choice. 3 | c = True 4 | # Loop runs until this is true. 5 | cu = ["r","p","s"] 6 | # Stores the choices available for the computer 7 | ps = 0 8 | # This stores the player score. 9 | cus = 0 10 | # This stores the computer score. 11 | while(c): 12 | print("Enter r for \" ROCK \"") 13 | print("Enter p for \" PAPER \"") 14 | print("Enter s for \" SCISSOR \"") 15 | print("Enter w to reset") 16 | print("Enter q to quit the game") 17 | print("Player score = ",ps) 18 | print("Computer score = ",cus) 19 | # The current score gets printed. 20 | if(ps > cus): 21 | print("PLAYER Winning.") 22 | elif(cus > ps): 23 | print("COMPUTER Winning.") 24 | elif(ps == 0 and cus == 0): 25 | print("Let's Begin the Game!") 26 | else: 27 | print("It's a TIE!") 28 | # Comparing scores to determine the current winner. 29 | p_choice = input("Enter your choice ") 30 | # Inputting the choice 31 | for j in range(10000): 32 | print("\n") 33 | # This helps to clear the screen each time a move is made. 34 | c_choice = random.choice(cu) 35 | # This makes the random choice. 36 | print("Your Choice:\t",p_choice) 37 | if(p_choice=="r" or p_choice=="p" or p_choice=="s"): 38 | print("Computer chose:\t",c_choice) 39 | # This makes sure the statement is printed only when a valid moce is made. 40 | if (p_choice == "r" and c_choice == "p"): 41 | cus += 1 42 | print("Computer won.") 43 | elif (p_choice == "r" and c_choice == "s"): 44 | ps += 1 45 | print("Player won.") 46 | elif (p_choice == "p" and c_choice == "r"): 47 | ps += 1 48 | print("Player won.") 49 | elif (p_choice == "p" and c_choice == "s"): 50 | cus += 1 51 | print("Computer won.") 52 | elif (p_choice == "s" and c_choice == "p"): 53 | cus += 1 54 | print("Computer won.") 55 | elif (p_choice == "s" and c_choice == "r"): 56 | cus += 1 57 | print("Computer won.") 58 | # Incrementing the score whenever the computer wins and vice versa. 59 | elif (p_choice == c_choice): 60 | print("It's a Draw!") 61 | elif(p_choice == "w"): 62 | ps = 0 63 | cus = 0 64 | # This resets the scores. 65 | elif (p_choice == "q"): 66 | c = False 67 | # This ends the loop. 68 | else: 69 | print("Wrong input") 70 | # This handles invalid input. 71 | print("Game Over") -------------------------------------------------------------------------------- /Python Codes/scan.py: -------------------------------------------------------------------------------- 1 | n=int(input("enter number of processes in the queue :")) 2 | head=int(input("enter the position of head currently:")) 3 | loR=int(input("head moving towards left [0] or right [1]:")) 4 | pr=[] 5 | seekTime=0 6 | order=[] 7 | print("enter the positions of the processes in order :") 8 | for i in range(n): 9 | value=int(input()) 10 | pr.append(value) 11 | pr.sort() 12 | #print(pr) 13 | temp=0 14 | index=0 15 | if(loR==0): 16 | for i in range(n): 17 | if(pr[i]temp): 18 | #temp=pr[i] 19 | index=i 20 | #print(index) 21 | #print(index) 22 | #print(pr[index]) 23 | temp=index 24 | order.append(pr[temp]) 25 | seekTime+=abs(pr[temp]-head) 26 | #print(seekTime) 27 | temp-=1 28 | while(temp>=0): 29 | order.append(pr[temp]) 30 | seekTime+=abs(pr[temp]-pr[temp+1]) 31 | #print(seekTime) 32 | temp-=1 33 | #print(temp) 34 | 35 | order.append(0) 36 | seekTime+=abs(pr[0]-0) 37 | #print(seekTime) 38 | #print(pr[temp]-0) 39 | #print(seekTime) 40 | temp=index+1 41 | order.append(pr[temp]) 42 | seekTime+=abs(pr[temp]-0) 43 | #print(seekTime) 44 | temp+=1 45 | while(temp",end=" ") 53 | for i in range(n+1): 54 | print(order[i]," ->",end=" ") 55 | print("end\n") 56 | else: 57 | temp=1000 58 | for i in range(n): 59 | if(pr[i]>head and pr[i]=0): 77 | order.append(pr[temp]) 78 | seekTime+=abs(pr[temp]-pr[temp+1]) 79 | temp-=1 80 | print("seek Time = ",seekTime) 81 | print("order of scheduling :\n") 82 | print(head," ->",end=" ") 83 | for i in range(n+1): 84 | print(order[i]," ->",end=" ") 85 | print("end\n") 86 | -------------------------------------------------------------------------------- /Python Codes/screenrecorder.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy 3 | import pyautogui 4 | import time 5 | 6 | Screen_size = (1920,1080) 7 | 8 | fourcc = cv2.VideoWriter_fourcc(*"XVID") 9 | out = cv2.VideoWriter("./videos/output.avi",fourcc,20.0,(Screen_size)) 10 | 11 | fps = 120 12 | prev = 0 13 | 14 | while True: 15 | time_elapsed = time.time() - prev 16 | images = pyautogui.screenshot() 17 | if time_elapsed > 1.0/fps: 18 | prev = time.time() 19 | frame = numpy.array(images) 20 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) 21 | out.write(frame) 22 | cv2.waitKey(1) 23 | 24 | cv2.destroyAllWindows() 25 | out.release() 26 | -------------------------------------------------------------------------------- /Python Codes/selenium-automation.py: -------------------------------------------------------------------------------- 1 | # Automating the process of checking internet speed and tweeting a complaint on twitter 2 | 3 | from selenium import webdriver 4 | from time import sleep 5 | 6 | PROMISED_DOWN = 150 7 | PROMISED_UP = 50 8 | CHROME_DRIVER_PATH = '###CHROMEDRIVER PATH####' 9 | TWITTER_EMAIL = '###EMAIL###' 10 | TWITTER_PASSWORD = '###PASSWORD####' 11 | 12 | 13 | class InternetSpeedTwitterBot: 14 | def __init__(self): 15 | self.driver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH) 16 | self.down = PROMISED_DOWN 17 | self.up = PROMISED_UP 18 | 19 | def get_internet_speed(self): 20 | self.driver.get('https://www.speedtest.net/') 21 | self.driver.maximize_window() 22 | self.go = self.driver.find_element_by_xpath('/html/body/div[3]/div/div[3]/div/div/div/div[2]/div[3]/div[1]/a') 23 | self.go.click() 24 | print("clicked") 25 | sleep(50) 26 | self.down = self.driver.find_element_by_xpath( 27 | '/html/body/div[3]/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[2]/div/div[2]/span').text 28 | self.up = self.driver.find_element_by_xpath( 29 | '/html/body/div[3]/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[3]/div/div[2]/span').text 30 | print("Down:", self.down) 31 | print("UP:", self.up) 32 | self.message = f"Hey Internet provider, why is my internet speed {self.down}down/{self.up}up when I pay for" \ 33 | f" {PROMISED_DOWN}down/{PROMISED_UP}up?" 34 | 35 | def tweet_at_provider(self): 36 | self.driver.get('https://twitter.com/login') 37 | sleep(1) 38 | username = self.driver.find_element_by_xpath( 39 | '/html/body/div/div/div/div[2]/main/div/div/div[2]/form/div/div[1]/label/div/div[2]/div/input') 40 | username.send_keys(TWITTER_EMAIL) 41 | password = self.driver.find_element_by_xpath( 42 | '/html/body/div/div/div/div[2]/main/div/div/div[2]/form/div/div[2]/label/div/div[2]/div/input') 43 | password.send_keys(TWITTER_PASSWORD) 44 | button = self.driver.find_element_by_xpath( 45 | '/html/body/div/div/div/div[2]/main/div/div/div[2]/form/div/div[3]/div') 46 | button.click() 47 | sleep(2) 48 | write_here = self.driver.find_element_by_xpath( 49 | '/html/body/div/div/div/div[2]/main/div/div/div/div/div/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[1]/div/div/div/div/div/div/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div') 50 | write_here.send_keys(self.message) 51 | tweet = self.driver.find_element_by_xpath( 52 | '/html/body/div/div/div/div[2]/main/div/div/div/div/div/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[4]/div/div/div[2]/div[3]') 53 | tweet.click() 54 | print("Tweeted Successfully!") 55 | 56 | 57 | complain_bot = InternetSpeedTwitterBot() 58 | complain_bot.get_internet_speed() 59 | complain_bot.tweet_at_provider() 60 | -------------------------------------------------------------------------------- /Python Codes/speak.py: -------------------------------------------------------------------------------- 1 | from gtts import gTTS 2 | import os 3 | 4 | def speak(str): 5 | #from win32com.client import Dispatch 6 | #from toga-win32.client import Dispatch 7 | language = 'en' 8 | speech = gTTS(text = str, lang = language, slow = False) 9 | speech.save('text.mp3') 10 | os.system('start text.mp3') 11 | 12 | if __name__ =='__main__': 13 | b=input("ENTER A STRING:") 14 | speak(b) -------------------------------------------------------------------------------- /Python Codes/sqrootbyBS.py: -------------------------------------------------------------------------------- 1 | def sqrt(x): 2 | if (x == 0 or x == 1): 3 | return x 4 | 5 | low, high, ans = 0, x, x 6 | 7 | while low <= high: 8 | mid = low + (high - low) // 2 9 | 10 | if mid * mid == x: 11 | return mid 12 | 13 | if mid * mid < x: 14 | # discard the left half 15 | low = mid + 1 16 | ans = mid 17 | else: 18 | high = mid - 1 19 | return ans 20 | 21 | # TC -> O(log n) 22 | # SC -> O(1) 23 | 24 | n = int(input()) 25 | print(sqrt(n)) 26 | 27 | -------------------------------------------------------------------------------- /Python Codes/staircase_pattern.py: -------------------------------------------------------------------------------- 1 | def staircase(n): 2 | spaces = n-1 3 | hashtags = 1 4 | for i in range(n): 5 | for j in range(spaces): 6 | print(end =" ") 7 | for k in range(hashtags): 8 | print("#",end="") 9 | print() 10 | hashtags += 1 11 | spaces -= 1 12 | 13 | 14 | def main(): 15 | size = int(input("Enter the size : ")) 16 | staircase(size) 17 | 18 | main() -------------------------------------------------------------------------------- /Python Codes/students_info.py: -------------------------------------------------------------------------------- 1 | file_name = input("Enter a valid name for your txt file : ") 2 | file_name = file_name + ".txt" 3 | open_file = open(file_name, "w") 4 | database = {} 5 | while True: 6 | name = input("Enter name of the student : ") 7 | class_ = input("Enter class of the student : ") 8 | database["Name"] = name 9 | database["Class"] = class_ 10 | open_file.write(database) 11 | choice = input("Want to add more data y/n ? : ") 12 | if choice == 'n': 13 | break 14 | open_file.close() 15 | -------------------------------------------------------------------------------- /Python Codes/sudoku game solver.py: -------------------------------------------------------------------------------- 1 | def empty_coord(giv): 2 | for q in range(0, 9, 1): 3 | for lo in range(0, 9, 1): 4 | if giv[q][lo] == 0: 5 | return q,lo 6 | def rule(giv, row, coloumn, inputt): 7 | wx, wy, wz = 0, 0, 0 8 | for compare in range(0, 9, 1): 9 | if (inputt == giv[row][compare]) or (inputt == giv[compare][coloumn]): 10 | wx = 1 11 | rott = row // 3 12 | cott = coloumn // 3 13 | for rq in range(rott * 3, rott * 3 + 3): 14 | for re in range(cott * 3, cott * 3 + 3): 15 | if inputt == giv[rq][re]: 16 | wy = 1 17 | if wx == 1 or wy == 1: 18 | wz = 1 19 | return wz 20 | def back_tracking(giv): 21 | fifi=empty_coord(giv) 22 | if not fifi: 23 | return True 24 | else: 25 | rr, yy = fifi 26 | for i in range(1,10,1): 27 | x=rule(giv,rr,yy,i) 28 | if x==0: 29 | giv[rr][yy]=i 30 | if back_tracking(giv)==True: 31 | return True 32 | else: 33 | giv[rr][yy]=0 34 | return False 35 | def board(giv): 36 | for p1 in range(0,9,1): 37 | print("|",giv[p1][0],giv[p1][1],giv[p1][2],"|",giv[p1][3],giv[p1][4],giv[p1][5],"|",giv[p1][6],giv[p1][7],giv[p1][8],"|") 38 | if p1+1==3 or p1+1==6: 39 | print("-------------------------") 40 | 41 | def input_values(giv): 42 | for qq1 in range(0,9,1): 43 | for qq2 in range(0,9,1): 44 | giv[qq1][qq2]=input("enter the value") 45 | 46 | 47 | giv = [[7, 8, 0, 4, 0, 0, 1, 2, 0], 48 | [6, 0, 0, 0, 7, 5, 0, 0, 9], 49 | [0, 0, 0, 6, 0, 1, 0, 7, 8], 50 | [0, 0, 7, 0, 4, 0, 2, 6, 0], 51 | [0, 0, 1, 0, 5, 0, 9, 3, 0], 52 | [9, 0, 4, 0, 6, 0, 0, 0, 5], 53 | [0, 7, 0, 3, 0, 0, 0, 1, 2], 54 | [1, 2, 0, 0, 0, 7, 4, 0, 0], 55 | [0, 4, 9, 2, 0, 6, 0, 0, 7]] 56 | 57 | 58 | 59 | 60 | board(giv) 61 | 62 | back_tracking(giv) 63 | 64 | print(" ") 65 | print("the solved is") 66 | print(" ") 67 | print("-------------------------") 68 | board(giv) 69 | print("-------------------------") 70 | -------------------------------------------------------------------------------- /Python Codes/sudoku-game-solver.py: -------------------------------------------------------------------------------- 1 | def empty_coord(giv): 2 | for q in range(0, 9, 1): 3 | for lo in range(0, 9, 1): 4 | if giv[q][lo] == 0: 5 | return q,lo 6 | def rule(giv, row, coloumn, inputt): 7 | wx, wy, wz = 0, 0, 0 8 | for compare in range(0, 9, 1): 9 | if (inputt == giv[row][compare]) or (inputt == giv[compare][coloumn]): 10 | wx = 1 11 | rott = row // 3 12 | cott = coloumn // 3 13 | for rq in range(rott * 3, rott * 3 + 3): 14 | for re in range(cott * 3, cott * 3 + 3): 15 | if inputt == giv[rq][re]: 16 | wy = 1 17 | if wx == 1 or wy == 1: 18 | wz = 1 19 | return wz 20 | def back_tracking(giv): 21 | fifi=empty_coord(giv) 22 | if not fifi: 23 | return True 24 | else: 25 | rr, yy = fifi 26 | for i in range(1,10,1): 27 | x=rule(giv,rr,yy,i) 28 | if x==0: 29 | giv[rr][yy]=i 30 | if back_tracking(giv)==True: 31 | return True 32 | else: 33 | giv[rr][yy]=0 34 | return False 35 | def board(giv): 36 | for p1 in range(0,9,1): 37 | print("|",giv[p1][0],giv[p1][1],giv[p1][2],"|",giv[p1][3],giv[p1][4],giv[p1][5],"|",giv[p1][6],giv[p1][7],giv[p1][8],"|") 38 | if p1+1==3 or p1+1==6: 39 | print("-------------------------") 40 | 41 | def input_values(giv): 42 | for qq1 in range(0,9,1): 43 | for qq2 in range(0,9,1): 44 | giv[qq1][qq2]=input("enter the value") 45 | 46 | 47 | giv = [[7, 8, 0, 4, 0, 0, 1, 2, 0], 48 | [6, 0, 0, 0, 7, 5, 0, 0, 9], 49 | [0, 0, 0, 6, 0, 1, 0, 7, 8], 50 | [0, 0, 7, 0, 4, 0, 2, 6, 0], 51 | [0, 0, 1, 0, 5, 0, 9, 3, 0], 52 | [9, 0, 4, 0, 6, 0, 0, 0, 5], 53 | [0, 7, 0, 3, 0, 0, 0, 1, 2], 54 | [1, 2, 0, 0, 0, 7, 4, 0, 0], 55 | [0, 4, 9, 2, 0, 6, 0, 0, 7]] 56 | 57 | 58 | 59 | 60 | board(giv) 61 | 62 | back_tracking(giv) 63 | 64 | print(" ") 65 | print("the solved is") 66 | print(" ") 67 | print("-------------------------") 68 | board(giv) 69 | print("-------------------------") -------------------------------------------------------------------------------- /Python Codes/sudoku.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | problem = [[6 , 7 , 0 , 0 , 0 , 0 , 0 , 0 , 2], 4 | [0 , 0 , 1 , 7 , 9 , 0 , 0 , 3 , 0], 5 | [0 , 5 , 0 , 0 , 6 , 2 , 0 , 0 , 0], 6 | [0 , 0 , 0 , 0 , 0 , 0 , 0 , 2 , 5], 7 | [0 , 0 , 0 , 3 , 0 , 8 , 0 , 0 , 0], 8 | [2 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0], 9 | [0 , 0 , 0 , 1 , 3 , 0 , 0 , 5 , 0], 10 | [0 , 8 , 0 , 0 , 5 , 7 , 1 , 0 , 0], 11 | [5 , 0 , 0 , 0 , 0 , 0 , 0 , 9 , 6]] 12 | 13 | np_problem = np.array(problem) 14 | 15 | fixed_coordinates = [] # first getting the coordinates where fixed numbers are present 16 | empty_coordinates = [] 17 | for i , sub_array in enumerate(problem) : 18 | temp = [[i , c] for c , sub_element in enumerate(sub_array) if sub_element > 0] 19 | temp2 = [[i , j] for j , sub_element2 in enumerate(sub_array) if sub_element2 == 0] 20 | for z in temp : fixed_coordinates.append(z) 21 | for w in temp2 : empty_coordinates.append(w) 22 | 23 | l , m , r = [0 , 3 , 6] , [1 , 4 , 7] , [2 , 5 , 8] 24 | 25 | avoid_dict = {idx : [] for idx in list(range(0 , len(empty_coordinates)))} 26 | 27 | def generate_bounds(r , c) -> list: 28 | 29 | lower_bound_c = c if c in l else c - 1 if c in m else c - 2 30 | upper_bound_c = c + 3 if c in l else c + 2 if c in m else c + 1 31 | 32 | lower_bound_r = r if r in l else r - 1 if r in m else r - 2 33 | upper_bound_r = r + 3 if r in l else r + 2 if r in m else r + 1 34 | 35 | return [lower_bound_c , upper_bound_c , lower_bound_r , upper_bound_r] 36 | 37 | 38 | def backtrack(return_coordinates) : 39 | 40 | n_r , n_c = empty_coordinates[empty_coordinates.index(return_coordinates) - 1] # getting back element coordinates 41 | 42 | while [n_r , n_c] != empty_coordinates[empty_coordinates.index(return_coordinates) + 1]: 43 | 44 | if np_problem[n_r , n_c] != 0 : 45 | avoid_dict[empty_coordinates.index([n_r , n_c])].append(np_problem[n_r , n_c]) 46 | 47 | fix_flag = False 48 | r , c = n_r , n_c 49 | for num in range(1 , 10) : 50 | 51 | l_b_c , u_b_c , l_b_r , u_b_r = generate_bounds(r , c) 52 | 53 | if all([num not in np_problem[l_b_r : u_b_r , l_b_c : u_b_c] , num not in np_problem[r , :] , num not in np_problem[: , c]]) : 54 | if num not in avoid_dict.get(empty_coordinates.index([n_r , n_c])) : 55 | np_problem[n_r , n_c] , fix_flag = num , True 56 | break 57 | 58 | if fix_flag : n_r , n_c = empty_coordinates[empty_coordinates.index([n_r , n_c]) + 1] 59 | 60 | if not fix_flag : 61 | np_problem[n_r , n_c] = 0 62 | avoid_dict[empty_coordinates.index([n_r , n_c])].clear() 63 | n_r , n_c = empty_coordinates[empty_coordinates.index([n_r , n_c]) - 1] 64 | 65 | 66 | for r in range(9) : 67 | for c in range(9) : 68 | 69 | if [r , c] not in fixed_coordinates : 70 | 71 | fix_flag = False 72 | 73 | for num in range(1 , 10) : 74 | 75 | l_b_c , u_b_c , l_b_r , u_b_r = generate_bounds(r , c) 76 | 77 | if all([num not in np_problem[l_b_r : u_b_r , l_b_c : u_b_c] , num not in np_problem[r , :] , num not in np_problem[: , c]]) : 78 | 79 | np_problem[r , c] , fix_flag = num , True 80 | break 81 | 82 | if not fix_flag : backtrack([r , c]) 83 | 84 | 85 | print(np_problem) 86 | -------------------------------------------------------------------------------- /Python Codes/texttospeech.py: -------------------------------------------------------------------------------- 1 | #we first need to install docx by pip install python-docx 2 | #we then need to insatll pyttsx3 by pip install pyttsx3 3 | #we then need to install PyPDF2 by pip install PyPDF2 4 | """ 5 | In this python script we are trying to open a pdf file and make an automatic text to speech converter 6 | we are able to do this using pyttsx to make a offline text to speech convertor 7 | this does not save a audio file and it will directly run the speech function 8 | we are able to read the pdf file by using the package PyPDF2 9 | We have also added the readability of docx files 10 | and this is done using docx package 11 | this package helps us to read simple pdf text files 12 | """ 13 | import docx 14 | import pyttsx3 15 | import PyPDF2 16 | 17 | #getting the path 18 | path = input("Please give us the path to the pdf file or docx(Word) file") 19 | mytext="" 20 | #checking if it is of proper file type 21 | if(path.endswith(".pdf") or path.endswith(".docx")): 22 | try: 23 | #we use a try and except block to check if we can open the file 24 | if(path.endswith(".pdf")): 25 | #reading the pdf file 26 | pdfFileObj = open(path, 'rb') 27 | pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 28 | for i in range (0,pdfReader.numPages): 29 | mytext+=pdfReader.getPage(i).extractText() 30 | else: 31 | #reading the docx file 32 | text=[] 33 | doc= docx.Document(path) 34 | for para in doc.paragraphs: 35 | mytext+=para.text 36 | print(mytext) 37 | except (Exception) as e: 38 | # if we cant open the file or an error occurs during reading 39 | print(e) 40 | if(mytext!=""): 41 | try: 42 | #the text to speech function 43 | engine=pyttsx3.init() 44 | engine.say(mytext) 45 | engine.runAndWait() 46 | except (Exception)as e: 47 | print(e) 48 | else: 49 | print("The given path does contains a empty pdf file") 50 | 51 | else: 52 | # if the type is not correct 53 | print("Please ensure that u provide a pdf or docx file") 54 | -------------------------------------------------------------------------------- /Python Codes/tkinter/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/tkinter/background.png -------------------------------------------------------------------------------- /Python Codes/tkinter/kanye.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wbhoomika/python4beginners-Hacktoberfest21/8fa07ab733b25c178a8eed93f8ef3a5aeec1ce36/Python Codes/tkinter/kanye.png -------------------------------------------------------------------------------- /Python Codes/tkinter/main.py: -------------------------------------------------------------------------------- 1 | # A Tkinter Quotes Desktop Application 2 | 3 | from tkinter import * 4 | import requests 5 | 6 | def get_quote(): 7 | response = requests.get("https://api.kanye.rest/") 8 | response.raise_for_status() 9 | data=response.json() 10 | quote=data["quote"] 11 | canvas.itemconfig(quote_text,text=quote) 12 | 13 | window = Tk() 14 | window.title("Kanye Says...") 15 | window.config(padx=50, pady=50) 16 | 17 | canvas = Canvas(width=300, height=414) 18 | background_img = PhotoImage(file="background.png") 19 | canvas.create_image(150, 207, image=background_img) 20 | quote_text = canvas.create_text(150, 207, text="Kanye Quote Goes HERE", width=250, font=("Arial", 30, "bold"), fill="white") 21 | canvas.grid(row=0, column=0) 22 | 23 | kanye_img = PhotoImage(file="kanye.png") 24 | kanye_button = Button(image=kanye_img, highlightthickness=0, command=get_quote) 25 | kanye_button.grid(row=1, column=0) 26 | get_quote() 27 | 28 | window.mainloop() -------------------------------------------------------------------------------- /Python Codes/twoSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | #Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target 3 | def twoSum(self, num, target): 4 | map = {} 5 | for i in range(len(num)): 6 | if num[i] not in map: 7 | map[target - num[i]] = i + 1 8 | else: 9 | return map[num[i]], i + 1 10 | 11 | return -1, -1 12 | -------------------------------------------------------------------------------- /Python Codes/typewriter-macro.py: -------------------------------------------------------------------------------- 1 | import time 2 | import pyautogui 3 | 4 | def run(repeat, number, timebetween): 5 | time.sleep(5) # time to move to text field 6 | for i in range(0, int(number)): 7 | pyautogui.typewrite(repeat) 8 | time.sleep(int(timebetween)) 9 | 10 | 11 | if __name__ == "__main__": 12 | repeat = input("What macro do you want to repeat: ") 13 | number = input("How many times: ") 14 | timebetween = input("Time between repeats: ") 15 | run(repeat, number, timebetween) 16 | -------------------------------------------------------------------------------- /Python Codes/wordSearch.py: -------------------------------------------------------------------------------- 1 | #Given an m x n grid of characters board and a string word, return true if word exists in the grid. 2 | def exist(self, board, word): 3 | if not board: 4 | return False 5 | for i in xrange(len(board)): 6 | for j in xrange(len(board[0])): 7 | if self.dfs(board, i, j, word): 8 | return True 9 | return False 10 | 11 | # check whether can find word, start at (i,j) position 12 | def dfs(self, board, i, j, word): 13 | if len(word) == 0: # all the characters are checked 14 | return True 15 | if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]: 16 | return False 17 | tmp = board[i][j] # first character is found, check the remaining part 18 | board[i][j] = "#" # avoid visit agian 19 | # check whether can find "word" along one direction 20 | res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \ 21 | or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:]) 22 | board[i][j] = tmp 23 | return res 24 | -------------------------------------------------------------------------------- /Python Codes/ytdownloader.py: -------------------------------------------------------------------------------- 1 | #import tkinter module , its an gui library for python 2 | import Tkinter 3 | #import pytube to use youtube methods 4 | from pytube import YouTube 5 | #create an instance of gui window 6 | root=Tk() 7 | #set window size 8 | root.geometry("400x350") 9 | #set window title 10 | root.title("Youtube downloader") 11 | 12 | def download(): 13 | try: 14 | #to set dialog box text 15 | myVar.set("downloading") 16 | #updating gui window to set text 17 | root.update() 18 | 19 | #main code to download video from the source 20 | YouTube(link.get()).streams.first().download() 21 | #status update 22 | link.set("operation successful") 23 | except Exception as e: 24 | #throw exception dialog 25 | myVar.set("error") 26 | root.update() 27 | link.set("enter correct link") 28 | #gui label 29 | Label(root,text="welcome to downloader",font="Consolas 15 bold").pack() 30 | myVar=StringVar() 31 | #to accept the link 32 | myVar.Set("Enter the link below") 33 | Entry(root,textvariable=myVar,width=40).pack(pady=10) 34 | link=StringVar() 35 | Entry(root,textvariable=link,width=40).pack(pady=10) 36 | Button(root,text="Download",command=download).pack() 37 | root.mainloop() 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python4beginners-Hacktoberfest21 2 | 3 |

4 | 5 | 6 | 7 |

8 | 9 | ## Update : 1st Nov 2021 10 | 11 | HacktoberFest 21 can end but our enthusiasm for open source contribution cannot. Intrested can still contribute to this repository and I will keep approving further PR's. 12 | 13 | # HacktoberFest21 14 | 15 | Hello Hackers! HacktoberFest has begun again for year 2021, and everyone's excited to get started! 16 | Contribute between:

1 OCTOBER - 31 OCTOBER

17 | 18 | Create a Pull request and add any feature update to the repository. 19 | 20 | * [Click here to register for hacktoberfest2021.](https://hacktoberfest.digitalocean.com/) 21 | 22 | ## A BIG Thanks To Our Contributors :handshake: :handshake: 23 | 24 | 25 | 26 | 27 | ## How to contribute to this project? 28 | 29 | Here are 2 quick and painless ways to contribute to this project: 30 | 31 | * Create a simple python program of your choice or try fixing bugs in the repository. 32 | * Add your name to the `CONTRIBUTORS.md` file. 33 | 34 | Choose both, make a pull request for your work and wait for it to be merged!! 35 | 36 | ## Getting started 37 | * Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 38 | * Clone your fork down to your local machine. 39 | 40 | ```markdown 41 | git clone https://github.com/wbhoomika/python4beginners-Hacktoberfest21 42 | ``` 43 | 44 | * Create a branch 45 | 46 | ```markdown 47 | git checkout -b your-branch-name 48 | ``` 49 | 50 | * Make your changes. 51 | * Commit and push your code. 52 | 53 | ```markdown 54 | git add . 55 | git commit -m 'Commit message' 56 | git push origin branch-name 57 | ``` 58 | 59 | * Create a new pull request from your forked repository (Click the `New Pull Request` button located at the top of your repo) 60 | * Wait for your PR review and merge approval... 61 | * __Star this repository__ if you had fun contributing! --------------------------------------------------------------------------------