diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 071fd27..c64af25 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,4 @@ # What You Waiting For Fork it! Feel free to fork the repository and make changes! If you feel there is need to change something pull request! -I'll check and review the changed program if it adds anu value to the repo i'll definitely merge it! +I'll check and review the changed program if it adds any value to the repo i'll definitely merge it! diff --git a/Display ASCII Value of a Character.py b/Display ASCII Value of a Character.py new file mode 100644 index 0000000..04ad522 --- /dev/null +++ b/Display ASCII Value of a Character.py @@ -0,0 +1,7 @@ +# ASCII Value of Character + +# Simply ender a character from the keyboard +user_input = input('Give me a character: ') + +# Print the ASCII value of assigned character +print("The ASCII value of '" + user_input + "' is", ord(user_input)) diff --git a/Double the number pattern b/Double the number pattern new file mode 100644 index 0000000..6864bfd --- /dev/null +++ b/Double the number pattern @@ -0,0 +1,5 @@ +rows = 9 +for i in range(1, rows): + for j in range(-1+i, -1, -1): + print(format(2**j, "4d"), end=' ') + print("") diff --git a/Drawing_With_Turtle.py b/Drawing_With_Turtle.py new file mode 100644 index 0000000..ecd2987 --- /dev/null +++ b/Drawing_With_Turtle.py @@ -0,0 +1,11 @@ +#This is a example for turtle +#This shows how to draw a star +#For more tutorials visit https://www.tutorialspoint.com/turtle-programming-in-python + +# import turtle library +import turtle +my_pen = turtle.Turtle() +for i in range(50): + my_pen.forward(50) + my_pen.right(144) +turtle.done() \ No newline at end of file diff --git a/Medium level python program b/Medium level python program new file mode 100644 index 0000000..74a4b84 --- /dev/null +++ b/Medium level python program @@ -0,0 +1,5 @@ +rows = 6 +for row in range(1, rows): + for column in range(row, 0, -1): + print(column, end=' ') + print("") diff --git a/Pattern Program b/Pattern Program new file mode 100644 index 0000000..cf143f1 --- /dev/null +++ b/Pattern Program @@ -0,0 +1,5 @@ +rows = 6 +for num in range(rows): + for i in range(num): + print(num, end=" ") # print number + print(" ") diff --git a/Pattern Python Program b/Pattern Python Program new file mode 100644 index 0000000..759efd3 --- /dev/null +++ b/Pattern Python Program @@ -0,0 +1,6 @@ +rows = 5 +for i in range(rows, 0, -1): + num = i + for j in range(0, i): + print(num, end=' ') + print("\r") diff --git a/README.md b/README.md index 69c471f..619621c 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,18 @@ # Beginners-Python-Programs -Basic python CLI programs as examples
-All the examples are useful examples
-This examples are of beginners level
-
-Hey guys i wrote these programs when i was just starting up with programming, now i realize that many of 'em feel very un-professional and useless so i decided to go one by one through all and make 'em more usefull and professional ! -
+[18 Nov 2025] Final Update: This was my first Repo and I created it when I was fairly young and completely new to computer programming. I no longer have time to update/maintain it in anyway.
Thus, starting today, This Repository will be available as a Public Archive only.

-Note: In 2.x versions input isn't useful , lly , in 3.x versions raw_input isn't useful. Also, xrange() and other methods are discontinued or changed in 3.x versions of python. Change the keywords accordingly! +Basic python CLI programs as examples.
+All the examples are useful examples.
+These examples are of beginner level.
-
-NOTE: WORK IN PROGRESS!
-Files Outside Particular Folders/Directories have not been checked yet!
-Files inside, directories offer much elegant code and explaination
-
-
-

