├── AreaTriangle ├── Auto Website Visitor ├── BMI CALCULATER ├── Binary Search ├── Breadth First search ├── Car Game in Python ├── Car driving ├── Cloning or Copying a list ├── Comparison ├── Convert Video to audio ├── DFS ├── Dayofprogrammer ├── FUNDING.yml ├── Factorial of a Number ├── Factorial! ├── Fibonacci number ├── Greater Number ├── Guess the no ├── Hourglass ├── KNN_algorithm ├── Knapsack_problem.py ├── Linear Search ├── Matrix Multiplication ├── Matrix Multiplication in Python ├── Matrix Multiplication using Nested Loop.py ├── MaxSumOfIncreasinSubsequence ├── Pacman ├── PrintHelloWorld.py ├── PythCalc ├── Python Program to Make a Simple Calculator ├── Python program to convert Celsius to Fahrenheit ├── Python3 program to find compound ├── Quadratic formula ├── QuickSelect.py ├── README.md ├── Repeated_Substring_Pattern.py ├── Simple Calculator ├── Snake ├── Snake water gun game ├── Sort Words in Alphabetic Order.py ├── Sorting a Stack using Recursion ├── The multi-line form of this code would be ├── Tic-Tac-Toe ├── Use of dictionary ├── WAP to Calculate Simple Interest(SI),Read the principle, rate of interest and number of years from the user. ├── addition using function ├── audiobook ├── avgno ├── calculator ├── calender ├── class BasicLexer with python programming ├── dfsTraversal ├── diagonaldifference ├── factorial ├── fibonacci.py ├── find area of circle ├── find even or odd ├── forloopinpython ├── funny weight converter ├── greatearno ├── leap year ├── libraries ├── longestPalindrome ├── mergesort ├── multiplication_table ├── number guess game ├── oddeven ├── prime number ├── printing pattern ├── pythonevenodd ├── pythonprime ├── pythonprogram ├── simple interest ├── solveQuadraticEq ├── split.py ├── stringPopulation ├── swaping of variables ├── tic_tac_toe.py └── twilio_sms.py /AreaTriangle: -------------------------------------------------------------------------------- 1 | a = float(input('Enter first side: ')) 2 | b = float(input('Enter second side: ')) 3 | c = float(input('Enter third side: ')) 4 | 5 | # calculate the semi-perimeter 6 | s = (a + b + c) / 2 7 | 8 | # calculate the area 9 | area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 10 | print('The area of the triangle is %0.2f' %area) 11 | -------------------------------------------------------------------------------- /Auto Website Visitor: -------------------------------------------------------------------------------- 1 | ##--- Auto Website Visitor by khalsalabs ---- #### 2 | import urllib2 3 | import random 4 | import threading 5 | import sys 6 | import time 7 | class Connect: 8 | req = urllib2.Request('http://your-website-name.com') 9 | con_sucess, con_failed, con_total=0,0,0 10 | url_total, proxy_total= 0,0 11 | url_list =[] 12 | proxy_list= [] 13 | agent_list =[] 14 | 15 | def __init__(self): 16 | pF = open('proxy.txt','r') 17 | pR = pF.read() 18 | self.proxy_list = pR.split('n') 19 | 20 | uF = open('url.txt','r') 21 | uR = uF.read() 22 | self.url_list = uR.split('n') 23 | 24 | aF = open('agent.txt','r') 25 | aR = aF.read() 26 | self.agent_list = aR.split('n') 27 | 28 | def prep_con(self): 29 | rURL = random.randint(0,(len(self.url_list))-1) 30 | self.req = urllib2.Request(self.url_list[rURL]) 31 | rAGENT = random.randint(0,(len(self.agent_list))-1) 32 | self.req.add_header('User-agent',self.agent_list[rAGENT]) 33 | 34 | def make_con(self): 35 | count, time_stamp =0,0 36 | for proxy in self.proxy_list: 37 | self.req.set_proxy(proxy,'http') 38 | if count%4==0: 39 | if self.con_total < 2*count: 40 | time_stamp = 6 41 | else: 42 | time_stamp = 3 43 | threading.Thread(target=self.visitURL).start() 44 | time.sleep(time_stamp) 45 | count += 1 46 | 47 | def visit(self): 48 | try: 49 | f = urllib2.urlopen(self.req) 50 | self.con_sucess += 1 51 | except: 52 | self.con_failed += 1 53 | self.con_total += 1 54 | print self.con_total,"total connections, success = ",self.con_sucess," failed= ",self.con_failed 55 | 56 | def visitURL(self): 57 | self.prep_con() 58 | self.visit() 59 | 60 | if __name__ == "__main__": 61 | cnct = Connect() 62 | cnct.make_con() 63 | -------------------------------------------------------------------------------- /BMI CALCULATER: -------------------------------------------------------------------------------- 1 | filter_none 2 | edit 3 | play_arrow 4 | 5 | brightness_4 6 | #Python program to illustrate 7 | # how to calculate BMI 8 | def BMI(height, weight): 9 | bmi = weight/(height**2) 10 | return bmi 11 | 12 | # Driver code 13 | height = 1.79832 14 | weight = 70 15 | 16 | # calling the BMI function 17 | bmi = BMI(height, weight) 18 | print("The BMI is", format(bmi), "so ", end='') 19 | 20 | # Conditions to find out BMI category 21 | if (bmi < 18.5): 22 | print("underweight") 23 | 24 | elif ( bmi >= 18.5 and bmi < 24.9): 25 | print("Healthy") 26 | 27 | elif ( bmi >= 24.9 and bmi < 30): 28 | print("overweight") 29 | 30 | elif ( bmi >=30): 31 | print("Suffering from Obesity") 32 | -------------------------------------------------------------------------------- /Binary Search: -------------------------------------------------------------------------------- 1 | # Returns index of x in arr if present, else -1 2 | 3 | def binary_search(arr, low, high, x): 4 | 5 | if high >= low: 6 | mid = (high + low) // 2 7 | 8 | 9 | 10 | # If element is present at the middle itself 11 | 12 | if arr[mid] == x: 13 | 14 | return mid 15 | 16 | 17 | 18 | # If element is smaller than mid, then it can only 19 | 20 | # be present in left subarray 21 | 22 | elif arr[mid] > x: 23 | 24 | return binary_search(arr, low, mid - 1, x) 25 | 26 | 27 | 28 | # Else the element can only be present in right subarray 29 | 30 | else: 31 | 32 | return binary_search(arr, mid + 1, high, x) 33 | 34 | 35 | 36 | else: 37 | 38 | # Element is not present in the array 39 | 40 | return -1 41 | 42 | 43 | 44 | arr = [ 2, 3, 4, 10, 40 ] 45 | 46 | x = 10 47 | result = binary_search(arr, 0, len(arr)-1, x) 48 | if result != -1: 49 | 50 | print("Element is present at index", str(result)) 51 | 52 | else: 53 | 54 | print("Element is not present 55 | -------------------------------------------------------------------------------- /Breadth First search: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | # BFS algorithm 4 | def bfs(graph, root): 5 | 6 | visited, queue = set(), collections.deque([root]) 7 | visited.add(root) 8 | 9 | while queue: 10 | 11 | # Dequeue a vertex from queue 12 | vertex = queue.popleft() 13 | print(str(vertex) + " ", end="") 14 | 15 | # If not visited, mark it as visited, and 16 | # enqueue it 17 | for neighbour in graph[vertex]: 18 | if neighbour not in visited: 19 | visited.add(neighbour) 20 | queue.append(neighbour) 21 | 22 | 23 | if __name__ == '__main__': 24 | graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]} 25 | print("Following is Breadth First Traversal: ") 26 | bfs(graph, 0) 27 | -------------------------------------------------------------------------------- /Car Game in Python: -------------------------------------------------------------------------------- 1 | import pygame 2 | import time 3 | import random 4 | 5 | pygame.init() 6 | 7 | display_width = 800 8 | display_height = 600 9 | 10 | black = (0,0,0) 11 | white = (255,255,255) 12 | red = (255,0,0) 13 | 14 | car_width = 73 15 | 16 | gameDisplay = pygame.display.set_mode((display_width,display_height)) 17 | pygame.display.set_caption('A bit Racey') 18 | clock = pygame.time.Clock() 19 | 20 | carImg = pygame.image.load('racecar.png') 21 | 22 | def things(thingx, thingy, thingw, thingh, color): 23 | pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) 24 | 25 | def car(x,y): 26 | gameDisplay.blit(carImg,(x,y)) 27 | 28 | def text_objects(text, font): 29 | textSurface = font.render(text, True, black) 30 | return textSurface, textSurface.get_rect() 31 | 32 | def message_display(text): 33 | largeText = pygame.font.Font('freesansbold.ttf',115) 34 | TextSurf, TextRect = text_objects(text, largeText) 35 | TextRect.center = ((display_width/2),(display_height/2)) 36 | gameDisplay.blit(TextSurf, TextRect) 37 | 38 | pygame.display.update() 39 | 40 | time.sleep(2) 41 | 42 | game_loop() 43 | 44 | 45 | 46 | def crash(): 47 | message_display('You Crashed') 48 | 49 | def game_loop(): 50 | x = (display_width * 0.45) 51 | y = (display_height * 0.8) 52 | 53 | x_change = 0 54 | 55 | thing_startx = random.randrange(0, display_width) 56 | thing_starty = -600 57 | thing_speed = 7 58 | thing_width = 100 59 | thing_height = 100 60 | 61 | gameExit = False 62 | 63 | while not gameExit: 64 | 65 | for event in pygame.event.get(): 66 | if event.type == pygame.QUIT: 67 | pygame.quit() 68 | quit() 69 | 70 | if event.type == pygame.KEYDOWN: 71 | if event.key == pygame.K_LEFT: 72 | x_change = -5 73 | if event.key == pygame.K_RIGHT: 74 | x_change = 5 75 | 76 | if event.type == pygame.KEYUP: 77 | if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 78 | x_change = 0 79 | 80 | x += x_change 81 | gameDisplay.fill(white) 82 | 83 | # things(thingx, thingy, thingw, thingh, color) 84 | things(thing_startx, thing_starty, thing_width, thing_height, black) 85 | thing_starty += thing_speed 86 | car(x,y) 87 | 88 | if x > display_width - car_width or x < 0: 89 | crash() 90 | 91 | if thing_starty > display_height: 92 | thing_starty = 0 - thing_height 93 | thing_startx = random.randrange(0,display_width) 94 | 95 | #### 96 | if y < thing_starty+thing_height: 97 | print('y crossover') 98 | 99 | if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width: 100 | print('x crossover') 101 | crash() 102 | #### 103 | 104 | pygame.display.update() 105 | clock.tick(60) 106 | 107 | 108 | game_loop() 109 | pygame.quit() 110 | quit() 111 | -------------------------------------------------------------------------------- /Car driving: -------------------------------------------------------------------------------- 1 | var1=18 2 | var2=int(input("Enter Your Age: ")) 3 | if var2>var1: 4 | print("drive") 5 | elif var2==var1: 6 | print("decide") 7 | 8 | else: 9 | print ("do not drive") 10 | -------------------------------------------------------------------------------- /Cloning or Copying a list: -------------------------------------------------------------------------------- 1 | # Python code to clone or copy a list 2 | # Using the in-built function list() 3 | def Cloning(li1): 4 | li_copy = list(li1) 5 | return li_copy 6 | 7 | # Driver Code 8 | li1 = [4, 8, 2, 10, 15, 18] 9 | li2 = Cloning(li1) 10 | print("Original List:", li1) 11 | print("After Cloning:", li2) 12 | -------------------------------------------------------------------------------- /Comparison: -------------------------------------------------------------------------------- 1 | a = int(input("enter a\n")) 2 | b = int(input("enter b\n")) 3 | if b < a: 4 | print("a is greater than b") 5 | else: 6 | print("b is greater than a") 7 | -------------------------------------------------------------------------------- /Convert Video to audio: -------------------------------------------------------------------------------- 1 | import moviepy.editor as mp #[at first install moviepy in ur system] 2 | 3 | clip = mp.VideoFileClip(r'C:\\Users\\ADMIN\\Desktop\\Despacito.mp4') #[copy and paste the path where u saved ur video] 4 | 5 | clip.audio.write_audiofile('C:\\Users\\ADMIN\\Desktop\\Despacito_cvrt.mp3') #[give the path where u want to save ur audio file] 6 | -------------------------------------------------------------------------------- /DFS: -------------------------------------------------------------------------------- 1 | # Python program to print DFS traversal for complete graph 2 | 3 | from collections import defaultdict 4 | 5 | 6 | # This class represents a directed graph using adjacency 7 | # list representation 8 | 9 | class Graph: 10 | 11 | 12 | 13 | # Constructor 14 | 15 | def __init__(self): 16 | 17 | 18 | 19 | # default dictionary to store graph 20 | 21 | self.graph = defaultdict(list) 22 | 23 | 24 | 25 | # function to add an edge to graph 26 | 27 | def addEdge(self,u,v): 28 | 29 | self.graph[u].append(v) 30 | 31 | 32 | 33 | # A function used by DFS 34 | 35 | def DFSUtil(self, v, visited): 36 | 37 | 38 | 39 | # Mark the current node as visited and print it 40 | 41 | visited[v]= True 42 | 43 | print v, 44 | 45 | 46 | 47 | # Recur for all the vertices adjacent to 48 | 49 | # this vertex 50 | 51 | for i in self.graph[v]: 52 | 53 | if visited[i] == False: 54 | 55 | self.DFSUtil(i, visited) 56 | 57 | 58 | 59 | 60 | 61 | # The function to do DFS traversal. It uses 62 | 63 | # recursive DFSUtil() 64 | 65 | def DFS(self): 66 | 67 | V = len(self.graph) #total vertices 68 | 69 | 70 | 71 | # Mark all the vertices as not visited 72 | 73 | visited =[False]*(V) 74 | 75 | 76 | 77 | # Call the recursive helper function to print 78 | 79 | # DFS traversal starting from all vertices one 80 | 81 | # by one 82 | 83 | for i in range(V): 84 | 85 | if visited[i] == False: 86 | 87 | self.DFSUtil(i, visited) 88 | 89 | 90 | -------------------------------------------------------------------------------- /Dayofprogrammer: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | import sys 3 | y = int(raw_input().strip()) 4 | # your code goes here 5 | months = {0:31,1:28,2:31,3:30,4:31,5:30,6:31,7:31,8:30,9:31,10:30,11:31} 6 | if y <= 1917: 7 | tot = 0 8 | for i in range(12): 9 | if tot + months[i] > 256: 10 | break 11 | if y % 4 == 0 and i == 1: 12 | tot = tot + 29 13 | else: 14 | tot = tot + months[i] 15 | ans = "" 16 | day = 256 - tot 17 | month = i + 1 18 | ans = ans + str(day) + ".0" + str(month) + "." + str(y) 19 | print ans 20 | elif y == 1918: 21 | tot = 0 22 | for i in range(12): 23 | if tot + months[i] > 256: 24 | break 25 | if i == 1: 26 | tot = tot + 15 27 | else: 28 | tot = tot + months[i] 29 | ans = "" 30 | day = 256 - tot 31 | month = i + 1 32 | ans = ans + str(day) + ".0" + str(month) + "." + str(y) 33 | print ans 34 | else: 35 | tot = 0 36 | for i in range(12): 37 | if tot + months[i] > 256: 38 | break 39 | if (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)) and i == 1: 40 | tot = tot + 29 41 | else: 42 | tot = tot + months[i] 43 | ans = "" 44 | day = 256 - tot 45 | month = i + 1 46 | ans = ans + str(day) + ".0" + str(month) + "." + str(y) 47 | print ans 48 | -------------------------------------------------------------------------------- /FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: 4 | patreon: # 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: -------------------------------------------------------------------------------- /Factorial of a Number: -------------------------------------------------------------------------------- 1 | # Python program to find the factorial of a number provided by the user. 2 | 3 | # change the value for a different result 4 | num = 7 5 | 6 | # To take input from the user 7 | #num = int(input("Enter a number: ")) 8 | 9 | factorial = 1 10 | 11 | # check if the number is negative, positive or zero 12 | if num < 0: 13 | print("Sorry, factorial does not exist for negative numbers") 14 | elif num == 0: 15 | print("The factorial of 0 is 1") 16 | else: 17 | for i in range(1,num + 1): 18 | factorial = factorial*i 19 | print("The factorial of",num,"is",factorial) 20 | -------------------------------------------------------------------------------- /Factorial!: -------------------------------------------------------------------------------- 1 | Python program to find the factorial of a number provided by the user. 2 | 3 | # change the value for a different result 4 | num = 7 5 | 6 | # To take input from the user 7 | #num = int(input("Enter a number: ")) 8 | 9 | factorial = 1 10 | 11 | # check if the number is negative, positive or zero 12 | if num < 0: 13 | print("Sorry, factorial does not exist for negative numbers") 14 | elif num == 0: 15 | print("The factorial of 0 is 1") 16 | else: 17 | for i in range(1,num + 1): 18 | factorial = factorial*i 19 | print("The factorial of",num,"is",factorial) 20 | -------------------------------------------------------------------------------- /Fibonacci number: -------------------------------------------------------------------------------- 1 | 2 | import math 3 | def isPerfectSquare(x): 4 | s = int(math.sqrt(x)) 5 | return s*s == x 6 | 7 | 8 | def isFibonacci(n): 9 | 10 | return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) 11 | 12 | 13 | for i in range(1,11): 14 | if (isFibonacci(i) == True): 15 | print i,"is a Fibonacci Number" 16 | else: 17 | print i,"is a not Fibonacci Number " 18 | -------------------------------------------------------------------------------- /Greater Number: -------------------------------------------------------------------------------- 1 | # Python program to find the greatest of two numbers using the built-in function 2 | 3 | num1 = int(input("Enter the first number: ")) 4 | num2 = int(input("Enter the second number: ")) 5 | print(max(num1, num2), "is greater") 6 | -------------------------------------------------------------------------------- /Guess the no: -------------------------------------------------------------------------------- 1 | n=20 2 | number_of_guesses=1 3 | print("Number of guesses is limited to 9 times: ") 4 | while (number_of_guesses<=9): 5 | guess_number=int(input("Guess the no :\n")) 6 | if guess_number<20: 7 | print("please input greater no:\n") 8 | elif guess_number>20: 9 | print("please enter less no:\n") 10 | else: 11 | print("you won\n") 12 | print (number_of_gueeses, "number of guesses he took to finish.") 13 | break 14 | print(9-number_of_guesses, "number of guesses left") 15 | number_of_guesses = number_of_guesses + 1 16 | if(number_of_guesses>9): 17 | print("Game Over") 18 | -------------------------------------------------------------------------------- /Hourglass: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | 11 | if __name__ == '__main__': 12 | arr = [] 13 | 14 | for _ in range(6): 15 | arr.append(list(map(int, input().rstrip().split()))) 16 | maximum = -9 * 7 17 | 18 | for i in range(6): 19 | for j in range(6): 20 | if j + 2 < 6 and i + 2 < 6: 21 | result = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2] 22 | if result > maximum: 23 | maximum = result 24 | 25 | print(maximum) 26 | -------------------------------------------------------------------------------- /KNN_algorithm: -------------------------------------------------------------------------------- 1 | from sklearn import datasets 2 | from sklearn.model_selection import train_test_split 3 | from sklearn.neighbors import KNeighborsClassifier 4 | from sklearn.metrics import accuracy_score 5 | from scipy.spatial import distance 6 | 7 | def euc(a,b): 8 | return distance.euclidean(a, b) 9 | 10 | 11 | class ScrappyKNN(): 12 | def fit(self, features_train, labels_train): 13 | self.features_train = features_train 14 | self.labels_train = labels_train 15 | 16 | def predict(self, features_test): 17 | predictions = [] 18 | for item in features_test: 19 | label = self.closest(item) 20 | predictions.append(label) 21 | 22 | return predictions 23 | 24 | def closest(self, item): 25 | best_dist = euc(item, self.features_train[0]) 26 | best_index = 0 27 | for i in range(1,len(self.features_train)): 28 | dist = euc(item, self.features_train[i]) 29 | if dist < best_dist: 30 | best_dist = dist 31 | best_index = i 32 | return self.labels_train[best_index] 33 | 34 | iris = datasets.load_iris() 35 | 36 | print(iris) 37 | 38 | features = iris.data 39 | labels = iris.target 40 | 41 | print(features) 42 | print(labels) 43 | 44 | features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=.5) 45 | #print(len(features)) 46 | #print(len(features_train)) 47 | 48 | my_classifier = ScrappyKNN() 49 | #my_classifier = KNeighborsClassifier() 50 | my_classifier.fit(features_train, labels_train) 51 | 52 | prediction = my_classifier.predict(features_test) 53 | 54 | print(prediction) 55 | print(accuracy_score(labels_test, prediction)) 56 | 57 | iris1 = [[7.1, 2.9, 5.3, 2.4]] #virginica 58 | iris_prediction = my_classifier.predict(iris1) 59 | 60 | if iris_prediction == 0: 61 | print("Setosa") 62 | if iris_prediction == 1: 63 | print("Versicolor") 64 | if iris_prediction == 2: 65 | print("Virginica") 66 | -------------------------------------------------------------------------------- /Knapsack_problem.py: -------------------------------------------------------------------------------- 1 | # A Dynamic Programming based Python 2 | # Program for 0-1 Knapsack problem 3 | # Returns the maximum value that can 4 | # be put in a knapsack of capacity W 5 | def knapSack(W, wt, val, n): 6 | K = [[0 for x in range(W + 1)] for x in range(n + 1)] 7 | 8 | # Build table K[][] in bottom up manner 9 | for i in range(n + 1): 10 | for w in range(W + 1): 11 | if i == 0 or w == 0: 12 | K[i][w] = 0 13 | elif wt[i-1] <= w: 14 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) 15 | else: 16 | K[i][w] = K[i-1][w] 17 | 18 | return K[n][W] 19 | 20 | # Driver program to test above function 21 | val = [60, 100, 120] 22 | wt = [10, 20, 30] 23 | W = 50 24 | n = len(val) 25 | print(knapSack(W, wt, val, n)) 26 | 27 | # This code is contributed by Vanasetty Rohit 28 | -------------------------------------------------------------------------------- /Linear Search: -------------------------------------------------------------------------------- 1 | def linear_search(alist, key): 2 | """Return index of key in alist. Return -1 if key not present.""" 3 | for i in range(len(alist)): 4 | if alist[i] == key: 5 | return i 6 | return -1 7 | 8 | 9 | alist = input('Enter the list of numbers: ') 10 | alist = alist.split() 11 | alist = [int(x) for x in alist] 12 | key = int(input('The number to search for: ')) 13 | 14 | index = linear_search(alist, key) 15 | if index < 0: 16 | print('{} was not found.'.format(key)) 17 | else: 18 | print('{} was found at index {}.'.format(key, index)) 19 | -------------------------------------------------------------------------------- /Matrix Multiplication: -------------------------------------------------------------------------------- 1 | # Program to multiply two matrices using nested loops 2 | 3 | # 3x3 matrix 4 | X = [[12,7,3], 5 | [4 ,5,6], 6 | [7 ,8,9]] 7 | # 3x4 matrix 8 | Y = [[5,8,1,2], 9 | [6,7,3,0], 10 | [4,5,9,1]] 11 | # result is 3x4 12 | result = [[0,0,0,0], 13 | [0,0,0,0], 14 | [0,0,0,0]] 15 | 16 | # iterate through rows of X 17 | for i in range(len(X)): 18 | # iterate through columns of Y 19 | for j in range(len(Y[0])): 20 | # iterate through rows of Y 21 | for k in range(len(Y)): 22 | result[i][j] += X[i][k] * Y[k][j] 23 | 24 | for r in result: 25 | print(r) 26 | 27 | ######################################################## 28 | -------------------------------------------------------------------------------- /Matrix Multiplication in Python: -------------------------------------------------------------------------------- 1 | def matrix_multiplication(M,N): 2 | 3 | R = [[0, 0, 0, 0], 4 | [0, 0, 0, 0], 5 | [0, 0, 0, 0], 6 | [0, 0, 0, 0]] 7 | 8 | for i in range(0, 4): 9 | for j in range(0, 4): 10 | for k in range(0, 4): 11 | R[i][j] += M[i][k] * N[k][j] 12 | 13 | for i in range(0,4): 14 | for j in range(0,4): 15 | print(R[i][j],end=" ") 16 | print("\n",end="") 17 | 18 | M = [[1, 1, 1, 1], 19 | [2, 2, 2, 2], 20 | [3, 3, 3, 3], 21 | [4, 4, 4, 4]] 22 | 23 | N = [[1, 1, 1, 1], 24 | [2, 2, 2, 2], 25 | [3, 3, 3, 3], 26 | [4, 4, 4, 4]] 27 | 28 | matrix_multiplication(M,N) 29 | -------------------------------------------------------------------------------- /Matrix Multiplication using Nested Loop.py: -------------------------------------------------------------------------------- 1 | # Program to multiply two matrices using nested loops 2 | 3 | # 3x3 matrix 4 | X = [[12,7,3], 5 | [4 ,5,6], 6 | [7 ,8,9]] 7 | # 3x4 matrix 8 | Y = [[5,8,1,2], 9 | [6,7,3,0], 10 | [4,5,9,1]] 11 | # result is 3x4 12 | result = [[0,0,0,0], 13 | [0,0,0,0], 14 | [0,0,0,0]] 15 | 16 | # iterate through rows of X 17 | for i in range(len(X)): 18 | # iterate through columns of Y 19 | for j in range(len(Y[0])): 20 | # iterate through rows of Y 21 | for k in range(len(Y)): 22 | result[i][j] += X[i][k] * Y[k][j] 23 | 24 | for r in result: 25 | print(r) 26 | -------------------------------------------------------------------------------- /MaxSumOfIncreasinSubsequence: -------------------------------------------------------------------------------- 1 | ts=int(input()) 2 | l3=[] 3 | l1=[] 4 | for j in range (ts): 5 | n=int(input()) 6 | l3.clear() 7 | li=list(map(int, input().split())) 8 | for i in range(1,n): 9 | t=li[i-1] 10 | for j in range(0,i): 11 | if(li[i]>li[j]): 12 | t=t+li[j] 13 | l3.append(t) 14 | if(len(l3)!=0): 15 | print (max(l3)) 16 | li.clear() 17 | -------------------------------------------------------------------------------- /Pacman: -------------------------------------------------------------------------------- 1 | from random import choice 2 | from turtle import * 3 | from freegames import floor, vector 4 | 5 | state = {'score': 0} 6 | path = Turtle(visible=False) 7 | writer = Turtle(visible=False) 8 | aim = vector(5, 0) 9 | pacman = vector(-40, -80) 10 | ghosts = [ 11 | [vector(-180, 160), vector(5, 0)], 12 | [vector(-180, -160), vector(0, 5)], 13 | [vector(100, 160), vector(0, -5)], 14 | [vector(100, -160), vector(-5, 0)], 15 | ] 16 | tiles = [ 17 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18 | 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 19 | 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 20 | 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 21 | 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 22 | 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 23 | 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 24 | 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 25 | 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 26 | 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 27 | 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 28 | 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 29 | 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 30 | 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 31 | 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 32 | 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 33 | 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 34 | 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 35 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37 | ] 38 | 39 | def square(x, y): 40 | "Draw square using path at (x, y)." 41 | path.up() 42 | path.goto(x, y) 43 | path.down() 44 | path.begin_fill() 45 | 46 | for count in range(4): 47 | path.forward(20) 48 | path.left(90) 49 | 50 | path.end_fill() 51 | 52 | def offset(point): 53 | "Return offset of point in tiles." 54 | x = (floor(point.x, 20) + 200) / 20 55 | y = (180 - floor(point.y, 20)) / 20 56 | index = int(x + y * 20) 57 | return index 58 | 59 | def valid(point): 60 | "Return True if point is valid in tiles." 61 | index = offset(point) 62 | 63 | if tiles[index] == 0: 64 | return False 65 | 66 | index = offset(point + 19) 67 | 68 | if tiles[index] == 0: 69 | return False 70 | 71 | return point.x % 20 == 0 or point.y % 20 == 0 72 | 73 | def world(): 74 | "Draw world using path." 75 | bgcolor('black') 76 | path.color('blue') 77 | 78 | for index in range(len(tiles)): 79 | tile = tiles[index] 80 | 81 | if tile > 0: 82 | x = (index % 20) * 20 - 200 83 | y = 180 - (index // 20) * 20 84 | square(x, y) 85 | 86 | if tile == 1: 87 | path.up() 88 | path.goto(x + 10, y + 10) 89 | path.dot(2, 'white') 90 | 91 | def move(): 92 | "Move pacman and all ghosts." 93 | writer.undo() 94 | writer.write(state['score']) 95 | 96 | clear() 97 | 98 | if valid(pacman + aim): 99 | pacman.move(aim) 100 | 101 | index = offset(pacman) 102 | 103 | if tiles[index] == 1: 104 | tiles[index] = 2 105 | state['score'] += 1 106 | x = (index % 20) * 20 - 200 107 | y = 180 - (index // 20) * 20 108 | square(x, y) 109 | 110 | up() 111 | goto(pacman.x + 10, pacman.y + 10) 112 | dot(20, 'yellow') 113 | 114 | for point, course in ghosts: 115 | if valid(point + course): 116 | point.move(course) 117 | else: 118 | options = [ 119 | vector(5, 0), 120 | vector(-5, 0), 121 | vector(0, 5), 122 | vector(0, -5), 123 | ] 124 | plan = choice(options) 125 | course.x = plan.x 126 | course.y = plan.y 127 | 128 | up() 129 | goto(point.x + 10, point.y + 10) 130 | dot(20, 'red') 131 | 132 | update() 133 | 134 | for point, course in ghosts: 135 | if abs(pacman - point) < 20: 136 | return 137 | 138 | ontimer(move, 100) 139 | 140 | def change(x, y): 141 | "Change pacman aim if valid." 142 | if valid(pacman + vector(x, y)): 143 | aim.x = x 144 | aim.y = y 145 | 146 | setup(420, 420, 370, 0) 147 | hideturtle() 148 | tracer(False) 149 | writer.goto(160, 160) 150 | writer.color('white') 151 | writer.write(state['score']) 152 | listen() 153 | onkey(lambda: change(5, 0), 'Right') 154 | onkey(lambda: change(-5, 0), 'Left') 155 | onkey(lambda: change(0, 5), 'Up') 156 | onkey(lambda: change(0, -5), 'Down') 157 | world() 158 | move() 159 | done() 160 | -------------------------------------------------------------------------------- /PrintHelloWorld.py: -------------------------------------------------------------------------------- 1 | #It's very simple to code in Python :) 2 | print("Hello World !") 3 | -------------------------------------------------------------------------------- /PythCalc: -------------------------------------------------------------------------------- 1 | 2 | # Function to add two numbers 3 | 4 | def add(num1, num2): 5 | 6 | return num1 + num2 7 | 8 | 9 | # Function to subtract two numbers 10 | 11 | def subtract(num1, num2): 12 | 13 | return num1 - num2 14 | 15 | 16 | # Function to multiply two numbers 17 | 18 | def multiply(num1, num2): 19 | 20 | return num1 * num2 21 | 22 | 23 | # Function to divide two numbers 24 | 25 | def divide(num1, num2): 26 | 27 | return num1 / num2 28 | 29 | 30 | 31 | print("Please select operation -\n" \ 32 | 33 | "1. Add\n" \ 34 | 35 | "2. Subtract\n" \ 36 | 37 | "3. Multiply\n" \ 38 | 39 | "4. Divide\n") 40 | 41 | 42 | 43 | 44 | # Take input from the user 45 | 46 | select = int(input("Select operations form 1, 2, 3, 4 :")) 47 | 48 | 49 | 50 | number_1 = int(input("Enter first number: ")) 51 | 52 | number_2 = int(input("Enter second number: ")) 53 | 54 | 55 | 56 | if select == 1: 57 | 58 | print(number_1, "+", number_2, "=", 59 | 60 | add(number_1, number_2)) 61 | 62 | 63 | 64 | elif select == 2: 65 | 66 | print(number_1, "-", number_2, "=", 67 | 68 | subtract(number_1, number_2)) 69 | 70 | 71 | 72 | elif select == 3: 73 | 74 | print(number_1, "*", number_2, "=", 75 | 76 | multiply(number_1, number_2)) 77 | 78 | 79 | 80 | elif select == 4: 81 | 82 | print(number_1, "/", number_2, "=", 83 | 84 | divide(number_1, number_2)) 85 | 86 | else: 87 | 88 | print("Invalid input") 89 | -------------------------------------------------------------------------------- /Python Program to Make a Simple Calculator: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | 3 | """This function adds two numbers"" 4 | 5 | return x + y 6 | 7 | def subtract(x, y): 8 | 9 | """This function subtracts two numbers""" 10 | 11 | return x - y 12 | 13 | def multiply(x, y): 14 | 15 | """This function multiplies two numbers""" 16 | 17 | return x * y 18 | 19 | def divide(x, y): 20 | 21 | """This function divides two numbers""" 22 | 23 | return x / y 24 | 25 | 26 | 27 | print("Select operation.") 28 | 29 | print("1.Add") 30 | 31 | print("2.Subtract") 32 | 33 | print("3.Multiply") 34 | 35 | print("4.Divide") 36 | 37 | 38 | 39 | choice = input("Enter choice(1/2/3/4):") 40 | 41 | 42 | 43 | num1 = int(input("Enter first number: ")) 44 | 45 | num2 = int(input("Enter second number: ")) 46 | 47 | 48 | 49 | if choice == '1': 50 | 51 | print(num1,"+",num2,"=", add(num1,num2)) 52 | 53 | 54 | 55 | elif choice == '2': 56 | 57 | print(num1,"-",num2,"=", subtract(num1,num2)) 58 | 59 | 60 | 61 | elif choice == '3': 62 | 63 | print(num1,"*",num2,"=", multiply(num1,num2)) 64 | 65 | elif choice == '4': 66 | 67 | print(num1,"/",num2,"=", divide(num1,num2)) 68 | 69 | else: 70 | 71 | print("Invalid input") 72 | -------------------------------------------------------------------------------- /Python program to convert Celsius to Fahrenheit: -------------------------------------------------------------------------------- 1 | fahrenheit = float(input("Enter temperature in fahrenheit: ")) 2 | celsius = (fahrenheit - 32) * 5/9 3 | print('%.2f Fahrenheit is: %0.2f Celsius' %(fahrenheit, celsius)) 4 | -------------------------------------------------------------------------------- /Python3 program to find compound: -------------------------------------------------------------------------------- 1 | # Python3 program to find compound 2 | # interest for given values. 3 | 4 | def compound_interest(principle, rate, time): 5 | 6 | # Calculates compound interest 7 | Amount = principle * (pow((1 + rate / 100), time)) 8 | CI = Amount - principle 9 | print("Compound interest is", CI) 10 | 11 | # Driver Code 12 | compound_interest(10000, 10.25, 5) 13 | -------------------------------------------------------------------------------- /Quadratic formula: -------------------------------------------------------------------------------- 1 | import cmath 2 | 3 | print('Solve the quadratic equation: ax**2 + bx + c = 0') 4 | a = float(input('Please enter a : ')) 5 | b = float(input('Please enter b : ')) 6 | c = float(input('Please enter c : ')) 7 | delta = (b**2) - (4*a*c) 8 | solution1 = (-b-cmath.sqrt(delta))/(2*a) 9 | solution2 = (-b+cmath.sqrt(delta))/(2*a) 10 | 11 | print('The solutions are {0} and {1}'.format(solution1,solution2)) 12 | -------------------------------------------------------------------------------- /QuickSelect.py: -------------------------------------------------------------------------------- 1 | def quickselect(array,startind,endind,position): 2 | while True: 3 | pivotind = startind 4 | leftmark = startind + 1 5 | rightmark = endind 6 | while leftmark <= rightmark: 7 | if array[leftmark] > array[pivotind] and array[rightmark] < array[pivotind]: 8 | swap(leftmark,rightmark,array) 9 | if array[leftmark] <= array[pivotind]: 10 | leftmark += 1 11 | if array[rightmark] >= array[pivotind]: 12 | rightmark -=1 13 | swap(pivotind, rightmark,array) 14 | if rightmark == position: 15 | print(array[rightmark]) 16 | return 17 | elif rightmark < position : 18 | startind = rightmark+1 19 | else : 20 | endind = rightmark - 1 21 | 22 | def swap(one,two,array): 23 | array[one],array[two]=array[two],array[one] 24 | 25 | for _ in range(int(input())): 26 | n = int(input()) 27 | arr = list(map(int,input().split())) 28 | k = int(input()) 29 | quickselect(arr,0,n-1,k-1) 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pythonprogram 2 | 3 | 4 | it is a new python program 5 | its help for beginners 6 | #python 7 | #beginners 8 | #code 9 | #2020 10 | 11 | -------------------------------------------------------------------------------- /Repeated_Substring_Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | cal = run = 0 4 | tem = s[:cal] 5 | for i in range(len(s)): 6 | cal += 1 7 | tem = s[:cal] 8 | 9 | # Jump is with the size of searching elelment i.e cal 10 | for j in range(cal, len(s), cal): 11 | if tem == s[j: j + cal]: 12 | run = j + cal 13 | if run == len(s): 14 | return True 15 | else: 16 | break 17 | return False 18 | 19 | -------------------------------------------------------------------------------- /Simple Calculator: -------------------------------------------------------------------------------- 1 | # Program make a simple calculator 2 | 3 | # This function adds two numbers 4 | def add(x, y): 5 | return x + y 6 | 7 | # This function subtracts two numbers 8 | def subtract(x, y): 9 | return x - y 10 | 11 | # This function multiplies two numbers 12 | def multiply(x, y): 13 | return x * y 14 | 15 | # This function divides two numbers 16 | def divide(x, y): 17 | return x / y 18 | 19 | 20 | print("Select operation.") 21 | print("1.Add") 22 | print("2.Subtract") 23 | print("3.Multiply") 24 | print("4.Divide") 25 | 26 | while True: 27 | # Take input from the user 28 | choice = input("Enter choice(1/2/3/4): ") 29 | 30 | # Check if choice is one of the four options 31 | if choice in ('1', '2', '3', '4'): 32 | num1 = float(input("Enter first number: ")) 33 | num2 = float(input("Enter second number: ")) 34 | 35 | if choice == '1': 36 | print(num1, "+", num2, "=", add(num1, num2)) 37 | 38 | elif choice == '2': 39 | print(num1, "-", num2, "=", subtract(num1, num2)) 40 | 41 | elif choice == '3': 42 | print(num1, "*", num2, "=", multiply(num1, num2)) 43 | 44 | elif choice == '4': 45 | print(num1, "/", num2, "=", divide(num1, num2)) 46 | break 47 | else: 48 | print("Invalid Input") 49 | -------------------------------------------------------------------------------- /Snake: -------------------------------------------------------------------------------- 1 | pip install pygame 2 | 3 | import pygame 4 | import time 5 | pygame.init() 6 | 7 | white = (255, 255, 255) 8 | black = (0, 0, 0) 9 | red = (255, 0, 0) 10 | 11 | dis_width = 800 12 | dis_height = 600 13 | dis = pygame.display.set_mode((dis_width, dis_width)) 14 | pygame.display.set_caption('Snake Game by Baibhav') 15 | 16 | game_over = False 17 | 18 | x1 = dis_width/2 19 | y1 = dis_height/2 20 | 21 | snake_block=10 22 | 23 | x1_change = 0 24 | y1_change = 0 25 | 26 | clock = pygame.time.Clock() 27 | snake_speed=30 28 | 29 | font_style = pygame.font.SysFont(None, 50) 30 | 31 | def message(msg,color): 32 | mesg = font_style.render(msg, True, color) 33 | dis.blit(mesg, [dis_width/2, dis_height/2]) 34 | 35 | while not game_over: 36 | for event in pygame.event.get(): 37 | if event.type == pygame.QUIT: 38 | game_over = True 39 | if event.type == pygame.KEYDOWN: 40 | if event.key == pygame.K_LEFT: 41 | x1_change = -snake_block 42 | y1_change = 0 43 | elif event.key == pygame.K_RIGHT: 44 | x1_change = snake_block 45 | y1_change = 0 46 | elif event.key == pygame.K_UP: 47 | y1_change = -snake_block 48 | x1_change = 0 49 | elif event.key == pygame.K_DOWN: 50 | y1_change = snake_block 51 | x1_change = 0 52 | 53 | if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: 54 | game_over = True 55 | 56 | x1 += x1_change 57 | y1 += y1_change 58 | dis.fill(white) 59 | pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block]) 60 | 61 | pygame.display.update() 62 | 63 | clock.tick(snake_speed) 64 | 65 | message("You lost",red) 66 | pygame.display.update() 67 | time.sleep(2) 68 | 69 | pygame.quit() 70 | quit() 71 | -------------------------------------------------------------------------------- /Snake water gun game: -------------------------------------------------------------------------------- 1 | # SNAKE WATER GUN GAME 2 | 3 | import random 4 | lst=['s','w','g'] 5 | chance=10 6 | no_of_chance=0 7 | human_points =0 8 | computer_points=0 9 | print("\t \t \t \t SNAKE, WATER , GUN GAME \t \t \t \t") 10 | print("s for sanke ") 11 | print("w for water") 12 | print("g for gun") 13 | while no_of_chancehuman_points: 72 | print("computer wins and human loose") 73 | else: 74 | print(" human wins and computer loose") 75 | 76 | print(f"human point is {human_points}and computer point is {computer_points}") 77 | -------------------------------------------------------------------------------- /Sort Words in Alphabetic Order.py: -------------------------------------------------------------------------------- 1 | # Program to sort alphabetically the words form a string provided by the user 2 | 3 | my_str = "Hello this Is an Example With cased letters" 4 | 5 | # To take input from the user 6 | #my_str = input("Enter a string: ") 7 | 8 | # breakdown the string into a list of words 9 | words = my_str.split() 10 | 11 | # sort the list 12 | words.sort() 13 | 14 | # display the sorted words 15 | 16 | print("The sorted words are:") 17 | for word in words: 18 | print(word) 19 | -------------------------------------------------------------------------------- /Sorting a Stack using Recursion: -------------------------------------------------------------------------------- 1 | def sortedInsert(s , element): 2 | 3 | 4 | 5 | # Base case: Either stack is empty or newly inserted 6 | 7 | # item is greater than top (more than all existing) 8 | 9 | if len(s) == 0 or element > s[-1]: 10 | 11 | s.append(element) 12 | 13 | return 14 | 15 | else: 16 | 17 | 18 | 19 | # Remove the top item and recur 20 | 21 | temp = s.pop() 22 | 23 | sortedInsert(s, element) 24 | 25 | 26 | 27 | # Put back the top item removed earlier 28 | 29 | s.append(temp) 30 | 31 | 32 | # Method to sort stack 33 | 34 | def sortStack(s): 35 | 36 | 37 | 38 | # If stack is not empty 39 | 40 | if len(s) != 0: 41 | 42 | 43 | 44 | # Remove the top item 45 | 46 | temp = s.pop() 47 | 48 | 49 | 50 | # Sort remaining stack 51 | 52 | sortStack(s) 53 | 54 | 55 | 56 | # Push the top item back in sorted stack 57 | 58 | sortedInsert(s , temp) 59 | 60 | 61 | # Printing contents of stack 62 | 63 | def printStack(s): 64 | 65 | for i in s[::-1]: 66 | 67 | print(i , end=" ") 68 | 69 | print() 70 | 71 | 72 | 73 | if __name__=='__main__': 74 | 75 | s = [ ] 76 | 77 | s.append(30) 78 | 79 | s.append(-5) 80 | 81 | s.append(18) 82 | 83 | s.append(14) 84 | 85 | s.append(-3) 86 | 87 | 88 | 89 | print("Stack elements before sorting: ") 90 | 91 | printStack(s) 92 | 93 | 94 | 95 | sortStack(s) 96 | 97 | 98 | 99 | print("\nStack elements after sorting: ") 100 | 101 | printStack(s) 102 | -------------------------------------------------------------------------------- /The multi-line form of this code would be: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | b = int(input("Enter value for b: ")) 4 | 5 | if b >= 0: 6 | a = "positive" 7 | else: 8 | a = "negative" 9 | 10 | print(a) 11 | -------------------------------------------------------------------------------- /Tic-Tac-Toe: -------------------------------------------------------------------------------- 1 | def Welcome(): 2 | print(' *Welcome to tic-tac-toe game*') 3 | #dont take sleep more than 2 seconds then user will get bored 4 | sleep(1) 5 | print() 6 | print('Computer will decide who will play first') 7 | print() 8 | #for Hint Feature In Computer AI i have passed Player letter instead of computer letter 9 | print('If you need Hint in the middle of game \npress any of this [Hint,hint,H,h]') 10 | sleep(1) 11 | print() 12 | print(''' *** Format of Game ** 13 | | | 1 | 2 | 3 14 | - - - - - - - - - - - - 15 | | | 4 | 5 | 6 16 | - - - - - - - - - - - - 17 | | | 7 | 8 | 9 18 | ''') 19 | 20 | 21 | #Fuction to draw Board 22 | #you can modify this sleep method if you dont need it 23 | def DrawBoard(board,NeedSleep=True): 24 | #I thought for hint u dont need sleep method so i given default value for Needsleep 25 | if NeedSleep: 26 | sleep(1) 27 | print() 28 | print(' '+board[1]+' | '+board[2]+' | '+board[3]) 29 | print(' - - - - - - - ') 30 | print(' '+board[4]+' | '+board[5]+' | '+board[6]) 31 | print(' - - - - - - - ') 32 | print(' '+board[7]+' | '+board[8]+' | '+board[9]) 33 | print() 34 | 35 | #asking the player to choose thier Letter (X or O) 36 | def InputPlayerLetter(): 37 | letter='' 38 | #Ask untill user enters x or o 39 | while not(letter == 'X' or letter == 'O'): 40 | print('Do you want to be X or O') 41 | letter = input().upper() 42 | 43 | #returning list bcz of later use 44 | if letter == 'X': 45 | return ['X','O'] 46 | if letter == 'O': 47 | return ['O','X'] 48 | 49 | #Deciding who should play first randomly 50 | #in usual tic-tac-toe games player first,but it selects randomly between computer and player 51 | def WhoFirst(): 52 | opponents = ['computer','player'] 53 | if choice(opponents) == 'computer': 54 | return 'computer' 55 | else : 56 | return 'player' 57 | 58 | #this function asks player to play again 59 | def PlayAgain(): 60 | print() 61 | print('Do you want to Play Again (y or n)') 62 | playagain = input().lower().startswith('y') 63 | return playagain 64 | 65 | #function for making move 66 | def MakeMove(board,letter,move): 67 | board[move] = letter 68 | 69 | #check if any one win,returns True if wins 70 | #In tic-tac-toe there are 8 possibilities of winning 71 | #horizontal => 3 | vertical => 3 | diagonal => 2 72 | def IsWinner(board,letter): 73 | return ( (board[7] == letter and board[8] == letter and board[9] == letter ) or 74 | (board[4] == letter and board[5] == letter and board[6] == letter ) or 75 | (board[1] == letter and board[2] == letter and board[3] == letter ) or 76 | (board[1] == letter and board[4] == letter and board[7] == letter ) or 77 | (board[2] == letter and board[5] == letter and board[8] == letter ) or 78 | (board[3] == letter and board[6] == letter and board[9] == letter ) or 79 | (board[1] == letter and board[5] == letter and board[9] == letter ) or 80 | (board[3] == letter and board[5] == letter and board[7] == letter ) ) 81 | 82 | #duplicate board is useful when we wanted to make temporary changes to the temporary copy of the board without changing the original board 83 | def GetBoardCopy(board): 84 | DupeBoard = [] 85 | for i in board: 86 | DupeBoard.append(i) 87 | return DupeBoard 88 | 89 | #fuction to check is space is free 90 | def IsSpaceFree(board,move): 91 | return board[move] == ' ' 92 | 93 | #Getting the player move 94 | def GetPlayerMove(board): 95 | move = '' 96 | 97 | while move not in '1 2 3 4 5 6 7 8 9'.split() or not IsSpaceFree(board,int(move)): 98 | print() 99 | print('Enter your move (1 - 9)') 100 | move = input() 101 | #if player wants Hint 102 | if move in HintInput: 103 | return move 104 | break 105 | return int(move) 106 | 107 | #choose random move from given list 108 | #it is used when AI wants to choose out of many possibilities 109 | def ChooseRandomFromList(board,MoveList): 110 | PossibleMoves = [] 111 | for i in MoveList: 112 | if IsSpaceFree(board,i): 113 | PossibleMoves.append(i) 114 | if len(PossibleMoves) != 0: 115 | return choice(PossibleMoves) 116 | else: 117 | return None 118 | 119 | #creating computers AI 120 | #this ai works on this algorithm 121 | #1.it checks if computer can win in next move,else 122 | #2.it checks if player can win in next move,then it blocks it,else 123 | #3.it chooses any available spaces from the corner[1,3,7,9],else 124 | #4.it fills middle square if space free,else 125 | #5.it chooses any available spaces from sides,ie,[2,4,6,8] 126 | #if you interchange the 3 and 4 steps the AI becomes little Hard,ie,it fills middle then corner 127 | #-------------------------------------- 128 | #Get computer move 129 | def GetComputerMove(board,ComputerLetter): 130 | if ComputerLetter == 'X': 131 | PlayerLetter = 'O' 132 | else: 133 | PlayerLetter = 'X' 134 | 135 | #1.check computer can win in next move 136 | for i in range(1,10): 137 | copy = GetBoardCopy(board) 138 | if IsSpaceFree(copy,i): 139 | MakeMove(copy,ComputerLetter,i) 140 | if IsWinner(copy,ComputerLetter): 141 | return i 142 | 143 | 144 | #2.check player can win in next move 145 | for i in range(1,10): 146 | copy = GetBoardCopy(board) 147 | if IsSpaceFree(copy,i): 148 | MakeMove(copy,PlayerLetter,i) 149 | if IsWinner(copy,PlayerLetter): 150 | return i 151 | 152 | #3.checking for corner 153 | move = ChooseRandomFromList(board,[1,3,7,9]) 154 | if move != None: 155 | return move 156 | 157 | #4.checking for the center 158 | if IsSpaceFree(board,5): 159 | return 5 160 | 161 | #5.checking for sides 162 | return ChooseRandomFromList(board,[2,4,6,8]) 163 | 164 | #--------------------------------------- 165 | 166 | #checking board is full or not 167 | def IsBoardFull(board): 168 | for i in range(1,10): 169 | if IsSpaceFree(board,i): 170 | return False 171 | return True 172 | 173 | #fuction to print the final win or tie board 174 | #made this to separate usual board and winning or tie board 175 | def FinalBoard(board,NeedSleep=True): 176 | print(' |-------------|') 177 | DrawBoard(board,NeedSleep) 178 | print(' |-------------|') 179 | 180 | 181 | #LETS START THE GAME 182 | Welcome() 183 | while True: 184 | #intialising board 185 | TheBoard = [' '] * 10 186 | PlayerLetter,ComputerLetter = InputPlayerLetter() 187 | turn = WhoFirst() 188 | print(f'The {turn} will go first') 189 | 190 | #gameloop 191 | Playing = True 192 | while Playing: 193 | 194 | if turn == 'player': 195 | print(f" Turn => {turn}") 196 | HintInput = ['Hint','hint','H','h'] 197 | #taking players input 198 | move = GetPlayerMove(TheBoard) 199 | #if player needs Hint 200 | while move in HintInput: 201 | #following code gives hint to the user 202 | #it runs player letter to computer AI 203 | HintBox = [] 204 | for i in TheBoard: 205 | HintBox.append(i) 206 | hint = GetComputerMove(HintBox,PlayerLetter) 207 | MakeMove(HintBox,PlayerLetter,hint) 208 | print(f'HINT : placing at {hint} is better') 209 | FinalBoard(HintBox,False) 210 | move = GetPlayerMove(TheBoard) 211 | 212 | MakeMove(TheBoard,PlayerLetter,move) 213 | 214 | 215 | if IsWinner(TheBoard,PlayerLetter): 216 | FinalBoard(TheBoard) 217 | print('❤You have WON the game❤') 218 | Playing = not Playing 219 | elif IsBoardFull(TheBoard): 220 | FinalBoard(TheBoard) 221 | print('The game is TIE\nIts good to PLAY untill you WIN❤') 222 | Playing = not Playing 223 | else : 224 | DrawBoard(TheBoard) 225 | turn = 'computer' 226 | 227 | else : 228 | #computer move 229 | print(f" Turn => {turn}") 230 | move = GetComputerMove(TheBoard,ComputerLetter) 231 | MakeMove(TheBoard,ComputerLetter,move) 232 | 233 | 234 | if IsWinner(TheBoard,ComputerLetter): 235 | FinalBoard(TheBoard) 236 | print('❤Try again bro you will win❤') 237 | Playing = not Playing 238 | elif IsBoardFull(TheBoard): 239 | FinalBoard(TheBoard) 240 | print('The game is TIE\nIts good to PLAY untill you WIN❤') 241 | Playing = not Playing 242 | else : 243 | DrawBoard(TheBoard) 244 | turn = 'player' 245 | 246 | if not PlayAgain(): 247 | print("***❤GIVE STAR ONLY IF YOU LIKE❤***") 248 | break 249 | 250 | -------------------------------------------------------------------------------- /Use of dictionary: -------------------------------------------------------------------------------- 1 | d1={"Shyam":"Honey", "Imli":"Lichi", "Raj":"Mango", "Marie": "Coco"} 2 | print(d1) 3 | a=input("Enter the Word:") 4 | b=a.capitalize() 5 | print(b,"=",d1[b]) 6 | -------------------------------------------------------------------------------- /WAP to Calculate Simple Interest(SI),Read the principle, rate of interest and number of years from the user.: -------------------------------------------------------------------------------- 1 | principle = eval(input("Enter the principle")) 2 | ROI = eval(input("Enter the ROI")) 3 | Years = eval(input("Enter the years")) 4 | print("Principle:-",principle) 5 | print("ROI:-",ROI) 6 | print("Years:-",Years) 7 | SI = principle * ROI * Years/100 8 | print("The Simple interest of the number",SI) 9 | -------------------------------------------------------------------------------- /addition using function: -------------------------------------------------------------------------------- 1 | #Python program to add two numbers using function 2 | 3 | def add_num(a,b):#function for addition 4 | sum=a+b; 5 | return sum; #return value 6 | 7 | num1=25 #variable declaration 8 | num2=55 9 | print("The sum is",add_num(num1,num2))#call the function 10 | -------------------------------------------------------------------------------- /audiobook: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | import PyPDF2 3 | book = open('book.pdf','rb') 4 | pdfReader = PyPDF2.PdfFileReader(book) 5 | number_of_pages = pdfReader.numPages 6 | print(number_of_pages) 7 | speaker = pyttsx3.init() 8 | for num in range(1, number_of_pages): 9 | page_number = pdfReader.getPage(10) 10 | text = page_number.extractText() 11 | speaker.say(text) 12 | speaker.runAndWait() 13 | -------------------------------------------------------------------------------- /avgno: -------------------------------------------------------------------------------- 1 | def cal_average(num): 2 | sum_num = 0 3 | for t in num: 4 | sum_num = sum_num + t 5 | 6 | avg = sum_num / len(num) 7 | return avg 8 | 9 | print("The average is", cal_average([17,26,3,21,35])) 10 | -------------------------------------------------------------------------------- /calculator: -------------------------------------------------------------------------------- 1 | 2 | from tkinter import * 3 | expression = "" 4 | def press(num): 5 | 6 | global expression 7 | expression = expression + str(num) 8 | 9 | # update the expression by using set method 10 | equation.set(expression) 11 | 12 | 13 | # Function to evaluate the final expression 14 | def equalpress(): 15 | 16 | try: 17 | 18 | global expression 19 | 20 | # eval function evaluate the expression 21 | # and str function convert the result 22 | # into string 23 | total = str(eval(expression)) 24 | 25 | equation.set(total) 26 | 27 | # initialze the expression variable 28 | # by empty string 29 | expression = "" 30 | 31 | # if error is generate then handle 32 | # by the except block 33 | except: 34 | 35 | equation.set(" error ") 36 | expression = "" 37 | 38 | 39 | # Function to clear the contents 40 | # of text entry box 41 | def clear(): 42 | global expression 43 | expression = "" 44 | equation.set("") 45 | 46 | 47 | # Driver code 48 | if __name__ == "__main__": 49 | # create a GUI window 50 | gui = Tk() 51 | 52 | # set the background colour of GUI window 53 | gui.configure(background="light green") 54 | 55 | # set the title of GUI window 56 | gui.title("Simple Calculator") 57 | 58 | # set the configuration of GUI window 59 | gui.geometry("270x150") 60 | 61 | # StringVar() is the variable class 62 | # we create an instance of this class 63 | equation = StringVar() 64 | 65 | # create the text entry box for 66 | # showing the expression . 67 | expression_field = Entry(gui, textvariable=equation) 68 | 69 | # grid method is used for placing 70 | # the widgets at respective positions 71 | # in table like structure . 72 | expression_field.grid(columnspan=4, ipadx=70) 73 | 74 | equation.set('enter your expression') 75 | 76 | # create a Buttons and place at a particular 77 | # location inside the root window . 78 | # when user press the button, the command or 79 | # function affiliated to that button is executed . 80 | button1 = Button(gui, text=' 1 ', fg='black', bg='red', 81 | command=lambda: press(1), height=1, width=7) 82 | button1.grid(row=2, column=0) 83 | 84 | button2 = Button(gui, text=' 2 ', fg='black', bg='red', 85 | command=lambda: press(2), height=1, width=7) 86 | button2.grid(row=2, column=1) 87 | 88 | button3 = Button(gui, text=' 3 ', fg='black', bg='red', 89 | command=lambda: press(3), height=1, width=7) 90 | button3.grid(row=2, column=2) 91 | 92 | button4 = Button(gui, text=' 4 ', fg='black', bg='red', 93 | command=lambda: press(4), height=1, width=7) 94 | button4.grid(row=3, column=0) 95 | 96 | button5 = Button(gui, text=' 5 ', fg='black', bg='red', 97 | command=lambda: press(5), height=1, width=7) 98 | button5.grid(row=3, column=1) 99 | 100 | button6 = Button(gui, text=' 6 ', fg='black', bg='red', 101 | command=lambda: press(6), height=1, width=7) 102 | button6.grid(row=3, column=2) 103 | 104 | button7 = Button(gui, text=' 7 ', fg='black', bg='red', 105 | command=lambda: press(7), height=1, width=7) 106 | button7.grid(row=4, column=0) 107 | 108 | button8 = Button(gui, text=' 8 ', fg='black', bg='red', 109 | command=lambda: press(8), height=1, width=7) 110 | button8.grid(row=4, column=1) 111 | 112 | button9 = Button(gui, text=' 9 ', fg='black', bg='red', 113 | command=lambda: press(9), height=1, width=7) 114 | button9.grid(row=4, column=2) 115 | 116 | button0 = Button(gui, text=' 0 ', fg='black', bg='red', 117 | command=lambda: press(0), height=1, width=7) 118 | button0.grid(row=5, column=0) 119 | 120 | plus = Button(gui, text=' + ', fg='black', bg='red', 121 | command=lambda: press("+"), height=1, width=7) 122 | plus.grid(row=2, column=3) 123 | 124 | minus = Button(gui, text=' - ', fg='black', bg='red', 125 | command=lambda: press("-"), height=1, width=7) 126 | minus.grid(row=3, column=3) 127 | 128 | multiply = Button(gui, text=' * ', fg='black', bg='red', 129 | command=lambda: press("*"), height=1, width=7) 130 | multiply.grid(row=4, column=3) 131 | 132 | divide = Button(gui, text=' / ', fg='black', bg='red', 133 | command=lambda: press("/"), height=1, width=7) 134 | divide.grid(row=5, column=3) 135 | 136 | equal = Button(gui, text=' = ', fg='black', bg='red', 137 | command=equalpress, height=1, width=7) 138 | equal.grid(row=5, column=2) 139 | 140 | clear = Button(gui, text='Clear', fg='black', bg='red', 141 | command=clear, height=1, width=7) 142 | clear.grid(row=5, column='1') 143 | 144 | Decimal= Button(gui, text='.', fg='black', bg='red', 145 | command=lambda: press('.'), height=1, width=7) 146 | Decimal.grid(row=6, column=0) 147 | # start the GUI 148 | gui.mainloop() 149 | -------------------------------------------------------------------------------- /calender: -------------------------------------------------------------------------------- 1 | def is_leap_year(year): 2 | return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0) 3 | 4 | def numberOfDaysInAYear(year) : 5 | if year == 2010 and output.is_leap_year = True: 6 | print (365) 7 | elif year==2011 : 8 | print(365) 9 | elif year==2012 : 10 | print (366) 11 | elif year==2013 : 12 | print(365) 13 | elif year==2014 : 14 | print(365) 15 | elif year==2015 : 16 | print(365) 17 | elif year==2016 : 18 | print (366) 19 | elif year==2017 : 20 | print(365) 21 | elif year==2018 : 22 | print(365) 23 | elif year==2019 : 24 | print(365) 25 | elif year == 2020 : 26 | print (366) 27 | 28 | else: print('') 29 | 30 | 31 | 32 | print ( year == 2010 ,"Days are 365") 33 | print ( year == 2011 ,"Days are 365") 34 | print ( year == 2012 ,"Days are 366") 35 | print ( year == 2013 ,"Days are 365") 36 | print ( year == 2014 ,"Days are 365") 37 | print ( year == 2015 ,"Days are 365") 38 | print ( year == 2016 ,"Days are 366") 39 | print ( year == 2017 ,"Days are 365") 40 | print ( year == 2018 ,"Days are 365") 41 | print ( year == 2019 ,"Days are 365") 42 | print ( year == 2020 ,"Days are 366") 43 | 44 | 45 | -------------------------------------------------------------------------------- /class BasicLexer with python programming: -------------------------------------------------------------------------------- 1 | tokens = { NAME, NUMBER, STRING } 2 | ignore = '\t ' 3 | literals = { '=', '+', '-', '/', 4 | '*', '(', ')', ',', ';'} 5 | 6 | 7 | # Define tokens as regular expressions 8 | # (stored as raw strings) 9 | NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' 10 | STRING = r'\".*?\"' 11 | 12 | # Number token 13 | @_(r'\d+') 14 | def NUMBER(self, t): 15 | 16 | # convert it into a python integer 17 | t.value = int(t.value) return t 18 | 19 | # Comment token 20 | @_(r'//.*') 21 | def COMMENT(self, t): 22 | pass 23 | 24 | # Newline token(used only for showing 25 | # errors in new line) 26 | @_(r'\n+') 27 | def newline(self, t): 28 | self.lineno = t.value.count('\n') 29 | -------------------------------------------------------------------------------- /dfsTraversal: -------------------------------------------------------------------------------- 1 | 2 | from collections import defaultdict 3 | 4 | class Graph: 5 | 6 | 7 | def __init__(self): 8 | 9 | 10 | self.graph = defaultdict(list) 11 | 12 | 13 | def addEdge(self, u, v): 14 | self.graph[u].append(v) 15 | 16 | 17 | def DFSUtil(self, v, visited): 18 | 19 | 20 | visited[v] = True 21 | print(v, end = ' ') 22 | 23 | 24 | for i in self.graph[v]: 25 | if visited[i] == False: 26 | self.DFSUtil(i, visited) 27 | 28 | 29 | def DFS(self, v): 30 | 31 | 32 | visited = [False] * (max(self.graph)+1) 33 | 34 | 35 | self.DFSUtil(v, visited) 36 | 37 | 38 | 39 | # Create a graph given 40 | 41 | g = Graph() 42 | g.addEdge(0, 1) 43 | g.addEdge(0, 2) 44 | g.addEdge(1, 2) 45 | g.addEdge(2, 0) 46 | g.addEdge(2, 3) 47 | g.addEdge(3, 3) 48 | 49 | print("Following is DFS from (starting from vertex 2)") 50 | g.DFS(2) 51 | 52 | -------------------------------------------------------------------------------- /diagonaldifference: -------------------------------------------------------------------------------- 1 | def diagonalDifference(arr) #function accepting a 2d array 2 | 3 | sum1=0 4 | sum2=0 5 | res=0 6 | for i in range(0,len(arr)): 7 | sum1=sum1+arr[i][i] 8 | sum2=sum2+arr[i][(len(arr)-1)-i] 9 | res=sum1-sum2 10 | return abs(res) 11 | if __name__ == '__main__': 12 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 13 | 14 | n = int(input().strip) #size 15 | 16 | arr = [] 17 | 18 | for _ in range(n): 19 | arr.append(list(map(int, input().rstrip().split()))) 20 | 21 | print( diagonalDifference(arr)) 22 | 23 | -------------------------------------------------------------------------------- /factorial: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if n < 0: 3 | return 0 4 | elif n == 0 or n == 1: 5 | return 1 6 | else: 7 | fact = 1 8 | while(n > 1): 9 | fact *= n 10 | n -= 1 11 | return fact 12 | 13 | # Driver Code 14 | num = 5; 15 | print("Factorial of",num,"is", 16 | factorial(num)) 17 | -------------------------------------------------------------------------------- /fibonacci.py: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term 2 | 3 | nterms = int(input("How many terms? ")) 4 | 5 | # first two terms 6 | n1, n2 = 0, 1 7 | count = 0 8 | 9 | # check if the number of terms is valid 10 | if nterms <= 0: 11 | print("Please enter a positive integer") 12 | elif nterms == 1: 13 | print("Fibonacci sequence upto",nterms,":") 14 | print(n1) 15 | else: 16 | print("Fibonacci sequence:") 17 | while count < nterms: 18 | print(n1) 19 | nth = n1 + n2 20 | # update values 21 | n1 = n2 22 | n2 = nth 23 | count += 1 24 | -------------------------------------------------------------------------------- /find area of circle: -------------------------------------------------------------------------------- 1 | # Python program to find Area of a circle 2 | 3 | def findArea(r): 4 | PI = 3.142 5 | return PI * (r*r); 6 | 7 | # Driver method 8 | print("Area is %.6f" % findArea(5)); 9 | 10 | # enjoy 11 | -------------------------------------------------------------------------------- /find even or odd: -------------------------------------------------------------------------------- 1 | """ 2 | Simple snake 3 | made a python game 4 | hope you like it 5 | 6 | """ 7 | 8 | import pygame 9 | 10 | # --- Globals --- 11 | # Colors 12 | BLACK = (0, 0, 0) 13 | WHITE = (255, 255, 255) 14 | 15 | # Set the width and height of each snake segment 16 | segment_width = 15 17 | segment_height = 15 18 | # Margin between each segment 19 | segment_margin = 3 20 | 21 | # Set initial speed 22 | x_change = segment_width + segment_margin 23 | y_change = 0 24 | 25 | 26 | class Segment(pygame.sprite.Sprite): 27 | """ Class to represent one segment of the snake. """ 28 | # -- Methods 29 | # Constructor function 30 | def __init__(self, x, y): 31 | # Call the parent's constructor 32 | super().__init__() 33 | 34 | # Set height, width 35 | self.image = pygame.Surface([segment_width, segment_height]) 36 | self.image.fill(WHITE) 37 | 38 | # Make our top-left corner the passed-in location. 39 | self.rect = self.image.get_rect() 40 | self.rect.x = x 41 | self.rect.y = y 42 | 43 | # Call this function so the Pygame library can initialize itself 44 | pygame.init() 45 | 46 | # Create an 800x600 sized screen 47 | screen = pygame.display.set_mode([800, 600]) 48 | 49 | # Set the title of the window 50 | pygame.display.set_caption('Snake Example') 51 | 52 | allspriteslist = pygame.sprite.Group() 53 | 54 | # Create an initial snake 55 | snake_segments = [] 56 | for i in range(15): 57 | x = 250 - (segment_width + segment_margin) * i 58 | y = 30 59 | segment = Segment(x, y) 60 | snake_segments.append(segment) 61 | allspriteslist.add(segment) 62 | 63 | 64 | clock = pygame.time.Clock() 65 | done = False 66 | 67 | while not done: 68 | 69 | for event in pygame.event.get(): 70 | if event.type == pygame.QUIT: 71 | done = True 72 | 73 | # Set the speed based on the key pressed 74 | # We want the speed to be enough that we move a full 75 | # segment, plus the margin. 76 | if event.type == pygame.KEYDOWN: 77 | if event.key == pygame.K_LEFT: 78 | x_change = (segment_width + segment_margin) * -1 79 | y_change = 0 80 | if event.key == pygame.K_RIGHT: 81 | x_change = (segment_width + segment_margin) 82 | y_change = 0 83 | if event.key == pygame.K_UP: 84 | x_change = 0 85 | y_change = (segment_height + segment_margin) * -1 86 | if event.key == pygame.K_DOWN: 87 | x_change = 0 88 | y_change = (segment_height + segment_margin) 89 | 90 | # Get rid of last segment of the snake 91 | # .pop() command removes last item in list 92 | old_segment = snake_segments.pop() 93 | allspriteslist.remove(old_segment) 94 | 95 | # Figure out where new segment will be 96 | x = snake_segments[0].rect.x + x_change 97 | y = snake_segments[0].rect.y + y_change 98 | segment = Segment(x, y) 99 | 100 | # Insert new segment into the list 101 | snake_segments.insert(0, segment) 102 | allspriteslist.add(segment) 103 | 104 | # -- Draw everything 105 | # Clear screen 106 | screen.fill(BLACK) 107 | 108 | allspriteslist.draw(screen) 109 | 110 | # Flip screen 111 | pygame.display.flip() 112 | 113 | # Pause 114 | clock.tick(5) 115 | 116 | pygame.quit() 117 | -------------------------------------------------------------------------------- /forloopinpython: -------------------------------------------------------------------------------- 1 | fruits = ["apple", "banana", "cherry"] 2 | for x in fruits: 3 | if x == "banana": 4 | break 5 | print(x) 6 | -------------------------------------------------------------------------------- /funny weight converter: -------------------------------------------------------------------------------- 1 | print('sup,user') 2 | boi = input('what is your name name boi: ') 3 | print("i guessed it, " + boi) 4 | print(boi + " ,here v r going to convert your weight into pounds(lbs) from kilograms") 5 | kgs = input("your weight in kgs: ") 6 | kga = int(kgs) * 0.49 7 | kg = 'get some more weight kid, eat pizzas. u r 🤣🤣🤣' 8 | kgb ='oh, workout football belly man. u r🤣🤣🤣🤣 ' 9 | 10 | if kga>50: 11 | print(kg) 12 | else: 13 | print(kgb) 14 | 15 | print(kga) 16 | print("pounds(lbs)") 17 | 18 | print("avoid the language😅, look code") 19 | print("please give me star , i am just 14 trying coding") 20 | print("to give a 🌟, tap the 3 dots and find star section and just tap on it please👍👍🤝") 21 | -------------------------------------------------------------------------------- /greatearno: -------------------------------------------------------------------------------- 1 | # importing random 2 | from random import * 3 | 4 | # taking input from user 5 | user_pass = input("Enter your password") 6 | 7 | # storing alphabet letter to use thm to crack password 8 | password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 9 | 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v', 10 | 'w', 'x', 'y', 'z',] 11 | 12 | # initializing an empty string 13 | guess = "" 14 | 15 | 16 | # using while loop to generate many passwords untill one of 17 | # them does not matches user_pass 18 | while (guess != user_pass): 19 | guess = "" 20 | # generating random passwords using for loop 21 | for letter in range(len(user_pass)): 22 | guess_letter = password[randint(0, 25)] 23 | guess = str(guess_letter) + str(guess) 24 | # printing guessed passwords 25 | print(guess) 26 | 27 | # printing the matched password 28 | print("Your password is",guess) 29 | -------------------------------------------------------------------------------- /leap year: -------------------------------------------------------------------------------- 1 | def checkYear(year): 2 | if (year % 4) == 0: 3 | if (year % 100) == 0: 4 | if (year % 400) == 0: 5 | return True 6 | else: 7 | return False 8 | else: 9 | return True 10 | else: 11 | return False 12 | 13 | # Driver Code 14 | year = 2000 15 | if(checkYear(year)): 16 | print("Leap Year") 17 | else: 18 | print("Not a Leap Year") 19 | -------------------------------------------------------------------------------- /libraries: -------------------------------------------------------------------------------- 1 | #the list of libraries in python 2 | TensorFlow 3 | Scikit-Learn 4 | Numpy 5 | Keras 6 | PyTorch 7 | LightGBM 8 | Eli5 9 | SciPy 10 | Theano 11 | Pandas 12 | Scikit- learn 13 | Truth Value Testing 14 | Boolean Operations — and, or, not 15 | Comparisons 16 | Numeric Types — int, float, complex 17 | Iterator Types 18 | Sequence Types — list, tuple, range 19 | Text Sequence Type — str 20 | Binary Sequence Types — bytes, bytearray, memoryview 21 | Set Types — set, frozenset 22 | Mapping Types — dict 23 | Context Manager Types 24 | Other Built-in Types 25 | Special Attributes 26 | Built-in Exceptions 27 | Base classes 28 | Concrete exceptions 29 | Warnings 30 | Exception hierarchy 31 | Text Processing Services 32 | string — Common string operations 33 | re — Regular expression operations 34 | difflib — Helpers for computing deltas 35 | textwrap — Text wrapping and filling 36 | unicodedata — Unicode Database 37 | stringprep — Internet String Preparation 38 | readline — GNU readline interface 39 | rlcompleter — Completion function for GNU readline 40 | Binary Data Services 41 | struct — Interpret bytes as packed binary data 42 | codecs — Codec registry and base classes 43 | Data Types 44 | datetime — Basic date and time types 45 | calendar — General calendar-related functions 46 | collections — Container datatypes 47 | collections.abc — Abstract Base Classes for Containers 48 | heapq — Heap queue algorithm 49 | bisect — Array bisection algorithm 50 | array — Efficient arrays of numeric values 51 | weakref — Weak references 52 | types — Dynamic type creation and names for built-in types 53 | copy — Shallow and deep copy operations 54 | pprint — Data pretty printer 55 | reprlib — Alternate repr() implementation 56 | enum — Support for enumerations 57 | Numeric and Mathematical Modules 58 | numbers — Numeric abstract base classes 59 | math — Mathematical functions 60 | cmath — Mathematical functions for complex numbers 61 | decimal — Decimal fixed point and floating point arithmetic 62 | fractions — Rational numbers 63 | random — Generate pseudo-random numbers 64 | statistics — Mathematical statistics functions 65 | Functional Programming Modules 66 | itertools — Functions creating iterators for efficient looping 67 | functools — Higher-order functions and operations on callable objects 68 | operator — Standard operators as functions 69 | File and Directory Access 70 | pathlib — Object-oriented filesystem paths 71 | os.path — Common pathname manipulations 72 | fileinput — Iterate over lines from multiple input streams 73 | stat — Interpreting stat() results 74 | filecmp — File and Directory Comparisons 75 | tempfile — Generate temporary files and directories 76 | glob — Unix style pathname pattern expansion 77 | fnmatch — Unix filename pattern matching 78 | linecache — Random access to text lines 79 | shutil — High-level file operations 80 | Data Persistence 81 | pickle — Python object serialization 82 | copyreg — Register pickle support functions 83 | shelve — Python object persistence 84 | marshal — Internal Python object serialization 85 | dbm — Interfaces to Unix “databases” 86 | sqlite3 — DB-API 2.0 interface for SQLite databases 87 | Data Compression and Archiving 88 | zlib — Compression compatible with gzip 89 | gzip — Support for gzip files 90 | bz2 — Support for bzip2 compression 91 | lzma — Compression using the LZMA algorithm 92 | zipfile — Work with ZIP archives 93 | tarfile — Read and write tar archive files 94 | File Formats 95 | csv — CSV File Reading and Writing 96 | configparser — Configuration file parser 97 | netrc — netrc file processing 98 | xdrlib — Encode and decode XDR data 99 | plistlib — Generate and parse Mac OS X .plist files 100 | Cryptographic Services 101 | hashlib — Secure hashes and message digests 102 | hmac — Keyed-Hashing for Message Authentication 103 | secrets — Generate secure random numbers for managing secrets 104 | Generic Operating System Services 105 | os — Miscellaneous operating system interfaces 106 | io — Core tools for working with streams 107 | time — Time access and conversions 108 | argparse — Parser for command-line options, arguments and sub-commands 109 | getopt — C-style parser for command line options 110 | logging — Logging facility for Python 111 | logging.config — Logging configuration 112 | logging.handlers — Logging handlers 113 | getpass — Portable password input 114 | curses — Terminal handling for character-cell displays 115 | curses.textpad — Text input widget for curses programs 116 | curses.ascii — Utilities for ASCII characters 117 | curses.panel — A panel stack extension for curses 118 | platform — Access to underlying platform’s identifying data 119 | errno — Standard errno system symbols 120 | ctypes — A foreign function library for Python 121 | Concurrent Execution 122 | threading — Thread-based parallelism 123 | multiprocessing — Process-based parallelism 124 | multiprocessing.shared_memory — Provides shared memory for direct access across processes 125 | The concurrent package 126 | concurrent.futures — Launching parallel tasks 127 | subprocess — Subprocess management 128 | sched — Event scheduler 129 | queue — A synchronized queue class 130 | _thread — Low-level threading API 131 | _dummy_thread — Drop-in replacement for the _thread module 132 | dummy_threading — Drop-in replacement for the threading module 133 | contextvars — Context Variables 134 | Context Variables 135 | Manual Context Management 136 | asyncio support 137 | Networking and Interprocess Communication 138 | asyncio — Asynchronous I/O 139 | socket — Low-level networking interface 140 | ssl — TLS/SSL wrapper for socket objects 141 | select — Waiting for I/O completion 142 | selectors — High-level I/O multiplexing 143 | asyncore — Asynchronous socket handler 144 | asynchat — Asynchronous socket command/response handler 145 | signal — Set handlers for asynchronous events 146 | mmap — Memory-mapped file support 147 | Internet Data Handling 148 | email — An email and MIME handling package 149 | json — JSON encoder and decoder 150 | mailcap — Mailcap file handling 151 | mailbox — Manipulate mailboxes in various formats 152 | mimetypes — Map filenames to MIME types 153 | base64 — Base16, Base32, Base64, Base85 Data Encodings 154 | binhex — Encode and decode binhex4 files 155 | binascii — Convert between binary and ASCII 156 | quopri — Encode and decode MIME quoted-printable data 157 | uu — Encode and decode uuencode files 158 | Structured Markup Processing Tools 159 | html — HyperText Markup Language support 160 | html.parser — Simple HTML and XHTML parser 161 | html.entities — Definitions of HTML general entities 162 | XML Processing Modules 163 | xml.etree.ElementTree — The ElementTree XML API 164 | xml.dom — The Document Object Model API 165 | xml.dom.minidom — Minimal DOM implementation 166 | xml.dom.pulldom — Support for building partial DOM trees 167 | xml.sax — Support for SAX2 parsers 168 | xml.sax.handler — Base classes for SAX handlers 169 | xml.sax.saxutils — SAX Utilities 170 | xml.sax.xmlreader — Interface for XML parsers 171 | xml.parsers.expat — Fast XML parsing using Expat 172 | Internet Protocols and Support 173 | webbrowser — Convenient Web-browser controller 174 | cgi — Common Gateway Interface support 175 | cgitb — Traceback manager for CGI scripts 176 | wsgiref — WSGI Utilities and Reference Implementation 177 | urllib — URL handling modules 178 | urllib.request — Extensible library for opening URLs 179 | urllib.response — Response classes used by urllib 180 | urllib.parse — Parse URLs into components 181 | urllib.error — Exception classes raised by urllib.request 182 | urllib.robotparser — Parser for robots.txt 183 | http — HTTP modules 184 | http.client — HTTP protocol client 185 | ftplib — FTP protocol client 186 | poplib — POP3 protocol client 187 | imaplib — IMAP4 protocol client 188 | nntplib — NNTP protocol client 189 | smtplib — SMTP protocol client 190 | smtpd — SMTP Server 191 | telnetlib — Telnet client 192 | uuid — UUID objects according to RFC 4122 193 | socketserver — A framework for network servers 194 | http.server — HTTP servers 195 | http.cookies — HTTP state management 196 | http.cookiejar — Cookie handling for HTTP clients 197 | xmlrpc — XMLRPC server and client modules 198 | xmlrpc.client — XML-RPC client access 199 | xmlrpc.server — Basic XML-RPC servers 200 | ipaddress — IPv4/IPv6 manipulation library 201 | Multimedia Services 202 | audioop — Manipulate raw audio data 203 | aifc — Read and write AIFF and AIFC files 204 | sunau — Read and write Sun AU files 205 | wave — Read and write WAV files 206 | chunk — Read IFF chunked data 207 | colorsys — Conversions between color systems 208 | imghdr — Determine the type of an image 209 | sndhdr — Determine type of sound file 210 | ossaudiodev — Access to OSS-compatible audio devices 211 | Internationalization 212 | gettext — Multilingual internationalization services 213 | locale — Internationalization services 214 | Program Frameworks 215 | turtle — Turtle graphics 216 | cmd — Support for line-oriented command interpreters 217 | shlex — Simple lexical analysis 218 | Graphical User Interfaces with Tk 219 | tkinter — Python interface to Tcl/Tk 220 | tkinter.ttk — Tk themed widgets 221 | tkinter.tix — Extension widgets for Tk 222 | tkinter.scrolledtext — Scrolled Text Widget 223 | IDLE 224 | Other Graphical User Interface Packages 225 | Development Tools 226 | typing — Support for type hints 227 | pydoc — Documentation generator and online help system 228 | doctest — Test interactive Python examples 229 | unittest — Unit testing framework 230 | unittest.mock — mock object library 231 | unittest.mock — getting started 232 | 2to3 - Automated Python 2 to 3 code translation 233 | test — Regression tests package for Python 234 | test.support — Utilities for the Python test suite 235 | test.support.script_helper — Utilities for the Python execution tests 236 | Debugging and Profiling 237 | Audit events table 238 | bdb — Debugger framework 239 | faulthandler — Dump the Python traceback 240 | pdb — The Python Debugger 241 | The Python Profilers 242 | timeit — Measure execution time of small code snippets 243 | trace — Trace or track Python statement execution 244 | tracemalloc — Trace memory allocations 245 | Software Packaging and Distribution 246 | distutils — Building and installing Python modules 247 | ensurepip — Bootstrapping the pip installer 248 | venv — Creation of virtual environments 249 | zipapp — Manage executable Python zip archives 250 | Python Runtime Services 251 | sys — System-specific parameters and functions 252 | sysconfig — Provide access to Python’s configuration information 253 | builtins — Built-in objects 254 | __main__ — Top-level script environment 255 | warnings — Warning control 256 | dataclasses — Data Classes 257 | contextlib — Utilities for with-statement contexts 258 | abc — Abstract Base Classes 259 | atexit — Exit handlers 260 | traceback — Print or retrieve a stack traceback 261 | __future__ — Future statement definitions 262 | gc — Garbage Collector interface 263 | inspect — Inspect live objects 264 | site — Site-specific configuration hook 265 | Custom Python Interpreters 266 | code — Interpreter base classes 267 | codeop — Compile Python code 268 | Importing Modules 269 | zipimport — Import modules from Zip archives 270 | pkgutil — Package extension utility 271 | modulefinder — Find modules used by a script 272 | runpy — Locating and executing Python modules 273 | importlib — The implementation of import 274 | Using importlib.metadata 275 | Python Language Services 276 | parser — Access Python parse trees 277 | ast — Abstract Syntax Trees 278 | symtable — Access to the compiler’s symbol tables 279 | symbol — Constants used with Python parse trees 280 | token — Constants used with Python parse trees 281 | keyword — Testing for Python keywords 282 | tokenize — Tokenizer for Python source 283 | tabnanny — Detection of ambiguous indentation 284 | pyclbr — Python module browser support 285 | py_compile — Compile Python source files 286 | compileall — Byte-compile Python libraries 287 | dis — Disassembler for Python bytecode 288 | pickletools — Tools for pickle developers 289 | Miscellaneous Services 290 | formatter — Generic output formatting 291 | MS Windows Specific Services 292 | msilib — Read and write Microsoft Installer files 293 | msvcrt — Useful routines from the MS VC++ runtime 294 | winreg — Windows registry access 295 | winsound — Sound-playing interface for Windows 296 | Unix Specific Services 297 | posix — The most common POSIX system calls 298 | pwd — The password database 299 | spwd — The shadow password database 300 | grp — The group database 301 | crypt — Function to check Unix passwords 302 | termios — POSIX style tty control 303 | tty — Terminal control functions 304 | pty — Pseudo-terminal utilities 305 | fcntl — The fcntl and ioctl system calls 306 | pipes — Interface to shell pipelines 307 | resource — Resource usage information 308 | nis — Interface to Sun’s NIS (Yellow Pages) 309 | syslog — Unix syslog library routines 310 | Superseded Modules 311 | optparse — Parser for command line options 312 | imp — Access the import internals 313 | Undocumented Modules 314 | Platform specific modules 315 | -------------------------------------------------------------------------------- /longestPalindrome: -------------------------------------------------------------------------------- 1 | t= int(input()) 2 | for k in range(t): 3 | str=input() 4 | substring=[] 5 | for i in range(len(str)): 6 | for j in range(i+1,len(str)+1): 7 | substring.append(str[i:j]) 8 | pal=[] 9 | for i in range(0,len(substring)): 10 | temp=substring[i] 11 | temp1=temp[::-1] 12 | if (temp==temp1): 13 | pal.append(temp) 14 | max="" 15 | for i in range(0,len(pal)): 16 | if((len(pal[i])>len(max)) and (len(pal[i])>1)): 17 | max=pal[i] 18 | elif(len(max)<=1): 19 | max=pal[0] #max=str[:1] 20 | print(max) 21 | substring.clear() 22 | pal.clear() 23 | -------------------------------------------------------------------------------- /mergesort: -------------------------------------------------------------------------------- 1 | #This program gives an example of Merge sort 2 | 3 | # Merge sort is a divide and conquer algorithm. In the divide and 4 | # conquer paradigm, a problem is broken into pieces where each piece 5 | # still retains all the properties of the larger problem -- except 6 | # its size. To solve the original problem, each piece is solved 7 | # individually; then the pieces are merged back together. 8 | 9 | # Best = Average = Worst = O(nlog(n)) 10 | 11 | def merge(a,b): 12 | """ Function to merge two arrays """ 13 | c = [] 14 | while len(a) != 0 and len(b) != 0: 15 | if a[0] < b[0]: 16 | c.append(a[0]) 17 | a.remove(a[0]) 18 | else: 19 | c.append(b[0]) 20 | b.remove(b[0]) 21 | if len(a) == 0: 22 | c += b 23 | else: 24 | c += a 25 | return c 26 | 27 | # Code for merge sort 28 | 29 | def mergeSort(x): 30 | """ Function to sort an array using merge sort algorithm """ 31 | if len(x) == 0 or len(x) == 1: 32 | return x 33 | else: 34 | middle = len(x)//2 35 | a = mergeSort(x[:middle]) 36 | b = mergeSort(x[middle:]) 37 | return merge(a,b) 38 | 39 | if __name__ == '__main__': 40 | List = [3, 4, 2, 6, 5, 7, 1, 9] 41 | print('Sorted List:',mergeSort(List)) 42 | -------------------------------------------------------------------------------- /multiplication_table: -------------------------------------------------------------------------------- 1 | num = int(input("Show the multiplication table of? ")) 2 | # use for loop to iterate multiplication 10 times 3 | for i in range(1,11): 4 | print(num,'x',i,'=',num*i) 5 | -------------------------------------------------------------------------------- /number guess game: -------------------------------------------------------------------------------- 1 | import random 2 | r = random.randint(1,20) 3 | 4 | while(True): 5 | inp = int(input()) 6 | if(inpr): 9 | print("oops,try a smaller number") 10 | else: 11 | print("congrats you choosed write number") 12 | break; 13 | -------------------------------------------------------------------------------- /oddeven: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | num = int(input("Enter a number: ")) 3 | mod = num % 2 4 | if mod > 0: 5 | print("This is an odd number.") 6 | else: 7 | print("This is an even number.") 8 | -------------------------------------------------------------------------------- /prime number: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | num = 407 4 | 5 | # To take input from the user 6 | #num = int(input("Enter a number: ")) 7 | 8 | # prime numbers are greater than 1 9 | if num > 1: 10 | # check for factors 11 | for i in range(2,num): 12 | if (num % i) == 0: 13 | print(num,"is not a prime number") 14 | print(i,"times",num//i,"is",num) 15 | break 16 | else: 17 | print(num,"is a prime number") 18 | 19 | # if input number is less than 20 | # or equal to 1, it is not prime 21 | else: 22 | print(num,"is not a prime number") 23 | -------------------------------------------------------------------------------- /printing pattern: -------------------------------------------------------------------------------- 1 | rows = 5 2 | for row in range(1, rows+1): 3 | for column in range(1, row + 1): 4 | print(column, end=' ') 5 | print("") 6 | -------------------------------------------------------------------------------- /pythonevenodd: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | if (num % 2) == 0: 3 | print("{0} is Even number".format(num)) 4 | else: 5 | print("{0} is Odd number".format(num)) 6 | -------------------------------------------------------------------------------- /pythonprime: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | num = 407 4 | 5 | # To take input from the user 6 | #num = int(input("Enter a number: ")) 7 | 8 | # prime numbers are greater than 1 9 | if num > 1: 10 | # check for factors 11 | for i in range(2,num): 12 | if (num % i) == 0: 13 | print(num,"is not a prime number") 14 | print(i,"times",num//i,"is",num) 15 | break 16 | else: 17 | print(num,"is a prime number") 18 | 19 | # if input number is less than 20 | # or equal to 1, it is not prime 21 | else: 22 | print(num,"is not a prime number") 23 | -------------------------------------------------------------------------------- /pythonprogram: -------------------------------------------------------------------------------- 1 | num = 407 2 | 3 | # To take input from the user 4 | #num = int(input("Enter a number: ")) 5 | 6 | # prime numbers are greater than 1 7 | if num > 1: 8 | # check for factors 9 | for i in range(2,num): 10 | if (num % i) == 0: 11 | print(num,"is not a prime number") 12 | print(i,"times",num//i,"is",num) 13 | break 14 | else: 15 | print(num,"is a prime number") 16 | 17 | # if input number is less than 18 | # or equal to 1, it is not prime 19 | else: 20 | print(num,"is not a prime number") 21 | -------------------------------------------------------------------------------- /simple interest: -------------------------------------------------------------------------------- 1 | # Python3 program to find simple interest 2 | # for given principal amount, time and 3 | # rate of interest. 4 | 5 | 6 | def simple_interest(p,t,r): 7 | print('The principal is', p) 8 | print('The time period is', t) 9 | print('The rate of interest is',r) 10 | 11 | si = (p * t * r)/100 12 | 13 | print('The Simple Interest is', si) 14 | return si 15 | 16 | # Driver code 17 | simple_interest(1000, 2, 5) 18 | -------------------------------------------------------------------------------- /solveQuadraticEq: -------------------------------------------------------------------------------- 1 | # Solve the quadratic equation ax**2 + bx + c = 0 2 | 3 | # import complex math module 4 | import cmath 5 | 6 | a = 1 7 | b = 5 8 | c = 6 9 | 10 | # calculate the discriminant 11 | d = (b**2) - (4*a*c) 12 | 13 | # find two solutions irrespective of the nature of roots 14 | sol1 = (-b-cmath.sqrt(d))/(2*a) 15 | sol2 = (-b+cmath.sqrt(d))/(2*a) 16 | 17 | # printing the solution of quatratic equation 18 | print('The solution are {0} and {1}'.format(sol1,sol2)) 19 | -------------------------------------------------------------------------------- /split.py: -------------------------------------------------------------------------------- 1 | def split_in_two(elements, num): 2 | if num%2 == 0: 3 | return elements[2:] 4 | else: 5 | return elements[:2] 6 | -------------------------------------------------------------------------------- /stringPopulation: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | import string 3 | def extract_popular(textstring): 4 | """ 5 | Input: string 6 | Output: dictionary with counts for each character in a string 7 | """ 8 | d = defaultdict(int) 9 | exclude = set(string.punctuation) 10 | textstring = textstring.lower() 11 | textstring = ''.join(ch for ch in textstring if ch not in exclude) 12 | for c in textstring: 13 | d[c] += 1 14 | counts = [(d[c], c) for c in d] 15 | counts.sort() 16 | counts.reverse() 17 | return counts 18 | print(extract_popular("A man, a plan, a canal: Panama")) 19 | print(extract_popular("Testing, attention please")) 20 | -------------------------------------------------------------------------------- /swaping of variables: -------------------------------------------------------------------------------- 1 | # Python program to swap two variables 2 | 3 | x = 5 4 | y = 10 5 | 6 | # To take inputs from the user 7 | #x = input('Enter value of x: ') 8 | #y = input('Enter value of y: ') 9 | 10 | # create a temporary variable and swap the values 11 | temp = x 12 | x = y 13 | y = temp 14 | 15 | print('The value of x after swapping: {}'.format(x)) 16 | print('The value of y after swapping: {}'.format(y)) 17 | -------------------------------------------------------------------------------- /tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' '] 5 | player = 1 6 | 7 | ########win Flags########## 8 | Win = 1 9 | Draw = -1 10 | Running = 0 11 | Stop = 1 12 | ########################### 13 | Game = Running 14 | Mark = 'X' 15 | 16 | #This Function Draws Game Board 17 | def DrawBoard(): 18 | print(" %c | %c | %c " % (board[1],board[2],board[3])) 19 | print("___|___|___") 20 | print(" %c | %c | %c " % (board[4],board[5],board[6])) 21 | print("___|___|___") 22 | print(" %c | %c | %c " % (board[7],board[8],board[9])) 23 | print(" | | ") 24 | 25 | #This Function Checks position is empty or not 26 | def CheckPosition(x): 27 | if(board[x] == ' '): 28 | return True 29 | else: 30 | return False 31 | 32 | #This Function Checks player has won or not 33 | def CheckWin(): 34 | global Game 35 | #Horizontal winning condition 36 | if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '): 37 | Game = Win 38 | elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '): 39 | Game = Win 40 | elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '): 41 | Game = Win 42 | #Vertical Winning Condition 43 | elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '): 44 | Game = Win 45 | elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '): 46 | Game = Win 47 | elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '): 48 | Game=Win 49 | #Diagonal Winning Condition 50 | elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '): 51 | Game = Win 52 | elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '): 53 | Game=Win 54 | #Match Tie or Draw Condition 55 | elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '): 56 | Game=Draw 57 | else: 58 | Game=Running 59 | 60 | print("Tic-Tac-Toe Game Designed By Sourabh Somani") 61 | print("Player 1 [X] --- Player 2 [O]\n") 62 | print() 63 | print() 64 | print("Please Wait...") 65 | time.sleep(3) 66 | while(Game == Running): 67 | os.system('cls') 68 | DrawBoard() 69 | if(player % 2 != 0): 70 | print("Player 1's chance") 71 | Mark = 'X' 72 | else: 73 | print("Player 2's chance") 74 | Mark = 'O' 75 | choice = int(input("Enter the position between [1-9] where you want to mark : ")) 76 | if(CheckPosition(choice)): 77 | board[choice] = Mark 78 | player+=1 79 | CheckWin() 80 | 81 | os.system('cls') 82 | DrawBoard() 83 | if(Game==Draw): 84 | print("Game Draw") 85 | elif(Game==Win): 86 | player-=1 87 | if(player%2!=0): 88 | print("Player 1 Won") 89 | else: 90 | print("Player 2 Won") 91 | -------------------------------------------------------------------------------- /twilio_sms.py: -------------------------------------------------------------------------------- 1 | from twilio.rest import Client 2 | 3 | sid = #write here sid number 4 | token = #write token number here 5 | client = Client(sid,token) 6 | 7 | my_msg = "Hi, It's Working correctly...☺" 8 | 9 | client.messages.create( 10 | to= #type here number to whom you're sending , 11 | from_= #type your number , 12 | body=my_msg 13 | ) 14 | --------------------------------------------------------------------------------