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