+Note: In 2.x versions input isn't useful. Similarly, in 3.x versions raw_input isn't useful. Also, xrange() and other methods are discontinued or changed in 3.x versions of Python. Change the keywords accordingly. + +
+Update: I wrote these programs when I was just starting out with programming, now I realize that many of them seem quite amateur in their rendering so I've decided to audit through all of them and update them according to my current capabilities. +
+
+Files outside particular directories have not been checked yet
+Files inside, directories offer better code and explanation +
+
Also see this : Beginners-Python-Examples/CONTRIBUTING.md
-contact kalpaktake@gmail.com diff --git a/Turtle_Drawing.py b/Turtle_Drawing.py new file mode 100644 index 0000000..f979857 --- /dev/null +++ b/Turtle_Drawing.py @@ -0,0 +1,21 @@ +import turtle + +ninja = turtle.Turtle() + +ninja.speed(10) + +for i in range(180): + ninja.forward(100) + ninja.right(30) + ninja.forward(20) + ninja.left(60) + ninja.forward(50) + ninja.right(30) + + ninja.penup() + ninja.setposition(0, 0) + ninja.pendown() + + ninja.right(2) + +turtle.done() \ No newline at end of file diff --git a/algorithms/analysis/bigo_notation.py b/algorithms/analysis/bigo_notation.py new file mode 100644 index 0000000..34e673e --- /dev/null +++ b/algorithms/analysis/bigo_notation.py @@ -0,0 +1,24 @@ +from math import log +import numpy as np +import matplotlib.pyplot as plt +%matplotlib inline +plt.style.use('bmh') + +# Set up runtime comparisons + +n = np.linspace(1,10,1000) +labels = ['Constant','Logarithmic','Linear','Log Linear','Quadratic','Cubic','Exponential'] +big_o = [np.ones(n.shape),np.log(n),n,n*np.log(n),n**2,n**3,2**n] + +# Plot setup + +plt.figure(figsize=(12,10)) +plt.ylim(0,50) + +for i in range(len(big_o)): + plt.plot(n,big_o[i],label = labels[i]) + + +plt.legend(loc=0) +plt.ylabel('Relative Runtime') +plt.xlabel('n') diff --git a/algorithms/sorting/bubble_sort.py b/algorithms/sorting/bubble_sort.py index 9074ad0..e1fe084 100644 --- a/algorithms/sorting/bubble_sort.py +++ b/algorithms/sorting/bubble_sort.py @@ -67,7 +67,7 @@ def sort_(arr, temporary = False, reverse = False): # See proper explaination # at: https://www.geeksforgeeks.org/bubble-sort/ # a good site! - +#can add flag to reduce time complexity # Testing tests = [[7, 8, 9, 6, 4, 5, 3, 2, 1, 15], [1, 90, 1110, 1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases diff --git a/algorithms/sorting/insertion_sort.py b/algorithms/sorting/insertion_sort.py new file mode 100644 index 0000000..54adf00 --- /dev/null +++ b/algorithms/sorting/insertion_sort.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +# Insertion Sort +# Ideal sorting algorithm for +# small/small-medium data/array + +# temporary parameter tells +# function to sort a copy of +# orignal array, and not the array itself + +# reverse parameter tells func +# to sort array in reverse/decending +# order + + +def sort_(arr,temporary=False,reverse=False): + + # Making copy of array if temporary is true + if temporary: + ar = arr[:] + else: + ar = arr + + # To blend every element + # in correct position + # length of total array is required + length = len(ar) + + # After each iteration left-most + # sub-array is completed sorted + for i in range(1,length): + # In each iteration we place + # the current element to its + # proper position in left sorted + # sub array + tmp = ar[i] + j = i-1 + if reverse: + while j>=0 and tmp>ar[j]: + ar[j+1]=ar[j] + j-=1 + ar[j+1]=tmp + else: + while j>=0 and tmpar[j]: + min = j + + + # Replacing minimum/maximum + # with current element + tmp = ar[i] + ar[i]=ar[min] + ar[min]=tmp + + + + # if temporary, then returning + # copied arr's sorted form + # cuz if not returned, then function + # is literally of no use + if temporary: + return ar + + +# See proper explaination +# at: https://www.hotdogcode.com/selection-sort/ + + +# Testing +tests = [[7, 8, 9, 6, 4, 5, 3, 2, 1, 15], [1, 90, 1110, 1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases + +for test in tests: + accend, decend = sort_(test, True), sort_(test, True, True) + if accend == sorted(test) and decend == sorted(test, reverse = True): + print("Orignal: {}".format(test)) + print("Sorted: {}".format(accend)) + print("Sorted(reverse): {}\n".format(decend)) + else: + print("Something went wrong!\n") + + +# Seems our selection sort works +# however for small/small-medium data/array! + diff --git a/algorithms/string/check_anagram.py b/algorithms/string/check_anagram.py new file mode 100644 index 0000000..ec2532a --- /dev/null +++ b/algorithms/string/check_anagram.py @@ -0,0 +1,26 @@ +'''An anagram is a word or phrase created by rearranging the letters of another word or phrase. +For example, the word "heart" can be rearranged to form the word "earth". +So, "heart" and "earth" are anagrams of each other.''' + +def check_anagram(str1,str2): + # Remove all spaces from both the strings + # and convert them to lowercase + str1 = str1.replace(" ","").lower() + str2 =str2.replace(" ","").lower() + # if the length of both strings are not equal then return false + if len(str1) != len(str2): + return False + count1 = {} + count2 = {} + for i in range(len(str1)): + count1[str1[i]] = 1+count1.get(str1[i],0) + count2[str2[i]] = 1+count2.get(str2[i],0) + for c in count1: + if count1[c] != count2.get(c,0): + return False +str1 = input() +str2 = input() +if check_anagram(str1,str2): + print(f"{str1} and {str2} are anagrams") +else: + print(f"{str1} and {str2} are anagrams") \ No newline at end of file diff --git a/ansi-colors.py b/ansi-colors.py new file mode 100644 index 0000000..2d4f174 --- /dev/null +++ b/ansi-colors.py @@ -0,0 +1,42 @@ +""" +ansi-colors.py +Print 256 ANSI(8bit) color chart +Reference : https://en.wikipedia.org/wiki/ANSI_escape_code + +*** Warning! +In some terminal/OS environments, +this code may display different colors or color may not be displayed properly +""" + +START_ESCAPE_8BIT = "\033[38;5;" +END_ESCAPE = "\033[0;0m" +SQUARE_CHAR = '\u25A0' + + +def print_square_8bit(color): + print(START_ESCAPE_8BIT + str(color) + 'm' + SQUARE_CHAR + END_ESCAPE, end="") + + +print("System standard colors: ", end="") +for i in range(8): + print_square_8bit(i) +print() + +print("System high intensity colors: ", end="") +for i in range(8, 16): + print_square_8bit(i) +print() + +step = 0 +print("216 Colors: ") +for i in range(16, 232): + print_square_8bit(i) + step += 1 + if step % 24 == 0: # Make newline every 24 colors + print() +print() + +print("Grayscale colors: ", end="") +for i in range(232, 256): + print_square_8bit(i) +print() diff --git a/armstrong_number.py b/armstrong_number.py new file mode 100644 index 0000000..f0e8d9d --- /dev/null +++ b/armstrong_number.py @@ -0,0 +1,27 @@ +# Python program to check if the number is an Armstrong number with the index of 3 or not +# for input try numbers 153, 370, 371, 407 + +# take input from the user +num = int(input("Enter a number: ")) + +# initialize sum +sum = 0 +# finding the length of num +n = len(str(num)) + +# find the sum of the cube of each digit +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** n # power of n + temp //= 10 + +# display the result +if num == sum: + print(num, "is an Armstrong number.") +else: + print(num, "is not an Armstrong number.") + + + +# Originally contribution by denz647 diff --git a/bell_number.py b/bell_number.py new file mode 100644 index 0000000..4b47e6f --- /dev/null +++ b/bell_number.py @@ -0,0 +1,24 @@ +# Contribution by https://github.com/nightwarriorftw + +#Python program to print bell number +#Bell Number:-Let S(n, k) be total number of partitions of n elements into k sets. The value of n’th Bell Number is sum of S(n, k) for k = 1 to n. Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1) +A sample Bell triangle is as follows: +1 +1 3 +3 8 13 +13 23 33 43 +#The code to print the bell triangle is as follows- +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +n=int(input("enter the number of bell")) #taking value from the user +bell=0 #initialising bell to 'zero' +k=0 #initialising k to 'zero' +for i in range(0,n): #loop for changing rows from 0 to n + for j in range(0,i+1): #printing columns + if j==0 and i>0: #repeating the last number of previous row in new row + print(bell,'',end='') #printing first number of each line + else: + k=(i**2)+1+bell #to generate other numbers of line + print(k,'',end='') #printing other number in lines + bell=k #updating value of bell + print('\n') #for moving into next lines +print("last number of bell is",bell) diff --git a/bigo_notation.py b/bigo_notation.py new file mode 100644 index 0000000..76670b7 --- /dev/null +++ b/bigo_notation.py @@ -0,0 +1,26 @@ +# Contribution from https://github.com/Alok070899 + +from math import log +import numpy as np +import matplotlib.pyplot as plt +%matplotlib inline +plt.style.use('bmh') + +# Set up runtime comparisons + +n = np.linspace(1,10,1000) +labels = ['Constant','Logarithmic','Linear','Log Linear','Quadratic','Cubic','Exponential'] +big_o = [np.ones(n.shape),np.log(n),n,n*np.log(n),n**2,n**3,2**n] + +# Plot setup + +plt.figure(figsize=(12,10)) +plt.ylim(0,50) + +for i in range(len(big_o)): + plt.plot(n,big_o[i],label = labels[i]) + + +plt.legend(loc=0) +plt.ylabel('Relative Runtime') +plt.xlabel('n') diff --git a/bubble sort.py b/bubble sort.py new file mode 100644 index 0000000..a28bad4 --- /dev/null +++ b/bubble sort.py @@ -0,0 +1,47 @@ +'''Bubble Sort +Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. +Example: +First Pass: +( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. +( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 +( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 +( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. + +Second Pass: +( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) +( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) +Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. + +Third Pass: +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )''' + +# Python program for implementation of Bubble Sort + +def bubbleSort(arr): + n = len(arr) + + # Traverse through all array elements + for i in range(n): + + # Last i elements are already in place + for j in range(0, n-i-1): + + # traverse the array from 0 to n-i-1 + # Swap if the element found is greater + # than the next element + if arr[j] > arr[j+1] : + arr[j], arr[j+1] = arr[j+1], arr[j] + +# Driver code to test above +arr = [64, 34, 25, 12, 22, 11, 90] + +bubbleSort(arr) + +print ("Sorted array is:") +for i in range(len(arr)): + print ("%d" %arr[i]), diff --git a/cartesian_plane_quadrant.py b/cartesian_plane_quadrant.py index 606aec8..3631e97 100644 --- a/cartesian_plane_quadrant.py +++ b/cartesian_plane_quadrant.py @@ -12,7 +12,7 @@ def determine_quadrant(x, y): elif x > 0 and y < 0 : return 'IV(+,-)' else : - return 'Invalid parameters were provided') + return 'Invalid parameters were provided' except TypeError: return "X and Y co-ords must be integers and not X {}, Y{}".format(type(x), type(y)) diff --git a/client_file.py b/client_file.py new file mode 100644 index 0000000..1d9a17f --- /dev/null +++ b/client_file.py @@ -0,0 +1,20 @@ +import socket +server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) +host = socket.gethostbyname(socket.gethostname()) +port = 12345 +x = input("Enter file name : ") +server_socket.connect((host,port)) +name = server_socket.recv(1024).decode() +name = name.split('.')[-1] +name = x+'.'+name + +f = open(name,'wb') +while True : + c_msg = server_socket.recv(1024) + if c_msg == 'EOF'.encode() : + f.close() + server_socket.close() + break + f.write(c_msg) + + diff --git a/conways.py b/conways.py new file mode 100644 index 0000000..a834d76 --- /dev/null +++ b/conways.py @@ -0,0 +1,140 @@ +''' +-conway's game of life +-made by Tzara Northcut @Mecknavorz +-requires pygame +''' + +#import the stuff we need +import pygame, sys, time + +#----------------------------------------- +#initalize some variables and other things +#----------------------------------------- +width = 6 #cell size width +height = 6 #cell size height +space = 2 #thickness of world lines +#create the 2d array where we actually store vairables of cells +world = [[0 for x in range(100)] for y in range(100)] + +#initialzie pygame +pygame.init() + +size = [100*(width+space)+space, 100*(height+space)+space] #window size +screen = pygame.display.set_mode(size) #make the window the right size + +#set spme colors +BLACK = ( 0, 0, 0) #background color +WHITE = (255, 255, 255) #color of world +GREEN = ( 0, 0, 0) #color of cells that are alive and well +RED = (255, 0, 0) #colors of the cells about to die + +#speed stuff +clock = pygame.time.Clock() #clock used to manage game speed +pause = True #used to control the steps, might not need this +laststep = time.time() + +#used to keep runing until the game is closed +done = False + +#------------------------------------- +#some functions to be used in the game +#------------------------------------- +#determine #of cells nearby +def getclose(x, y): + nearby = 0 + #avoid out of bounds error and make the grid a torroid + if(x+1) > 99: + x = 0 + if(y+1) > 99: + y = 0 + #swcan nearby squares and if there's something there add 1 to the count + if world[x-1][y-1]: + nearby += 1 + if world[x][y-1]: + nearby += 1 + if world[x+1][y-1]: + nearby += 1 + if world[x-1][y]: + nearby += 1 + if world[x+1][y]: + nearby += 1 + if world[x-1][y+1]: + nearby += 1 + if world[x][y+1]: + nearby += 1 + if world[x+1][y+1]: + nearby += 1 + return nearby + +#calculate next step +def nextStep(): + for x in range(len(world)): + for y in range(len(world[0])): + near = getclose(x, y) + if near < 2: #if there are less than two neighbors then kill the cell + world[x][y] = 0 + if near > 3: #if there are more than three neighbors then kill the cell + world[x][y] = 0 + if (world[x][y] == 0) and (near == 3): #if there are 3 neighbors near a dead cell, revive it + world[x][y] = 1 + +#clear the board +def clear(): + for x in range(len(world)): + for y in range(len(world[0])): + world[x][y] = 0 + +#--------------------- +#the initale game loop +#--------------------- +while not done: + #to make sure the game quits when we need it to + for event in pygame.event.get(): + if event.type == pygame.QUIT: + done = True + elif event.type == pygame.MOUSEBUTTONDOWN: #if we get a click + pos = pygame.mouse.get_pos() #find where the click was + #change the pixel coords into game coords + x = pos[1] // (height+space) + y = pos[0] // (width+space) + #add or remove the cell that's there + if world[x][y] == 0: #if the tile is empty add a cell + world[x][y] = 1 + #print("nearby: ", getclose(x, y)) #used for debugging + else: #else if there's something there, remove the cell + world[x][y] = 0 + #print("click: ", pos, "grid coord: ", x, y) #debug stuff + elif event.type == pygame.KEYDOWN: #pause the game when space is pressed + if event.key == pygame.K_SPACE: + #print('space pressed') + if pause: + pause = False + elif not pause: + pause = True + elif event.key == pygame.K_RIGHT: #if we presws the right key go forward a step + nextStep() #calculate the next + elif event.key == pygame.K_ESCAPE: + clear() + + + #draw the world + screen.fill(BLACK) + #maybe move this to a seprate function to help with effeciency? + for x in range(len(world)): + for y in range(len(world[0])): + color = WHITE + if world[x][y] == 1: + color = GREEN + pygame.draw.rect(screen, color, [(space+width)*y+space, (space+height)*x+space, width, height]) + + #set frame rate + clock.tick(60) + if (not pause) and ((time.time() - laststep) > .1): + laststep = time.time() + #print(laststep) + nextStep() + #update screen + pygame.display.flip() + +#if we;ve gotten this far (eg out of the while loop) we know it's time to quit +pygame.quit() diff --git a/days_you_lived.py b/days_you_lived.py index c41e4a1..4b1118e 100644 --- a/days_you_lived.py +++ b/days_you_lived.py @@ -1,7 +1,6 @@ # We assume that given dates are correct # and # solved for problem set in cs course on udacity.com - from calendar import isleap def daysBetweenDates(year1, month1, day1, year2, month2, day2): @@ -26,3 +25,12 @@ def daysBetweenDates(year1, month1, day1, year2, month2, day2): days += sum(dom) return days + +date1=input("Enter a first date in YYYY-MM-DD format") +year1,month1,day1=map(int,date1.split('-')) + +date2=input("Enter a second date in YYYY-MM-DD format") +year2,month2,day2=map(int,date2.split('-')) + +days=daysBetweenDates(year1, month1, day1, year2, month2, day2) +print("Number of days between {} and {} is \n {}".format(date1,date2,abs(days))) diff --git a/dictionary.py b/dictionary.py index ea2c9b2..66eb87c 100644 --- a/dictionary.py +++ b/dictionary.py @@ -1,4 +1,3 @@ - global dictionary dictionary = {} @@ -9,53 +8,53 @@ def __init__(self, word, meaning): def add_new(self): dictionary[self.word] = self.meaning - print "Word Successfully Added" + print("Word Successfully Added") def delete_word(self): try: del dictionary[self.word] - print "Word Successfully Deleted" + print("Word Successfully Deleted") except KeyError: - print "The Word Does Not Exist in Dictionary. Try Again!" + print("The Word Does Not Exist in Dictionary. Try Again!") def edit_word(self): try: dictionary[self.word] = self.meaning - print "Word Was Successfully Edited" + print("Word Was Successfully Edited") except KeyError: - print "The Word You Trying To Edit Does Not Exist in Dictionary!" + print("The Word You Trying To Edit Does Not Exist in Dictionary!") def view_word(self): try: - print dictionary[self.word] + print(dictionary[self.word]) except KeyError: - print "The Word is not in Dictionary." + print("The Word is not in Dictionary.") def view_all(self): for i in dictionary.keys(): - print(i + " : " + dictionary[i]) + print(f"{i} : {dictionary[i]}") def start(): - get_op = raw_input("Add, Delete, Edit, View, View all : ") + get_op = input("Add, Delete, Edit, View, View all : ") if get_op in ["add", "Add"]: - get_word = raw_input("Word to add : ") - get_meaning = raw_input("Meaning : ") + get_word = input("Word to add : ") + get_meaning = input("Meaning : ") new = Dict(get_word, get_meaning) new.add_new() elif get_op in ["delete", "Delete"]: - get_word_to_del = raw_input("Word to delete : ") + get_word_to_del = input("Word to delete : ") delete = Dict(get_word_to_del, None) delete.delete_word() elif get_op in ["edit", "Edit"]: - get_word_to_edit = raw_input("Word to edit : ") - get_new_meaning = raw_input("New meaning : ") + get_word_to_edit = input("Word to edit : ") + get_new_meaning = input("New meaning : ") mean = Dict(get_word_to_edit, get_new_meaning) mean.edit_word() elif get_op in ["view", "View"]: - get_word_to_view = raw_input("Word to view : ") + get_word_to_view = input("Word to view : ") view = Dict(get_word_to_view, None) view.view_word() @@ -64,15 +63,15 @@ def start(): nothing.view_all() else: - print "Invalid Input. Try again!" + print("Invalid Input. Try again!") def end(): quit() def main(): while True: - s_or_e = raw_input("Start or End : ") - if s_or_e == "Start": + s_or_e = input("Start or End : ") + if s_or_e.lower() == "start": start() print(" ") continue @@ -82,4 +81,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/euclids_algorithm.py b/euclids_algorithm.py new file mode 100644 index 0000000..b17ef72 --- /dev/null +++ b/euclids_algorithm.py @@ -0,0 +1,16 @@ +# Recursive implementation of Euclidean algorithm +def gcd(m, n): + """ + Calculates the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm. + + Args: + m (int): First positive integer. + n (int): Second positive integer. + + Returns: + int: The GCD of m and n. + """ + (a, b) = (max(m, n), min(m, n)) + while b != 0: + a, b = b, a % b + return a \ No newline at end of file diff --git a/factorial.py b/factorial.py new file mode 100644 index 0000000..a58fc51 --- /dev/null +++ b/factorial.py @@ -0,0 +1,7 @@ +def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n-1) +n=int(input("Input a number to compute the factiorial : ")) +print(factorial(n)) diff --git a/find_square_root.py b/find_square_root.py index 15d0920..4c6212f 100644 --- a/find_square_root.py +++ b/find_square_root.py @@ -7,7 +7,7 @@ def find_square_root(x): if type(x) == str: return "Expected an integer! Cannot find square root of an string!" - for i in range(x): + for i in range(0, (x/2 )+2): if i ** 2 == x: return i return "{} is not a perfect square".format(x) diff --git a/hello_world.py b/hello_world.py index 48de24b..dc0ea25 100644 --- a/hello_world.py +++ b/hello_world.py @@ -2,7 +2,34 @@ # it is normally used to if check everything is okay import sys +#type 1 sys.stdout.write() sys.stdout.write("Hello, ") sys.stdout.write("World!") sys.stdout.write("\n") + +#type 2 print() print("Hello, World!") + +#type 3 - format() + +word1 = "Hello" +word2 = "World" +print("{} {}".format(word1, word2)) + +#type 4 - f-strings +word1 = "Hello" +word2 = "World" +print(f"{word1} {word2} ") + + +#type 5 - join +characters = ['H','e','l','l','o',' ','W','o','r','l','d'] +message = "".join(characters) +print(message) + +#type 6 - Dict +words = {"Eng_greeting": "Hello", "Eng_world": "World"} +message = " ".join(words.values()) +print(message) + + diff --git a/map_example.py b/map_example.py new file mode 100644 index 0000000..7a14c01 --- /dev/null +++ b/map_example.py @@ -0,0 +1,13 @@ +# Contribution by https://github.com/tyadav4268 + +#This is to demonstrate the use of map function in python +#Problem Statement: Using the function Map, count the number of words that start with ‘S’ in input_list. +#Sample Input: ['Santa Cruz','Santa fe','Mumbai','Delhi'] +#Sample Output: 2 + +#Solution: +input_list = ['Santa Cruz','Santa fe','Mumbai','Delhi'] + +count = sum(map(lambda x: x[0] == 'S', input_list)) + +print(count) # Output: 2 diff --git a/math/Binary_to_decimal b/math/Binary_to_decimal new file mode 100644 index 0000000..5a82316 --- /dev/null +++ b/math/Binary_to_decimal @@ -0,0 +1,62 @@ +# binary_to_decimal.py +# +# Description: A program to evaluate binary to decimal. +# +# Author: Chaitanya Mittal +# Date: 2023-11-17 10:14:20.288913 + +"""Idea: +- def a function to decode 1 byte: + - get the list + - get value by multiplying each element with 2** its index from reverse (pattern observation) + .... (instead of this we can multiply index to list reversed)...... + - return the sum of value + +- get input +- split it to get rid of spaces (assume user is well behaved and will enter 1-space separated string only) +- convert each byte and compile result in a list +- print the converted bytes separated by space +""" + + +def byte_decode(binary): + # Convert binary string to list + lst = list(binary)[::-1] + + # Initialize variables + length = len(binary) + sum = 0 + + # Loop through each character in the binary string + for i in range(length): + # Calculate value of each bit + value = int(lst[i]) * (2 ** i) + + # Add value to the sum + sum += value + + # Return the final sum + return sum + +# ____ Main Program ____ # + +# Get input of the required binary string +binary = input("Binary: ").split(" ") +""" TESTING PURPOSES +string = ("01010101 01101110 01100100 01100101 0110010 00100000 01011001 01101111 01110101 01110010 00100000 01010011 01100101 01100001 01110100").split() +binary = list(string)""" + +# Initialize an empty list to store 'evaluated' bytes +bytes_translated = list() +#translate the byte and append it to the list +for byte in binary: + bytes_translated.append(byte_decode(byte)) + +# Print the output +print(f'Evaluated: ', end = "") +for byte in bytes_translated: + print(byte, end = " ") +print() + + + diff --git a/math/FreefallCalculator b/math/FreefallCalculator new file mode 100644 index 0000000..47e8164 --- /dev/null +++ b/math/FreefallCalculator @@ -0,0 +1,62 @@ +# Gravity Simulation + +import math +import numpy as np + +# Welcome + +print("Welcome to a 1D Free Fall Simulation. Please enter only in metric integers. ") +print("You will enter the amount of time you want to simulate, it includes information about impact, \n" + "even if the simulation stops before impact.") + +# Constants + +g = 9.81 + +# Variables + +height = int(input("Drop Height: ")) +timeElapsed = 1 +runTime = int(input("How long do you want to record data from the fall? ")) +location = 0 +mass = int((input("Mass: "))) +timeToImpact = 0 + +# Simulation + +print("Second by second info of free fall in given time.") +while timeElapsed <= runTime and timeToImpact >= 0 and location >= 0: + + # Equations + + distanceTraveled = (g * timeElapsed ** 2) / 2 + velocity = distanceTraveled / timeElapsed + location = height - distanceTraveled + momentum = mass * velocity + timeToImpact = math.sqrt((2 * height) / g) + + # Print Stats + + print("\nTime to simulation end: " + str(runTime - timeElapsed)) + print('Y Location: ' + str(location) + 'M') + print('Velocity: ' + str(velocity) + 'M/S') + print('Distance Traveled: ' + str(distanceTraveled) + 'M') + print('Momentum: ' + str(momentum) + 'N') + print('Time Elapsed: ' + str(timeElapsed)) + print('Rough time to impact: ' + str(timeToImpact - timeElapsed)) + print() + + # Add to time elapsed + + timeElapsed = timeElapsed + 1 + +# Print impact results + +print("\n The Simulation is done. \n") +print("*This is printed even if the object fell past the ground, or never hit it.* \n Info on impact: ") +print('Y Location: 0M') +print('Velocity: ' + str(height / runTime) + 'M/S') +print('Distance Traveled: ' + str(height) + 'M') +print('Momentum: ' + str(mass * (height / runTime)) + 'N') +print('Time Spent in free fall: ' + str(timeToImpact)) +print() diff --git a/math/decimal_to_binary_converter.py b/math/decimal_to_binary_converter.py new file mode 100644 index 0000000..eb5003f --- /dev/null +++ b/math/decimal_to_binary_converter.py @@ -0,0 +1,21 @@ +""" +I came up with this algorithm to convert decimal(natural numbers only xd) to binary completely from scratch and +therefore it might not be the best most efficient implementation. +Optimizations are welcome. +""" + +def dec_to_bin(n): + quo = n + binary = 0 + while (quo>0): + tmp = quo + pows = 0 + while (quo > 1): + quo = quo // 2 + pows = pows + 1 + quo = tmp-pow(2,pows) + binary = binary+pow(10,pows) + return binary + +for i in range(0,101): + print("Natural Number:"+str(i)+" Binary:"+str(dec_to_bin(i))) diff --git a/primeNumbers.py b/primeNumbers.py index 14b5975..dcdb9a0 100644 --- a/primeNumbers.py +++ b/primeNumbers.py @@ -1,25 +1,50 @@ # Prime number Determiner # replace input() with raw_input() in Python version 2.7 input() works with version 3 +import math as Math -while True: - startOrEnd = str(input('Start or End : ')) - if startOrEnd == 'Start': - toCheckNum = int(input('Number to Check : ')) - if toCheckNum > 1: - for x in range(2, toCheckNum): - if toCheckNum % x == 0: - print(str(toCheckNum) + ' is divisible by ' + str(x)) - print(str(toCheckNum) + ' is not a Prime number') - break - elif toCheckNum % x > 0: - print(str(toCheckNum) + ' is a prime number') - break - continue - else : - print(str(toCheckNum) + ' is not a prime number') - continue - else : - print('Progarm Ended...') - break +POSITIVE_MESSAGE = " is a prime number" +NEGATIVE_MESSAGE = " is not a prime number" + + +def is_number_prime(number): + """ + Function which checks whether the number is a prime number or not + :param number: integer - to be checked for prime-ness + :return: boolean - true if prime, else false + """ + + """ + This is the main logic behind reducing the numbers to check for as factors + if N = a * b; where a<=b and a,b C (1, N) + then, a * b >= a*a; + which leads to => a*a <= N + => a <= sqrt(N) + Hence checking only till the square root of N + """ + upper_lim = Math.floor(Math.sqrt(number)) + 1 + is_prime = True if number != 1 else False + for i in range(2, upper_lim): + if number % i == 0: + is_prime = False + break + # The moment there is a divisor of 'number', break the iteration, as the number is not prime + + return is_prime + + +while True: + startOrEnd = str(input('Start or End : ')) + if startOrEnd == 'Start': + number = int(input('Number to Check : ')) + result = str(number) + prime_status = is_number_prime(number) + if prime_status: + result += POSITIVE_MESSAGE + else: + result += NEGATIVE_MESSAGE + print(result) + else: + print('Program Ended...') + break diff --git a/server_file.py b/server_file.py new file mode 100644 index 0000000..9389c5f --- /dev/null +++ b/server_file.py @@ -0,0 +1,22 @@ +import socket +server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) +host = socket.gethostbyname(socket.gethostname()) +port = 12345 +server_socket.bind((host,port)) +print("Server socket sucessfully Created on IP : {} at port {} ".format(host,port)) +server_socket.listen() +print("Server is waiting for clients to connect .... \n\n") +client_socket,client_addr = server_socket.accept() +print("Client is connected") +print("Client's IP {}:{}\n\n".format(*client_addr)) +f = open(input("Enter path to your file "),'rb') +name =f.name +client_socket.send(name.encode()) +for line in f: + client_socket.send(line) +else : + client_socket.send("EOF".encode()) + client_socket.close() + server_socket.close() + + diff --git a/shell_games/number_guessing_game.py b/shell_games/number_guessing_game.py index 1f428ba..44aee9f 100644 --- a/shell_games/number_guessing_game.py +++ b/shell_games/number_guessing_game.py @@ -1,40 +1,50 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- +#!/usr/bin/python3 +from random import randint -from random import randint as r_int +MAX_ = 500 # Specify biggest possible value from random number generation -# generates a random number -# in inclusive list from 0 to 10 -n = r_int(0, 10) -print("Hint: number is between 0 to 10 including 0 and 10\n") +# Asks user for a guess and returns this when successful +def get_guess(): + while True: # Run forever, until broken + try: # Try the following, if fails, run the except statment + user_input = int(input("Guess a number: ")) # Get user input and covert it to an int (number) + break # If the input can be converted, break the loop + except ValueError: # This runs if the input could not be converted - text was entered + print("Enter a number!\n") # Tell them to enter a number, then run loop again + return user_input # Return value when loop broken +num_to_guess = randint(0, MAX_) # Generates a random number between 0 and value of MAX_ +print("Welcome to my random number guessing game!\nGuess a number between 0 and ", MAX_, "\n") while True: - usr = int(raw_input("Guess a number: ")) - - # Make sure user got the hint - if usr <= 10 and usr >= 0: + guess = get_guess() + if guess >= 0 and guess <= MAX_: # Check if guess between 0 and max - # if correct - if usr == n: + # Correct number! + if guess == num_to_guess: print("That's a correct guess!\nYou got it!\n") break - # brings user closer to answer - elif usr < n: - print("Try a bigger num!") + # Incorrect - give hint + elif guess < num_to_guess: + print("Try a bigger num!") # Number to small else: - print("Try a smaller num!") + print("Try a smaller num!") # Number to big + # Number is not in range else: - print("Pls read the hint!") + print("Enter a number in between 0 and ", MAX_) - # Continue till guess does not match 'n' - # the random number print("") - continue -# Is an infinite loop if usr keeps guessing wrong -# an extra loop can be added to play game as long as user wants -# or can play number of times the user entered! -# Also can be made more harder to play +''' + +*Challenge* + + 1) Can you give the user the option to Play Again? + - if yes, the game will reset - including the random number + + 2) Try count the number of guesses and give a score to the user when they guess the number + - the lower the guesses, the higher the score + +''' diff --git a/simple_scripts/ListExample.py b/simple_scripts/ListExample.py new file mode 100644 index 0000000..131a26a --- /dev/null +++ b/simple_scripts/ListExample.py @@ -0,0 +1,23 @@ +my_list = ['p','y','t','h','o','n'] +# Output: p +print(my_list[0]) + +# Output: t +print(my_list[2]) + +# Output: o +print(my_list[4]) + +# Error! Only integer can be used for indexing +# my_list[4.0] + +# Nested List +n_list = ["Happy", [2,0,1,5]] + +# Nested indexing + +# Output: a +print(n_list[0][1]) + +# Output: 5 +print(n_list[1][3]) diff --git a/simple_scripts/README.md b/simple_scripts/README.md index 62e18b5..b572e3f 100644 --- a/simple_scripts/README.md +++ b/simple_scripts/README.md @@ -3,7 +3,6 @@ 'simple_scripts' Sub-directory contains all simplest programs, these programs are simple to read/write. -The programs have been re-checked and re-mastered by me!
+The programs have been re-checked and improved a bit
Although i've tried to keep it as orignal as possible.
-Keep Patience It'll take time to go through every program!!
Thanks diff --git a/simple_scripts/for_loop_fibonnaci b/simple_scripts/for_loop_fibonnaci new file mode 100644 index 0000000..0f17dab --- /dev/null +++ b/simple_scripts/for_loop_fibonnaci @@ -0,0 +1,9 @@ +#printing fibonnaci series till nth element +def print_fibonacci(n): + current_no = 1 + prev_no = 0 + for i in range(n): + print(current_no, end = " ") + prev_no,current_no = current_no, current_no + prev_no + +print_fibonacci(10) diff --git a/simple_scripts/for_loop_mountain.py b/simple_scripts/for_loop_mountain.py new file mode 100644 index 0000000..b311c8e --- /dev/null +++ b/simple_scripts/for_loop_mountain.py @@ -0,0 +1,27 @@ + +# Accept User Input, consider (4) +n = int(raw_input("How big? ")) + +# Building block of our mountain of money +s = '$' + +# Process for constructing mountain +# Since n = 4, +# range (1, n+1) would be all the integers from 1 to 4 including 1 and 4 +# Mountain formed would be: +# $ i = 1, ' ' * n-i = 4-1 = 3 is empty space taken 3 times, s*i is '$' taken once(i times) +# $$ i = 2, ' ' * n-i = 4-2 = 2 , s*i is '$' taken twice(i times) +# $$$ and so on +# $$$$ +# Again, notice how i and n change for each iteration +for i in range( 1 , n+1): + print (' ' *(n-i) + s*i) + + +print("\n") + + +# Other variant +s = '$$' +for i in range( 1 , n+1): + print (' ' *(n-i) + s*i) diff --git a/snake game/.idea/.gitignore b/snake game/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/snake game/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/snake game/.idea/inspectionProfiles/profiles_settings.xml b/snake game/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/snake game/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/snake game/.idea/misc.xml b/snake game/.idea/misc.xml new file mode 100644 index 0000000..4f58316 --- /dev/null +++ b/snake game/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/snake game/.idea/modules.xml b/snake game/.idea/modules.xml new file mode 100644 index 0000000..603a4d9 --- /dev/null +++ b/snake game/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/snake game/.idea/snake game.iml b/snake game/.idea/snake game.iml new file mode 100644 index 0000000..74d515a --- /dev/null +++ b/snake game/.idea/snake game.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/snake game/donut.png b/snake game/donut.png new file mode 100644 index 0000000..2364830 Binary files /dev/null and b/snake game/donut.png differ diff --git a/snake game/index.html b/snake game/index.html new file mode 100644 index 0000000..06edd87 --- /dev/null +++ b/snake game/index.html @@ -0,0 +1,15 @@ + + + + + +

