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 445bf37..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/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/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/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/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/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()
+
+
+