Live streaming

+
+ + +
+ + + + + diff --git a/snake game/main.py b/snake game/main.py new file mode 100644 index 0000000..843844a --- /dev/null +++ b/snake game/main.py @@ -0,0 +1,134 @@ +import math +import random +import cvzone +import cv2 +import numpy as np +from cvzone.HandTrackingModule import HandDetector +from flask import Flask,render_template,Response + +app=Flask(__name__) +cap = cv2.VideoCapture(0) +cap.set(3, 1280) +cap.set(4, 720) + +detector = HandDetector(detectionCon=0.8, maxHands=1) + + +class SnakeGameClass: + def __init__(self, pathFood): + self.points = [] # all points of the snake + self.lengths = [] # distance between each point + self.currentLength = 0 # total length of the snake + self.allowedLength = 150 # total allowed Length + self.previousHead = 0, 0 # previous head point + + self.imgFood = cv2.imread(pathFood, cv2.IMREAD_UNCHANGED) + self.hFood, self.wFood, _ = self.imgFood.shape + self.foodPoint = 0, 0 + self.randomFoodLocation() + + self.score = 0 + self.gameOver = False + + def randomFoodLocation(self): + self.foodPoint = random.randint(100, 1000), random.randint(100, 600) + + def update(self, imgMain, currentHead): + + if self.gameOver: + cvzone.putTextRect(imgMain, "Game Over", [300, 400], + scale=7, thickness=5, offset=20) + cvzone.putTextRect(imgMain, f'Your Score: {self.score}', [300, 550], + scale=7, thickness=5, offset=20) + else: + px, py = self.previousHead + cx, cy = currentHead + + self.points.append([cx, cy]) + distance = math.hypot(cx - px, cy - py) + self.lengths.append(distance) + self.currentLength += distance + self.previousHead = cx, cy + + # Length Reduction + if self.currentLength > self.allowedLength: + for i, length in enumerate(self.lengths): + self.currentLength -= length + self.lengths.pop(i) + self.points.pop(i) + if self.currentLength < self.allowedLength: + break + + # Check if snake ate the Food + rx, ry = self.foodPoint + if rx - self.wFood // 2 < cx < rx + self.wFood // 2 and \ + ry - self.hFood // 2 < cy < ry + self.hFood // 2: + self.randomFoodLocation() + self.allowedLength += 50 + self.score += 1 + print(self.score) + + # Draw Snake + if self.points: + for i, point in enumerate(self.points): + if i != 0: + cv2.line(imgMain, tuple(self.points[i - 1]), tuple(self.points[i]), (0, 0, 255), 20) + cv2.circle(imgMain, tuple(self.points[-1]), 20, (0, 255, 0), cv2.FILLED) + + # Draw Food + imgMain = cvzone.overlayPNG(imgMain, self.imgFood, + (rx - self.wFood // 2, ry - self.hFood // 2)) + + cvzone.putTextRect(imgMain, f'Score: {self.score}', [50, 80], + scale=3, thickness=3, offset=10) + + # Check for Collision + pts = np.array(self.points[:-2], np.int32) + pts = pts.reshape((-1, 1, 2)) + cv2.polylines(imgMain, [pts], False, (0, 255, 0), 3) + minDist = cv2.pointPolygonTest(pts, (cx, cy), True) + + if -1 <= minDist <= 1: + print("Hit") + self.gameOver = True + self.points = [] # all points of the snake + self.lengths = [] # distance between each point + self.currentLength = 0 # total length of the snake + self.allowedLength = 150 # total allowed Length + self.previousHead = 0, 0 # previous head point + self.randomFoodLocation() + + return imgMain + + +game = SnakeGameClass("donut.png") + +def game1(): + while True: + success, img = cap.read() + img = cv2.flip(img, 1) + hands, img = detector.findHands(img, flipType=False) + + if hands: + lmList = hands[0]['lmList'] + pointIndex = lmList[8][0:2] + img = game.update(img, pointIndex) + cv2.imshow("Image", img) + key = cv2.waitKey(1) + if key == ord('r'): + game.gameOver = False + yield (b'--frame\r\n' + b'Content-Type: image/jpeg\r\n\r\n' + img+ b'\r\n') + +@app.route('/') +def index(): + return render_template('index.html') + + +@app.route('/video') +def video(): + return Response(game1()) + + +if __name__=='__main__': + app.run() \ No newline at end of file diff --git a/snake_game.py b/snake_game.py new file mode 100644 index 0000000..b84b4a8 --- /dev/null +++ b/snake_game.py @@ -0,0 +1,128 @@ +# Contribution by https://github.com/Karan9034 + +import pygame +import sys +import random + +class Snake(object): + def __init__(self): + self.length=1 + self.positions=[((SCREEN_WIDTH/2),(SCREEN_HEIGHT/2))] + self.direction=random.choice([UP,DOWN,LEFT,RIGHT]) + self.color=(17,24,47) + + def get_head_position(self): + return self.positions[0] + + def turn(self,point): + if self.length>1 and (point[0] * -1, point[1] * -1) == self.direction: + return + else: + self.direction=point + + def move(self): + cur=self.get_head_position() + x,y=self.direction + new=((cur[0] + (x*GRIDSIZE))%SCREEN_WIDTH,(cur[1]+(y*GRIDSIZE))%SCREEN_HEIGHT) + if len(self.positions)>2 and new in self.positions[2:]: + pygame.quit() + sys.exit() + else: + self.positions.insert(0,new) + if len(self.positions)>self.length: + self.positions.pop() + + def draw(self,surface): + for p in self.positions: + r=pygame.Rect((p[0],p[1]),(GRIDSIZE,GRIDSIZE)) + pygame.draw.rect(surface,self.color,r) + pygame.draw.rect(surface,(93,216,228),r,1) + + def handle_keys(self): + for event in pygame.event.get(): + if event.type==pygame.QUIT: + pygame.quit() + sys.exit() + elif event.type==pygame.KEYDOWN: + if event.key==pygame.K_UP: + self.turn(UP) + elif event.key==pygame.K_DOWN: + self.turn(DOWN) + elif event.key==pygame.K_LEFT: + self.turn(LEFT) + elif event.key==pygame.K_RIGHT: + self.turn(RIGHT) + elif event.key==pygame.K_ESCAPE: + pygame.quit() + sys.exit() + +class Food(object): + def __init__(self): + self.position=(0,0) + self.color=(233,163,49) + self.randomize_position() + + def randomize_position(self): + self.position=(random.randint(0,GRID_WIDTH-1)*GRIDSIZE,random.randint(0,GRID_HEIGHT-1)*GRIDSIZE) + + def draw(self,surface): + r=pygame.Rect((self.position[0],self.position[1]),(GRIDSIZE,GRIDSIZE)) + pygame.draw.rect(surface,self.color,r) + pygame.draw.rect(surface,(93,216,228),r,1) + +def drawGrid(surface): + for y in range(0,int(GRID_HEIGHT)): + for x in range(0,int(GRID_WIDTH)): + if (x+y)%2==0: + r=pygame.Rect((x*GRIDSIZE,y*GRIDSIZE),(GRIDSIZE,GRIDSIZE)) + pygame.draw.rect(surface,(200,200,200),r) + else: + rr=pygame.Rect((x*GRIDSIZE,y*GRIDSIZE),(GRIDSIZE,GRIDSIZE)) + pygame.draw.rect(surface,(100,100,100),rr) + +SCREEN_WIDTH=480 +SCREEN_HEIGHT=480 + +GRIDSIZE=20 +GRID_WIDTH=SCREEN_WIDTH/GRIDSIZE +GRID_HEIGHT=SCREEN_HEIGHT/GRIDSIZE + +UP=(0,-1) +DOWN=(0,1) +LEFT=(-1,0) +RIGHT=(1,0) + +def main(): + pygame.init() + + clock=pygame.time.Clock() + screen=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0,32) + pygame.display.set_caption("Snake") + surface=pygame.Surface(screen.get_size()) + surface=surface.convert() + drawGrid(surface) + + snake=Snake() + food= Food() + + myfont=pygame.font.SysFont("monospace",16) + + score=0 + while True: + clock.tick(10) + snake.handle_keys() + drawGrid(surface) + snake.move() + if snake.get_head_position()==food.position: + snake.length+=1 + score+=1 + food.randomize_position() + snake.draw(surface) + food.draw(surface) + screen.blit(surface,(0,0)) + text=myfont.render("Score: {0}".format(score),1,(0,0,0)) + screen.blit(text,(5,10)) + pygame.display.update() + +if __name__=="__main__": + main() diff --git a/star_turtle.py b/star_turtle.py new file mode 100644 index 0000000..76aaf33 --- /dev/null +++ b/star_turtle.py @@ -0,0 +1,12 @@ +Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +>>> import turtle +>>> star=turtle.Turtle() +>>> win=turtle.Screen() +>>> win.setworldcoordinates(-100,-100,100,100) +>>> for i in range(5): + star.forward(50) + star.right(144) + + +>>> diff --git a/sum_array.py b/sum_array.py index b926753..039a30d 100644 --- a/sum_array.py +++ b/sum_array.py @@ -5,7 +5,9 @@ def sum_arr(n): return res nums = [52345,746587,98589,54398,9348,45887,49856] -test = sum_arr(nums) +test = sum_arr(nums) + +#sum() is Pythons built in method of adding all the elements in a list if test == sum(nums): print("Sum of arr: {}".format(test)) else: diff --git a/useful_scripts/Diffe_Hellman.py b/useful_scripts/Diffe_Hellman.py new file mode 100644 index 0000000..f4d80ea --- /dev/null +++ b/useful_scripts/Diffe_Hellman.py @@ -0,0 +1,74 @@ +import random, hashlib + +def list_prime(): + for num in range(3, 1000): + # all prime numbers are greater than 1 + if num > 1: + for i in range(2, num): + if (num % i) == 0: + break + else: + print(num, end=', ') + +def is_prime(n): + """if num > 1: + for i in range(2, num//2): + if (num % i) == 0: + return False + break + else: + return True + else: + return False""" + # Corner cases + if (n <= 1) : + return False + if (n <= 3) : + return True + + # This is checked so that we can skip + # middle five numbers in below loop + if (n % 2 == 0 or n % 3 == 0) : + return False + + i = 5 + while(i * i <= n) : + if (n % i == 0 or n % (i + 2) == 0) : + return False + i = i + 6 + + return True + +def cost(h, cost): + for i in range(cost): + h = hashlib.sha3_512(h.encode()).hexdigest() + return h + +print("type 'prime' to choose from list") +prime = input("Enter a largest prime number you can think of >>> ") +if prime == 'prime': + list_prime() + prime = int(input("Enter a largest prime number you can think of >>> ")) +else: + prime = int(prime) + +if is_prime(prime): + private = int(input("Enter your private key>>> ")) + public = random.randint(0, 999999999) + my_share = (public**private)%prime + my_exchange_key = cost(hashlib.sha3_512(str(my_share).encode()).hexdigest(), 5) + print() + print(f"Your exchange key is --> {my_exchange_key}") + print('*' * 100) + + bob_private = int(input("Enter Bob's private key>>> ")) + bob_share = (public**private)%prime + bob_exchange_key = cost(hashlib.sha3_512(str(bob_share).encode()).hexdigest(), 5) + print() + print(f"Bob'sexchange key is --> {bob_exchange_key}") + print() + print(f"my_exchange_key == bob_exchange_key\n{my_exchange_key == bob_exchange_key}") + print('*' * 100) + +else: + print("This is not a prime number") diff --git a/useful_scripts/pinger.py b/useful_scripts/pinger.py new file mode 100644 index 0000000..302dbb1 --- /dev/null +++ b/useful_scripts/pinger.py @@ -0,0 +1,47 @@ +import subprocess +from datetime import datetime +import matplotlib.pyplot as plt + +pings = [] +losses = [] +times = [] +i = 0 + +def update_line(): + plt.plot(times, pings) + plt.xticks(rotation=45) + plt.draw() + + +try: + plt.show() + while True: + output = subprocess.check_output("ping 8.8.8.8", shell=True) + losses.append(output.decode().split()[-18]) + output = output.decode().split()[-1] + time = datetime.now().strftime("%H:%M:%S") + pings.append(int(output.strip("ms"))) + times.append(time) + i += 1 + # update_line() +except KeyboardInterrupt: + pings = [int(i) for i in pings] + losses = [int(i) for i in losses] + + plt.figure() + plt.subplot(211) + plt.xticks(rotation=45) + plt.ylabel("ping (MS) - avg") + plt.plot(times, pings) + + if sum(losses) != 0: + plt.subplot(212) + plt.plot(times, losses) + + + plt.xticks(rotation=45) + plt.ylabel("Loss") + plt.show() + + +