From 4d4559532165cae5b1a77280d080d0b72996187a Mon Sep 17 00:00:00 2001 From: Jolinator Date: Sun, 2 Oct 2022 16:44:01 +0100 Subject: [PATCH 001/129] add summatory --- Summatory.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Summatory.py diff --git a/Summatory.py b/Summatory.py new file mode 100644 index 00000000..cc688af5 --- /dev/null +++ b/Summatory.py @@ -0,0 +1,8 @@ +def suma(slist): # SUMMATORY + sum = 0 + for x in slist: + if not (type(x) == int and type(x) == float): + sum += x + else: + raise ValueError("Item in list wasn't a number") + return sum From a46a6ff90793ac8087257304771938028c533039 Mon Sep 17 00:00:00 2001 From: Aarya Chopkar Date: Mon, 3 Oct 2022 16:11:28 +0530 Subject: [PATCH 002/129] SankeGame_GUI --- SankeGame_GUI.py | 179 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 SankeGame_GUI.py diff --git a/SankeGame_GUI.py b/SankeGame_GUI.py new file mode 100644 index 00000000..dae1921d --- /dev/null +++ b/SankeGame_GUI.py @@ -0,0 +1,179 @@ +#Our favourite Snake game with Basic Graphics. Made this using the turtle module. +#Random shaped food with colors pop up everytime. +#Also it keeps a look on your scores, play with friends and enjoy. + +import turtle +import time +import random + +delay = 0.1 +score = 0 +high_score = 0 + +#Window Screen +wn = turtle.Screen() +wn.title("SNAKE GAME") +wn.bgcolor("black") + +wn.setup(width=600,height=600) +wn.tracer(0) + +#Head of Snake +head = turtle.Turtle() +head.shape("square") +head.color("green") +head.penup() +head.goto(0, 0) +head.direction = "stop" + +#Food in the game +food = turtle.Turtle() +food.speed(0) +food.shape("circle") +food.color("red") +food.penup() +food.goto(0, 100) + +#Score +pen = turtle.Turtle() +pen.speed(0) +pen.shape("turtle") +pen.color("white") +pen.penup() +pen.hideturtle() +pen.goto(0, 250) +pen.write("Score : 0 High Score : 0", align="center", + font=("Times New Roman", 24, "bold")) + + +#Assigning key values +def goup(): + if head.direction != "down": + head.direction = "up" + +def godown(): + if head.direction != "up": + head.direction = "down" + +def goright(): + if head.direction != "left": + head.direction = "right" + +def goleft(): + if head.direction != "right": + head.direction = "left" + +def move(): + if head.direction == "up": + y = head.ycor() + head.sety(y+20) + + if head.direction == "down": + y = head.ycor() + head.sety(y-20) + + if head.direction == "right": + x = head.xcor() + head.setx(x+20) + + if head.direction == "left": + x = head.xcor() + head.setx(x-20) + +wn.listen() +wn.onkeypress(goup, "Up") +wn.onkeypress(godown, "Down") +wn.onkeypress(goleft, "Left") +wn.onkeypress(goright, "Right") + + +#Main Loop +segments = [] + +while True: + wn.update() + #for collisions with border + if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: + time.sleep(1) + head.goto(0, 0) + head.direction = "stop" + + #hiding segments of snake + for segment in segments: + segment.goto(1000,1000) + #clearing the segments + segments.clear() + + #reset score + score = 0 + + #reset delay + delay = 0.1 + + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + + #checking collision with food + if head.distance(food) < 20: + x = random.randint(-270, 270) + y = random.randint(-270, 270) + food.goto(x, y) + d = ["red","yellow","blue"] + colors = random.choice(d) + food.color(colors) + e = ["circle","square","triangle"] + shapes = random.choice(e) + food.shape(shapes) + + + #adding new segment + new_segment = turtle.Turtle() + new_segment.speed(0) + new_segment.color("green") + new_segment.shape("square") + new_segment.penup() + segments.append(new_segment) + + delay -= 0.001 + score += 10 + + if score>high_score: + high_score = score + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + + #moving segments in reverse order + for i in range(len(segments)-1,0,-1): + x = segments[i-1].xcor() + y = segments[i-1].ycor() + segments[i].goto(x,y) + if len(segments) > 0: + x = head.xcor() + y = head.ycor() + segments[0].goto(x, y) + + move() + + #Checking collisions with body + for segment in segments: + if segment.distance(head) < 20: + time.sleep(1) + head.goto(0,0) + head.direction = "stop" + + #hide segments + for segment in segments: + segment.goto(1000,1000) + segment.clear() + + score = 0 + delay = 0.1 + pen.clear() + pen.write("Score : {} High Score : {} ".format( + score, high_score), align="center", font=("Times New Roman", 24, "bold")) + time.sleep(delay) + +turtle.done() + From e0af784c8d6b3358e5fab08415e20ca160cdf711 Mon Sep 17 00:00:00 2001 From: Sugar Daddy <95568665+rajat-se@users.noreply.github.com> Date: Mon, 3 Oct 2022 19:36:46 +0530 Subject: [PATCH 003/129] Create calculator.py --- calculator.py | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 calculator.py diff --git a/calculator.py b/calculator.py new file mode 100644 index 00000000..6f0f018c --- /dev/null +++ b/calculator.py @@ -0,0 +1,59 @@ +num1=int(input("eneter a digit")) +num2=int(input("eneter a another digit")) +# defination for operators + +#addition +def add(num1, num2): + return num1+num2 +#substraction +def subtract(num1, num2): + return num1-num2 +#multiply +def multiply(num1, num2): + return num1*num2 +#division +def divide(num1, num2): + return num1/num2 + +#command for operation +print("choose operation") +print("press 1 for add") +print("press 2 for subs") +print("press 3 for multiply") +print("press 4 for devision") + + + + + +while True: + # take input from the user + choice = input("Enter choice(1/2/3/4): ") + + if choice in ('1', '2', '3', '4'): + + if choice == '1': + print(num1, "+", num2, "=", add(num1, num2)) + + + + elif choice == '2': + print(num1, "-", num2, "=", subtract(num1, num2)) + + elif choice == '3': + print(num1, "*", num2, "=", multiply(num1, num2)) + + + + + + elif choice == '4': + print(num1, "/", num2, "=", divide(num1, num2)) + # check if user wants another calculation + # break the while loop if answer is no + next_calculation = input("Let's do next calculation? (yes/no): ") + if next_calculation == "no": + break + + else: + print("Invalid Input") From 53745c2a757a922ea0d6dfa17d4f5e75afc03ccb Mon Sep 17 00:00:00 2001 From: Jolinator Date: Mon, 3 Oct 2022 15:15:39 +0100 Subject: [PATCH 004/129] Added Decomposing_factors.py --- Decomposing_factors.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Decomposing_factors.py diff --git a/Decomposing_factors.py b/Decomposing_factors.py new file mode 100644 index 00000000..e6f82f29 --- /dev/null +++ b/Decomposing_factors.py @@ -0,0 +1,17 @@ +def prime_factors(n): + final = [] + rstr = '' + while n != 1: + for x in range(2,n+1): + if n % x == 0: + n //= x + final.append(x) + break + for x in final: + if f'({x}**{final.count(x)})' in rstr: + continue + rstr += f'({x}**{final.count(x)})' if final.count(x) > 1 else f'({x})' + return rstr + +#Function that decomposes number into their base multiplicants. Usefull for simplifications of square roots etc. +#Example: prime_factors(30) outputs (2)(3)(5) because 30 = 2 * 3 * 5 From c785fc9fa851519addbb6e6c6782c8ab6a131d78 Mon Sep 17 00:00:00 2001 From: Jolinator Date: Mon, 3 Oct 2022 15:20:39 +0100 Subject: [PATCH 005/129] Deleted Summatory --- Summatory.py | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 Summatory.py diff --git a/Summatory.py b/Summatory.py deleted file mode 100644 index cc688af5..00000000 --- a/Summatory.py +++ /dev/null @@ -1,8 +0,0 @@ -def suma(slist): # SUMMATORY - sum = 0 - for x in slist: - if not (type(x) == int and type(x) == float): - sum += x - else: - raise ValueError("Item in list wasn't a number") - return sum From 25b8fac2571b10debcef13ad422fba2b1b999bc4 Mon Sep 17 00:00:00 2001 From: Aarya Chopkar Date: Mon, 3 Oct 2022 19:54:56 +0530 Subject: [PATCH 006/129] Added Youtube Downloader --- YoutubeDownloader.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 YoutubeDownloader.py diff --git a/YoutubeDownloader.py b/YoutubeDownloader.py new file mode 100644 index 00000000..c063f64d --- /dev/null +++ b/YoutubeDownloader.py @@ -0,0 +1,32 @@ +#pip install pytube to install library +from pytube import YouTube +link = input("Enter youtube url:") +yt = YouTube(link) + +SAVE_PATH = "E:/" + +#Title of Video +print("Title:",yt.title) + +#Number of Views +print("Views:",yt.views) + +#Length of Video +print("Length of Video:",yt.length,"seconds") + +#Rating of Video +print("Rating:",yt.rating) + +x = input("Do you want video or audio(v/a): ") +if x=="v": + print(yt.streams.filter(progressive=True)) + ys = yt.streams.get_by_itag('22') + +else: + print(yt.streams.filter(only_audio=True)) + ys = yt.streams.get_by_itag('251') + +#Downloading +print("***DOWNLOADING***") +ys.download(SAVE_PATH) +print("***DOWNLOADED***") \ No newline at end of file From 18a36c4504aba150f077f98f698c6316b68eaaaf Mon Sep 17 00:00:00 2001 From: Deveesh Shetty Date: Mon, 3 Oct 2022 19:56:45 +0530 Subject: [PATCH 007/129] CREATE: CLI adventure game --- adventure_game.py | 135 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 adventure_game.py diff --git a/adventure_game.py b/adventure_game.py new file mode 100644 index 00000000..0acc375b --- /dev/null +++ b/adventure_game.py @@ -0,0 +1,135 @@ +from time import * + +print("Hello! Welcome to the game") +choice = input("Do you want to start the game? Y/N: ").upper() +if choice == 'Y': + print("Let's Go!!") +else: + print("Let's play next time ☹") + sleep(20) +print("""In which path you want to go + A- Concrete road + B- Road in middle of forest + C- Swimming through the ocean\n""") +choice = input("Enter your choice: ").upper() +if choice == 'A': + ch = input("\nThere is a building in the front would u want to enter it? Y/N: ").upper() + if ch == 'Y': + print("\nYou entered the building....") + ch1 = input("Would you like to take the lift (type Y) or go from the stairs (type N)? ").upper() + if ch1 == 'Y': + print("\nYou took the lift and the lift stopped working and it crashed, you died") + sleep(20) + elif ch1 == 'N': + ch2 = input("\nYou reached the terrace u saw a parachute would you like to take it? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou took the parachute and landed on a playground.") + print("You went home empty handed. ") + sleep(20) + elif ch2 == 'N': + print("\nYou can't do anything the building security guard caught you and handed you to the police. ") + print("You failed") + sleep(20) + elif ch == 'N': + ch1 = input("\nYou passed the building and now there is a restaurant would you like to go and have lunch? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou entered the restaurant....") + ch2 = input("You had lunch, would you like to pay the bill(type Y) or run away(type N)? ").upper() + if ch2 == 'Y': + print("\nYou paid the bill but you had no money so the manager called the police and you got arrested") + sleep(20) + elif ch2 == 'N': + print("\nYou ran away... but somehow the police found you so u are arrested") + sleep(20) + elif ch1 == 'N': + print("\nYou were just walking randomly and fell into a manhole...U died") + sleep(20) +elif choice == 'B': + print("\nYou are lost in the forest...") + ch = input("There is a cave in front would you like to enter it? Y/N: ").upper() + if ch == 'Y': + print("\nYou entered the cave there was a giant inside...he wants to become your friend") + ch1 = input("Would you like to become is friend? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou both became friends and he took you to his kingdom made you the price of the kingdom...") + print("You both live a happy life...") + sleep(20) + if ch1 == 'N': + print("\nGiant became angry and ate you raw....RIP") + sleep(20) + elif ch =='N': + print("\nYou ignored the cave and continued your journey") + ch1 = input("You see something buried underground would you like to dig and remove it? Y/N: ").upper() + if ch1 == 'Y': + print("\nLucky you! It was a map and it lead to something ") + ch2 = input("Would you like to follow the map? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou are following the map and you ended up under a big tree and theres a \"X\" mark") + ch3 = input("Would you like to dig it? Y/N: ").upper() + if ch3 == 'Y': + print("\nYou found nothing...") + print("And you got lost in the forest and now you died due to starvation") + sleep(20) + elif ch3 == 'N': + print("\nAnd you got lost in the forest and now you died due to starvation") + sleep(20) + elif ch2 == 'N': + print("\nYou didn't follow the map and went ahead...") + ch3 = input("You saw a \"X\" mark in the ground would you like to dig and see whats there? Y/N: ").upper() + if ch3 == 'Y': + print("\nYou found and treasure worth billions...You realised that the map was a distraction") + print("You are now a billionaire and living your life peacefully") + sleep(20) + elif ch3 == 'N': + print("\nYou went too deep in the forest") + print("You got lost and now you died due to starvation") + sleep(20) + elif ch1 == 'N': + print("\nYou continued your journey and came across a river") + ch2 = input("Would you like to swim and cross the river? Y/N: ").upper() + if ch2 == 'Y': + print("\nYou jumped in the river and there was a crocodile...and you know what happened next lol ") + sleep(20) + elif ch2 == 'N': + print("\nYou went ahead and found a bridge and you crossed the river") + ch3 = input("There are two ways would you like to go right or left? R/L: ").upper() + if ch3 == 'R': + print("\nYou chose the right path and you reached the city and safely went back home!") + sleep(20) + elif ch3 == 'L': + print("\nYou went along the left path...") + print("You saw a cave but you realise that it is the same cave you found at beginning...") + print("And now you are in a infinite loop...Bye Have Fun ") + sleep(20) +elif choice == 'C': + print("\nYou are swimming in the ocean") + ch1 = input("You found an island would like to go there? Y/N: ").upper() + if ch1 == 'Y': + print("\nYou are now walking in the island...") + print("You find that the island is full of cannibals 💀") + ch2 = input("Do you want to run away(type Y) or be friends with them(type N)? ").upper() + if ch2 == 'Y': + print("\nYou are running and there was a bear trap and you stepped on it") + print("They found you....") + sleep(20) + elif ch2 == 'N': + print("\nYou tried to be their friend but you forgot that they don't understand your language...") + print("They thought you were teasing them and they had tasty lunch 🍴") + sleep(20) + elif ch1 == 'N': + print("\nYou ignored the island and swam ahead") + print("You found 2 fisherman in a boat") + ch2 = input("Would you like to join them? Y/N: ").upper() + if ch2 == 'Y': + print("\nThey were very good and they took you with them and you safely made to the land") + print("You are now at home chilling 😎") + sleep(20) + elif ch2 == 'N': + print("\nYou told them that you won't come with them") + print("You are now swimming ahead and you are in middle of nowhere...") + print("You died....") + sleep(20) +else: + print("\nSelect correction option!! ") + sleep(20) + From b95d41fb843d039fc166cd2a0d0cdfb1934ed312 Mon Sep 17 00:00:00 2001 From: Akshay-G-Dev <61789324+Akshay-G-Dev@users.noreply.github.com> Date: Mon, 3 Oct 2022 20:16:26 +0530 Subject: [PATCH 008/129] GUI PvP Tic Tac Toe --- GUI_Tic_Tac_Toe_pvp.py | 115 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 GUI_Tic_Tac_Toe_pvp.py diff --git a/GUI_Tic_Tac_Toe_pvp.py b/GUI_Tic_Tac_Toe_pvp.py new file mode 100644 index 00000000..5e600a40 --- /dev/null +++ b/GUI_Tic_Tac_Toe_pvp.py @@ -0,0 +1,115 @@ +import tkinter as tk +from functools import partial +import time + +gui=tk.Tk() +gui.geometry('500x200') +gui.title('Tic Tac Toe') + +movesPlayed=[] +game_over=False + +Xcount=0 +Ocount=0 +player,turn=1,'x' + +def clicked(obj): + global player,turn,Xcount,Ocount + + button_clicked=''.join(obj.split()) + #row,column=obj.split() + #row=row.split('w')[1] + + + if button_clicked not in movesPlayed: + globals()[button_clicked].configure(text=turn.center(6)) + movesPlayed.append(button_clicked) + globals()[button_clicked]['state']='disabled' + if player==1: + player,turn=2,'0' + Xcount+=1 + player_data.configure(text='Player-2(0) chance') + + + else: + player,turn=1,'x' + Ocount+=1 + player_data.configure(text='Player-1(x) chance') + + win_check() + else: + print('Move already played') + +def finish(string): + global game_over + game_over=True + player_data.configure(text='') + player_win.configure(text=string) + player_win.pack() + for i in ('row1','row2','row3'): + for j in range(3): + globals()[i+str(j+1)]['state']='disabled' + rtry=tk.Button(gui,text='Retry',command=Retry) + rtry.pack() + finish.rtry=rtry + +def Retry(): + global movesPlayed,player,turn,Xcount,Ocount,rtry + movesPlayed=[] + player,turn=1,'x' + Xcount,Ocount=0,0 + for i in ('row1','row2','row3'): + for j in range(3): + + globals()[i+str(j+1)].configure(text=f' ') + globals()[i+str(j+1)]['state']='active' + finish.rtry.pack_forget() + player_win.pack_forget() + player_data.configure(text='Player-1(x) chance') + +def win_check(): + + + + + if (row11['text'] == row12['text'] == row13['text'] != ' ' or + row21['text'] == row22['text'] == row23['text'] != ' ' or + row31['text'] == row32['text'] == row33['text'] != ' ' or + row11['text'] == row21['text'] == row31['text'] != ' ' or + row12['text'] == row22['text'] == row32['text'] != ' ' or + row13['text'] == row23['text'] == row33['text'] != ' ' or + row11['text'] == row22['text'] == row33['text'] != ' ' or + row13['text'] == row22['text'] == row31['text'] != ' ' + ): + + + if Xcount>Ocount: + string='Player 1(X) won' + else: + string='Player 2(O) won' + finish(string) + + if not game_over: + if (Xcount==5 and Ocount==4 or + Xcount==4 and Ocount==5): + finish('Draw match') +tk.Label(gui,text="PLAYER-1=X\nPLAYER-2=0").pack() +player_data=tk.Label(gui,text='Player-1(x) chance') +player_data.pack() + +row1=tk.Frame(gui) +row1.pack() +row2=tk.Frame(gui) +row2.pack() +row3=tk.Frame(gui) +row3.pack() + +player_win=tk.Label(gui,text='') +for i in ('row1','row2','row3'): + for j in range(3): + + vars()[i+str(j+1)]=tk.Button(vars()[i], text=f' ',bd='1',command=partial(clicked,i+' '+str(j+1))) + vars()[i+str(j+1)].pack(side='left') + + +gui.mainloop() From 2b64dccc842c8dde87bec8e9de7743c7c66d1a1b Mon Sep 17 00:00:00 2001 From: saurab1102 <58526210+saurab1102@users.noreply.github.com> Date: Mon, 3 Oct 2022 21:29:06 +0530 Subject: [PATCH 009/129] Armstrong Number Added a python program to check if the number is an Armstrong Number or not --- ArmstrongNumberCheck.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 ArmstrongNumberCheck.py diff --git a/ArmstrongNumberCheck.py b/ArmstrongNumberCheck.py new file mode 100644 index 00000000..1cfa836c --- /dev/null +++ b/ArmstrongNumberCheck.py @@ -0,0 +1,9 @@ +print("An Armstrong Number is a number which is equal to the sum of the cubes of it's digits.") +inputNumber = input("Enter a number to check if it's an Armstrong Number or not: ") +sumOfCubes=0 + +for digit in inputNumber: + sumOfCubes+=int(digit)**3 + +if sumOfCubes==int(inputNumber): print(inputNumber,"is an Armstrong Number.") +else: print(inputNumber,"is NOT an Armstrong Number.") From db4f4b116249dd10c52e40d5c7e4375f00c610ec Mon Sep 17 00:00:00 2001 From: Atharva Thakur Date: Mon, 3 Oct 2022 21:43:49 +0530 Subject: [PATCH 010/129] Ceiling of a number in a list program added --- cielingOfNumInList.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 cielingOfNumInList.py diff --git a/cielingOfNumInList.py b/cielingOfNumInList.py new file mode 100644 index 00000000..4016b27f --- /dev/null +++ b/cielingOfNumInList.py @@ -0,0 +1,26 @@ +# In this problem we have to find a number equal to or the smallest greatest number to the given target number. + +# so we use binary search for this +# case 1: mid==target +# so we have found a number equal to the target. problem solved +# case 2 : element is not in the array +# in this case we would reach the start>end and the while loop would stop. +# and the next greater element would be pointed at by the start. +# so the ceiling of the number would be arr[start]. + +arr =[1,2,3,4,8,9,10,15,19,23,27,29,34,39,45,46,55,59,60,63,68,69] +target = int(input("Enter the target element->")) +start = 0 +end = len(arr)-1 + +while(startarr[mid]: + start=mid+1 +else: + print(f"The ceiling of the element is {arr[start]}") From 86c3c7b55d94a35f1c2b8afd2b9bb74ea3edfa2e Mon Sep 17 00:00:00 2001 From: ParasSharma Date: Mon, 3 Oct 2022 21:47:21 +0530 Subject: [PATCH 011/129] sell, buy stocks to max profit --- Sell Buy Stocks to Max Profit.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Sell Buy Stocks to Max Profit.py diff --git a/Sell Buy Stocks to Max Profit.py b/Sell Buy Stocks to Max Profit.py new file mode 100644 index 00000000..092e02d9 --- /dev/null +++ b/Sell Buy Stocks to Max Profit.py @@ -0,0 +1,13 @@ +p = list(map(int, input().split())) #Enter the prices of each day + +maxProfit = 0 +currentMax = 0 + +for i in reversed(p): + currentMax = max(currentMax, i) + profit = currentMax - i + maxProfit = max(profit, maxProfit) + +print("Buy stock when price is:", currentMax-maxProfit) #Buying Price +print("Sell stock when price is:", currentMax) #Selling Price +print("Maximum profit earned:", maxProfit) #Profit Earned \ No newline at end of file From 179a03d5891823576abe118d0a6c2d12b12b380b Mon Sep 17 00:00:00 2001 From: Faizan96322 <72128134+Faizan96322@users.noreply.github.com> Date: Mon, 3 Oct 2022 22:04:32 +0530 Subject: [PATCH 012/129] Median of Two Sorted Arrays --- medianOf2SortedArray.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 medianOf2SortedArray.py diff --git a/medianOf2SortedArray.py b/medianOf2SortedArray.py new file mode 100644 index 00000000..5162d202 --- /dev/null +++ b/medianOf2SortedArray.py @@ -0,0 +1,41 @@ +# Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. +# example 1 +# Input: nums1 = [1,3], nums2 = [2] +# Output: 2.00000 +# Explanation: merged array = [1,2,3] and median is 2. + +#Input: nums1 = [1,2], nums2 = [3,4] +# Output: 2.50000 +# Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + +#nums1 and nums2 are 2 sorted arrays +def findMedianSortedArrays(A, B): + + med1 = med2 = i = j = 0 + n = len(A) + len(B) + + while (i + j) <= n / 2: + if i < len(A) and j < len(B): + med2 = med1 + if A[i] < B[j]: + med1 = A[i] + i += 1 + else: + med1 = B[j] + j += 1 + elif i < len(A): + med2 = med1 + med1 = A[i] + i += 1 + elif j < len(B): + med2 = med1 + med1 = B[j] + j += 1 + + if n % 2 == 0: + return (med1 + med2) / 2.0 + else: + return med1 + + + From eb496085d605dfda4861ba957fd40ed7afdaa0c0 Mon Sep 17 00:00:00 2001 From: Wahaj-Raza Date: Mon, 3 Oct 2022 22:10:40 +0500 Subject: [PATCH 013/129] Added Levenshtein distance.py --- Levenshtein_distance.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Levenshtein_distance.py diff --git a/Levenshtein_distance.py b/Levenshtein_distance.py new file mode 100644 index 00000000..710a3910 --- /dev/null +++ b/Levenshtein_distance.py @@ -0,0 +1,41 @@ +# The Levenshtein distance (Edit distance) Problem + +# Informally, the Levenshtein distance between two words is +# the minimum number of single-character edits (insertions, deletions or substitutions) +# required to change one word into the other. + +# For example, the Levenshtein distance between kitten and sitting is 3. +# The minimal edit script that transforms the former into the latter is: + +# kitten —> sitten (substitution of s for k) +# sitten —> sittin (substitution of i for e) +# sittin —> sitting (insertion of g at the end) + +def levenshtein_distance(word_1, chars_1, word_2, chars_2): + # base case if the strings are empty + if chars_1 == 0: + return chars_2 + if chars_2 == 0: + return chars_1 + + # if last characters of the string match, the cost of + # operations is 0, i.e. no changes are made + if word_1[chars_1 - 1] == word_2[chars_2 - 1]: + cost = 0 + else: + cost = 1 + + # calculating the numbers of operations recursively + deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1 + insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1 + substitution = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2 - 1) + cost + + return min(deletion, insertion, substitution) + +# driving script +if __name__ == '__main__': + word_1 = input("Enter Word 1 :") + word_2 = input("Enter Word 2 :") + + print('The Levenshtein distance is:') + print(levenshtein_distance(word_1, len(word_1), word_2, len(word_2))) \ No newline at end of file From d423265df7393d3aa537546b8ce56a91e606f743 Mon Sep 17 00:00:00 2001 From: Sugar Daddy <95568665+rajat-se@users.noreply.github.com> Date: Mon, 3 Oct 2022 22:48:37 +0530 Subject: [PATCH 014/129] Create print_star_using_loops.py --- print_star_using_loops.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 print_star_using_loops.py diff --git a/print_star_using_loops.py b/print_star_using_loops.py new file mode 100644 index 00000000..66fc5663 --- /dev/null +++ b/print_star_using_loops.py @@ -0,0 +1,15 @@ +print("How Many Row You Want To Print") +one= int(input()) +print("Type 1 Or 0") +two = int(input()) +new =bool(two) +if new == True: + for i in range(1,one+1): + for j in range(1,i+1): + print("*",end=" ") + print() +elif new ==False: + for i in range(one,0,-1): + for j in range(1,i+1): + print("*", end="") + print() From 23b8afd3f1233cd70eb92958cda2b796796b11e7 Mon Sep 17 00:00:00 2001 From: BiscuitCandy <70342294+BiscuitCandy@users.noreply.github.com> Date: Mon, 3 Oct 2022 23:48:14 +0530 Subject: [PATCH 015/129] Create Sieve_of _Eratosthenes.py --- Sieve_of _Eratosthenes.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Sieve_of _Eratosthenes.py diff --git a/Sieve_of _Eratosthenes.py b/Sieve_of _Eratosthenes.py new file mode 100644 index 00000000..e23ea370 --- /dev/null +++ b/Sieve_of _Eratosthenes.py @@ -0,0 +1,23 @@ +def SieveOfEratosthenes(n): + numbers = {i: True for i in range(2, n+1)} + primes = [] + + p = 2 + + while p**2 < n : + if numbers[p] : + for i in range(p**2, n+1, p): + numbers[i] = False + p+=1 + for i in range(2, n+1) : + if numbers[i] : + primes.append(i) + + return primes + +def main() : + n = int(input("Enter value of n to find primes between 1 and n (inclusive):")) + arr = SieveOfEratosthenes(n) + print("Primes:", *arr) + +main() From 810ac47b1a46c559990f2031aebb317d50b5c334 Mon Sep 17 00:00:00 2001 From: Santosh Kumar Doodala <84093797+yeskaydee@users.noreply.github.com> Date: Mon, 3 Oct 2022 23:57:17 +0530 Subject: [PATCH 016/129] menu based program option 1 : Append student option 2: remove student by Rollno option 3: view student by name option 4: copy list option 5: remove all students option 6: exit")) --- menu-based_student_record.py | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 menu-based_student_record.py diff --git a/menu-based_student_record.py b/menu-based_student_record.py new file mode 100644 index 00000000..2d892f77 --- /dev/null +++ b/menu-based_student_record.py @@ -0,0 +1,68 @@ +singlerecord=[] +studList=[] +choice='y' +while choice.lower()!='n': + studName=input('enter your name ') + Rollno=input('enter your Rollno ') + cgpa=int(input('cgpa :')) + singlerecord.append(studName) + singlerecord.append(Rollno) + singlerecord.append(cgpa) + studList.append(singlerecord) + singlerecord=[] + choice=input('enter your choice [y/n]') + +#append +def appendStudent(): + global studList + singlr = [] + studName=input('enter your name') + Rollno=input('enter your Rollno') + cgpa=int(input('cgpa :')) + singlr.append(studName) + singlr.append(Rollno) + singlr.append(cgpa) + studList.append(singlr) + + +# remove existing record by rollno +def removeRecord(): + global studList + rolln=int(input("enter student's rollno:")) + for record in studList: + if rolln in record: + studList.remove(record) + +# view student by name: +def viewRecord(): + name=input("enter student's name:") + for record in studList: + if name in record: + print(record) + +# copy +def copyList(): + print("what to do??") + +#remove all +def removeAll(): + studList.clear() + +flag = 'y' +while (flag == 'y'): + find = int(input("Enter \n option 1 : Append student \n option 2: remove student by Rollno\n option 3: view student by name\n option 4: copy list\n option 5: remove all students option \n 6: exit")) + if (find == 1): + appendStudent() + elif (find == 2): + removeRecord() + elif (find == 3): + viewRecord() + elif (find == 4): + copyList() + elif (find == 5): + removeAll() + elif (find == 6): + exit + else: + print("enter correct option !!") + flag = input("do u want to continue ? say y or n : \n") From 02d41637fce0f0cdb9ae04a2afda924f15b52d7e Mon Sep 17 00:00:00 2001 From: Saurabh-2809 <48317162+Saurabh-2809@users.noreply.github.com> Date: Tue, 4 Oct 2022 01:22:41 +0530 Subject: [PATCH 017/129] Created initial Password_generator.py --- Password_generator.py | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Password_generator.py diff --git a/Password_generator.py b/Password_generator.py new file mode 100644 index 00000000..942f3982 --- /dev/null +++ b/Password_generator.py @@ -0,0 +1,68 @@ +#Password Generator Project +import random as r +letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] +numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + +print("Welcome to the PyPassword Generator!") +nr_letters= int(input("How many letters would you like in your password?\n")) +nr_symbols = int(input(f"How many symbols would you like?\n")) +nr_numbers = int(input(f"How many numbers would you like?\n")) + +#Eazy Level - Order not randomised: +#e.g. 4 letter, 2 symbol, 2 number = JduE&!91 +random_letters = "" +for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters += random_letter + +# print(random_letters) + +random_symbols = "" +for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols += random_symbol + +# print(random_symbols) + +random_numbers = "" +for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers += random_number + +# print(random_numbers) + +final_password = random_letters + random_symbols + random_numbers +print(f"Here is your easy password : {final_password}") + +#Hard Level - Order of characters randomised: +#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P + +random_letters = [] +for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters.append(random_letter) + +# print(random_letters) + +random_symbols = [] +for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols.append(random_symbol) + +# print(random_symbols) + +random_numbers = [] +for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers.append(random_number) + +# print(random_numbers) + +final_password_list = random_letters + random_symbols + random_numbers +r.shuffle(final_password_list) + +final_pass_in_str = "" +for char in final_password_list: + final_pass_in_str += char +print(f"Here is your difficult password : {final_pass_in_str}") From 794552ed5b7ca564b94f3770e393e4179b51a9ca Mon Sep 17 00:00:00 2001 From: Kartik Kapoor Date: Tue, 4 Oct 2022 03:07:27 +0530 Subject: [PATCH 018/129] Add codes for a simple vending machine and parse csv along with the required files. --- college.csv | 7 ++++++ employee.csv | 6 +++++ parse_csv.py | 52 +++++++++++++++++++++++++++++++++++++++ simple_vending_machine.py | 35 ++++++++++++++++++++++++++ university.csv | 7 ++++++ vendingitems.txt | 5 ++++ 6 files changed, 112 insertions(+) create mode 100644 college.csv create mode 100644 employee.csv create mode 100644 parse_csv.py create mode 100644 simple_vending_machine.py create mode 100644 university.csv create mode 100644 vendingitems.txt diff --git a/college.csv b/college.csv new file mode 100644 index 00000000..bf9d3a22 --- /dev/null +++ b/college.csv @@ -0,0 +1,7 @@ +branch,cgpa,name,year +COE,9.0,Nikhil,2 +COE,9.1,Sanchit,2 +IT,9.3,Aditya,2 +SE,9.5,Sagar,1 +MCE,7.8,Prateek,3 +EP,9.1,Sahil,2 diff --git a/employee.csv b/employee.csv new file mode 100644 index 00000000..558e682f --- /dev/null +++ b/employee.csv @@ -0,0 +1,6 @@ +name,department,birthday month +John Smith,Accounting,November +Erica Meyers,IT,March +David Warne,Accounting,April +May Myers,IT,October +Ryan Gosling,HR,November \ No newline at end of file diff --git a/parse_csv.py b/parse_csv.py new file mode 100644 index 00000000..c3525697 --- /dev/null +++ b/parse_csv.py @@ -0,0 +1,52 @@ +import csv +#read from csv +fields=list() +rows=list() +with open('employee.csv','r') as csv_file: + csv_reader=csv.reader(csv_file) + fields=next(csv_reader) #csv reader object + for row in csv_reader: + rows.append(row) + print("Total no. of rows={}".format(csv_reader.line_num)) +print("Field Names are:"+",".join(field for field in fields)) +print("First 5 rows are:\n") +for row in rows[:5]: + for col in row: + print("{}".format(col),end=" "), + print("\n") +#write to csv +flds=['Name','Branch','Year','CGPA'] +rw= [['Nikhil', 'COE', '2', '9.0'], + ['Sanchit', 'COE', '2', '9.1'], + ['Aditya', 'IT', '2', '9.3'], + ['Sagar', 'SE', '1', '9.5'], + ['Prateek', 'MCE', '3', '7.8'], + ['Sahil', 'EP', '2', '9.1']] +with open("university.csv",'w') as csvfile: + csvwriter=csv.writer(csvfile) + csvwriter.writerow(flds) + csvwriter.writerows(rw) +#write dictionary to csv + +mydict =[{'branch': 'COE', 'cgpa': '9.0', + 'name': 'Nikhil', 'year': '2'}, + {'branch': 'COE', 'cgpa': '9.1', + 'name': 'Sanchit', 'year': '2'}, + {'branch': 'IT', 'cgpa': '9.3', + 'name': 'Aditya', 'year': '2'}, + {'branch': 'SE', 'cgpa': '9.5', + 'name': 'Sagar', 'year': '1'}, + {'branch': 'MCE', 'cgpa': '7.8', + 'name': 'Prateek', 'year': '3'}, + {'branch': 'EP', 'cgpa': '9.1', + 'name': 'Sahil', 'year': '2'}] + +with open("college.csv",'w',newline='') as cv: + fieldnames=["branch","cgpa","name","year"] + writer=csv.DictWriter(cv,fieldnames=fieldnames) + writer.writeheader() + writer.writerows(mydict) +with open("college.csv",'r') as cvf: + reader=csv.DictReader(cvf) + for row in reader: + print(row['name'],row['branch']) \ No newline at end of file diff --git a/simple_vending_machine.py b/simple_vending_machine.py new file mode 100644 index 00000000..b9582807 --- /dev/null +++ b/simple_vending_machine.py @@ -0,0 +1,35 @@ +a=dict() +key_list=list() +def readFile(): + with open("vendingitems.txt",'r') as f: + for line in f: + (k,v)=line.strip().split('|') + a[k]=int(v) + key_list=a.keys() + print("Items available in vending machine",key_list) + +def vendingMachine(): + readFile() + while True: + item=input("Enter item name\n") + if(item in a.keys()): + print("Valid Item Name") + #break + cash=int(input("Enter money to deposit\n")) + if(isinstance(cash,int)==False): + print("Bad Input {}\n Try Again!".format(str(cash))) + #continue + else: + if(cash>a[item]): + print("Thank you for your purchase.Enjoy\n") + print("Do not forget to collect your change,{} Rs".format(cash-a[item])) + break + else: + print("Not enough Money to but the item\n") + continue + else: + print("Available Items are {} ,\nTry Again!".format(a.keys())) + continue + + +vendingMachine() \ No newline at end of file diff --git a/university.csv b/university.csv new file mode 100644 index 00000000..eee3eaf5 --- /dev/null +++ b/university.csv @@ -0,0 +1,7 @@ +Name,Branch,Year,CGPA +Nikhil,COE,2,9.0 +Sanchit,COE,2,9.1 +Aditya,IT,2,9.3 +Sagar,SE,1,9.5 +Prateek,MCE,3,7.8 +Sahil,EP,2,9.1 diff --git a/vendingitems.txt b/vendingitems.txt new file mode 100644 index 00000000..4e791db0 --- /dev/null +++ b/vendingitems.txt @@ -0,0 +1,5 @@ +Potato Chips|20 +Popcorn|30 +Chocolate|15 +Biscuit|10 +Soft Drink|12 \ No newline at end of file From 2b683e0ac7546dfde789cb5ba9936c8c089d1c00 Mon Sep 17 00:00:00 2001 From: Imam Suyuti Date: Tue, 4 Oct 2022 10:24:18 +0700 Subject: [PATCH 019/129] Add alphabet rangoli --- alphabet_rangoli.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 alphabet_rangoli.py diff --git a/alphabet_rangoli.py b/alphabet_rangoli.py new file mode 100644 index 00000000..eaa0df0e --- /dev/null +++ b/alphabet_rangoli.py @@ -0,0 +1,16 @@ +def print_rangoli(size): + rangoli = [] + l = (size-1)*4+1 + pattern = "" + for i in range(97+size-1, 96, -1): + pattern = f"{pattern}-{chr(i)}" if pattern != "" else chr(i) + leftSide = f"{pattern :->{l//2+1}}" + rightSide = leftSide[-2::-1] + rangoli.append(leftSide + rightSide) + + print('\n'.join(rangoli)) + print('\n'.join(rangoli[-2::-1])) + +if __name__ == '__main__': + n = int(input()) + print_rangoli(n) \ No newline at end of file From 828e85fafb0e8d344ec6d0b806c4168f6ec2fb8a Mon Sep 17 00:00:00 2001 From: Arjun M S <64315213+arjun-ms@users.noreply.github.com> Date: Tue, 4 Oct 2022 08:58:11 +0530 Subject: [PATCH 020/129] Add Banking System OOP Program --- banking_system.py | 70 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 banking_system.py diff --git a/banking_system.py b/banking_system.py new file mode 100644 index 00000000..c729cc91 --- /dev/null +++ b/banking_system.py @@ -0,0 +1,70 @@ +# TODO: +# Parent Class : User +# Holds details about an user +# Has function to show user details +# Child Class : Bank +# Stores details about the account balance +# Stores details about the amount +# Allows for deposit, withdraw and view balance + +# Parent Class +class User(): + def __init__(self,name,age,gender): + self.name = name + self.age = age + self.gender = gender + + def show_details(self): + print(f""" + Personal Details + ------------------------- + Name : {self.name} + Age : {self.age} + Gender : {self.gender} + """) + +# arjun = User('Arjun',20,'Male') +# print(arjun) +# arjun.show_details() + +# Child Class +class Bank(User): + def __init__(self, name, age, gender): + super().__init__(name, age, gender) + self.balance = 0 + + def deposit(self,amount): + self.amount = amount + self.balance += self.amount + print(f"Successfully Deposited : ${self.amount}") + print(f"Current Balance : ${self.balance}") + print() + + def withdraw(self,amount): + self.amount = amount + if self.amount < self.balance: + self.balance -= self.amount + print(f"Successfully Withdrawn ${self.amount}") + print(f"Current Balance : ${self.balance}") + print() + else: + print("Not Enough Balance!!!") + print(f"Current Balance : ${self.balance}") + print() + + def view_balance(self): + self.show_details() + print(" -------------------------") + print(f" Current Balance : ${self.balance}") + print() + +#-------------------------------------------------- + +sbi = Bank('Akshay',20,'Male') +print(sbi) +# sbi.show_details() +# sbi.view_balance() +# sbi.deposit(100) +sbi.deposit(1000) +sbi.withdraw(100) +# sbi.withdraw(1100) From dc456fe367c962de76b4bcdf61d0a718a307251a Mon Sep 17 00:00:00 2001 From: Imam Suyuti Date: Tue, 4 Oct 2022 10:36:49 +0700 Subject: [PATCH 021/129] Add Designer door mat --- Designer_door_mat.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Designer_door_mat.py diff --git a/Designer_door_mat.py b/Designer_door_mat.py new file mode 100644 index 00000000..521a9d79 --- /dev/null +++ b/Designer_door_mat.py @@ -0,0 +1,10 @@ +pattern = '.|.' +a, b = map(int, input().split()) # 5 < a < 101 and 15 < b < 303 + +for i in range(1,a,2): + print((pattern*i).center(b, '-')) + +print('WELCOME'.center(b,'-')) + +for i in reversed(range(1,a,2)): + print((pattern*i).center(b, '-')) \ No newline at end of file From ef09e5260d54c2de05300d3b319fe1ec9f0f1687 Mon Sep 17 00:00:00 2001 From: shriyans Date: Tue, 4 Oct 2022 09:14:24 +0530 Subject: [PATCH 022/129] " --- subtitle_synchronizer.py | 65 +++++++++++++++++++++++++++++++++++ two_sum_using_two_pointers.py | 21 +++++++++++ 2 files changed, 86 insertions(+) create mode 100644 subtitle_synchronizer.py create mode 100644 two_sum_using_two_pointers.py diff --git a/subtitle_synchronizer.py b/subtitle_synchronizer.py new file mode 100644 index 00000000..aebd1d68 --- /dev/null +++ b/subtitle_synchronizer.py @@ -0,0 +1,65 @@ +def convertToMilliseconds(time): + milliseconds = 0 + hh,mm,ms = time.split(":") + ms = ms.strip().replace(",","") + hh = int(hh) + mm = int(mm) + ms = int(ms) + + milliseconds = hh*3600000+mm*60000+ms + return milliseconds + +def synchronize(time,shift): + return time-shift + +def convertToTime(milliseconds): + hh = milliseconds//3600000 + milliseconds = milliseconds%3600000 + hh = str(hh) + if len(hh) < 2: hh = "0"+hh + + mm = milliseconds//60000 + milliseconds = milliseconds%60000 + mm = str(mm) + if len(mm) < 2: mm = "0"+mm + + ss = milliseconds//1000 + milliseconds = milliseconds%1000 + ss = str(ss) + if len(ss) < 2: ss = "0"+ss + + milliseconds = str(milliseconds) + while len(milliseconds) < 3: + milliseconds = "0"+milliseconds + + return f"{hh}:{mm}:{ss},{milliseconds}" + + +def main(): + SHIFT = int(input("Please enter the shift in milliseconds: ")) + f = open("input.txt", "r", errors="ignore") + output = open("output.txt","a") + for x in f: + if "-->" in x: + start,end = x.split("-->") + start,end = convertToMilliseconds(start), convertToMilliseconds(end) + start,end = synchronize(start,SHIFT),synchronize(end,SHIFT) + start,end = convertToTime(start),convertToTime(end) + output.write(f"{start} --> {end}\n") + else: + output.write(x) + + +#Right click the subtitles file you want to synchronize and open it in a notepad +#Then copy all of its content and paste it into a new file and name it as "input.txt" + +#You must have your "input.txt" in the same folder as this program + +#Once you run this program you will be asked to enter a shift in milliseconds. + +#You can find the shift when you are watching the video as it is impossible to +#determine that using any program since it is variable for every video. + +#Once the program has finished running, you will have your subtitles synchronized +#in a file that says "output.txt". Copy its content and paste it into your original subtitles file. +main() \ No newline at end of file diff --git a/two_sum_using_two_pointers.py b/two_sum_using_two_pointers.py new file mode 100644 index 00000000..de142cb4 --- /dev/null +++ b/two_sum_using_two_pointers.py @@ -0,0 +1,21 @@ +# This function takes 2 parameters the numbers array and the target +# If the target is found it returns the indices of the numbers which add up to the target +# If not found, it returns [-1,-1] + +# Time Complexity for this is O(NlogN) due to sorting +# Space Complexity is O(1) because we are not using any additional space + +def twoSum(nums, target): + nums.sort() + l, r = 0, len(nums) - 1 + + while l < r: + cur_sum = nums[l] + nums[r] + if cur_sum < target: + l += 1 + elif cur_sum > target: + r -= 1 + else: + return [l, r] + + return [-1, -1] From 5bf6e2a1d3efdb8b44220defded643a1b3107822 Mon Sep 17 00:00:00 2001 From: shriyans Date: Tue, 4 Oct 2022 09:15:43 +0530 Subject: [PATCH 023/129] 2 programs added. TwoSum using 2 pointerss and a subtitle synchronizer with comments for usage --- subtitle_synchronizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subtitle_synchronizer.py b/subtitle_synchronizer.py index aebd1d68..65d55991 100644 --- a/subtitle_synchronizer.py +++ b/subtitle_synchronizer.py @@ -62,4 +62,4 @@ def main(): #Once the program has finished running, you will have your subtitles synchronized #in a file that says "output.txt". Copy its content and paste it into your original subtitles file. -main() \ No newline at end of file +main() \ No newline at end of file From ac1b3921a384971006745ef53dbf30183811bbd8 Mon Sep 17 00:00:00 2001 From: Aayush Chaudhary <68678455+gamedevCloudy@users.noreply.github.com> Date: Tue, 4 Oct 2022 11:44:59 +0530 Subject: [PATCH 024/129] Create csvgen.py This is a simple CSV generator using python --- csvgen.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 csvgen.py diff --git a/csvgen.py b/csvgen.py new file mode 100644 index 00000000..0485bded --- /dev/null +++ b/csvgen.py @@ -0,0 +1,16 @@ +#This file generates a CSV file with integer values, +# Use cases: you can use it for eg. input for testing your sroting algorithms and other program inputs when you need to test with large data. + +import random as rd; + +minNum = 0; +maxNum = 1000; #maximum number in array +lengthOfItems= 500; #this will generate 500 random numbers. + +file = open("newFile.csv", "a") # creates a new file named newFile.csv - feel free to edit file name + +for i in range(lengthOfItems): + file.write(str(str(rd.randint(minNum,maxNum)) + ",")) + +file.close() +#note - you will have to split first line at "," and convert to int From d912d151cbbe118f619fab2bafed7dbdf9f15788 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Tue, 4 Oct 2022 11:51:59 +0530 Subject: [PATCH 025/129] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5c2df28e..908b36ab 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Basic-Python-Programs This repository will contain basic python programming questions and their solutions. +# Do give us a Star # Contributions From 2cc5d7d5a6d2897d7da53ab7046d3d9f2b1d8ee2 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Tue, 4 Oct 2022 11:53:34 +0530 Subject: [PATCH 026/129] Create contributing.md --- contributing.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 contributing.md diff --git a/contributing.md b/contributing.md new file mode 100644 index 00000000..4f36fa6d --- /dev/null +++ b/contributing.md @@ -0,0 +1,5 @@ +- Add a new program which don't exist earlier +- It should be in .py extenstion +- Please run the program and check if there are no errors before making the PR +- Review other PR's as well +- No Spamming allowed, make sure to include all programs in one PR. From f3dabfea5d511cb5aa51dd2c039160a9c4d58a33 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Tue, 4 Oct 2022 11:55:03 +0530 Subject: [PATCH 027/129] Create CONTRIBUTING.md --- CONTRIBUTING.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..4f36fa6d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,5 @@ +- Add a new program which don't exist earlier +- It should be in .py extenstion +- Please run the program and check if there are no errors before making the PR +- Review other PR's as well +- No Spamming allowed, make sure to include all programs in one PR. From 9ef7a43c92135b21033c1cdeef852a42cadffceb Mon Sep 17 00:00:00 2001 From: Saurabh-2809 <48317162+Saurabh-2809@users.noreply.github.com> Date: Tue, 4 Oct 2022 11:56:29 +0530 Subject: [PATCH 028/129] Updated Password_generator.py --- Password_generator.py | 128 ++++++++++++++++++++++-------------------- 1 file changed, 67 insertions(+), 61 deletions(-) diff --git a/Password_generator.py b/Password_generator.py index 942f3982..62d3368a 100644 --- a/Password_generator.py +++ b/Password_generator.py @@ -4,65 +4,71 @@ numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] -print("Welcome to the PyPassword Generator!") -nr_letters= int(input("How many letters would you like in your password?\n")) -nr_symbols = int(input(f"How many symbols would you like?\n")) -nr_numbers = int(input(f"How many numbers would you like?\n")) -#Eazy Level - Order not randomised: -#e.g. 4 letter, 2 symbol, 2 number = JduE&!91 -random_letters = "" -for i in range(0,nr_letters): - random_letter = r.choice(letters) - random_letters += random_letter - -# print(random_letters) - -random_symbols = "" -for i in range(0,nr_symbols): - random_symbol = r.choice(symbols) - random_symbols += random_symbol - -# print(random_symbols) - -random_numbers = "" -for i in range(0,nr_numbers): - random_number = r.choice(numbers) - random_numbers += random_number - -# print(random_numbers) - -final_password = random_letters + random_symbols + random_numbers -print(f"Here is your easy password : {final_password}") - -#Hard Level - Order of characters randomised: -#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P - -random_letters = [] -for i in range(0,nr_letters): - random_letter = r.choice(letters) - random_letters.append(random_letter) - -# print(random_letters) - -random_symbols = [] -for i in range(0,nr_symbols): - random_symbol = r.choice(symbols) - random_symbols.append(random_symbol) - -# print(random_symbols) - -random_numbers = [] -for i in range(0,nr_numbers): - random_number = r.choice(numbers) - random_numbers.append(random_number) - -# print(random_numbers) - -final_password_list = random_letters + random_symbols + random_numbers -r.shuffle(final_password_list) - -final_pass_in_str = "" -for char in final_password_list: - final_pass_in_str += char -print(f"Here is your difficult password : {final_pass_in_str}") +def easy_pass(nr_letters,nr_symbols,nr_numbers): + random_letters = "" + for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters += random_letter + + random_symbols = "" + for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols += random_symbol + + random_numbers = "" + for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers += random_number + + #Easy Level - Order not randomised: + #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 + final_password = random_letters + random_symbols + random_numbers + print(f"Here is your easy password : {final_password}") + +def hard_pass(nr_letters,nr_symbols,nr_numbers): + random_letters = [] + for i in range(0,nr_letters): + random_letter = r.choice(letters) + random_letters.append(random_letter) + + random_symbols = [] + for i in range(0,nr_symbols): + random_symbol = r.choice(symbols) + random_symbols.append(random_symbol) + + random_numbers = [] + for i in range(0,nr_numbers): + random_number = r.choice(numbers) + random_numbers.append(random_number) + + final_password_list = random_letters + random_symbols + random_numbers + r.shuffle(final_password_list) + + + #Hard Level - Order of characters randomised: + #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P + final_pass_in_str = "" + for char in final_password_list: + final_pass_in_str += char + print(f"Here is your hard password : {final_pass_in_str}") + + +def password_generator(): + print("Welcome to the PyPassword Generator!") + nr_letters= int(input("How many letters would you like in your password?\n")) + nr_symbols = int(input(f"How many symbols would you like?\n")) + nr_numbers = int(input(f"How many numbers would you like?\n")) + + print() + easy_pass(nr_letters,nr_symbols,nr_numbers) + print() + hard_pass(nr_letters,nr_symbols,nr_numbers) + + +def main(): + password_generator() + + +if __name__ == '__main__': + main() From a84875d962f13dd47397f8f3b6ce276f865a7c20 Mon Sep 17 00:00:00 2001 From: Kishan Modasiya Date: Tue, 4 Oct 2022 12:44:42 +0530 Subject: [PATCH 029/129] Create Tic Tac Toe game using Tkinter GUI --- TicTacToe.py | 124 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 TicTacToe.py diff --git a/TicTacToe.py b/TicTacToe.py new file mode 100644 index 00000000..04329745 --- /dev/null +++ b/TicTacToe.py @@ -0,0 +1,124 @@ +from tkinter import * +from tkinter import messagebox +import random as r +import functools + + +def button(f): + button1 = Button(f, text=" ", fg="Black", font="Arial 20 bold", height=1, width=2, padx=25, pady=20, bg="White", borderwidth=0, + activebackground="White", cursor="hand2", state=NORMAL) + return button1 + + +def full(): + for row in range(3): + for col in range(3): + if b[row][col]['text'] == " ": + return False + return True + + +def empty(): + for row in range(3): + for col in range(3): + b[row][col].config(text=" ", state=NORMAL) + + +def winner(s): + return b[0][0]['text'] == b[0][1]['text'] == b[0][2]['text'] == s or b[1][0]['text'] == b[1][1]['text'] == b[1][2]['text'] == s\ + or b[2][0]['text'] == b[2][1]['text'] == b[2][2]['text'] == s or b[0][0]['text'] == b[1][0]['text'] == b[2][0]['text'] == s\ + or b[0][1]['text'] == b[1][1]['text'] == b[2][1]['text'] == s or b[0][2]['text'] == b[1][2]['text'] == b[2][2]['text'] == s\ + or b[0][0]['text'] == b[1][1]['text'] == b[2][2]['text'] == s or b[0][2]['text'] == b[1][1]['text'] == b[2][0]['text'] == s + + +user_checked = [] +com_checked = [] + + +def click(event, param1, param2): + sign = 0 + if (param1, param2) in user_checked or (param1, param2) in com_checked: + messagebox.showwarning("Warning", "Select Another Box.") + else: + user_checked.append((param1, param2)) + b[param1][param2]['text'] = 'O' + + if winner("O"): + messagebox.showinfo("Winner", "You Won...") + user_score.set(user_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + sign = 1 + + if full(): + messagebox.showinfo("Tie", "Match Tie...!") + tie_score.set(tie_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + sign = 1 + + if sign == 0: + unchecked = [] + for row in range(3): + for col in range(3): + if b[row][col]['text'] == " ": + unchecked.append([row, col]) + index = r.sample(unchecked, 1) + b[index[0][0]][index[0][1]].config(text="X", state=DISABLED) + com_checked.append((index[0][0], index[0][1])) + if winner("X"): + messagebox.showinfo("Winner", "Computer Won...") + com_score.set(com_score.get() + 1) + empty() + user_checked.clear() + com_checked.clear() + else: + pass + + +root = Tk() +root.title("Tic Tac Toe") +root.geometry("420x500") +root.resizable(0, 0) +root.configure(bg="Black") +Label(root, text="TIC TAC TOE", fg="White", bg="Black", font="times 25 bold").pack() + +Frame(root, bg="White").pack(fill=X, pady=10) +frame = Frame(root, bg="Black") +Label(frame, text="YOU", fg="Yellow", bg="Black", font="System 10 bold", padx=50, pady=5).pack(side=LEFT) +Label(frame, text="TIE", fg="Yellow", bg="Black", font="System 10 bold", padx=48, pady=5).pack(side=LEFT) +Label(frame, text="COMPUTER", fg="Yellow", bg="Black", font="System 10 bold", padx=30, pady=5).pack(side=LEFT) +frame.pack(pady=5) + +frame = Frame(root, bg="Black") +user_score = IntVar() +tie_score = IntVar() +com_score = IntVar() +user_score.set(0) +tie_score.set(0) +com_score.set(0) +user = Entry(frame, textvariable=user_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +user.pack(side=LEFT, padx=35) +tie = Entry(frame, textvariable=tie_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +tie.pack(side=LEFT, padx=15) +com = Entry(frame, textvariable=com_score, fg="white", bg="Black", font="System 10 bold", width=10, borderwidth=0, + justify=CENTER) +com.pack(side=LEFT, padx=50) +frame.pack(pady=10) + +Frame(root, bg="White").pack(fill=X, pady=15) + +b = [[], [], []] +for i in range(3): + frame = Frame(root, highlightbackground="Black", highlightthickness=3, bg="Black") + for j in range(3): + b[i].append(button(frame)) + b[i][j].bind("", functools.partial(click, param1=i, param2=j)) + b[i][j].pack(side=LEFT, padx=5) + frame.pack() + +root.mainloop() From 7cacaa9b864ce84d6feb4baf1ab2708412e46ea5 Mon Sep 17 00:00:00 2001 From: Piyush Mishra Date: Tue, 4 Oct 2022 15:27:53 +0530 Subject: [PATCH 030/129] Create Pong_Game.py Created a basic pong game --- Pong_Game.py | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 Pong_Game.py diff --git a/Pong_Game.py b/Pong_Game.py new file mode 100644 index 00000000..e2afeede --- /dev/null +++ b/Pong_Game.py @@ -0,0 +1,121 @@ +import turtle as t +playerAscore=0 +playerBscore=0 + +#create a window and declare a variable called window and call the screen() +window=t.Screen() +window.title("The Pong Game") +window.bgcolor("green") +window.setup(width=800,height=600) +window.tracer(0) + +#Creating the left paddle +leftpaddle=t.Turtle() +leftpaddle.speed(0) +leftpaddle.shape("square") +leftpaddle.color("white") +leftpaddle.shapesize(stretch_wid=5,stretch_len=1) +leftpaddle.penup() +leftpaddle.goto(-350,0) + +#Creating the right paddle +rightpaddle=t.Turtle() +rightpaddle.speed(0) +rightpaddle.shape("square") +rightpaddle.color("white") +rightpaddle.shapesize(stretch_wid=5,stretch_len=1) +rightpaddle.penup() +rightpaddle.goto(-350,0) + +#Code for creating the ball +ball=t.Turtle() +ball.speed(0) +ball.shape("circle") +ball.color("red") +ball.penup() +ball.goto(5,5) +ballxdirection=0.2 +ballydirection=0.2 + +#Code for creating pen for scorecard update +pen=t.Turtle() +pen.speed(0) +pen.color("Blue") +pen.penup() +pen.hideturtle() +pen.goto(0,260) +pen.write("score",align="center",font=('Arial',24,'normal')) + +#code for moving the leftpaddle +def leftpaddleup(): + y=leftpaddle.ycor() + y=y+90 + leftpaddle.sety(y) + +def leftpaddledown(): + y=leftpaddle.ycor() + y=y+90 + leftpaddle.sety(y) + +#code for moving the rightpaddle +def rightpaddleup(): + y=rightpaddle.ycor() + y=y+90 + rightpaddle.sety(y) + +def rightpaddledown(): + y=rightpaddle.ycor() + y=y+90 + rightpaddle.sety(y) + +#Assign keys to play +window.listen() +window.onkeypress(leftpaddleup,'w') +window.onkeypress(leftpaddledown,'s') +window.onkeypress(rightpaddleup,'Up') +window.onkeypress(rightpaddledown,'Down') + +while True: + window.update() + + #moving the ball + ball.setx(ball.xcor()+ballxdirection) + ball.sety(ball.ycor()+ballxdirection) + + #border set up + if ball.ycor()>290: + ball.sety(290) + ballydirection=ballydirection*-1 + if ball.ycor()<-290: + ball.sety(-290) + ballydirection=ballydirection*-1 + + if ball.xcor() > 390: + ball.goto(0,0) + ball_dx = ball_dx * -1 + player_a_score = player_a_score + 1 + pen.clear() + pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + os.system("afplay wallhit.wav&") + + + + if(ball.xcor()) < -390: # Left width paddle Border + ball.goto(0,0) + ball_dx = ball_dx * -1 + player_b_score = player_b_score + 1 + pen.clear() + pen.write("Player A: {} Player B: {} ".format(player_a_score,player_b_score),align="center",font=('Monaco',24,"normal")) + os.system("afplay wallhit.wav&") + + # Handling the collisions with paddles. + + if(ball.xcor() > 340) and (ball.xcor() < 350) and (ball.ycor() < rightpaddle.ycor() + 40 and ball.ycor() > rightpaddle.ycor() - 40): + ball.setx(340) + ball_dx = ball_dx * -1 + os.system("afplay paddle.wav&") + + if(ball.xcor() < -340) and (ball.xcor() > -350) and (ball.ycor() < leftpaddle.ycor() + 40 and ball.ycor() > leftpaddle.ycor() - 40): + ball.setx(-340) + ball_dx = ball_dx * -1 + os.system("afplay paddle.wav&") From 0ac5ac548c1d62e5eb018887f8d6200ff4064e6f Mon Sep 17 00:00:00 2001 From: misbahulhaque234 Date: Tue, 4 Oct 2022 16:32:00 +0530 Subject: [PATCH 031/129] Recursion Questinos --- GeoMetric_sum.py | 16 ++++++++++++++++ Sum_of_Digits.py | 11 +++++++++++ 2 files changed, 27 insertions(+) create mode 100644 GeoMetric_sum.py create mode 100644 Sum_of_Digits.py diff --git a/GeoMetric_sum.py b/GeoMetric_sum.py new file mode 100644 index 00000000..4aa53151 --- /dev/null +++ b/GeoMetric_sum.py @@ -0,0 +1,16 @@ +# Geometric Sum = 1 + 1/2 + 1/4 + 1/8 + 1/16 + ... + 1/(2^n) +# where n is the input from the user +# Example: +# Input: 3 +# Output: 1.875 + +def geometricSum(n): + if n == 0: # base case + return 1 # return 1 if n == 0 + smallOutput = geometricSum(n - 1) # recursion call + # adding and smallOutput vaule + 1 and divide using 2^n + return smallOutput + 1 / pow(2, n) + + +n = int(input()) # taking input from user +print(geometricSum(n)) # calling the function and printing the result diff --git a/Sum_of_Digits.py b/Sum_of_Digits.py new file mode 100644 index 00000000..95e3c940 --- /dev/null +++ b/Sum_of_Digits.py @@ -0,0 +1,11 @@ +# Program for sum of digits + +def sumOfDigits(n): + if n == 0: # base case + return 0 # if n== 0 than return 0 + # return last digit + sum of digit of remaining number + return (n % 10 + sumOfDigits(int(n/10))) + + +n = int(input("Enter the number: ")) # taking input from user +sumOfDigits(n) # calling the function From 5258a8c36c8ce7e817c2cbc08aeede636eab2f5e Mon Sep 17 00:00:00 2001 From: Abhinav Reddy <99203556+16AbhinavReddy@users.noreply.github.com> Date: Tue, 4 Oct 2022 16:56:24 +0530 Subject: [PATCH 032/129] Added python files Added python graphics , random team generator and text audio generator --- Random Team Generator.py | 15 +++++++++++++++ python graphics.py | 23 +++++++++++++++++++++++ text-audio-generator.py | 15 +++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 Random Team Generator.py create mode 100644 python graphics.py create mode 100644 text-audio-generator.py diff --git a/Random Team Generator.py b/Random Team Generator.py new file mode 100644 index 00000000..23670025 --- /dev/null +++ b/Random Team Generator.py @@ -0,0 +1,15 @@ +import random +y = ["abhinav","sravan","koundinya","ajitesh","teja","tt"] +t1 = [] +t2 = [] +while (len(y) != 0): + x = random.choice(y) + if (len(t1) == len(t2)): + t1.append(x) + y.remove(x) + elif (len(t1) > len(t2)): + t2.append(x) + y.remove(x) +print("Team A: ", t1) +print("Team B: ", t2) + diff --git a/python graphics.py b/python graphics.py new file mode 100644 index 00000000..f2bd7e6d --- /dev/null +++ b/python graphics.py @@ -0,0 +1,23 @@ +import random +import turtle +colors = ['violet','indigo','blue','green','yellow','orange','red'] # Added VIBGYOR +t = turtle.Turtle() +t.speed(10) +turtle.bgcolor("black") +length=100 +angle =50 +size=5 +for i in range(length): + color=random.choice(colors) + t.pencolor(color) + t.fillcolor(color) + t.penup() + t.forward(i+50) + t.pendown() + t.left(angle) + t.begin_fill() + t.circle(size) + t.end_fill() +turtle.exitonclick() +turtle.bgcolor("black") + \ No newline at end of file diff --git a/text-audio-generator.py b/text-audio-generator.py new file mode 100644 index 00000000..cd6e8c6f --- /dev/null +++ b/text-audio-generator.py @@ -0,0 +1,15 @@ +''' + Before running this code, do type these commands in command prompt. + --> pip install gTTS + --> pip install playsound +''' +from gtts import gTTS + +from playsound import playsound +text_val = input("Enter the text which you want to convert: ") # Example : 'Learn Some Cool and Basic Python Programs here.' # + +language = 'en' +obj = gTTS(text=text_val, lang=language, slow=False) +obj.save("python.mp3") # This helps to save our audio file in the existing folder. + +playsound("python.mp3") # This runs the audio when you run the program. \ No newline at end of file From 57d36a1c36dced05f4ad938271f80f6d0ac48d88 Mon Sep 17 00:00:00 2001 From: mclmza Date: Tue, 4 Oct 2022 13:38:07 +0200 Subject: [PATCH 033/129] Added selection sort --- selection_sort.py | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 selection_sort.py diff --git a/selection_sort.py b/selection_sort.py new file mode 100644 index 00000000..c8450f2d --- /dev/null +++ b/selection_sort.py @@ -0,0 +1,48 @@ +# The selection sort algorithm sorts an array by repeatedly finding the minimum element. +# Time Complexity : O(n*n) + +""" +Algorithm :- +Step 1 − Set MIN to location 0 +Step 2 − Search the minimum element in the list +Step 3 − Swap with value at location MIN +Step 4 − Increment MIN to point to next element +Step 5 − Repeat until list is sorted +Pseudocode Selection Sort :- + list : array of items + n : size of list + for i = 1 to n - 1 + /* set current element as minimum*/ + min = i + + /* check the element to be minimum */ + for j = i+1 to n + if list[j] < list[min] then + min = j; + end if + end for + /* swap the minimum element with the current element*/ + if indexMin != i then + swap list[min] and list[i] + end if + end for + +end procedure +""" + + +def selection_sort(alist): + for i in range(0, len(alist) - 1): + smallest = i + for j in range(i + 1, len(alist)): + if alist[j] < alist[smallest]: + smallest = j + alist[i], alist[smallest] = alist[smallest], alist[i] + + +# Created a User-Input Array +alist = input('Enter The Numbers : ').split() +alist = [int(x) for x in alist] +selection_sort(alist) +print('Sorted List: ', end='') +print(alist) \ No newline at end of file From 2b397d9afa6191ebf65cd8540642360840f20638 Mon Sep 17 00:00:00 2001 From: Abhinav Reddy <99203556+16AbhinavReddy@users.noreply.github.com> Date: Tue, 4 Oct 2022 17:09:30 +0530 Subject: [PATCH 034/129] Update Random Team Generator.py --- Random Team Generator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Random Team Generator.py b/Random Team Generator.py index 23670025..73d6d3b5 100644 --- a/Random Team Generator.py +++ b/Random Team Generator.py @@ -1,5 +1,5 @@ import random -y = ["abhinav","sravan","koundinya","ajitesh","teja","tt"] +y = list(map(str,input().split())) t1 = [] t2 = [] while (len(y) != 0): From e3ccd09a1833bbc04003bb099a950284dcf5ba78 Mon Sep 17 00:00:00 2001 From: adarsh_nidamanuri <99207348+Adarsh-N123@users.noreply.github.com> Date: Tue, 4 Oct 2022 17:23:18 +0530 Subject: [PATCH 035/129] Add files via upload --- img_to_pencil.py | 15 +++++++++++++++ notification.py | 35 +++++++++++++++++++++++++++++++++++ password_generator.py | 27 +++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 img_to_pencil.py create mode 100644 notification.py create mode 100644 password_generator.py diff --git a/img_to_pencil.py b/img_to_pencil.py new file mode 100644 index 00000000..fc4b9c9e --- /dev/null +++ b/img_to_pencil.py @@ -0,0 +1,15 @@ +import cv2 +print("Enter file_name with extension in this folder(image):") +name = input() +print("Enter output file name without extension") +out = input() +out = out+".png" +image = cv2.imread(name) + +grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) +invert = cv2.bitwise_not(grey_img) + +blur = cv2.GaussianBlur(invert, (21, 21), 0) +invertedblur = cv2.bitwise_not(blur) +sketch = cv2.divide(grey_img, invertedblur, scale=256.0) +cv2.imwrite(out, sketch) diff --git a/notification.py b/notification.py new file mode 100644 index 00000000..bb38b8c1 --- /dev/null +++ b/notification.py @@ -0,0 +1,35 @@ +import time +from plyer import notification +print("Enter the Remainder Message:") +msg = input() +print("Enter the mode of time seconds or minutes or hours") +mode = input() +print("Enter the time left for remainder or time after which remainder should show:") +t = int(input()) +if mode == "seconds": + + time.sleep(t) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + +elif mode == "minutes": + + time.sleep(t*60) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + +elif mode == "hours": + + time.sleep(t*3600) + notification.notify( + title = "REMAINDER!!!", + message = msg, + timeout = 10 + ) + \ No newline at end of file diff --git a/password_generator.py b/password_generator.py new file mode 100644 index 00000000..b69fc98f --- /dev/null +++ b/password_generator.py @@ -0,0 +1,27 @@ +import random +special = ["!","@","#","$","%","^","&","*"] +alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] +num = [1,2,3,4,5,6,7,8,9,0] +print("Enter length of password:") +length = int(input()) +print("Enter no of special characters:") +spec = int(input()) +rem_char = length-spec +num_num = rem_char//3 +num_alpha = rem_char-num_num +L=[] +alpha_list = random.sample(alpha,num_alpha) +num_list = random.sample(num,num_num) +spec_list = random.sample(special,spec) +for i in alpha_list: + L.append(i) +for i in num_list: + L.append(i) +for i in spec_list: + L.append(i) +random.shuffle(L) +password="" +for i in L: + password +=str(i) +print("your password is :",password) + From c42ad4b86fb1aef75b76d0eea68c67d17a94480f Mon Sep 17 00:00:00 2001 From: Raluca Ginga Date: Tue, 4 Oct 2022 15:20:38 +0300 Subject: [PATCH 036/129] Added Tic Tac Toe program, but using MINIMAX Algorithm --- Player.py | 84 +++++++++++++++++++++++++++++++++++++++++ TicTacToe.py | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 Player.py create mode 100644 TicTacToe.py diff --git a/Player.py b/Player.py new file mode 100644 index 00000000..7b28c746 --- /dev/null +++ b/Player.py @@ -0,0 +1,84 @@ +import math +import random + + +class Player(): + def __init__(self, player): + self.player = player + + def get_move(self, game): + pass + + +class Human(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + valid_square = False + val = None + while not valid_square: + square = input(self.player + ' turn. Please introduce a move (1-9): ') + try: + val = int(square) - 1 + if val not in game.remaining_moves(): + raise ValueError + valid_square = True + except ValueError: + print('Invalid square. Try again.') + return val + + +class RandomComputer(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + square = random.choice(game.remaining_moves()) + return square + + +class SmartComputer(Player): + def __init__(self, player): + super().__init__(player) + + def get_move(self, game): + if len(game.remaining_moves()) == 9: + square = random.choice(game.remaining_moves()) + else: + square = self.minimax(game, self.player)['position'] + return square + + def minimax(self, state, player): + max_player = self.player + min_player = '0' if player == 'X' else 'X' + + # checking if the previous move is winner + if state.actual_winner == min_player: + return {'position': None, + 'score': 1 * (state.number_null_squares() + 1) if min_player == max_player + else -1 * (state.number_null_squares() + 1)} + elif not state.null_squares(): + return {'position': None, 'score': 0} + + if player == max_player: + best = {'position': None, 'score': -math.inf} + else: + best = {'position': None, 'score': math.inf} + + for possible_move in state.remaining_moves(): + state.make_a_move(possible_move, player) + sim_score = self.minimax(state, min_player) + + # undo move + state.board[possible_move] = ' ' + state.actual_winner = None + sim_score['position'] = possible_move + + if player == max_player: + if sim_score['score'] > best['score']: + best = sim_score + else: + if sim_score['score'] < best['score']: + best = sim_score + return best diff --git a/TicTacToe.py b/TicTacToe.py new file mode 100644 index 00000000..e74c53bf --- /dev/null +++ b/TicTacToe.py @@ -0,0 +1,104 @@ +import math +import time +from Player import SmartComputer, RandomComputer, Human + + +class TicTacToe(): + def __init__(self): + self.board = self.create_board() + self.actual_winner = None + + @staticmethod + def create_board(): + return [' ' for _ in range(9)] + + def board_show(self): + for cell in [self.board[i*3:(i+1)*3] for i in range(3)]: + print('| ' + ' | '.join(cell) + ' |') + + @staticmethod + def show_board_numbers(): + number_from_board = [[str(i + 1) for i in range(j*3, (j+1)*3)] for j in range(3)] + for cell in number_from_board: + print('| ' + ' | '.join(cell) + ' |') + + def make_a_move(self, square, player): + if self.board[square] == ' ': + self.board[square] = player + if self.winner_rules(square, player): + self.actual_winner = player + return True + return False + + def winner_rules(self, square, player): + # Checking the row + row_index = math.floor(square / 3) + row = self.board[row_index*3:(row_index+1)*3] + if all([l == player for l in row]): + return True + + # Checking the column + col_index = square % 3 + column = [self.board[col_index+i*3] for i in range(3)] + if all([l == player for l in column]): + return True + + # Checking for diagonal + if square % 2 == 0: + principal_diagonal = [self.board[i] for i in [0, 4, 8]] + if all([l == player for l in principal_diagonal]): + return True + + secondary_diagonal = [self.board[i] for i in [2, 4, 6]] + if all([l == player for l in secondary_diagonal]): + return True + + return False + + def null_squares(self): + return ' ' in self.board + + def number_null_squares(self): + return self.board.count(' ') + + def remaining_moves(self): + return [p for p, i in enumerate(self.board) if i == ' '] + + +def play(game, x_player, o_player, show_game = True): + if show_game: + game.show_board_numbers() + + player = 'X' + while game.null_squares(): + if player == '0': + square = o_player.get_move(game) + else: + square = x_player.get_move(game) + if game.make_a_move(square, player): + if show_game: + print(f'{player} makes a move to square {square}') + game.board_show() + print(' ') + + if game.actual_winner: + if show_game: + print(f'{player} wins!') + return player + player = '0' if player == 'X' else 'X' + + time.sleep(.8) + + if show_game: + print('Tie!') + + +if __name__ == '__main__': + #x_player = RandomComputer('0') + x_player = SmartComputer('0') + o_player = Human('X') + t = TicTacToe() + play(t, o_player, x_player, True) + + + From 72ea57c5a7233b340929614c3738945be07ec93d Mon Sep 17 00:00:00 2001 From: Raluca Ginga Date: Tue, 4 Oct 2022 15:20:55 +0300 Subject: [PATCH 037/129] Created a Reddit Scraper for different topics --- reddit_scraper.py | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 reddit_scraper.py diff --git a/reddit_scraper.py b/reddit_scraper.py new file mode 100644 index 00000000..0b5f9bf4 --- /dev/null +++ b/reddit_scraper.py @@ -0,0 +1,60 @@ +import requests +import csv +import time +from bs4 import BeautifulSoup + + +class HaikuScraper: + """ + This scraper is designed with the purpose of scraping Haikus (Japanese poems) from Reddit. + """ + def __init__(self, url: str, headers: dict): + self.url = url + self.headers = headers + + def make_request(self): + time.sleep(3) + page = requests.get(self.url, headers=self.headers) + soup = BeautifulSoup(page.text, 'html.parser') + return soup + + def get_next_page(self, soup: BeautifulSoup): + time.sleep(3) + next_button = soup.find('span', class_='next-button') + next_page_link = next_button.find("a").attrs['href'] + return next_page_link + + def get_haikus(self, soup: BeautifulSoup): + haikus = [str(title.text) for title in soup.find_all("a", class_="title may-blank ")] + return haikus + + def write_haikus_to_csv(self, haikus: list): + with open('scraped_haikus_v2.txt', 'a') as f: + writer = csv.writer(f) + for haiku in haikus: + writer.writerow([haiku]) + f.close() + + + +url = "https://old.reddit.com/r/haiku/" +# Headers to mimic a browser visit +headers = {'User-Agent': 'Mozilla/5.0'} + +scraper = HaikuScraper(url, headers) +soup = scraper.make_request() + +haikus = scraper.get_haikus(soup) +scraper.write_haikus_to_csv(haikus) + +counter = 1 + +while (counter <= 2500): + time.sleep(2) + link = scraper.get_next_page(soup) + print(f"Page {counter + 1}. Link {link}.") + scraper = HaikuScraper(link, headers) + soup = scraper.make_request() + haikus = scraper.get_haikus(soup) + scraper.write_haikus_to_csv(haikus) + counter += 1 \ No newline at end of file From eb5f9a3e61fefc2187dbdb39d13f1c41b2cf3c60 Mon Sep 17 00:00:00 2001 From: Muhammad Ahsan <69692532+Muhammad-Ahsan-Rasheed@users.noreply.github.com> Date: Tue, 4 Oct 2022 18:20:00 +0500 Subject: [PATCH 038/129] Added Age Calculator A simple python program to calculate the age of person using datetime. --- Age Calculator.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Age Calculator.py diff --git a/Age Calculator.py b/Age Calculator.py new file mode 100644 index 00000000..af545f45 --- /dev/null +++ b/Age Calculator.py @@ -0,0 +1,24 @@ +# Calculate the complete age of a person in years, months and days + +import datetime + +def calculate_age(born): + today = datetime.date.today() + return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) + +def main(): + + # Get the date of birth + dob = input("Enter your date of birth (YYYY-MM-DD): ") + + # Split the date into year, month and day + year, month, day = map(int, dob.split('-')) + + # Calculate the age + age = calculate_age(datetime.date(year, month, day)) + + # Print the age + print("Your age is: {}".format(age)) + +if __name__ == '__main__': + main() \ No newline at end of file From c1852111c466cbda47a557b2c6d5bb29269a6ad1 Mon Sep 17 00:00:00 2001 From: sumukh mg <83581264+sumukhmg@users.noreply.github.com> Date: Tue, 4 Oct 2022 19:08:43 +0530 Subject: [PATCH 039/129] Added 2048 game and Indian Flag using Turtle --- 2048game.py | 255 +++++++++++++++++++++++++++++++++++++++++++ Indianflag-Turtle.py | 90 +++++++++++++++ 2 files changed, 345 insertions(+) create mode 100644 2048game.py create mode 100644 Indianflag-Turtle.py diff --git a/2048game.py b/2048game.py new file mode 100644 index 00000000..868279e8 --- /dev/null +++ b/2048game.py @@ -0,0 +1,255 @@ +# logic.py to be +# imported in the 2048.py file + +# importing random package +# for methods to generate random +# numbers. +import random + +# function to initialize game / grid +# at the start +def start_game(): + + # declaring an empty list then + # appending 4 list each with four + # elements as 0. + mat =[] + for i in range(4): + mat.append([0] * 4) + + # printing controls for user + print("Commands are as follows : ") + print("'W' or 'w' : Move Up") + print("'S' or 's' : Move Down") + print("'A' or 'a' : Move Left") + print("'D' or 'd' : Move Right") + + # calling the function to add + # a new 2 in grid after every step + add_new_2(mat) + return mat + +# function to add a new 2 in +# grid at any random empty cell +def add_new_2(mat): + +# choosing a random index for +# row and column. + r = random.randint(0, 3) + c = random.randint(0, 3) + + # while loop will break as the + # random cell chosen will be empty + # (or contains zero) + while(mat[r] != 0): + r = random.randint(0, 3) + c = random.randint(0, 3) + + # we will place a 2 at that empty + # random cell. + mat[r] = 2 + +# function to get the current +# state of game +def get_current_state(mat): + + # if any cell contains + # 2048 we have won + for i in range(4): + for j in range(4): + if(mat[i][j]== 2048): + return 'WON' + + # if we are still left with + # atleast one empty cell + # game is not yet over + for i in range(4): + for j in range(4): + if(mat[i][j]== 0): + return 'GAME NOT OVER' + + # or if no cell is empty now + # but if after any move left, right, + # up or down, if any two cells + # gets merged and create an empty + # cell then also game is not yet over + for i in range(3): + for j in range(3): + if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]): + return 'GAME NOT OVER' + + for j in range(3): + if(mat[3][j]== mat[3][j + 1]): + return 'GAME NOT OVER' + + for i in range(3): + if(mat[i][3]== mat[i + 1][3]): + return 'GAME NOT OVER' + + # else we have lost the game + return 'LOST' + +# all the functions defined below +# are for left swap initially. + +# function to compress the grid +# after every step before and +# after merging cells. +def compress(mat): + + # bool variable to determine + # any change happened or not + changed = False + + # empty grid + new_mat = [] + + # with all cells empty + for i in range(4): + new_mat.append([0] * 4) + + # here we will shift entries + # of each cell to it's extreme + # left row by row + # loop to traverse rows + for i in range(4): + pos = 0 + + # loop to traverse each column + # in respective row + for j in range(4): + if(mat[i][j] != 0): + + # if cell is non empty then + # we will shift it's number to + # previous empty cell in that row + # denoted by pos variable + new_mat[i][pos] = mat[i][j] + + if(j != pos): + changed = True + pos += 1 + + # returning new compressed matrix + # and the flag variable. + return new_mat, changed + +# function to merge the cells +# in matrix after compressing +def merge(mat): + + changed = False + + for i in range(4): + for j in range(3): + + # if current cell has same value as + # next cell in the row and they + # are non empty then + if(mat[i][j] == mat[i][j + 1] and mat[i][j] != 0): + + # double current cell value and + # empty the next cell + mat[i][j] = mat[i][j] * 2 + mat[i][j + 1] = 0 + + # make bool variable True indicating + # the new grid after merging is + # different. + changed = True + + return mat, changed + +# function to reverse the matrix +# means reversing the content of +# each row (reversing the sequence) +def reverse(mat): + new_mat =[] + for i in range(4): + new_mat.append([]) + for j in range(4): + new_mat[i].append(mat[i][3 - j]) + return new_mat + +# function to get the transpose +# of matrix means interchanging +# rows and column +def transpose(mat): + new_mat = [] + for i in range(4): + new_mat.append([]) + for j in range(4): + new_mat[i].append(mat[j][i]) + return new_mat + +# function to update the matrix +# if we move / swipe left +def move_left(grid): + + # first compress the grid + new_grid, changed1 = compress(grid) + + # then merge the cells. + new_grid, changed2 = merge(new_grid) + + changed = changed1 or changed2 + + # again compress after merging. + new_grid, temp = compress(new_grid) + + # return new matrix and bool changed + # telling whether the grid is same + # or different + return new_grid, changed + +# function to update the matrix +# if we move / swipe right +def move_right(grid): + + # to move right we just reverse + # the matrix + new_grid = reverse(grid) + + # then move left + new_grid, changed = move_left(new_grid) + + # then again reverse matrix will + # give us desired result + new_grid = reverse(new_grid) + return new_grid, changed + +# function to update the matrix +# if we move / swipe up +def move_up(grid): + + # to move up we just take + # transpose of matrix + new_grid = transpose(grid) + + # then move left (calling all + # included functions) then + new_grid, changed = move_left(new_grid) + + # again take transpose will give + # desired results + new_grid = transpose(new_grid) + return new_grid, changed + +# function to update the matrix +# if we move / swipe down +def move_down(grid): + + # to move down we take transpose + new_grid = transpose(grid) + + # move right and then again + new_grid, changed = move_right(new_grid) + + # take transpose will give desired + # results. + new_grid = transpose(new_grid) + return new_grid, changed + +# this file only contains all the logic +# functions to be called in main function +# present in the other file diff --git a/Indianflag-Turtle.py b/Indianflag-Turtle.py new file mode 100644 index 00000000..71744244 --- /dev/null +++ b/Indianflag-Turtle.py @@ -0,0 +1,90 @@ +import turtle +from turtle import* + +#screen for output +screen = turtle.Screen() + +# Defining a turtle Instance +t = turtle.Turtle() +speed(0) + +# initially penup() +t.penup() +t.goto(-400, 250) +t.pendown() + +# Orange Rectangle +#white rectangle +t.color("orange") +t.begin_fill() +t.forward(800) +t.right(90) +t.forward(167) +t.right(90) +t.forward(800) +t.end_fill() +t.left(90) +t.forward(167) + +# Green Rectangle +t.color("green") +t.begin_fill() +t.forward(167) +t.left(90) +t.forward(800) +t.left(90) +t.forward(167) +t.end_fill() + +# Big Blue Circle +t.penup() +t.goto(70, 0) +t.pendown() +t.color("navy") +t.begin_fill() +t.circle(70) +t.end_fill() + +# Big White Circle +t.penup() +t.goto(60, 0) +t.pendown() +t.color("white") +t.begin_fill() +t.circle(60) +t.end_fill() + +# Mini Blue Circles +t.penup() +t.goto(-57, -8) +t.pendown() +t.color("navy") +for i in range(24): + t.begin_fill() + t.circle(3) + t.end_fill() + t.penup() + t.forward(15) + t.right(15) + t.pendown() + +# Small Blue Circle +t.penup() +t.goto(20, 0) +t.pendown() +t.begin_fill() +t.circle(20) +t.end_fill() +# Spokes +t.penup() +t.goto(0, 0) +t.pendown() +t.pensize(2) +for i in range(24): + t.forward(60) + t.backward(60) + t.left(15) + +#to hold the +#output window +turtle.done() \ No newline at end of file From b75523d6d14ff65edd0d4da1e32ae878cae23168 Mon Sep 17 00:00:00 2001 From: Sreeharan Date: Tue, 4 Oct 2022 19:25:15 +0530 Subject: [PATCH 040/129] Added reverse the words in a string program --- reverse_words_of_string.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 reverse_words_of_string.py diff --git a/reverse_words_of_string.py b/reverse_words_of_string.py new file mode 100644 index 00000000..dab11533 --- /dev/null +++ b/reverse_words_of_string.py @@ -0,0 +1,14 @@ +""" + This is Leetcode question: https://leetcode.com/problems/reverse-words-in-a-string/ + +""" + +def reverseWords(s: str) -> str: + s = s.split() + s.reverse() + return " ".join(s) + + +assert reverseWords(" Hello World ")=="World Hello" +assert reverseWords("a good example")=="example good a" +assert reverseWords("okay")=="okay" From 9e3a2a95fff486826259fa67e6b83693a7171fca Mon Sep 17 00:00:00 2001 From: niro Date: Tue, 4 Oct 2022 15:59:00 +0200 Subject: [PATCH 041/129] Improved existing calculator --- calculator.py | 85 +++++++++++++++++++++++++++++---------------------- 1 file changed, 48 insertions(+), 37 deletions(-) diff --git a/calculator.py b/calculator.py index 6f0f018c..88bcdb35 100644 --- a/calculator.py +++ b/calculator.py @@ -1,59 +1,70 @@ -num1=int(input("eneter a digit")) -num2=int(input("eneter a another digit")) -# defination for operators - -#addition -def add(num1, num2): - return num1+num2 -#substraction -def subtract(num1, num2): - return num1-num2 -#multiply -def multiply(num1, num2): - return num1*num2 -#division -def divide(num1, num2): - return num1/num2 - -#command for operation -print("choose operation") -print("press 1 for add") -print("press 2 for subs") -print("press 3 for multiply") -print("press 4 for devision") - - - +while True: + # definition for operators + + #addition + def add(num1, num2): + return num1+num2 + + #substraction + def subtract(num1, num2): + return num1-num2 + + #multiplication + def multiply(num1, num2): + return num1*num2 + + #division + def divide(num1, num2): + try: + return num1/num2 + except ZeroDivisionError: + print ("WARNING: Invalid division, cannot divide by zero") + + #exponent + def exponent(num1, num2): + return num1**num2 + + while True: + try: + num1=float(input("Enter a digit: ")) + num2=float(input("Enter another digit: ")) + break + except ValueError: + print("The input was not a valid digit") + #command for operation + print("Choose an operation") + print("Press 1 for addition") + print("Press 2 for substraction") + print("Press 3 for multiplication") + print("Press 4 for division") + print("Press 5 for exponent") -while True: # take input from the user - choice = input("Enter choice(1/2/3/4): ") + choice = input("Enter choice(1/2/3/4/5): ") - if choice in ('1', '2', '3', '4'): + if choice in ('1', '2', '3', '4', '5'): if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) - - elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) - - - - elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) + + elif choice == '5': + print(num1, "to the power of", num2, "=", exponent(num1, num2)) + # check if user wants another calculation # break the while loop if answer is no - next_calculation = input("Let's do next calculation? (yes/no): ") + next_calculation = input("Do you want to do another calculation? (yes/no): ") if next_calculation == "no": break else: - print("Invalid Input") + print("Invalid input") From 7b1ca1249788df269ed077f178b3ee747feec9cb Mon Sep 17 00:00:00 2001 From: Bharath_acchu Date: Tue, 4 Oct 2022 19:34:54 +0530 Subject: [PATCH 042/129] Added dijkstra's algorithm Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. --- DjikistraAlgorithm.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 DjikistraAlgorithm.py diff --git a/DjikistraAlgorithm.py b/DjikistraAlgorithm.py new file mode 100644 index 00000000..65238794 --- /dev/null +++ b/DjikistraAlgorithm.py @@ -0,0 +1,43 @@ +class Graph: + def __init__(self): + self.nodes = set() + self.edges = defaultdict(list) + self.distances = {} + + def add_node(self, value): + self.nodes.add(value) + + def add_edge(self, from_node, to_node, distance): + self.edges[from_node].append(to_node) + self.edges[to_node].append(from_node) + self.distances[(from_node, to_node)] = distance + + +def dijsktra(graph, initial): + visited = {initial: 0} + path = {} + + nodes = set(graph.nodes) + + while nodes: + min_node = None + for node in nodes: + if node in visited: + if min_node is None: + min_node = node + elif visited[node] < visited[min_node]: + min_node = node + + if min_node is None: + break + + nodes.remove(min_node) + current_weight = visited[min_node] + + for edge in graph.edges[min_node]: + weight = current_weight + graph.distance[(min_node, edge)] + if edge not in visited or weight < visited[edge]: + visited[edge] = weight + path[edge] = min_node + + return visited, path \ No newline at end of file From ed72964a46cd42e4c53c14e7ccc93e942c1b87db Mon Sep 17 00:00:00 2001 From: sumit-awasthi <72277800+sumit-awasthi@users.noreply.github.com> Date: Tue, 4 Oct 2022 19:36:06 +0530 Subject: [PATCH 043/129] Created Economy_Chart.py --- Economy_chart.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Economy_chart.py diff --git a/Economy_chart.py b/Economy_chart.py new file mode 100644 index 00000000..40a095ae --- /dev/null +++ b/Economy_chart.py @@ -0,0 +1,15 @@ +import matplotlib.pyplot as plt; plt.rcdefaults() +import numpy as np +import matplotlib.pyplot as plt + +#objects = ('America', 'India', 'Africa', 'UK', 'UAE','Iran') +objects = ('Brazil', 'Italy', 'Canada', 'France', 'UK','India','Germany','Japan','China','USA') +y_pos = np.arange(len(objects)) +performance=[1.80,2.00,2.10,2.80,3.30,3.50,4.10,4.80,19.80,24.10] + +plt.barh(y_pos, performance, align='center', alpha=1) +plt.yticks(y_pos, objects) +plt.xlabel('Usage') +plt.title('Top 10 Economies of the World in 2022') + +plt.show() From d72c87985f25dbacdf00bb3a6dc770699c0ba284 Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Tue, 4 Oct 2022 13:53:56 -0300 Subject: [PATCH 044/129] Add arabic_to_roman_numbers.py --- arabic_to_roman_numbers.py | 90 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 arabic_to_roman_numbers.py diff --git a/arabic_to_roman_numbers.py b/arabic_to_roman_numbers.py new file mode 100644 index 00000000..c36f1be7 --- /dev/null +++ b/arabic_to_roman_numbers.py @@ -0,0 +1,90 @@ +def toRoman(num): + romans = { + 1000: "M", + 900: "CM", + 500: "D", + 400: "CD", + 100: "C", + 90: "XC", + 50: "L", + 40: "XL", + 10: "X", + 9: "IX", + 5: "V", + 4: "IV", + 1: "I" + } + + if num < 4000: + results = '' + + for decimal, rom in zip(romans.keys(), romans.values()): + div, num = divmod(num, decimal) + results += rom * div + + return results + + else: + return toRoman(num // 1000) + ' ⎺ ' + toRoman(num - 1000 * (num // 1000)) + +# Tests +def test(value, expected): + results = toRoman(value) + if results == expected: + print(f'✓ Test {value} correct') + else: + print(f'✗ Test {value} incorrect. Expected {expected}, obtained {results}') + +# Tests +def test(value, expected): + results = toRoman(value) + if results == expected: + print(f'✓ Test {value} correct') + else: + print(f'✗ Test {value} incorrect. Expected {expected}, obtained {results}') + + +# test(1, "I") +# test(2, "II") +# test(3, "III") +# test(4, "IV") +# test(5, "V") +# test(6, "VI") +# test(7, "VII") +# test(8, "VIII") +# test(9, "IX") +# test(10, "X") +# test(12, "XII") +# test(15, "XV") +# test(18, "XVIII") +# test(19, "XIX") +# test(29, "XXIX") +# test(38, "XXXVIII") +# test(47, "XLVII") +# test(56, "LVI") +# test(65, "LXV") +# test(74, "LXXIV") +# test(83, "LXXXIII") +# test(90, "XC") +# test(92, "XCII") +# test(100, "C") +# test(110, "CX") +# test(200, "CC") +# test(220, "CCXX") +# test(300, "CCC") +# test(330, "CCCXXX") +# test(400, "CD") +# test(440, "CDXL") +# test(500, "D") +# test(550, "DL") +# test(600, "DC") +# test(660, "DCLX") +# test(700, "DCC") +# test(770, "DCCLXX") +# test(800, "DCCC") +# test(880, "DCCCLXXX") +# test(900, "CM") +# test(990, "CMXC") +# test(1000, "M") + +toRoman(100) From 0d3d617eb87fb89bce053472de1646b6479b2ceb Mon Sep 17 00:00:00 2001 From: OjashKush Date: Tue, 4 Oct 2022 22:49:31 +0530 Subject: [PATCH 045/129] Add python program that omit all vowels --- novowels.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 novowels.py diff --git a/novowels.py b/novowels.py new file mode 100644 index 00000000..0fdceb7f --- /dev/null +++ b/novowels.py @@ -0,0 +1,14 @@ +def main(): + sts = str(input("Input: ")) + without_vowels = shorten(sts) + print("Output: " + without_vowels) + +def shorten(word): + lttr = "" + for letter in word: + if not letter.lower() in ['a', 'e', 'i', 'o', 'u']: + lttr += letter + return lttr + +if __name__ == "__main__": + main() \ No newline at end of file From b190941f265cd063f5e85fe19f5009944e6589ef Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Tue, 4 Oct 2022 15:28:33 -0300 Subject: [PATCH 046/129] Add question em coments --- arabic_to_roman_numbers.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/arabic_to_roman_numbers.py b/arabic_to_roman_numbers.py index c36f1be7..060f3548 100644 --- a/arabic_to_roman_numbers.py +++ b/arabic_to_roman_numbers.py @@ -1,3 +1,11 @@ +################################################################################ + +# Question +# Write a script that convert numbers from arabic to roman format + +################################################################################ + +# Answer def toRoman(num): romans = { 1000: "M", @@ -27,7 +35,9 @@ def toRoman(num): else: return toRoman(num // 1000) + ' ⎺ ' + toRoman(num - 1000 * (num // 1000)) -# Tests +################################################################################ + +# Test def test(value, expected): results = toRoman(value) if results == expected: @@ -35,15 +45,9 @@ def test(value, expected): else: print(f'✗ Test {value} incorrect. Expected {expected}, obtained {results}') -# Tests -def test(value, expected): - results = toRoman(value) - if results == expected: - print(f'✓ Test {value} correct') - else: - print(f'✗ Test {value} incorrect. Expected {expected}, obtained {results}') - +################################################################################ +# Remove coment from line below to test some exemples # test(1, "I") # test(2, "II") # test(3, "III") @@ -87,4 +91,9 @@ def test(value, expected): # test(990, "CMXC") # test(1000, "M") +################################################################################ + +# Working exemple toRoman(100) + +################################################################################ From 46f18ec56e650e6b14ab6d595612ec4966f3daf8 Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Tue, 4 Oct 2022 15:30:27 -0300 Subject: [PATCH 047/129] Remove duplicate information --- CONTRIBUTING.md | 5 ----- contributing.md | 5 ----- 2 files changed, 10 deletions(-) delete mode 100644 CONTRIBUTING.md delete mode 100644 contributing.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 4f36fa6d..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,5 +0,0 @@ -- Add a new program which don't exist earlier -- It should be in .py extenstion -- Please run the program and check if there are no errors before making the PR -- Review other PR's as well -- No Spamming allowed, make sure to include all programs in one PR. diff --git a/contributing.md b/contributing.md deleted file mode 100644 index 4f36fa6d..00000000 --- a/contributing.md +++ /dev/null @@ -1,5 +0,0 @@ -- Add a new program which don't exist earlier -- It should be in .py extenstion -- Please run the program and check if there are no errors before making the PR -- Review other PR's as well -- No Spamming allowed, make sure to include all programs in one PR. From 30610831846b9e405ecae07c0ff20f27093bdd46 Mon Sep 17 00:00:00 2001 From: HariKiran Date: Wed, 5 Oct 2022 00:05:46 +0530 Subject: [PATCH 048/129] Simple Hashmap implementation --- simple_custom_hash_map_implementation.py | 79 ++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 simple_custom_hash_map_implementation.py diff --git a/simple_custom_hash_map_implementation.py b/simple_custom_hash_map_implementation.py new file mode 100644 index 00000000..83a70919 --- /dev/null +++ b/simple_custom_hash_map_implementation.py @@ -0,0 +1,79 @@ +# This class is to demonstate the how Hashmap generally works +# Feel free to make changes and play with it + +class MyHashMap: + def __init__(self, max_size=10): + self.MAX_SIZE = max_size + self.map = [None] * self.MAX_SIZE + + # function will return index in the array based on the key + def _hash_function(self, key): + if type(key) == str: + hash_val = 0 + for i in range(len(key)): + hash_val += ((i+1)*ord(key[i])) + else: + hash_val = int(key) + + return hash_val % self.MAX_SIZE + + # function to add key and value and + # if key already present updates the value + def add(self, key, val): + idx = self._hash_function(key) + if self.map[idx] is None: + self.map[idx] = [[key, val]] + else: + if self.is_present(key): + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + self.map[idx][i][1] = val + else: + self.map[idx].append([key, val]) + + # returns value if key exits + # else raises an error + def get(self, key): + if self.is_present(key): + idx = self._hash_function(key) + for key_val in self.map[idx]: + if key_val[0] == key: + return key_val[1] + else: + raise KeyError("Key: {} doesn't exist".format(key)) + + # deletes a value if key exists + # else raises error + def delete(self, key): + if self.is_present(key): + idx = self._hash_function(key) + for i in range(len(self.map[idx])): + if self.map[idx][i][0] == key: + del self.map[idx][i] + else: + raise KeyError("Key: {} doesn't exist".format(key)) + + # returns True if key exists + # else False + def is_present(self, key): + idx = self._hash_function(key) + + if self.map[idx] is None: + return False + + for key_val in self.map[idx]: + if key_val[0] == key: + return True + + return False + + +if __name__ == '__main__': + h = MyHashMap() + h.add('name', "Hari") + h.add('roll', 202089) + h.add('name', "kiran") + h.add(3.2, 'float') + print(h.get('name')) + print(h.get('roll')) + print(h.get(3.2)) From c2f809ba397ccc2a4611b1fb9a07e82f7951e4f1 Mon Sep 17 00:00:00 2001 From: brihad24 Date: Wed, 5 Oct 2022 00:32:20 +0530 Subject: [PATCH 049/129] Create Areas.py --- Areas.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Areas.py diff --git a/Areas.py b/Areas.py new file mode 100644 index 00000000..a5608da0 --- /dev/null +++ b/Areas.py @@ -0,0 +1,58 @@ +# Program to calculate the ares of 2d shapes + +import math + + + +def square(side): + area = side * side + return area + +def rectangle(length, breadth): + area = length * breadth + return area + +def triangle(side1, side2, side3): + s = (side1 + side2 + side3)/2 + area = math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) + return area + +def circle(radius): + area = 3.14 * radius * radius + return area + +final_area = 0.0 +print("Choose the shape you want to calculate area of: ") + +while True: + print("Square, Rectangle, Triangle, Circle") + shape = input('>> ') + print(shape.lower()) + + if shape.lower() == "square": + side = float(input("Enter the value of side: ")) + final_area = square(side) + break + + elif shape.lower() == "rectangle": + length = float(input("Enter value of length: ")) + breadth = float(input("Enter value of breadth: ")) + final_area = rectangle(length, breadth) + break + + elif shape.lower() == "triangle": + side1 = float(input("Enter the value of 1st side: ")) + side2 = float(input("Enter the value of 2nd side: ")) + side3 = float(input("Enter the value of 3rd side: ")) + final_area = triangle(side1, side2, side3) + break + + elif shape.lower() == "circle": + radius = float(input("Enter the value of radius: ")) + final_area = circle(radius) + break + + else: + print("Please choose a shape from the given 4 or check your spelling again") + +print(f"The area of the shape is: {final_area}") \ No newline at end of file From edaae2fbc2a8701fc82ac20570f22ae9cced5818 Mon Sep 17 00:00:00 2001 From: brihad24 Date: Wed, 5 Oct 2022 00:34:22 +0530 Subject: [PATCH 050/129] Created Areas.py --- Areas.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Areas.py b/Areas.py index a5608da0..80518366 100644 --- a/Areas.py +++ b/Areas.py @@ -1,9 +1,7 @@ -# Program to calculate the ares of 2d shapes +# Program to calculate the areas of 2d shapes import math - - def square(side): area = side * side return area From aa08ee7ab0f97d98546b6a44e547f4b6bc79ae67 Mon Sep 17 00:00:00 2001 From: Aishwarya Nevrekar <37922612+aishwaryanevrekar@users.noreply.github.com> Date: Wed, 5 Oct 2022 01:02:21 +0530 Subject: [PATCH 051/129] Create ProductOfSumAndDifference.py You are given two integers, a and b. Compute the Sum and Difference of a and b. Return the Product of Sum and Difference. Input Format First Parameter - Integer a Second Parameter - Integer b Output Format Return the integer. Example 1: Input: 5 2 Output: 21 Explanation: Sum is (5 + 2) = 7 and Difference is (5 - 2) = 3. The product of Sum and Difference is 21. --- ProductOfSumAndDifference.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 ProductOfSumAndDifference.py diff --git a/ProductOfSumAndDifference.py b/ProductOfSumAndDifference.py new file mode 100644 index 00000000..560b0c9b --- /dev/null +++ b/ProductOfSumAndDifference.py @@ -0,0 +1,8 @@ +def solve(a, b): + return (a+b)*(a-b) + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + res = solve(a, b) + print(res) From 4410bd5c5727fd18fa19e137ab884f73dfc3e32a Mon Sep 17 00:00:00 2001 From: Felix Baron Date: Tue, 4 Oct 2022 23:32:38 +0200 Subject: [PATCH 052/129] added a test (pytest) to Bubble_Sort --- Bubble_Sort.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Bubble_Sort.py b/Bubble_Sort.py index b801c382..90a2690d 100644 --- a/Bubble_Sort.py +++ b/Bubble_Sort.py @@ -44,6 +44,14 @@ def main(): sort.bubbleSortRecursive() print("Sorted array :\n", sort) + +# Tests ('pip install pytest'; run with 'pytest Bubble_Sort.py') +def test_result_in_order(): + array = [64, 34, 25, 12, 22, 11, 90] + sort = bubbleSort(array) + sort.bubbleSortRecursive() + for i in range(sort.length-1): + assert sort.array[i] < sort.array[i+1] if __name__ == "__main__": From 1a8a2e7fae678770903ec5f39b4604b0242688c2 Mon Sep 17 00:00:00 2001 From: Vasilis Asimakopoulos Date: Wed, 5 Oct 2022 00:34:56 +0300 Subject: [PATCH 053/129] Create Bifurcation diagram .py --- Bifurcation diagram .py | 65 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Bifurcation diagram .py diff --git a/Bifurcation diagram .py b/Bifurcation diagram .py new file mode 100644 index 00000000..ad3d215a --- /dev/null +++ b/Bifurcation diagram .py @@ -0,0 +1,65 @@ +# Bifurcation diagram + + +from cmath import inf +import numpy as np +import matplotlib.pyplot as plt +import math +import csv +import matplotlib as mpl +import time +from numba import njit +import multiprocessing +from multiprocessing import Pool +multiprocessing.cpu_count() +from functools import reduce + +from functools import partial + + + +start_time = time.time() + + +#change these values +x0=0.1 +q0=-0.1 +begin_r=0 +end_r=1 +step=0.0001 + + + +r=np.arange(begin_r,end_r,step) +X=[] +Y=[] + +@njit +def bif(q0, x0, r): + N=1000 + x = np.zeros(len(range(0, N))) + x[0]=x0 + q=q0 + for i in range(1,N): + x[i]= r *(1 + x[i - 1]) * (1 + x[i- 1]) * (2 - x[i - 1]) + q #logistic with extra parameter + + return (x[-130:]) + +bif1 = partial(bif, q0, x0) +if __name__ == '__main__': + # create and configure the process pool + with Pool(4) as p: + + for i,ch in enumerate(p.map(bif1,r,chunksize=2500)) : + x1=np.ones(len(ch))*r[i] + X.append(x1) + Y.append(ch) + print("--- %s seconds ---" % (time.time() - start_time)) + + plt.style.use('dark_background') + plt.plot(X,Y, ".w", alpha=1, ms=1.2) + figure = plt.gcf() # get current figure + figure.set_size_inches(1920 / 40, 1080 / 40) + # print("--- %s seconds ---" % (time.time() - start_time)) +plt.show() + From 63f84d4f99aecbbaf86712e2138cdec64ccb308c Mon Sep 17 00:00:00 2001 From: Felix Baron Date: Tue, 4 Oct 2022 23:35:32 +0200 Subject: [PATCH 054/129] added main ideom to binarySearch and added two tests for main idiom see: https://docs.python.org/3/library/__main__.html#idiomatic-usage --- binarySearch.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/binarySearch.py b/binarySearch.py index d815d09c..c6cd336e 100644 --- a/binarySearch.py +++ b/binarySearch.py @@ -28,4 +28,16 @@ def userInput(): else: print("The element was found at index ", result) -userInput() +# Tests ('pip install pytest'; run with 'pytest binarySearch.py') +def test_find_element_in_list(): + arr = [11, 12, 22, 25, 34, 64, 90, 91] + result = binarySearch(arr, 25) + assert result == 3 + +def test_elem_missing(): + arr = [11, 12, 22, 25, 34, 64, 90, 91] + result = binarySearch(arr, 16) + assert result == -1 + +if __name__ == "__main__": + userInput() \ No newline at end of file From ca39cb78578cfba7b41570a5329034118f232ddb Mon Sep 17 00:00:00 2001 From: Vasilis Asimakopoulos Date: Wed, 5 Oct 2022 00:37:45 +0300 Subject: [PATCH 055/129] add the logistic map --- Bifurcation diagram .py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Bifurcation diagram .py b/Bifurcation diagram .py index ad3d215a..aeac4f41 100644 --- a/Bifurcation diagram .py +++ b/Bifurcation diagram .py @@ -23,9 +23,8 @@ #change these values x0=0.1 -q0=-0.1 begin_r=0 -end_r=1 +end_r=4 step=0.0001 @@ -35,17 +34,16 @@ Y=[] @njit -def bif(q0, x0, r): +def bif(x0, r): N=1000 x = np.zeros(len(range(0, N))) x[0]=x0 - q=q0 for i in range(1,N): - x[i]= r *(1 + x[i - 1]) * (1 + x[i- 1]) * (2 - x[i - 1]) + q #logistic with extra parameter + x[i] = r * x[i-1] * (1 - x[i-1]) #logistic map #logistic with extra parameter return (x[-130:]) -bif1 = partial(bif, q0, x0) +bif1 = partial(bif,x0) if __name__ == '__main__': # create and configure the process pool with Pool(4) as p: From 5aee116c0b5b998e331fa7f1715ff13dff01f107 Mon Sep 17 00:00:00 2001 From: Hardik Gupta <29226479+Hardikg13@users.noreply.github.com> Date: Wed, 5 Oct 2022 03:34:20 +0530 Subject: [PATCH 056/129] Create Emoji_Convertor --- Emoji_Convertor | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Emoji_Convertor diff --git a/Emoji_Convertor b/Emoji_Convertor new file mode 100644 index 00000000..d105353f --- /dev/null +++ b/Emoji_Convertor @@ -0,0 +1,12 @@ +message = input("> ") +words = message.split() +emojis = { + ":)" :"😄", + ":(" :"😔", + ":D" :"😁" + +} +output = " " +for word in words: + output+=emojis.get( word,word) + " " +print(output) From 21031aa29c6293a3f71b055ff0c7545ec40c0c97 Mon Sep 17 00:00:00 2001 From: Samuel Darkow <97488839+sddark@users.noreply.github.com> Date: Tue, 4 Oct 2022 18:45:33 -0400 Subject: [PATCH 057/129] Added parentesis_checker.py --- paranthesis_checker.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 paranthesis_checker.py diff --git a/paranthesis_checker.py b/paranthesis_checker.py new file mode 100644 index 00000000..50f973c0 --- /dev/null +++ b/paranthesis_checker.py @@ -0,0 +1,41 @@ +""" +Paranthesis checker check to see if in a given array all paranthesis +are closed, if so the function returns true otherwise false. +i.e. {}, [], (), and ([]) would return true. }, or ([)] would return +false. A stack is implemented to check only when a }, ], or ) are +present in array. +Note that if nothing is entered the function returns true. +""" + +def parenthesis_check(parenthesis_array): + + stack = [] + for parenthesis in parenthesis_array: + if parenthesis == '}': + if len(stack) == 0: + return False + prev_parenthesis = stack.pop() + if prev_parenthesis != '{': + return False + elif parenthesis == ']': + if len(stack) == 0: + return False + prev_parenthesis = stack.pop() + if prev_parenthesis != '[': + return False + elif parenthesis == ')': + if len(stack) == 0: + return False + prev_parenthesis = stack.pop() + if prev_parenthesis != '(': + return False + else: stack.append(parenthesis) + + if len(stack) > 0: + return False + else: + return True + +str = input("Input: ") +arr = list(str) +print(parenthesis_check(arr)) \ No newline at end of file From 7bccf4a3f436cdd9a5529687684d30adba2963e3 Mon Sep 17 00:00:00 2001 From: Samuel Darkow <97488839+sddark@users.noreply.github.com> Date: Tue, 4 Oct 2022 18:48:12 -0400 Subject: [PATCH 058/129] Corrected typos --- paranthesis_checker.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/paranthesis_checker.py b/paranthesis_checker.py index 50f973c0..aa9e510e 100644 --- a/paranthesis_checker.py +++ b/paranthesis_checker.py @@ -1,7 +1,7 @@ """ -Paranthesis checker check to see if in a given array all paranthesis +Paranthesis checker checks to see if in a given array all paranthesis are closed, if so the function returns true otherwise false. -i.e. {}, [], (), and ([]) would return true. }, or ([)] would return +i.e. {}, [], (), and ([]) would return true, }, or ([)] would return false. A stack is implemented to check only when a }, ], or ) are present in array. Note that if nothing is entered the function returns true. From bb832799cc0d90e75bc9beb485093b45a7bca936 Mon Sep 17 00:00:00 2001 From: oops-aman Date: Wed, 5 Oct 2022 08:14:24 +0530 Subject: [PATCH 059/129] added depth first search --- dfs.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 dfs.py diff --git a/dfs.py b/dfs.py new file mode 100644 index 00000000..25244444 --- /dev/null +++ b/dfs.py @@ -0,0 +1,23 @@ +#DFS +n = int(input("Enter the number of nodes : ")) +graph = {}; +for i in range(n): + temp = list(map(str, input().split())) + if len(temp) > 1: + graph[temp[0]] = temp[1:] + else: + graph[temp[0]] = [] + +visited = set(); + +def dfs(visited, graph, node): + if node not in visited: + print(node, end = ' ') + + visited.add(node) + for neighbour in graph[node]: + dfs(visited, graph, neighbour); + +source = str(input("Enter the source node : ")) +print("Following DFS is : ") +dfs(visited, graph, source) \ No newline at end of file From 463eb9b0383855b8fa5f9420aef7ac6006d5787a Mon Sep 17 00:00:00 2001 From: Sohini Joarder <74846050+SohinijRover@users.noreply.github.com> Date: Wed, 5 Oct 2022 08:56:30 +0530 Subject: [PATCH 060/129] Added JumpSearch.py --- JumpSearch.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 JumpSearch.py diff --git a/JumpSearch.py b/JumpSearch.py new file mode 100644 index 00000000..d5b7e0e3 --- /dev/null +++ b/JumpSearch.py @@ -0,0 +1,47 @@ + +# Python3 code to implement Jump Search +import math + +def jumpSearch( arr , x , n ): + + # Finding block size to be jumped + step = math.sqrt(n) + + # Finding the block where element is + # present (if it is present) + prev = 0 + while arr[int(min(step, n)-1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + + # Doing a linear search for x in + # block beginning with prev. + while arr[int(prev)] < x: + prev += 1 + + # If we reached next block or end + # of array, element is not present. + if prev == min(step, n): + return -1 + + # If element is found + if arr[int(prev)] == x: + return prev + + return -1 + +# Driver code to test function +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 ] +x = 55 +n = len(arr) + +# Find the index of 'x' using Jump Search +index = jumpSearch(arr, x, n) + +# Print the index where 'x' is located +print("Number" , x, "is at index" ,"%.0f"%index) + +#contributed by Rover Phoenix \ No newline at end of file From d6ea0d0de3a16cd743876b71b33b0192e6ab8d92 Mon Sep 17 00:00:00 2001 From: alwenpy Date: Wed, 5 Oct 2022 09:53:42 +0530 Subject: [PATCH 061/129] added some python programs --- hcf_lcm.py | 32 ++++++++++++++++++++++++++++++++ insertion_sort.py | 12 ++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 hcf_lcm.py create mode 100644 insertion_sort.py diff --git a/hcf_lcm.py b/hcf_lcm.py new file mode 100644 index 00000000..5992f73c --- /dev/null +++ b/hcf_lcm.py @@ -0,0 +1,32 @@ +#Finding HCF in python + +a = int(input("Enter the first number: ")) +b = int(input("Enter the second number: ")) + +HCF = 1 + +for i in range(2,a+1): + if(a%i==0 and b%i==0): + HCF = i + +print("First Number is: ",a) +print("Second Number is: ",b) +print("HCF of the numbers is: ",HCF) + + +#Finding LCM in python +a = int(input("Enter the first number: ")) +b = int(input("Enter the second number: ")) + +HCF = 1 + +for i in range(2,a+1): + if(a%i==0 and b%i==0): + HCF = i + +print("First Number is: ",a) +print("Second Number is: ",b) + +LCM = int((a*b)/(HCF)) +print("LCM of the two numbers is: ",LCM) + diff --git a/insertion_sort.py b/insertion_sort.py new file mode 100644 index 00000000..b6b6da16 --- /dev/null +++ b/insertion_sort.py @@ -0,0 +1,12 @@ +def insertion_sort(InputList): + for i in range(1, len(InputList)): + j = i-1 + nxt_element = InputList[i] +# Compare the current element with next one + while (InputList[j] > nxt_element) and (j >= 0): + InputList[j+1] = InputList[j] + j=j-1 + InputList[j+1] = nxt_element +list = [19,2,31,45,30,11,121,27] +insertion_sort(list) +print(list) \ No newline at end of file From fec52103d1f0b734fef0b5fe0adb4bc5ddcbcdd8 Mon Sep 17 00:00:00 2001 From: Jerin Paul Date: Wed, 5 Oct 2022 10:39:36 +0530 Subject: [PATCH 062/129] added anagram.py --- an4gram.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 an4gram.py diff --git a/an4gram.py b/an4gram.py new file mode 100644 index 00000000..6188034e --- /dev/null +++ b/an4gram.py @@ -0,0 +1,45 @@ +#anagram is where both the strings have each characters of the same frequency +#danger and garden is an example of an anagram + +def isanagram(s1,s2): + if(len(s1)!=len(s2)): + return False + + # return sorted(s1) == sorted(s2) + freq1 = {} #declaring dictionaries for mapping purpose + freq2 = {} + + #using dictionary(hash table) for assigning the character as key and no of times it repeated as values + # { + # char1:value1 + # } + for char in s1: + if char in freq1: + freq1[char] += 1 + else: + freq1[char] = 1 + + for char in s2: + if char in freq2: + freq2[char] += 1 + else: + freq2[char] = 1 + + # for every key in dictionary freq1 we are comparing it with the key in dictionary freq2 + # if the key is not found then it will return false + # and simillarly the values from both the dictionaries are being compared + # if any one of the condition is false it will return false "or" is being used + for key in freq1: + if key not in freq2 or freq1[key]!=freq2[key]: + return False + return True + + + +s1 = input("Enter a string\n") +s2 = input("Enter second string\n") + +if isanagram(s1,s2): + print(f"\nThe {s1} and {s2} are Anagrams") +else: + print(f"{s1} and {s2} are not anagram") \ No newline at end of file From b7b02fb2461bf24710ccaeeedccb50f10b12e1fc Mon Sep 17 00:00:00 2001 From: Aaryan Trivedi Date: Wed, 5 Oct 2022 11:55:30 +0530 Subject: [PATCH 063/129] Create weightConverterGUI.py --- weightConverterGUI.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 weightConverterGUI.py diff --git a/weightConverterGUI.py b/weightConverterGUI.py new file mode 100644 index 00000000..8242c6fa --- /dev/null +++ b/weightConverterGUI.py @@ -0,0 +1,37 @@ +from tkinter import * +window = Tk() +def from_kg(): + gram = float(e2_value.get())*1000 + pound = float(e2_value.get())*2.20462 + ounce = float(e2_value.get())*35.274 + t1.delete("1.0",END) + t1.insert(END, gram) + t2.delete("1.0", END) + t2.insert(END, pound) + t3.delete("1.0", END) + t3.insert(END, ounce) + +e1 = Label(window, text="Input the weight in KG") +e2_value = StringVar() +e2 = Entry(window, textvariable=e2_value) +e3 = Label(window, text="Gram") +e4 = Label(window, text="Pound") +e5 = Label(window, text="Ounce") + +t1 = Text(window, height=5, width=30) +t2 = Text(window, height=5, width=30) +t3 = Text(window, height=5, width=30) + +b1 = Button(window, text="Convert", command=from_kg) + +e1.grid(row=0, column=0) +e2.grid(row=0, column=1) +e3.grid(row=1, column=0) +e4.grid(row=1, column=1) +e5.grid(row=1, column=2) +t1.grid(row=2, column=0) +t2.grid(row=2, column=1) +t3.grid(row=2, column=2) +b1.grid(row=0, column=2) + +window.mainloop() From d0e10a4911e799af951cf885ccf340396b3b5c71 Mon Sep 17 00:00:00 2001 From: Sushrut Mishra <41235363+sushrutmishra27@users.noreply.github.com> Date: Wed, 5 Oct 2022 11:56:48 +0530 Subject: [PATCH 064/129] Beginner level python game project --- Story-generator-game.py | 139 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 Story-generator-game.py diff --git a/Story-generator-game.py b/Story-generator-game.py new file mode 100644 index 00000000..7242fda0 --- /dev/null +++ b/Story-generator-game.py @@ -0,0 +1,139 @@ +import time +import random +from string import ascii_lowercase + +print('This is a game where you guess the randomly chosen word and if you win, you get a randomly generated short story !') +print('Enjoy !!') +print('\n') + +time.sleep(4) + +name=input('Player Name :- ') +print('\n') +print('Welcome ' + name + '. Let''s play Hangman') +print('') + +time.sleep(1) + +friends=['Chandler','Joey','Monica','Rachel','Ross','Phoebe','Gunther','Janice','Ugly Naked Guy','Mr Heckles','Judy','Jack'] +ramaayan=['Shri Ram','Sita maa','Lakshman','Bharat','Raavan','Hanuman','Maarich','Dashrath','Kaikeyi','King Janak','KumbhKarn','Baali'] +Got=['Theon','Danaerys','Jon Snow','Joeffry','Cersie','Tyrion','Drogon','Baratheon','Starks','Greyjoy','Viserys'] + +print('Choose Category :- ') +choose=int(input('1. F.R.I.E.N.D.S 2. Game Of Thrones 3. Ramaayan ')) +if choose==1: + word=random.choice(friends) +elif choose==2: + word=random.choice(Got) +elif choose==3: + word=random.choice(ramaayan) + +print('HINT : Starts with' + word[0]) +print('\n') +print("Start guessing...") +time.sleep(0.5) +guess='' +turn=10 + +while turn>0: + fail=0 + for c in word: + if c in guess: + print(c) + else: + print('_') + fail+=1 + if fail==0: + print('You Won ' + name + ' !') + print('\n') + print('Here is your story - ') + theme=random.choice(["real world","high fantasy","space sci-fi","alt-history","cyberpunk"]) + if theme == "real world": + subsetting=random.choice(["the Ayodhya","Kishkindha","Lanka","Panchvati","Janakpuri"]) + setting=random.choice(["a small town in ","a big city in ","a farm in ","a school in ","the ocean","the entire world"]) + if setting != "the ocean" or "the entire world": + setting=setting+subsetting + age=random.choice(["newborn ","toddler ","child ","teenager ","young adult ","adult ","middle aged ","elder "]) + race=random.choice(["ayodhyan ","janakis ","lankan ","indian "]) + gengender=random.randint(0,100) + if gengender <= 10: + gender = ("transgender ") + if gengender >= 9: + if gengender >= 47: + gender = ("male ") + if gengender <= 46: + gender = ("female ") + protagonist=age+race+gender + antagonist=random.choice(["a female","a male","a king","a government","a tragic event","traffic","religion","a disease","a rival","the law","an old friend","a dog"]) + if theme == "high fantasy": + setting=random.choice(["The Great Empire","a vast desert","a dark corrupted land","a magic swamp","a unending labryinth","floating islands","a mystical forest","a frozen wasteland","a dangerous jungle land"]) + gender=random.choice(["male ","male ","male ","female ","female ","female ","magical transgender ","agender ","third gender "]) + race=random.choice(["human ","human ","elf ","orc ","dwarf ","gnome ","demon ","angel ","kitsune ","dark elf ","troll ","unicorn "]) + classs=random.choice(["marksmen ","warrior ","wizard ","bard ","thief ","merchant","knight ","spellsword ","peasant ","necromancer ","preist ","bandit ","monarch"]) + protagonist = gender+race+classs + antagonist=random.choice(["a female","a male","an entire race","a god","an evil mage","an order of knights","evil itself","a giant","an invading army","a tyrant","magic","a greedy merchant","a monster","a dragon"]) + if theme == "space sci-fi": + setting=random.choice(["the deep void of space","an asteroid belt","an ice planet","a lava planet","a gas giant","an alien home world","future Earth","another galaxy, far far away","the multiverse"]) + protagonist=random.choice(["human","robot","hive mind","alien","alien","blob","human"]) + antagonist=random.choice(["a female","a male","an entire alien race","a starfleet","an alien","an artifical intellgence","a galactic federation","a glitch in space-time","an invading army","a incredibly infectious space fungus","the limits of science","a robot"]) + if theme == "alt-history": + setting=random.choice(["America","Religion","the Classical Era","the Middle Ages","the Renaissance","the Industrial Era","World War I","World War II","the Modern Era"]) + if setting == "America": + figures=["Abraham Lincoln","George W. Bush Jr.","Benjamin Franklin","Donald Trump","Ronald Reagan","John Adams","Hilary Clinton","King George III","King George Washington","Andrew Jackson","Thomas Edison","Steve Jobs"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "Religion": + figure=random.choice(["Jesus","Muhammad","Buddha","Krishna","Moses","L. Ron Hubbard","Joseph Smith","Zeus","Ra","Thor"]) + antagonist=random.choice(["Christianity","Islam","Hinduism","Buddhism","Greek mythology","Scientology","the Mormons","Paganism","Heresies"]) + if setting == "the Classical Era": + figures=["Alexander The Great","Julius Caesar","Aristotle","King Tut","Qin Shi Huang","Homer","Augustus","Plato","Cleopatra","Ashoka","Attila the Hun","Leonidas"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Middle Ages": + figures=["Charlemagne","Ghenghis Khan","Saladin","William the Conqueror","Ragnar Lodbrok","Oda Nobunaga","King Richard III","William Wallace","El Cid","Eleanor of Aquitaine","Erik the Red","Vlad the Impaler"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Renaissance": + figures=["Marco Polo","Joan of Arc","Christopher Columbus","Blackbeard","Leonardo da Vinci","William Shakespeare","Henry VIII","Michelangelo","Donatello","Galileo","Admiral Yi Sun-sin","Suleiman the Magnificent"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "the Industrial Era": + figures=["Henry Ford","Karl Marx","Charles Dickens","John D. Rockefeller","Thomas Edison","Nikola Tesla","Amelia Earheart","Frank C. Mars","Albert Einstein","Napoleon","Ghandi","Mark Twain"] + figure=random.choice(figures) + antagonist=random.choice(figures) + if setting == "World War I": + figure=random.choice(["Woodrow Wilson","Winston Churchill","Tsar Nicholas II","Lenin","Paul von Hindenburg","Ataturk"]) + antagonist=random.choice(["the Ottoman Empire","Germany","the United States","Britain","Austria-Hungary","France"]) + if setting == "World War II": + figure=random.choice(["Hitler","Queen Elizabeth","Franklin D. Roosevelt","Joseph Stalin","Harry Truman","General Hideki Tojo"]) + antagonist=random.choice(["the United States","Germany","the Soviet Union","the United Kingdom","Japan","Italy"]) + if setting == "the Modern Era": + figures=["Obama","Putin","Kim Jong-un","Kanye West","Bill Gates","Guido van Rossum","The Beatles","ISIS","Pope Francis","Mike Tyson","Pewdiepie","Hilary Cliton"] + figure=random.choice(figures) + antagonist=random.choice(figures) + afigure=("figure known as ") + protagonist= afigure+figure + if theme == "cyberpunk": + setting=random.choice(["high-tech Tokyo","New New York","a dystopia","a utopia","a computer simulation","the SuperWeb","Mega Silicon Valley","an underwater city","an extensive underground facility"]) + gender=random.choice(["male ","male ","female ","female ","robogender ","unigender ","agender ","mega genderfluid ","third gender "]) + classs=random.choice(["hacker","cyborg","DJ","technopath","engineer","bomber","corporate","street rat","anarchist"]) + protagonist=gender+classs + antagonist=random.choice(["a large corporation","an evil AI","Python","a gang","a secret society","a new technology","robots","internet trolls","the most powerful cyborg"]) + conflict=random.choice(["fell in love with ","fought against ","attempted to stop ","defended against ","tried to befriend ","explored with ","tried to evade ","competed with ","exceeded beyond ","sought revenge against "]) + end=random.choice(["It did not end well.","It ended very well.","Died tragically.","Lived happily ever after.","It ended sadly.","It was glorious.","In the end, nothing changed.","It ended with a twist.","Gave up."]) + print("In the",theme,"setting of",setting,", there was a", protagonist, "who",conflict,antagonist,".",end) + + break + + + + guesses=input('Guess a character :- ') + guess=guess+guesses + if guesses not in word: + turn-=1 + print('Wrong. You have ' + str(turn) + ' more guesses.') + if turn==0: + print('You lose ! The word was ' + word + '. Sorry, you don''t get the story.') + print('\n') + print('Write your story on your own.') +#Winstoryhangman From 7390111b04673468717e208e28260f62dfa8af2f Mon Sep 17 00:00:00 2001 From: Swapnil05Rai <87640978+Swapnil05Rai@users.noreply.github.com> Date: Wed, 5 Oct 2022 12:00:57 +0530 Subject: [PATCH 065/129] Add files via upload --- turtle race.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 turtle race.py diff --git a/turtle race.py b/turtle race.py new file mode 100644 index 00000000..4693c252 --- /dev/null +++ b/turtle race.py @@ -0,0 +1,48 @@ +from turtle import Turtle +from random import randint + +aman=Turtle() +aman.color('blue') +aman.shape('turtle') +aman.penup() +aman.goto(-180,100) +aman.pendown() + +swati=Turtle() +swati.color('red') +swati.shape('turtle') +swati.penup() +swati.goto(-180,70) +swati.pendown() + +ram=Turtle() +ram.color('green') +ram.shape('turtle') +ram.penup() +ram.goto(-180,40) +ram.pendown() + +krishna=Turtle() +krishna.color('dark blue') +krishna.shape('turtle') +krishna.penup() +krishna.goto(-180,10) +krishna.pendown() + +for movement in range(100): + aman.forward(randint(1,5)) + swati.forward(randint(1, 5)) + ram.forward(randint(1, 5)) + krishna.forward(randint(1, 5)) +if aman.position() > (swati.position() and ram.position()and krishna.position()): + print(("Aman won the race")) +elif swati.position()>(aman.position() and ram.position() and krishna.position()): + print("swati won the race") +elif ram.position()> (aman.position() and swati.position() and krishna.position()): + print("ram won the race") +else: + print("Krishna won the race") + + + +input(" ...") From 8b25ea53e4e4bb6b054c01c84877c6c8f34e777e Mon Sep 17 00:00:00 2001 From: Aaryan Trivedi Date: Wed, 5 Oct 2022 12:32:35 +0530 Subject: [PATCH 066/129] Create RomanToInt.py --- RomanToInt.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 RomanToInt.py diff --git a/RomanToInt.py b/RomanToInt.py new file mode 100644 index 00000000..1846a8b4 --- /dev/null +++ b/RomanToInt.py @@ -0,0 +1,21 @@ +val = input("Enter your value: ") +class Solution(object): + def romanToInt(self, s): + """ + :type s: str + :rtype: int + """ + roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900} + i = 0 + num = 0 + while i < len(s): + if i+1 Date: Wed, 5 Oct 2022 12:35:40 +0530 Subject: [PATCH 067/129] Added n-queens.py --- n-queens.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 n-queens.py diff --git a/n-queens.py b/n-queens.py new file mode 100644 index 00000000..64df57de --- /dev/null +++ b/n-queens.py @@ -0,0 +1,57 @@ +# Function to check if two queens threaten each other or not +def isSafe(mat, r, c): + + # return false if two queens share the same column + for i in range(r): + if mat[i][c] == 'Q': + return False + + # return false if two queens share the same `` diagonal + (i, j) = (r, c) + while i >= 0 and j >= 0: + if mat[i][j] == 'Q': + return False + i = i - 1 + j = j - 1 + + # return false if two queens share the same reverse diagonal + (i, j) = (r, c) + while i >= 0 and j < len(mat): + if mat[i][j] == 'Q': + return False + i = i - 1 + j = j + 1 + return True + + +def printSolution(mat): + for r in mat: + print(str(r).replace(',', '').replace('\'', '')) + print() + + +def nQueen(mat, r): + # if `N` queens are placed successfully, print the solution + if r == len(mat): + printSolution(mat) + return + + # place queen at every square in the current row `r` + # and recur for each valid movement + for i in range(len(mat)): + # if no two queens threaten each other + if isSafe(mat, r, i): + # place queen on the current square + mat[r][i] = 'Q' + # recur for the next row + nQueen(mat, r + 1) + # backtrack and remove the queen from the current square + mat[r][i] = '-' + +if __name__ == '__main__': + + # `N × N` chessboard + N = int(input("Enter number of queens: ")) + mat = [['-' for x in range(N)] for y in range(N)] + + nQueen(mat, 0) \ No newline at end of file From cf25897e686f01f7c113a94882c3991791367cd6 Mon Sep 17 00:00:00 2001 From: Brihad Gunapu <78583705+brihad24@users.noreply.github.com> Date: Wed, 5 Oct 2022 12:46:07 +0530 Subject: [PATCH 068/129] Delete n-queens.py --- n-queens.py | 57 ----------------------------------------------------- 1 file changed, 57 deletions(-) delete mode 100644 n-queens.py diff --git a/n-queens.py b/n-queens.py deleted file mode 100644 index 64df57de..00000000 --- a/n-queens.py +++ /dev/null @@ -1,57 +0,0 @@ -# Function to check if two queens threaten each other or not -def isSafe(mat, r, c): - - # return false if two queens share the same column - for i in range(r): - if mat[i][c] == 'Q': - return False - - # return false if two queens share the same `` diagonal - (i, j) = (r, c) - while i >= 0 and j >= 0: - if mat[i][j] == 'Q': - return False - i = i - 1 - j = j - 1 - - # return false if two queens share the same reverse diagonal - (i, j) = (r, c) - while i >= 0 and j < len(mat): - if mat[i][j] == 'Q': - return False - i = i - 1 - j = j + 1 - return True - - -def printSolution(mat): - for r in mat: - print(str(r).replace(',', '').replace('\'', '')) - print() - - -def nQueen(mat, r): - # if `N` queens are placed successfully, print the solution - if r == len(mat): - printSolution(mat) - return - - # place queen at every square in the current row `r` - # and recur for each valid movement - for i in range(len(mat)): - # if no two queens threaten each other - if isSafe(mat, r, i): - # place queen on the current square - mat[r][i] = 'Q' - # recur for the next row - nQueen(mat, r + 1) - # backtrack and remove the queen from the current square - mat[r][i] = '-' - -if __name__ == '__main__': - - # `N × N` chessboard - N = int(input("Enter number of queens: ")) - mat = [['-' for x in range(N)] for y in range(N)] - - nQueen(mat, 0) \ No newline at end of file From 74bf2c5bc50983576687a8aa9b64fca0cccc58af Mon Sep 17 00:00:00 2001 From: Pranav Yatnalkar Date: Wed, 5 Oct 2022 15:38:05 +0530 Subject: [PATCH 069/129] Adding 4 new programs --- camelCase-to-snake_case.py | 9 +++++++++ meal-of-the-day.py | 20 ++++++++++++++++++++ remove-vowels.py | 9 +++++++++ text-to-emoji.py | 7 +++++++ 4 files changed, 45 insertions(+) create mode 100644 camelCase-to-snake_case.py create mode 100644 meal-of-the-day.py create mode 100644 remove-vowels.py create mode 100644 text-to-emoji.py diff --git a/camelCase-to-snake_case.py b/camelCase-to-snake_case.py new file mode 100644 index 00000000..f4833605 --- /dev/null +++ b/camelCase-to-snake_case.py @@ -0,0 +1,9 @@ +name = input("Enter name of variable in camelCase: ") + +j = 0 + +for char in name: + if char.isupper(): + print("_" + char.lower(), end = "") + else: + print(char, end = "") \ No newline at end of file diff --git a/meal-of-the-day.py b/meal-of-the-day.py new file mode 100644 index 00000000..3e9be0fa --- /dev/null +++ b/meal-of-the-day.py @@ -0,0 +1,20 @@ +def main(): + x = convert(input("Enter time of the day [in hh:mm 24 hour format] : ")) + + if 7 <= x <= 8: + print("breakfast time") + elif 12 <= x <= 13: + print("lunch time") + elif 18 <= x <= 19: + print("dinner time") + + +def convert(time): + hours, minutes = time.split(":") + hours = int(hours) + minutes = float(minutes)/60 + return hours + minutes + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/remove-vowels.py b/remove-vowels.py new file mode 100644 index 00000000..4b8d0d43 --- /dev/null +++ b/remove-vowels.py @@ -0,0 +1,9 @@ +vowels = ['a', 'e', 'i', 'o', 'u'] + +text = input("Enter some text: ") + +for char in text: + if(char.lower() in vowels): + continue + else: + print(char, end = '') \ No newline at end of file diff --git a/text-to-emoji.py b/text-to-emoji.py new file mode 100644 index 00000000..f79bb8be --- /dev/null +++ b/text-to-emoji.py @@ -0,0 +1,7 @@ +def main(): + print(convert(input("Enter any text: "))) + +def convert(text): + return text.replace(":(", "🙁").replace(":)", "🙂") + +main() \ No newline at end of file From 6fbae50b54d3717546ef5db588745fca618cca21 Mon Sep 17 00:00:00 2001 From: Meenakshy Bindu Suresh Date: Wed, 5 Oct 2022 15:38:21 +0530 Subject: [PATCH 070/129] Create rainbowSpiral.py This turtle programme is among the most gorgeous and amazing ones ever. --- rainbowSpiral.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 rainbowSpiral.py diff --git a/rainbowSpiral.py b/rainbowSpiral.py new file mode 100644 index 00000000..d4b6979b --- /dev/null +++ b/rainbowSpiral.py @@ -0,0 +1,27 @@ +import turtle +from turtle import * + +turtle.title("rainbow spiral") +speed(15) +bgcolor("black") +r,g,b=255,0,0 + +for i in range(255*2): + colormode(255) + if i<255//3: + g+=3 + elif i<255*2//3: + r-=3 + elif i<255: + b+=3 + elif i<255*4//3: + g-=3 + elif i<255*5//3: + r+=3 + else: + b-=3 + fd(50+i) + rt(91) + pencolor(r,g,b) + +done() From 7b8f024a7f3adfff8d1d3f4c8ae750955f0f26ab Mon Sep 17 00:00:00 2001 From: Meenakshy Bindu Suresh Date: Wed, 5 Oct 2022 15:46:33 +0530 Subject: [PATCH 071/129] Create BMI.py BMI Calculator Using Python Tkinter --- BMI.py | 131 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 BMI.py diff --git a/BMI.py b/BMI.py new file mode 100644 index 00000000..40219a3b --- /dev/null +++ b/BMI.py @@ -0,0 +1,131 @@ +from tkinter import * +from tkinter import messagebox + +def reset_entry(): + age_tf.delete(0,'end') + height_tf.delete(0,'end') + weight_tf.delete(0,'end') + +def calculate_bmi(): + kg = int(weight_tf.get()) + m = int(height_tf.get())/100 + bmi = kg/(m*m) + bmi = round(bmi, 1) + bmi_index(bmi) + +def bmi_index(bmi): + + if bmi < 18.5: + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Underweight') + elif (bmi > 18.5) and (bmi < 24.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Normal') + elif (bmi > 24.9) and (bmi < 29.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Overweight') + elif (bmi > 29.9): + messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Obesity') + else: + messagebox.showerror('bmi-pythonguides', 'something went wrong!') + +ws = Tk() +ws.title('BMI') +ws.geometry('400x300') +ws.config(bg='#686e70') + +var = IntVar() + +frame = Frame( + ws, + padx=10, + pady=10 +) +frame.pack(expand=True) + + +age_lb = Label( + frame, + text="Enter Age (2 - 120)" +) +age_lb.grid(row=1, column=1) + +age_tf = Entry( + frame, +) +age_tf.grid(row=1, column=2, pady=5) + +gen_lb = Label( + frame, + text='Select Gender' +) +gen_lb.grid(row=2, column=1) + +frame2 = Frame( + frame +) +frame2.grid(row=2, column=2, pady=5) + +male_rb = Radiobutton( + frame2, + text = 'Male', + variable = var, + value = 1 +) +male_rb.pack(side=LEFT) + +female_rb = Radiobutton( + frame2, + text = 'Female', + variable = var, + value = 2 +) +female_rb.pack(side=RIGHT) + +height_lb = Label( + frame, + text="Enter Height (cm) " +) +height_lb.grid(row=3, column=1) + +weight_lb = Label( + frame, + text="Enter Weight (kg) ", + +) +weight_lb.grid(row=4, column=1) + +height_tf = Entry( + frame, +) +height_tf.grid(row=3, column=2, pady=5) + +weight_tf = Entry( + frame, +) +weight_tf.grid(row=4, column=2, pady=5) + +frame3 = Frame( + frame +) +frame3.grid(row=5, columnspan=3, pady=10) + +cal_btn = Button( + frame3, + text='Calculate', + command=calculate_bmi +) +cal_btn.pack(side=LEFT) + +reset_btn = Button( + frame3, + text='Reset', + command=reset_entry +) +reset_btn.pack(side=LEFT) + +exit_btn = Button( + frame3, + text='Exit', + command=lambda:ws.destroy() +) +exit_btn.pack(side=RIGHT) + +ws.mainloop() From f647bb6121af04ab6ee2ada142963b3d4a4993f0 Mon Sep 17 00:00:00 2001 From: Meenakshy Bindu Suresh Date: Wed, 5 Oct 2022 16:03:11 +0530 Subject: [PATCH 072/129] Create DigitalClock.py Digital Clock using tkinter --- DigitalClock.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 DigitalClock.py diff --git a/DigitalClock.py b/DigitalClock.py new file mode 100644 index 00000000..8fba4bdc --- /dev/null +++ b/DigitalClock.py @@ -0,0 +1,31 @@ +# importing whole module +from tkinter import * +from tkinter.ttk import * + +# importing strftime function to +# retrieve system's time +from time import strftime + +# creating tkinter window +root = Tk() +root.title('Clock') + +# This function is used to +# display time on the label +def time(): + string = strftime('%H:%M:%S %p') + lbl.config(text = string) + lbl.after(1000, time) + +# Styling the label widget so that clock +# will look more attractive +lbl = Label(root, font = ('calibri', 40, 'bold'), + background = 'purple', + foreground = 'white') + +# Placing clock at the centre +# of the tkinter window +lbl.pack(anchor = 'center') +time() + +mainloop() From 716cb389986435f3c610d6c6b48e1644a4499e9a Mon Sep 17 00:00:00 2001 From: Boshra Jaber Date: Wed, 5 Oct 2022 10:34:25 +0000 Subject: [PATCH 073/129] Print Calendar of a Given Date --- calendar_program.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 calendar_program.py diff --git a/calendar_program.py b/calendar_program.py new file mode 100644 index 00000000..533a7930 --- /dev/null +++ b/calendar_program.py @@ -0,0 +1,33 @@ +import calendar +''' +Write a Python program that prints the calendar of a given month in a given year after validating the user input. +''' + + +def validate_user_input(): + is_valid_year = False + is_valid_month = False + '''user should enter a valid year''' + while not is_valid_year: + year = input("Enter the year \n format: YYYY: ") + if len(year) == 4 and year.isdigit(): + is_valid_year = True + else: + print("Kindly Enter a vaild four-digit year number") + '''user should enter a valid month''' + while not is_valid_month: + month = input("Enter month \n format: 1-12: ") + if month.isdigit() and 12 >= int(month) >= 1: + is_valid_month = True + else: + print("Kindly Enter a vaild month number between 1 and 12") + return [int(year), int(month)] + + +def print_given_month(): + year, month = validate_user_input() + print(year, month) + print(calendar.month(year, month)) + + +print_given_month() \ No newline at end of file From a318f0883b71f0bcf05f16912dbfd3cfceda327c Mon Sep 17 00:00:00 2001 From: Meenakshy Bindu Suresh Date: Wed, 5 Oct 2022 16:10:16 +0530 Subject: [PATCH 074/129] Create InsertionSort.py Insertion Sort Implementation In Python In order to rank an array of size N ascendingly: Over the array, iterate from arr[1] to arr[N]. Comparing the current (key) element to the previous one. Compare the key element to the previous elements to see if it is smaller. In order to make room for the substituted element, move the larger elements up one position. --- InsertionSort.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 InsertionSort.py diff --git a/InsertionSort.py b/InsertionSort.py new file mode 100644 index 00000000..3a1aaad6 --- /dev/null +++ b/InsertionSort.py @@ -0,0 +1,17 @@ +def insertion_sort(arr): + + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + + while j >= 0 and key < arr[j]: + arr[j + 1] = arr[j] + j = j - 1 + + + arr[j + 1] = key + +arr = [9, 8, 6, 7, 1] +print("Unsorted Array:", arr) +insertion_sort(arr) +print('Sorted Array: ', arr) From 93e97d7f801e3e8f4845561d28b38d54319e706e Mon Sep 17 00:00:00 2001 From: ram vikram singh <106332857+ramvikrams@users.noreply.github.com> Date: Wed, 5 Oct 2022 16:13:26 +0530 Subject: [PATCH 075/129] radixSort.py sir this is python code for Radix Sort --- radixSort.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 radixSort.py diff --git a/radixSort.py b/radixSort.py new file mode 100644 index 00000000..ae4955fd --- /dev/null +++ b/radixSort.py @@ -0,0 +1,60 @@ +# Python program for implementation of Radix Sort + +# A function to do counting sort of arr[] according to +# the digit represented by exp. +def countingSort(arr, exp1): + + n = len(arr) + + # The output array elements that will have sorted arr + output = [0] * (n) + + # initialize count array as 0 + count = [0] * (10) + + # Store count of occurrences in count[] + for i in range(0, n): + index = (arr[i]/exp1) + count[int((index)%10)] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this digit in output array + for i in range(1,10): + count[i] += count[i-1] + + # Build the output array + i = n-1 + while i>=0: + index = (arr[i]/exp1) + output[ count[ int((index)%10) ] - 1] = arr[i] + count[int((index)%10)] -= 1 + i -= 1 + + # Copying the output array to arr[], + # so that arr now contains sorted numbers + i = 0 + for i in range(0,len(arr)): + arr[i] = output[i] + +# Method to do Radix Sort +def radixSort(arr): + + # Find the maximum number to know number of digits + max1 = max(arr) + + # Do counting sort for every digit. Note that instead + # of passing digit number, exp is passed. exp is 10^i + # where i is current digit number + exp = 1 + while max1/exp > 0: + countingSort(arr,exp) + exp *= 10 + +# Driver code to test above +arr = [ 170, 45, 75, 90, 802, 24, 2, 66] +radixSort(arr) + +for i in range(len(arr)): + print(arr[i],end=" ") + + From 072fb80263bcb0d6ed96e6e19feec1a7a3bbc154 Mon Sep 17 00:00:00 2001 From: ram vikram singh <106332857+ramvikrams@users.noreply.github.com> Date: Wed, 5 Oct 2022 16:17:31 +0530 Subject: [PATCH 076/129] GrayCodetoBinary.py python code for converting gray code to binary --- GrayCodetoBinary.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 GrayCodetoBinary.py diff --git a/GrayCodetoBinary.py b/GrayCodetoBinary.py new file mode 100644 index 00000000..d3396448 --- /dev/null +++ b/GrayCodetoBinary.py @@ -0,0 +1,37 @@ +def flip_num(my_nu): + return '1' if(my_nu == '0') else '0'; + +def gray_to_binary(gray): + binary_code="" + binary_code += gray[0] + for i in range(1,len(gray)): + + if (gray[i]=='0'): + binary_code += binary_code[i-1] + else: + binary_code += flip_num(binary_code[i-1]) + + return binary_code + +# gray_code="01101001" + + +gray_code=input("please enter the gray code\n") +print("the gray code is : ") +print(gray_code) +# x=gray_to_binary(gray_code) +print("binary code of", gray_code, "is",gray_to_binary(gray_code)) + +# for converting binary numb to decimal +value=0 +b_num=list(gray_to_binary(gray_code)) + +for i in range(len(b_num)): + digit=b_num.pop() + if digit =='1': + value = value + pow(2,i) + +print("the decimal value of the number is ", value) + + +# print(12//5) From 6e7ae0ab475bc29b603d26e06b74f1ab045bd4a9 Mon Sep 17 00:00:00 2001 From: Deepak Dhage Date: Wed, 5 Oct 2022 17:21:57 +0530 Subject: [PATCH 077/129] Removed un-necessory semi colons ; and round up to two decimal places from 6 --- area-of-circle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/area-of-circle.py b/area-of-circle.py index ea74423b..b05d9d76 100644 --- a/area-of-circle.py +++ b/area-of-circle.py @@ -1,6 +1,6 @@ def findArea(r): PI = 3.142 - return PI * (r*r); + return PI * (r*r) -print("Area is %.6f" % findArea(5)); +print("Area is %.2f" % findArea(5)) From 57f70e5058652fc9aab997a2755aefec96e1db70 Mon Sep 17 00:00:00 2001 From: Yash Raj <87474641+programmer-offbeat@users.noreply.github.com> Date: Wed, 5 Oct 2022 17:58:14 +0530 Subject: [PATCH 078/129] A simple Banking program in CLUI Beginner friendly Python program of a banking game. Uses while loop ! --- BankGame.py | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 BankGame.py diff --git a/BankGame.py b/BankGame.py new file mode 100644 index 00000000..846f4b4a --- /dev/null +++ b/BankGame.py @@ -0,0 +1,114 @@ +import random +class BankGame : + @staticmethod + def main( args) : + print("---WELCOME TO ELIX BANKING SERVICES---") + print("") + print("________________________") + print("Enter your name: ") + name = input() + # I am inserting do loop to make the program run forever under correct inputs. + print("Hi, " + name + "\bWelcome to my program!") + print("____________________________") + print("Do you want to start/repeat the program?") + print("Enter Y for Yes and N for No: ") + temp = input()[0] + passw = 4758 + bal = 10000 + leftbal = 0 + print("If you don\'t know the password refer the first line of the program") + print("Please enter the password: ") + # Condition when the statement goes true i.e.- temp equals 1 + while True : + if (temp == 'Y' or temp == 'y') : + if (passw == 4758) : + print("") + print("Your initial account balance is Rs. 10000") + # Using for statement to perform 5 operation on each login + x = 0 + while (x <= 6) : + print("0. Exit") + print("1. Deposit") + print("2. Withdraw") + print("3. Change passcode") + print("4. Check balance") + print("5. Customer care") + print("Enter the serial no. of your choice") + choice = int(input()) + print("Enter captha to verify that you are not a robot.") + captha = random.randrange(10000) + print(captha) + print("Enter the number shown above: ") + verify = int(input()) + if (verify == captha) : + # If captha gets matched, then these switch statements are executed. + if (choice==0): + print("BYE!......" + name + " HAVE A NICE DAY!") + print("__________________________") + print("@author>[@programmer-yash") + print("Please comment here or open an issue if you have any queries or suggestions!") + print("") + print("#hacktoberfest") + return 0 + elif(choice==1): + print("You have chosen to deposit.") + print("Enter the amount to deposit : ") + deposit = int(input()) + bal = bal + deposit + print(str(deposit) + " has been deposited to your account.") + print("Left balance is " + str(bal)) + elif(choice==2): + print("You have chosen to withdraw.") + print("Enter the amount to be withdrawn") + withdraw = int(input()) + print(str(+withdraw) + " has been withdrawn from your account.") + bal = bal - withdraw + print("Check the cash printer.") + print("Left balance is " + str(bal)) + elif(choice==3): + print("You have chosen to change passcode.") + print("Enter the current passcode: ") + check = int(input()) + if (check == passw) : + print("Enter the new passcode") + newP = int(input()) + passw = newP + print("Your new password is " + str(newP)) + else : + print("Wrong passcode!") + elif(choice==4): + print("You have chosen to check balanace.") + print("Your current account balance is " + str(bal)) + elif(choice==5): + print("You have chosen for customer care.") + print("Contact us at:") + print(" Email: yash197911@gmail.com") + else: + print("Wrong choice!!! Choose again...!") + else : + print("xCAPTHA NOT CORRECTx") + x += 1 + continue + elif(temp == 'N' or temp == 'n') : + print("BYE!......" + name + " HAVE A NICE DAY!") + print("__________________________") + print("@author>[@programmer-offbeat]") + print("Please comment here if you have any queries or suggestions!") + print("--OR--") + print("create an issue") + print("I will rightly see and reply to your messages and suggestions!") + print() + print("HAPPY CODING!:-)") + return 0 + else : + print("Err!..... You have entered a wrong choice!") + print("Try again....!") + # Comdition if password mismatches. + if (passw != 4758) : + print("You have entered wrong password.....Try again!") + if((temp < 100) == False) : + break + + +if __name__=="__main__": + BankGame.main([]) From 12605cd3eb802731eff7f85ed608e067a5ed90db Mon Sep 17 00:00:00 2001 From: Yash Raj <87474641+programmer-offbeat@users.noreply.github.com> Date: Wed, 5 Oct 2022 18:03:10 +0530 Subject: [PATCH 079/129] Update BankGame.py --- BankGame.py | 1 + 1 file changed, 1 insertion(+) diff --git a/BankGame.py b/BankGame.py index 846f4b4a..6560f87e 100644 --- a/BankGame.py +++ b/BankGame.py @@ -1,3 +1,4 @@ +#default password is 4758 import random class BankGame : @staticmethod From b0ef0a0850ab7cb9d6adee93005dedeb959dd94b Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Wed, 5 Oct 2022 09:51:37 -0300 Subject: [PATCH 080/129] Add number base converter in python --- number_base_converter.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 number_base_converter.py diff --git a/number_base_converter.py b/number_base_converter.py new file mode 100644 index 00000000..b4d48585 --- /dev/null +++ b/number_base_converter.py @@ -0,0 +1,36 @@ +#################################################################################################### + +# Question +# Write a Python script that reads any integer and asks the user to choose which option to convert: +# 1 for Binary +# 2 for Octal +# 3 for Hexadecimal + +#################################################################################################### +num = 0 +num = int(input("\nDigit an integer positive or -1 to finish: ")) + +while num != -1: + print(""" + Choose one of the bases to convert: + + [ 1 ] convert to BINARY + [ 2 ] convert to OCTAL + [ 3 ] convert to HEXADECIMAL + """) + + option = int(input("Your choose: ")) + + if option == 1: + print(f"\n{num} converted to BINARY is {bin(num)[2:]}") + elif option == 2: + print(f"\n{num} converted to OCTAL is {oct(num)[2:]}") + elif option == 3: + print(f"\n{num} converted to HEXADECIMAL is {hex(num)[2:].upper()}") + else: + print("\n #### Invalid option. Try again. ####") + + num = int(input("\nDigit an integer positive or -1 to finish: ")) + +print("Bye!!!") +#################################################################################################### From dceab6736a22579f302de0fd1045c3e2eac21963 Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Wed, 5 Oct 2022 10:16:15 -0300 Subject: [PATCH 081/129] Remove wrong file --- arabic_to_roman_numbers.py | 99 -------------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 arabic_to_roman_numbers.py diff --git a/arabic_to_roman_numbers.py b/arabic_to_roman_numbers.py deleted file mode 100644 index 060f3548..00000000 --- a/arabic_to_roman_numbers.py +++ /dev/null @@ -1,99 +0,0 @@ -################################################################################ - -# Question -# Write a script that convert numbers from arabic to roman format - -################################################################################ - -# Answer -def toRoman(num): - romans = { - 1000: "M", - 900: "CM", - 500: "D", - 400: "CD", - 100: "C", - 90: "XC", - 50: "L", - 40: "XL", - 10: "X", - 9: "IX", - 5: "V", - 4: "IV", - 1: "I" - } - - if num < 4000: - results = '' - - for decimal, rom in zip(romans.keys(), romans.values()): - div, num = divmod(num, decimal) - results += rom * div - - return results - - else: - return toRoman(num // 1000) + ' ⎺ ' + toRoman(num - 1000 * (num // 1000)) - -################################################################################ - -# Test -def test(value, expected): - results = toRoman(value) - if results == expected: - print(f'✓ Test {value} correct') - else: - print(f'✗ Test {value} incorrect. Expected {expected}, obtained {results}') - -################################################################################ - -# Remove coment from line below to test some exemples -# test(1, "I") -# test(2, "II") -# test(3, "III") -# test(4, "IV") -# test(5, "V") -# test(6, "VI") -# test(7, "VII") -# test(8, "VIII") -# test(9, "IX") -# test(10, "X") -# test(12, "XII") -# test(15, "XV") -# test(18, "XVIII") -# test(19, "XIX") -# test(29, "XXIX") -# test(38, "XXXVIII") -# test(47, "XLVII") -# test(56, "LVI") -# test(65, "LXV") -# test(74, "LXXIV") -# test(83, "LXXXIII") -# test(90, "XC") -# test(92, "XCII") -# test(100, "C") -# test(110, "CX") -# test(200, "CC") -# test(220, "CCXX") -# test(300, "CCC") -# test(330, "CCCXXX") -# test(400, "CD") -# test(440, "CDXL") -# test(500, "D") -# test(550, "DL") -# test(600, "DC") -# test(660, "DCLX") -# test(700, "DCC") -# test(770, "DCCLXX") -# test(800, "DCCC") -# test(880, "DCCCLXXX") -# test(900, "CM") -# test(990, "CMXC") -# test(1000, "M") - -################################################################################ - -# Working exemple -toRoman(100) - -################################################################################ From 84b55e935e06cfc136e676b2a770b181e4d98f89 Mon Sep 17 00:00:00 2001 From: BiscuitCandy <70342294+BiscuitCandy@users.noreply.github.com> Date: Wed, 5 Oct 2022 18:50:35 +0530 Subject: [PATCH 082/129] Create dirTree,py --- dirTree,py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 dirTree,py diff --git a/dirTree,py b/dirTree,py new file mode 100644 index 00000000..bc5db55f --- /dev/null +++ b/dirTree,py @@ -0,0 +1,29 @@ +import os +import os.path +from pathlib import Path + +def display(path, level = 0): + try : + path = Path(path) + except: + print("Enter right path") + return + k = os.listdir(path) + for i in k: + if os.path.isfile(os.path.join(path, i)): + print(" "*level, "--F--", i) + elif os.path.isdir(os.path.join(path, i)): + print(" "*level, "+-D--", i) + display(os.path.join(path, i), level = level + 1) + else: + print(i) + return + + +if __name__ == "__main__": + print("Enter a path") + s = input() + if s == "" : + s = os.getcwd() + l = 0 + display(s, level = 0) From 17b62e49565e4f0455455483a2b28d0c6d3c10d4 Mon Sep 17 00:00:00 2001 From: BiscuitCandy <70342294+BiscuitCandy@users.noreply.github.com> Date: Wed, 5 Oct 2022 18:53:04 +0530 Subject: [PATCH 083/129] created dirTree.py --- dirTree,py => dirTree.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename dirTree,py => dirTree.py (100%) diff --git a/dirTree,py b/dirTree.py similarity index 100% rename from dirTree,py rename to dirTree.py From f0c4b99a84c9c71b3e3b2cb0e6f24090c43f552e Mon Sep 17 00:00:00 2001 From: tht-jxny <37499965+tht-jxny@users.noreply.github.com> Date: Wed, 5 Oct 2022 16:05:44 +0200 Subject: [PATCH 084/129] Added sha256 hashing --- sha256_hashing.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 sha256_hashing.py diff --git a/sha256_hashing.py b/sha256_hashing.py new file mode 100644 index 00000000..ba166ade --- /dev/null +++ b/sha256_hashing.py @@ -0,0 +1,5 @@ +from hashlib import sha256 +print("Please enter password to be hashed:") +passwd = input() +hashed = sha256(passwd.encode()).hexdigest() +print("Hashed password:\n" + hashed) From 6e76175bd820fb9e3d59a6d191e759dbbb1f708d Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Wed, 5 Oct 2022 11:15:56 -0300 Subject: [PATCH 085/129] Add Arithmetic Progression Generator --- arithmetic_progression.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 arithmetic_progression.py diff --git a/arithmetic_progression.py b/arithmetic_progression.py new file mode 100644 index 00000000..c52e177f --- /dev/null +++ b/arithmetic_progression.py @@ -0,0 +1,31 @@ +########################################################################### + +# Question - Arithmetic Progression Generator + +# # Develop a program that: +# 1- read the first term and the common difference of a arithmetic progression +# 2- show the first 10 terms of this progression +# 3- ask to user if he wants show some more terms +# 4- finish the program when user says he wants to show 0 terms + +########################################################################### + +print("Arithmetic Progression Generator") +print("-=" * 50) +first_term = int(input("First term: ")) +common_difference = int(input("Common difference: ")) +term = first_term +cont = 1 +more = 10 +total = 0 +while more != 0: + total += more + while cont <= total: + print(f"{term}", end=" --> ") + term += common_difference + cont += 1 + + print("PAUSE.\n") + + more = int(input("How many terms you want to show more? ")) +print(f"\n\nArithmetic Progression was finished with {total} terms shown.\n\n") From 5e51e9b3856b54dc85446825be72cda5a8f50875 Mon Sep 17 00:00:00 2001 From: Harshal Date: Wed, 5 Oct 2022 20:14:03 +0530 Subject: [PATCH 086/129] I have added a Python program to print prime factors of a given number --- prime factors of a given number.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 prime factors of a given number.py diff --git a/prime factors of a given number.py b/prime factors of a given number.py new file mode 100644 index 00000000..1ccdc9e4 --- /dev/null +++ b/prime factors of a given number.py @@ -0,0 +1,29 @@ +# Python program to print prime factors + +import math + + +def primeFactors(n): + + # Print the number of two\'s that divide n + while n % 2 == 0: + print (2), + n = n / 2 + + # n must be odd at this point + # so a skip of 2 ( i = i + 2) can be used + for i in range(3,int(math.sqrt(n))+1,2): + + # while i divides n , print i ad divide n + while n % i== 0: + print (i), + n = n / i + + + if n > 2: + print (n) + + +n = 315 +primeFactors(n) + From 7a68c54732eb17247e65f62234853782bf43e2de Mon Sep 17 00:00:00 2001 From: Lalit Chaudhary <86573888+CodeLalit007@users.noreply.github.com> Date: Wed, 5 Oct 2022 21:00:50 +0530 Subject: [PATCH 087/129] Create perfect_num.py --- perfect_num.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 perfect_num.py diff --git a/perfect_num.py b/perfect_num.py new file mode 100644 index 00000000..ae5e28b9 --- /dev/null +++ b/perfect_num.py @@ -0,0 +1,11 @@ +#Perfect Number or Not Check + +n = int(input("Enter the number : ")) +sum=0 +for i in range(1,n): + if n%i==0: + sum+=i +if sum==n: + print("Perfect !") +else: + print("Nah !") From 1290b9383a06362a8fc2be80d3e52a4ca06b3732 Mon Sep 17 00:00:00 2001 From: derco19 Date: Wed, 5 Oct 2022 21:53:41 +0530 Subject: [PATCH 088/129] 12 digit Password Generator with constraints of special_chars and digits --- random_password_generator.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 random_password_generator.py diff --git a/random_password_generator.py b/random_password_generator.py new file mode 100644 index 00000000..c7a12fae --- /dev/null +++ b/random_password_generator.py @@ -0,0 +1,22 @@ +import secrets +import string + +letters = string.ascii_letters +digits = string.digits +special_chars = string.punctuation + +alphabet = letters + digits + special_chars + +# fix password length +pwd_length = 12 + +# generate password meeting constraints +while True: + pwd = '' + for i in range(pwd_length): + pwd += ''.join(secrets.choice(alphabet)) + + if (any(char in special_chars for char in pwd) and + sum(char in digits for char in pwd) >= 2): + break +print(pwd) From ac7f7b3c0fd8cdb705fa143faaf2a381b35c02f8 Mon Sep 17 00:00:00 2001 From: lakshya bhasin Date: Wed, 5 Oct 2022 22:15:46 +0530 Subject: [PATCH 089/129] Added a few CLI game - LAKSHYA BHASIN --- Blackjack.py | 91 ++++++++++++++++++++++++++++++++++++++++++++ Guessnumber.py | 37 ++++++++++++++++++ HangmanGame.py | 88 ++++++++++++++++++++++++++++++++++++++++++ PasswordGenerator.py | 56 +++++++++++++++++++++++++++ RockPaperScissors.py | 16 ++++++++ 5 files changed, 288 insertions(+) create mode 100644 Blackjack.py create mode 100644 Guessnumber.py create mode 100644 HangmanGame.py create mode 100644 PasswordGenerator.py create mode 100644 RockPaperScissors.py diff --git a/Blackjack.py b/Blackjack.py new file mode 100644 index 00000000..d81e3907 --- /dev/null +++ b/Blackjack.py @@ -0,0 +1,91 @@ +logo=""" +.------. _ _ _ _ _ +|A_ _ |. | | | | | | (_) | | +|( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __ +| \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ / +| \/ | / \ | | |_) | | (_| | (__| <| | (_| | (__| < +`-----| \ / | |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\ + | \/ K| _/ | + `------' |__/ +""" +import random + +print(logo) +cards=[11,2,3,4,5,6,7,8,9,10,10,10,10] + +player=[] +computer=[] + +player_sum=0 +computer_sum=0 + +player.append(random.choice(cards)) + + +rand = random.choice(cards) +if (rand == 11 and rand + computer_sum > 21): + player.append(1) +else: + player.append(rand) + + +computer.append(random.choice(cards)) + + +randco = random.choice(cards) +if (rand == 11 and rand + computer_sum > 21): + computer.append(1) +else: + computer.append(rand) + +player_sum+=player[0]+player[1] +computer_sum+=computer[0]+computer[1] + +while(player_sum<=21): + print(f"Your cards : {player} ,current score : {player_sum}") + print(f"Computer's first card : {computer[0]}") + + accept=input("Type y to get another card , Type n to pass : ") + if(accept=='y'): + rand=random.choice(cards) + if(rand==11 and rand+player_sum>21): + player_sum+=1 + player.append(1) + else: + player_sum+=rand + player.append(rand) + else:break + +if player_sum>21: + print(f"Your cards : {player} ,current score : {player_sum}") + print("You Lost") + exit() + +while computer_sum 21): + computer_sum += 1 + computer.append(1) + else: + computer_sum += rand + computer.append(rand) + +if computer_sum>21 or player_sum>computer_sum : + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("You Won") + exit() +if(computer_sum==player_sum): + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("Draw!!") + exit() + +if(computer_sum>player_sum): + print(f"Your cards : {player} ,Your score : {player_sum}") + print(f"Computer cards : {computer} ,Computer score : {computer_sum}") + + print("You Lost") + exit() \ No newline at end of file diff --git a/Guessnumber.py b/Guessnumber.py new file mode 100644 index 00000000..278b02cd --- /dev/null +++ b/Guessnumber.py @@ -0,0 +1,37 @@ +import random +number=random.randint(1,100) + + +def guessNUmber(number, num , level): + + while level!=1: + if(num>number): + print("Too High") + else:print("Too Low") + level-=1 + print(f"YOU have {level} attemps left") + num = int(input("Guess the number : ")) + + if(num==number):print(f"YOU GUESSED IT CORRECT IT WAS {num}") + else:print(f"YOU GUESSED IT WRONG IT WAS {number}") + +print("choose the level of game 'hard' or 'easy'") +level = input().lower() + +while True: + + + if(level!="hard" and level!="easy"): + print("Invalid Choice") + else:break + + print("choose the level of game 'hard' or 'easy'") + level = input().lower() + +print("I am thinking of a number betwen 1-100. \n ") +num = int(input("Guess the number : ")) + +if level == "hard": + guessNUmber(number, num, 5) +elif level == "easy:": + guessNUmber(number, num, 10) diff --git a/HangmanGame.py b/HangmanGame.py new file mode 100644 index 00000000..c9d9d07e --- /dev/null +++ b/HangmanGame.py @@ -0,0 +1,88 @@ +import random + +stages = [''' + +---+ + | | + O | + /|\ | + / \ | + | +========= +''', ''' + +---+ + | | + O | + /|\ | + / | + | +========= +''', ''' + +---+ + | | + O | + /|\ | + | + | +========= +''', ''' + +---+ + | | + O | + /| | + | + | +=========''', ''' + +---+ + | | + O | + | | + | + | +========= +''', ''' + +---+ + | | + O | + | + | + | +========= +''', ''' + +---+ + | | + | + | + | + | +========= +'''] +lives = 6 +word_list = ["baboon", "delhi", "adamantium", "dehradun"] +# choosing a random word from the list +word = random.choice(word_list); +print(f"The chosen word is {word}") +blank_list = [] + +for i in range(len(word)): + blank_list += "_" +end_game=False +while end_game == False: + guess = input("Guess a letter\n") + + if guess not in word: + lives=lives-1 + else: + for i in range(len(word)): + if word[i]==guess: + blank_list[i]=guess + + if lives==0 or "_" not in blank_list: + end_game=True + + # Clear.clear() + for i in blank_list: + print(i,end=" ") + print(stages[lives]) + +if(lives==0):print("YOU LOSE!!") +else :print("YOU WON!!") \ No newline at end of file diff --git a/PasswordGenerator.py b/PasswordGenerator.py new file mode 100644 index 00000000..ae774e82 --- /dev/null +++ b/PasswordGenerator.py @@ -0,0 +1,56 @@ +#Password Generator Project +import random +letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', + 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z'] +numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + +print("Welcome to the PyPassword Generator!") + + +no_letters=int(input("How many letters would you like to use in password?\n")) +no_symbols=int(input("How many symbols would you like? \n")) +no_numbers=int(input("How many numbers would you like? \n")) + + + + +def easy_version(): + password = "" + for i in range(no_letters): + ran=random.randint(0,len(letters)) + password+=letters[ran] + for i in range(no_numbers): + ran=random.randint(0,len(numbers)) + password+=str(numbers[ran]) + for i in range(no_symbols): + ran=random.randint(0,len(symbols)) + password+=str(symbols[ran]) + print(password) + +def hard_version(): + password_list=[] + password="" + for i in range(no_letters): + ran=random.randint(0,len(letters)-1) + password_list+=letters[ran] + for i in range(no_numbers): + ran=random.randint(0,len(numbers)-1) + password_list+=str(numbers[ran]) + for i in range(no_symbols): + ran=random.randint(0,len(symbols)-1) + password_list+=str(symbols[ran]) + + random.shuffle(password_list) + for i in password_list: + password+=i + + print(password) + + +hard_version() + + diff --git a/RockPaperScissors.py b/RockPaperScissors.py new file mode 100644 index 00000000..2bb0ddd1 --- /dev/null +++ b/RockPaperScissors.py @@ -0,0 +1,16 @@ +import random + +randomInteger=random.randint(0,2) +userInput=int(input("What do you choose ? Type 0 for Rock,1 for Paper or 2 for Scissors\n")) +if(userInput!=0 and userInput!=1 and userInput!=2): + print("Wrong choise") + exit() + +if(userInput==randomInteger): + print("DRAW!!!") +elif (userInput==randomInteger-1 or (userInput==2 and randomInteger==0)): + print("Computer Won") +elif (randomInteger==userInput-1 or (randomInteger==2 and userInput==0)): + print("YOU WON!!!") +print(userInput) +print(f"computer choose {randomInteger}") \ No newline at end of file From 6d246fb2c257cefa13bd77a729347d04bef3e571 Mon Sep 17 00:00:00 2001 From: lukas1505 Date: Wed, 5 Oct 2022 21:36:16 +0200 Subject: [PATCH 090/129] ADD webscraper.py --- webscraper.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 webscraper.py diff --git a/webscraper.py b/webscraper.py new file mode 100644 index 00000000..24907aeb --- /dev/null +++ b/webscraper.py @@ -0,0 +1,16 @@ +import requests +from bs4 import BeautifulSoup +# Make a request +page = requests.get("Paste a Domain here") +soup = BeautifulSoup(page.content, 'html.parser') + +# Create all_h1_tags as empty list +all_h1_tags = [] + +# Set all_h1_tags to all h1 tags of the soup +for element in soup.select('h1'): + all_h1_tags.append(element.text) + +print(all_h1_tags) + +# give you all h1 tags \ No newline at end of file From 7ef964c3f55457590a12565746ac3f80b0e023e1 Mon Sep 17 00:00:00 2001 From: Abhimanyu Singh Date: Thu, 6 Oct 2022 05:02:44 +0530 Subject: [PATCH 091/129] Created EMI Calculator --- emi-calculator.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 emi-calculator.py diff --git a/emi-calculator.py b/emi-calculator.py new file mode 100644 index 00000000..e9b570d8 --- /dev/null +++ b/emi-calculator.py @@ -0,0 +1,20 @@ +def emi_calculator(p:float, r:float, t:float): + """EMI Calculator for one months + -------------------------------- + Parameters: + p - principal + r - interest rate per month + t - time period (in years) + """ + r = r / (12 * 100) # one month interest + t = t * 12 # one month period + emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1) + return emi + + +principal = float(input("Enter principal amount (in ₹):")) +rate = float(input("Enter Interest Rate per month (%):")) +time = float(input("Enter Time period (in years):")) +emi = emi_calculator(principal, rate, time) +print("Your Monthly EMI is ₹", round(emi,2)) + From 6b75c12522c71128f7ec1689183c4e03017b3f1a Mon Sep 17 00:00:00 2001 From: Abin M <48612234+abin-m@users.noreply.github.com> Date: Thu, 6 Oct 2022 11:34:08 +0530 Subject: [PATCH 092/129] added 2 string programs --- Extracting_Numbers_from_textString.py | 40 +++++++++++++++++++++++++++ substring.py | 19 +++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 Extracting_Numbers_from_textString.py create mode 100644 substring.py diff --git a/Extracting_Numbers_from_textString.py b/Extracting_Numbers_from_textString.py new file mode 100644 index 00000000..fcd50640 --- /dev/null +++ b/Extracting_Numbers_from_textString.py @@ -0,0 +1,40 @@ +# Given Sentence +sentence="Ramu have 150 Apples and 10 bananas" +sentence2="Ramu Sell 1 Apple at 15.5 Rupees" + +list1=[] +list2=[] + +sum=0 +sum2=0 +# split is used to split sentence +# This code is not fit for Decimal Nos. + +print("---------------EXTRACTING NUMBER FROM STRING---------------\n") +for word in sentence.split(): + if word.isdigit(): + list1.append(word) + +print("New List",list1) + + + +# Calculating the SUM +for i in list1: + sum=sum+int(i) + +print("No. without Fraction \nsum=",sum,"\n") + +# If Decimal Numbers occured in the Sentence +for word2 in sentence2.split(): + if not word2.isalpha(): + list2.append(word2) + +print("New List",list2) + +# Calculating the SUM +for j in list2: + sum2=sum2+float(j) + +print("No. with Fraction \nsum=",sum2) +print("-----------------------------------------------------------") \ No newline at end of file diff --git a/substring.py b/substring.py new file mode 100644 index 00000000..657abe9e --- /dev/null +++ b/substring.py @@ -0,0 +1,19 @@ +def substring(str1,n): + for i in range(0,n): + for j in range(i+1,n+1): + # Printing the substrings using slicing + # Suppose we have str1="Hello" Str1[0:1] will print "H" + # Str1[1:2] will print "He" + # Str1[1:3] will print "Hel" + # Str1[1:4] will print "Hell" + # Str1[1:5] will print "Hello" + # then i will increment i=2 + # Str1[2:3] will print "e" + # Str1[2:4] will print "el" + # And So On + print(str1[i:j]) + + +str1 = input("Enter a String:") +n=len(str1) +substring(str1,n) \ No newline at end of file From f2434640b4eeafea5efd0b3a1eb7d0e2867b86a3 Mon Sep 17 00:00:00 2001 From: Dineshwar Doddapaneni <63300423+dinesh9-ai@users.noreply.github.com> Date: Thu, 6 Oct 2022 12:04:55 +0530 Subject: [PATCH 093/129] added kadanes algorithm --- kadanes_algorithm.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 kadanes_algorithm.py diff --git a/kadanes_algorithm.py b/kadanes_algorithm.py new file mode 100644 index 00000000..d719823a --- /dev/null +++ b/kadanes_algorithm.py @@ -0,0 +1,18 @@ +""" +This algorithm is used to find the largest sum in the given array in O(n) Time complexity +""" + +arr=[-1,0,3,4,2,6,-10,5,-9] + +max_sum=0 +curr_sum=0 + +for i in arr: + curr_sum += i + max_sum=max(max_sum,curr_sum) + + if curr_sum<0: + curr_sum=0 + + +print(max_sum) \ No newline at end of file From 960a869552d2d86ac3cb18aba96909ae6db84e57 Mon Sep 17 00:00:00 2001 From: kawago2 <90557836+kawago2@users.noreply.github.com> Date: Thu, 6 Oct 2022 17:57:25 +0700 Subject: [PATCH 094/129] add program budgeting plan for (indonesian) rupiah --- rupiah_budgeting_plan.py | 77 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 rupiah_budgeting_plan.py diff --git a/rupiah_budgeting_plan.py b/rupiah_budgeting_plan.py new file mode 100644 index 00000000..ecb1b6e3 --- /dev/null +++ b/rupiah_budgeting_plan.py @@ -0,0 +1,77 @@ +from turtle import delay +from modul import * +import time + +# assume value is a decimal +def transform_to_rupiah_format(value): + str_value = str(value) + separate_decimal = str_value.split(".") + after_decimal = separate_decimal[0] + before_decimal = separate_decimal[1] + + reverse = after_decimal[::-1] + temp_reverse_value = "" + + for index, val in enumerate(reverse): + if (index + 1) % 3 == 0 and index + 1 != len(reverse): + temp_reverse_value = temp_reverse_value + val + "." + else: + temp_reverse_value = temp_reverse_value + val + + temp_result = temp_reverse_value[::-1] + + return "Rp " + temp_result + ",0" + before_decimal + + +def formatrupiah(uang): + y = str(uang) + if len(y) <= 3: + return 'Rp ' + y + else: + p = y[-3:] + q = y[:-3] + return formatrupiah(q) + '.' + p + + +# default budgeting percentage (single) +living = 0.30 +playing = 0.20 +saving = 0.50 + +# # default budgeting percentage (married) +# living = 0.30 +# playing = 0.15 +# saving = 0.55 + +budget = int(input('Masukkan pemasukan anda: ')) + + +# tiap tiap kategorinya +percent_living = living * 100 +percent_playing = playing * 100 +percent_saving = saving * 100 +percentage = [percent_playing, percent_living, percent_saving] +sum = 00.0 +percent_budget = (living + playing + saving)*100 + +budget_living = budget * living +budget_playing = budget * playing +budgett_saving = budget * saving + +print('========================================================') +for x in percentage: + print('Checking Persen Budgeting '+'{}'.format(sum)+' %'+' (Checking)') + time.sleep(2) + sum += x + +print('Checking Persen Budgeting '+'{}'.format(percent_budget)+'%'+' (Done)') +time.sleep(2) +print('Budgeting anda adalah sebesar {}'.format(formatrupiah(budget))+',00') +print('Pemasukan anda untuk kebutuhan hidup adalah\t: {}'.format( + transform_to_rupiah_format(budget_living))) + +print('Pemasukan anda untuk kegiatan adalah\t\t: {}'.format( + transform_to_rupiah_format(budget_playing))) +print('Pemasukan anda untuk tabungan adalah\t\t: {}'.format( + transform_to_rupiah_format(budgett_saving))) +print('========================================================') From 1a7b3857e806b71c7f4f5f68664bf82bc7c3a5a1 Mon Sep 17 00:00:00 2001 From: Harish Adityawan Date: Thu, 6 Oct 2022 21:13:23 +0700 Subject: [PATCH 095/129] add tower of hanoi --- TowerOfHanoi.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 TowerOfHanoi.py diff --git a/TowerOfHanoi.py b/TowerOfHanoi.py new file mode 100644 index 00000000..e3f76e49 --- /dev/null +++ b/TowerOfHanoi.py @@ -0,0 +1,12 @@ +def TowerOfHanoi(Disks, source, temp, destination): + if(Disks == 1): + print("Move Disk 1 From {} to {}".format(source, destination)) + return + TowerOfHanoi(Disks - 1, source, destination, temp) + print("Move Disk {} From {} to {}".format(Disks, source, destination)) + TowerOfHanoi(Disks - 1, temp, source, destination) + +Disks = int(input("Enter Number of Disks: ")) + +# Source : A, Intermediate : B, Destination : C +TowerOfHanoi(Disks, 'A', 'B', 'C') \ No newline at end of file From 48f2a9ef0839bba43977caec58808455a9307593 Mon Sep 17 00:00:00 2001 From: Rafael Souza Date: Thu, 6 Oct 2022 14:39:40 -0300 Subject: [PATCH 096/129] Create dice_roller.py creates a dice rolling simulator --- dice_roller.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 dice_roller.py diff --git a/dice_roller.py b/dice_roller.py new file mode 100644 index 00000000..c981a987 --- /dev/null +++ b/dice_roller.py @@ -0,0 +1,21 @@ +from random import randint, seed + +# The randint(a,b) function return a pseudorandom number between a and b, including both. +# The seed() function defines a new seed for pseudorandom numbers. + +# This function defines a die roll. If no specific side is defined, it 'rolls' a six-sided die. + +def die(sides=6): + seed() + result = randint(1, sides) + return result + +# This function defines a dice roll. +# If no specific side and number of dies are defined, it 'rolls' a six-sided die. +#Returns a list of ints with the dice rolls. + +def dice(number_of_die=1, sides=6): + rolls = [] + for roll in range(0, number_of_die): + rolls.append(die(sides)) + return rolls \ No newline at end of file From 1f0e7f8dd01a2a9ae4f8c8c6e7c4431c5927c72c Mon Sep 17 00:00:00 2001 From: Pooja1030 <95880894+Pooja1030@users.noreply.github.com> Date: Thu, 6 Oct 2022 23:20:29 +0530 Subject: [PATCH 097/129] Add files via upload --- OTP generator.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 OTP generator.py diff --git a/OTP generator.py b/OTP generator.py new file mode 100644 index 00000000..937b5935 --- /dev/null +++ b/OTP generator.py @@ -0,0 +1,22 @@ +import os +import math +import random +import smtplib +digits = "012456789" +OTP = "" +for i in range(4): + OTP += digits[math.floor(random.random() * 10)] +msg = str(OTP) + "Your OTP is" + +s = smtplib.SMTP('smtp.gmail.com', 587) +s.starttls() + +emailid = "poojasawant1030@dbatu.ac.in" +s.login("poojasawant1030@gmail.com", " gwagviywswrmfhpo") +s.sendmail("poojasawant1030@gmail.com", emailid, msg) +a = input("Enter the OTP >>: ") +if a == OTP: + print("Verified") +else: + print("Incorrect OTP") +s.quit() From daab69da11799a7363506ac891702605507ca487 Mon Sep 17 00:00:00 2001 From: Pooja1030 <95880894+Pooja1030@users.noreply.github.com> Date: Thu, 6 Oct 2022 23:21:58 +0530 Subject: [PATCH 098/129] Update OTP generator.py --- OTP generator.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OTP generator.py b/OTP generator.py index 937b5935..f9d64c6c 100644 --- a/OTP generator.py +++ b/OTP generator.py @@ -11,9 +11,9 @@ s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() -emailid = "poojasawant1030@dbatu.ac.in" -s.login("poojasawant1030@gmail.com", " gwagviywswrmfhpo") -s.sendmail("poojasawant1030@gmail.com", emailid, msg) +emailid = "receiver's id" +s.login("sender's id", "google app password") +s.sendmail("sender's id", emailid, msg) a = input("Enter the OTP >>: ") if a == OTP: print("Verified") From 93742b7c5f442e8c1b4b7ebf3d160ce112d5d130 Mon Sep 17 00:00:00 2001 From: Rafael Souza Date: Thu, 6 Oct 2022 14:55:06 -0300 Subject: [PATCH 099/129] Create collatz_sequence.py Collatez Conjecture --- collatz_sequence.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 collatz_sequence.py diff --git a/collatz_sequence.py b/collatz_sequence.py new file mode 100644 index 00000000..564afaf8 --- /dev/null +++ b/collatz_sequence.py @@ -0,0 +1,18 @@ +# The Collatz Conjecture is a famous math problem. +# The conjecture is that after applying a sequence of one of two transformations, +# every positive integer will eventually transform into 1. +# The transformations are: divide by 2 if the number is even, multiply by 3 and add 1 if its odd. +# You can see more about it here https://en.wikipedia.org/wiki/Collatz_conjecture + +def collatz(initial_number): + num = initial_number + print(f'Initial number is: {initial_number}') + while num != 1: + print(num) + if num % 2 == 0: + num = int(num / 2) + else: + num = int(3 * num + 1) + else: + print(num) + print('Finally!') \ No newline at end of file From 9fde8d1999e12c069a64644dab3c566ddff522fd Mon Sep 17 00:00:00 2001 From: Rafael Souza Date: Thu, 6 Oct 2022 15:19:46 -0300 Subject: [PATCH 100/129] Create SI_units.py convert units to International System of Measurements --- SI_units.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 SI_units.py diff --git a/SI_units.py b/SI_units.py new file mode 100644 index 00000000..840f50b8 --- /dev/null +++ b/SI_units.py @@ -0,0 +1,26 @@ + +#converting pounds to kg + +def pounds_to_kg(pounds): + return pounds*0.453592 + +def feet_to_meters(feet): + return feet*0.3048 + +def inches_to_meters(inches): + return inches*0.0254 + +def yards_to_meters(yards): + return yards*0.9144 + +def miles_to_meters(miles): + return miles*1609.34 + +def miles_per_hour_to_ms(miles_per_hour): + return miles_per_hour*0.44704 + +def celsius_to_kelvin(celsius): + return celsius + 273.15 + +def farenheit_to_kelvin(farenheit): + return ((farenheit - 32)/1.8) +273.15 From b6d0472d1b9686441d542b21ea0ad600b1acc914 Mon Sep 17 00:00:00 2001 From: Yash Umale Date: Fri, 7 Oct 2022 00:59:28 +0530 Subject: [PATCH 101/129] Added Video to JPEG converter Python script --- video_jpeg_converter.py | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 video_jpeg_converter.py diff --git a/video_jpeg_converter.py b/video_jpeg_converter.py new file mode 100644 index 00000000..268f44c9 --- /dev/null +++ b/video_jpeg_converter.py @@ -0,0 +1,44 @@ +# File name: video_jpeg_converter.py +# Objective: To return a set of continuous JPEG images from an input video (useful for annotation of videos) + +from imutils import paths +import cv2 +import os + +# Path for input videos (which will be converted to a series of JPEG images) +dataPath = str(input("Copy the path to your video input data and paste it here: ")) + +# Path for output JPEG images +outPath = str(input("Copy the path to your output folder storing the JPEG images and paste it here: ")) + +for classPath in os.listdir(dataPath): + clipPaths = os.listdir(dataPath + "\\" + classPath) + os.mkdir((outPath + '\\' + classPath)) + + k = 1 + for clips in clipPaths: + os.mkdir((outPath + '\\' + classPath + '\\' + clips)) + os.chdir((outPath + '\\' + classPath + '\\' + clips)) + + f = dataPath + "\\" + classPath + "\\" + clips + cam = cv2.VideoCapture(f) + ret, frame = cam.read() + currentframe = 0 + i = 0 + + # a variable to set how many frames you want to skip + frame_skip = 5 # Since the videos are in 30 FPS, and we want 10 frames per clip + + while cam.isOpened(): + ret, frame = cam.read() + k += 1 + if not ret: + break + if (i > frame_skip - 1): + cv2.imwrite(classPath + '_' + clips + '_' + str(k) +'.jpg', frame) + i = 0 + continue + i += 1 + + cam.release() + cv2.destroyAllWindows() \ No newline at end of file From 75f3e1d3c56bb2e4b8494eb06d1a1a593ace3965 Mon Sep 17 00:00:00 2001 From: Harsh Tiwari <47390133+mrgokuji@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:02:39 +0530 Subject: [PATCH 102/129] Create .gitignore --- .gitignore | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b6e47617 --- /dev/null +++ b/.gitignore @@ -0,0 +1,129 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ From 221334702b14579e9db02b852984e1231d868be5 Mon Sep 17 00:00:00 2001 From: adebayo Date: Fri, 7 Oct 2022 02:56:33 +0100 Subject: [PATCH 103/129] A fast recursive implementation of fibonacci numbers --- fast_recursive_fibonacci.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 fast_recursive_fibonacci.py diff --git a/fast_recursive_fibonacci.py b/fast_recursive_fibonacci.py new file mode 100644 index 00000000..b2b9aebe --- /dev/null +++ b/fast_recursive_fibonacci.py @@ -0,0 +1,19 @@ +def fast_rec_fib_helper(n): + """returns the last two elements of the fibonacci sequence.""" + if n == 1: + return (0,1) + m = n//2 + hprv, hcur = fast_rec_fib_helper(m) + prev = (hprv ** 2) + (hcur **2) + curr = hcur * (2 * hprv + hcur) + next = prev + curr + if n % 2 == 0: + return (prev, curr) + else: + return (curr, next) + +def fast_rec_fib(n): + previous, current = fast_rec_fib_helper(n) + return current + +print(fast_rec_fib(1000)) \ No newline at end of file From ed0d247c1f23cef298a2d2c7e9065229bffd1411 Mon Sep 17 00:00:00 2001 From: adebayo Date: Fri, 7 Oct 2022 03:07:20 +0100 Subject: [PATCH 104/129] A fast recursive implementation of the fibonacci series --- fast_recursive_fibonacci.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fast_recursive_fibonacci.py b/fast_recursive_fibonacci.py index b2b9aebe..46fb7cab 100644 --- a/fast_recursive_fibonacci.py +++ b/fast_recursive_fibonacci.py @@ -1,6 +1,6 @@ def fast_rec_fib_helper(n): """returns the last two elements of the fibonacci sequence.""" - if n == 1: + if n <= 1: return (0,1) m = n//2 hprv, hcur = fast_rec_fib_helper(m) @@ -13,7 +13,9 @@ def fast_rec_fib_helper(n): return (curr, next) def fast_rec_fib(n): + if n==0: + return 0 previous, current = fast_rec_fib_helper(n) return current -print(fast_rec_fib(1000)) \ No newline at end of file +print(fast_rec_fib(2)) \ No newline at end of file From 6e7d3c4016e2f03a00273d020eaaf4ff4708a90c Mon Sep 17 00:00:00 2001 From: Shivsagar Mishra <89444163+sagarmishra1103@users.noreply.github.com> Date: Fri, 7 Oct 2022 16:42:52 +0530 Subject: [PATCH 105/129] Added MatrixOperation.py file to the directory. Added MatrixOperations.py File To the directory which is used to perform basic matrix operations such as 1. Addition 2. Subtraction 3. Multiplication 4. Transpose Its navigation is very userfriendly. --- MatrixOperation.py | 49 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 MatrixOperation.py diff --git a/MatrixOperation.py b/MatrixOperation.py new file mode 100644 index 00000000..811c2ce1 --- /dev/null +++ b/MatrixOperation.py @@ -0,0 +1,49 @@ +#Prgram Code Created by Shivsagar Mishra +#This is a program to perform basic matrix operarations such as 1. Addition 2.Substraction 3.Multiplication 4.Transpose + + +import numpy as np + +# Initialize matrix +a = np.array([[1,2,1], [6,5,4], [9,5,8]]) +b = np.array([[3,2,1], [8,6,4], [4,0,0]]) + +while True: + print("List of operations:\n1.Display\n2.Addition\n3.Substraction\n4.Multiplication\n5.Transpose") + counter=int(input("Enter the your Choice:")) + + if counter == 1: + #printing 1st matrix + print("First Matrix:") + print (a,"\n") + # printing 2nd Matrix + print("Second Matrix:") + print(b,"\n") + + elif counter == 2: + print ("The addition of matrices is : ") + print(a.__add__(b),"\n") + + elif counter == 3: + print ("The Substraction of matrices is : ") + print ("Substraction is:") + print(a.__sub__(b),"\n") + + elif counter == 4: + print ("The multiplication of matrices is : ") + print(a.__mul__(b),"\n") + + elif counter == 5: + print ("The Transposition of First matrix is: ") + print(np.transpose(a),"\n") + print("The Transposition of Second Matrix is:") + print(np.transpose(b),"\n") + else: + print("Invalid Option!") + + cont=int(input("Do you want to continue?: 1.Yes\t 2.No\t Enter your choice:")) + if cont==1: + continue + else: + break + From 8f1b1f926fbf7bf1cf3cb5665cd122a88c093a14 Mon Sep 17 00:00:00 2001 From: "Ahmed, Mehtab" Date: Fri, 7 Oct 2022 22:43:52 +0530 Subject: [PATCH 106/129] Added function to reverse a 32 bit signed int --- reverse32bitsignedint.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 reverse32bitsignedint.py diff --git a/reverse32bitsignedint.py b/reverse32bitsignedint.py new file mode 100644 index 00000000..8e84df4b --- /dev/null +++ b/reverse32bitsignedint.py @@ -0,0 +1,19 @@ +# reverse a 32 bit signed int +# if ans overflows then returns 0 +def reverse32bitsignedint(n): + is_negative = 0 + if n < 0: + is_negative = 1 + n = -n + ans = 0 + while n: + quotient = n // 10 + reminder = n % 10 + n = quotient + ans = ans * 10 + reminder + limit = 1 << 31 + if is_negative: + ans = -ans + if (ans <= -limit) or (ans >= limit - 1): + return 0 + return ans From 6b1c75e36486a4274e48036db4a699ad32ba082d Mon Sep 17 00:00:00 2001 From: Yash Londhe <99034957+yashlondhe90960@users.noreply.github.com> Date: Sat, 8 Oct 2022 11:23:24 +0530 Subject: [PATCH 107/129] Added program of reversing Linkedlist. Program for reversing linkedlist in python. --- Linkedlist_reverse.py | 59 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Linkedlist_reverse.py diff --git a/Linkedlist_reverse.py b/Linkedlist_reverse.py new file mode 100644 index 00000000..a50c0cb3 --- /dev/null +++ b/Linkedlist_reverse.py @@ -0,0 +1,59 @@ +# Python program to reverse a linked list + + +# Node class + + +class Node: + + # Constructor to initialize the node object + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to reverse the linked list + def reverse(self): + prev = None + current = self.head + while(current is not None): + next = current.next + current.next = prev + prev = current + current = next + self.head = prev + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Utility function to print the LinkedList + def printList(self): + temp = self.head + while(temp): + print (temp.data,end=" ") + temp = temp.next + + +# Driver program to test above functions +llist = LinkedList() +llist.push(20) +llist.push(4) +llist.push(15) +llist.push(85) + +print ("Given Linked List") +llist.printList() +llist.reverse() +print ("\nReversed Linked List") +llist.printList() + + From d745b8b614ccbf8ba4f87c86b2fd401d35dda8cf Mon Sep 17 00:00:00 2001 From: Dayita_C Date: Sat, 8 Oct 2022 13:23:12 +0530 Subject: [PATCH 108/129] Minesweeper_Game --- Minesweeper_Game.py | 121 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 Minesweeper_Game.py diff --git a/Minesweeper_Game.py b/Minesweeper_Game.py new file mode 100644 index 00000000..2de12f51 --- /dev/null +++ b/Minesweeper_Game.py @@ -0,0 +1,121 @@ +import random + +# Generate a random map to start the game. +def randomMap(n, k): + + arr = [[0 for row in range(0,n)] for column in range(0,n)] + + for num in range(0,k): + x = random.randint(0,n-1) + y = random.randint(0,n-1) + arr[y][x] = 'X' + + if (x >=0 and x <= n-2) and (y >= 0 and y <= n-1): + if arr[y][x+1] != 'X': + arr[y][x+1] += 1 # center right + + if (x >=1 and x <= n-1) and (y >= 0 and y <= n-1): + if arr[y][x-1] != 'X': + arr[y][x-1] += 1 # center left + + if (x >= 1 and x <= n-1) and (y >= 1 and y <= n-1): + if arr[y-1][x-1] != 'X': + arr[y-1][x-1] += 1 # top left + + if (x >= 0 and x <= n-2) and (y >= 1 and y <= n-1): + if arr[y-1][x+1] != 'X': + arr[y-1][x+1] += 1 # top right + + if (x >= 0 and x <= n-1) and (y >= 1 and y <= n-1): + if arr[y-1][x] != 'X': + arr[y-1][x] += 1 # top center + + if (x >=0 and x <= n-2) and (y >= 0 and y <= n-2): + if arr[y+1][x+1] != 'X': + arr[y+1][x+1] += 1 # bottom right + + if (x >= 1 and x <= n-1) and (y >= 0 and y <= n-2): + if arr[y+1][x-1] != 'X': + arr[y+1][x-1] += 1 # bottom left + + if (x >= 0 and x <= n-1) and (y >= 0 and y <= n-2): + if arr[y+1][x] != 'X': + arr[y+1][x] += 1 # bottom center + return arr + +# Generate the map for the player. +def playerMap(n): + arr = [['-' for row in range(0,n)] for column in range(0,n)] + return arr + +# Display the map on the screen. +def showMap(map): + for row in map: + print(" ".join(str(cell) for cell in row)) + print("") + +# Check if player has won. +def checkWin(map): + for row in map: + for cell in row: + if cell == '-': + return False + return True + +# Check if player is willing to continue the game. +def checkContinue(score): + print("Your score: ", score) + isContinue = input("Do you want to try again? (y/n) :") + if isContinue == 'n': + return False + return True + +# MINESWEEPER GAME +def Game(): + + GameStatus = True + while GameStatus: + difficulty = input("Select your difficulty (0,1,2):") + if difficulty.lower() == '0': + n = 5 + k = 3 + elif difficulty.lower() == '1': + n = 6 + k = 8 + else: + n = 8 + k = 20 + + minesweeper_map = randomMap(n, k) + player_map = playerMap(n) + score = 0 + + while True: + + if checkWin(player_map) == False: + print("Enter the cell you want to open :") + x,y = map(int,input().split()) + x -= 1 # 0 based indexing + y -= 1 # 0 based indexing + if (minesweeper_map[y][x] == 'X'): + print("Game Over!") + showMap(minesweeper_map) + GameStatus = checkContinue(score) + break + else: + player_map[y][x] = minesweeper_map[y][x] + showMap(player_map) + score += 1 + + else: + showMap(player_map) + print("Congratulation! You Win!") + GameStatus = checkContinue(score) + break + +# Main Program +if __name__ == "__main__": + try: + Game() + except KeyboardInterrupt: + print('\nGoodbye!') \ No newline at end of file From a4f89fcfbbd2a4efc089de723ba05a62101320ab Mon Sep 17 00:00:00 2001 From: Anukiran Ghosh <59087982+akghosh111@users.noreply.github.com> Date: Sat, 8 Oct 2022 14:11:06 +0530 Subject: [PATCH 109/129] weather_gui.py --- weather_gui.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 weather_gui.py diff --git a/weather_gui.py b/weather_gui.py new file mode 100644 index 00000000..20c9fdf7 --- /dev/null +++ b/weather_gui.py @@ -0,0 +1,42 @@ +import tkinter as tk +import requests +import time + + +def getWeather(canvas): + city = textField.get() + api = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=06c921750b9a82d8f5d1294e1586276f" + + json_data = requests.get(api).json() + condition = json_data['weather'][0]['main'] + temp = int(json_data['main']['temp'] - 273.15) + min_temp = int(json_data['main']['temp_min'] - 273.15) + max_temp = int(json_data['main']['temp_max'] - 273.15) + pressure = json_data['main']['pressure'] + humidity = json_data['main']['humidity'] + wind = json_data['wind']['speed'] + sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600)) + sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600)) + + final_info = condition + "\n" + str(temp) + "°C" + final_data = "\n"+ "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str(max_temp) + "°C" +"\n" + "Pressure: " + str(pressure) + "\n" +"Humidity: " + str(humidity) + "\n" +"Wind Speed: " + str(wind) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset + label1.config(text = final_info) + label2.config(text = final_data) + + +canvas = tk.Tk() +canvas.geometry("600x500") +canvas.title("Weather App") +f = ("poppins", 15, "bold") +t = ("poppins", 35, "bold") + +textField = tk.Entry(canvas, justify='center', width = 20, font = t) +textField.pack(pady = 20) +textField.focus() +textField.bind('', getWeather) + +label1 = tk.Label(canvas, font=t) +label1.pack() +label2 = tk.Label(canvas, font=f) +label2.pack() +canvas.mainloop() From 587e544db6a5e4f933369b2eba7539f15fdc03ad Mon Sep 17 00:00:00 2001 From: hamzahasann <64196922+hamzahasann@users.noreply.github.com> Date: Sun, 9 Oct 2022 01:07:47 +0500 Subject: [PATCH 110/129] Created disjoint_set_union.py Disjoint-Set-Union data structure for python. --- disjoint_set_union.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 disjoint_set_union.py diff --git a/disjoint_set_union.py b/disjoint_set_union.py new file mode 100644 index 00000000..83f360c0 --- /dev/null +++ b/disjoint_set_union.py @@ -0,0 +1,22 @@ +N = 1000 +P = [i for i in range(0,N+1)] # parent +S = [1 for i in range(0,N+1)] # size of set + +def find(u): + if u == P[u]: + return u + else: + P[u] = find(P[u]) + return P[u] + +def union(u,v): + u = find(u) + v = find(v) + if u != v: + # merge smaller set into bigger set + if S[u] < S[v]: + P[u] = v + S[v] += S[u] + else: + P[v] = u + S[u] += S[v] From d366a4c5a01d9ece42428f40c73904e35060cf48 Mon Sep 17 00:00:00 2001 From: hardikaj96 <42418299+hardikaj96@users.noreply.github.com> Date: Sun, 9 Oct 2022 03:02:27 +0000 Subject: [PATCH 111/129] add reverse number --- reverse_number.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 reverse_number.py diff --git a/reverse_number.py b/reverse_number.py new file mode 100644 index 00000000..b6298ced --- /dev/null +++ b/reverse_number.py @@ -0,0 +1,29 @@ +"""This file has the function which reverses real integer.""" + + +def reverse_number(number: int) -> int: + """ + This function reverses a number where number can be real integer + """ + if number == 0: + return 0 + + sign = 1 if number > 0 else -1 + number = abs(number) + reverse = 0 + while number > 0: + current_digit = number % 10 + reverse = reverse * 10 + current_digit + number //= 10 + return reverse if sign == 1 else reverse * -1 + +N = 567 +print(reverse_number(N)) + + +N = 0 +print(reverse_number(N)) + + +N = -35670 +print(reverse_number(N)) From dec97caffcbd6f7506b09a2e073c0be8a46ba488 Mon Sep 17 00:00:00 2001 From: DEBOBANI <87783113+DEBOBANI@users.noreply.github.com> Date: Sun, 9 Oct 2022 11:32:52 +0530 Subject: [PATCH 112/129] Strong Number Write a program to check if a number is a Strong number or not. --- strong.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 strong.py diff --git a/strong.py b/strong.py new file mode 100644 index 00000000..13cf2dc5 --- /dev/null +++ b/strong.py @@ -0,0 +1,16 @@ +sum1=0 +num=int(input("Enter a number:")) +temp=num +while(num): + i=1 + f=1 + r=num%10 + while(i<=r): + f=f*i + i=i+1 + sum1=sum1+f + num=num//10 +if(sum1==temp): + print("The number is a strong number") +else: + print("The number is not a strong number") From 97f2fbf637efc2b98abc86c4b9a5d16f566c18e5 Mon Sep 17 00:00:00 2001 From: Lakshgupta <58878154+cyborglaksh@users.noreply.github.com> Date: Sun, 9 Oct 2022 15:34:56 +0530 Subject: [PATCH 113/129] Create MaximizeProfitStockProblem.py Solution to the problem buying selling stock to maximize profit. Checking the global & the current profit mechanism to get the results. --- MaximizeProfitStockProblem.py | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 MaximizeProfitStockProblem.py diff --git a/MaximizeProfitStockProblem.py b/MaximizeProfitStockProblem.py new file mode 100644 index 00000000..85726c93 --- /dev/null +++ b/MaximizeProfitStockProblem.py @@ -0,0 +1,40 @@ +# Module to return the maximum profit that can be made after buying and selling the given stocks + +def maxProfit(price, start, end): + + # If the stocks can't be bought + if (end <= start): + return 0 + + # Initialise the profit + profit = 0 + + # The day at which the stock must be bought + for i in range(start, end, 1): + + # The day at which the stock must be sold + for j in range(i+1, end+1): + + # If buying the stock at ith day and selling it at jth day is profitable + if (price[j] > price[i]): + + # Update the current profit + current_profit = price[j] - price[i] +\ + maxProfit(price, start, i - 1) + \ + maxProfit(price, j + 1, end) + + # Update the maximum profit so far + profit = max(profit, current_profit) + + return profit + +# Example Driver Code +if __name__ == '__main__': + price = [100, 180, 260, 310, 40, 535, 695] + n = len(price) + + print(maxProfit(price, 0, n - 1)) + +# Solution: 865 + +# This code is contributed by Laksh Gupta From 75dc72dbb02223fcd44a7dc6e963d47bbdf1bc0f Mon Sep 17 00:00:00 2001 From: Ashwin Date: Sun, 9 Oct 2022 16:32:40 +0530 Subject: [PATCH 114/129] add huffman tree generator --- huffmantree.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 huffmantree.py diff --git a/huffmantree.py b/huffmantree.py new file mode 100644 index 00000000..ccbc6324 --- /dev/null +++ b/huffmantree.py @@ -0,0 +1,25 @@ +Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +from heapq import heapify as hpf +from heapq import heappop as hpp +from heapq import heappush as hppu +class Node: + def __init(self,ch,freq,left=None,right=None): + self.ch,self.freq=ch,freq + self.left,self.right=left,right + def __lt__(self,other): + return self.freq1: + left,right=hpp(pq),hpp(pq); + newFreq=left.freq+right.freq + hppu(pq,Node(None,newFreq,left,right)) + root=pq[0] + return root + From b87203ea3289dda938a3de2e9090f257cc03458b Mon Sep 17 00:00:00 2001 From: Dayita_C Date: Sun, 9 Oct 2022 19:34:41 +0530 Subject: [PATCH 115/129] image_compressor --- image_compress.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 image_compress.py diff --git a/image_compress.py b/image_compress.py new file mode 100644 index 00000000..162e8eb6 --- /dev/null +++ b/image_compress.py @@ -0,0 +1,27 @@ +# For inforation on Pillow visit https://pypi.org/project/Pillow/ +import os, sys +from PIL import Image + +def compressMe(file, verbose = False): + filepath = os.path.join(os.getcwd(), file) + picture = Image.open(filepath) + picture.save("Compressed_"+file, "JPEG", optimize = True, quality = 10) + return + +def main(): + verbose = False + if (len(sys.argv)>1): + if (sys.argv[1].lower()=="-v"): + verbose = True + cwd = os.getcwd() + formats = ('.jpg', '.jpeg') + + for file in os.listdir(cwd): + if os.path.splitext(file)[1].lower() in formats: + print('compressing', file) + compressMe(file, verbose) + print("Done") + +# Driver code +if __name__ == "__main__": + main() \ No newline at end of file From 8eb6ff22ad1e93f4f237b8df4dd540c6dc7362e6 Mon Sep 17 00:00:00 2001 From: codeMehtab <114514297+codeMehtab@users.noreply.github.com> Date: Mon, 10 Oct 2022 11:35:13 +0530 Subject: [PATCH 116/129] fixed typo in variable name --- reverse32bitsignedint.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reverse32bitsignedint.py b/reverse32bitsignedint.py index 8e84df4b..986604c2 100644 --- a/reverse32bitsignedint.py +++ b/reverse32bitsignedint.py @@ -8,9 +8,9 @@ def reverse32bitsignedint(n): ans = 0 while n: quotient = n // 10 - reminder = n % 10 + remainder = n % 10 n = quotient - ans = ans * 10 + reminder + ans = ans * 10 + remainder limit = 1 << 31 if is_negative: ans = -ans From 6b37b7e1a32efe2acdd4c79140e2fa5652aa8cbd Mon Sep 17 00:00:00 2001 From: alwenpy Date: Mon, 10 Oct 2022 12:37:38 +0530 Subject: [PATCH 117/129] added a dice roller program in python --- dice.py | 146 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 dice.py diff --git a/dice.py b/dice.py new file mode 100644 index 00000000..2198ce88 --- /dev/null +++ b/dice.py @@ -0,0 +1,146 @@ +"""Simulate a six-sided dice roll. + +Usage: + + $ python dice.py + How many dice do you want to roll? [1-6] 5 + +~~~~~~~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~~~~~~~ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ +│ ● │ │ │ │ ● │ │ ● │ │ ● │ +│ ● ● │ │ ● │ │ ● ● │ │ ● ● │ │ │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ +""" + +import random + +DICE_ART = { + 1: ( + "┌─────────┐", + "│ │", + "│ ● │", + "│ │", + "└─────────┘", + ), + 2: ( + "┌─────────┐", + "│ ● │", + "│ │", + "│ ● │", + "└─────────┘", + ), + 3: ( + "┌─────────┐", + "│ ● │", + "│ ● │", + "│ ● │", + "└─────────┘", + ), + 4: ( + "┌─────────┐", + "│ ● ● │", + "│ │", + "│ ● ● │", + "└─────────┘", + ), + 5: ( + "┌─────────┐", + "│ ● ● │", + "│ ● │", + "│ ● ● │", + "└─────────┘", + ), + 6: ( + "┌─────────┐", + "│ ● ● │", + "│ ● ● │", + "│ ● ● │", + "└─────────┘", + ), +} +DIE_HEIGHT = len(DICE_ART[1]) +DIE_WIDTH = len(DICE_ART[1][0]) +DIE_FACE_SEPARATOR = " " + + +def parse_input(input_string): + """Return `input_string` as an integer between 1 and 6. + + Check if `input_string` is an integer number between 1 and 6. + If so, return an integer with the same value. Otherwise, tell + the user to enter a valid number and quit the program. + """ + if input_string.strip() in {"1", "2", "3", "4", "5", "6"}: + return int(input_string) + else: + print("Please enter a number from 1 to 6.") + raise SystemExit(1) + + +def roll_dice(num_dice): + """Return a list of integers with length `num_dice`. + + Each integer in the returned list is a random number between + 1 and 6, inclusive. + """ + roll_results = [] + for _ in range(num_dice): + roll = random.randint(1, 6) + roll_results.append(roll) + return roll_results + + +def generate_dice_faces_diagram(dice_values): + """Return an ASCII diagram of dice faces from `dice_values`. + + The string returned contains an ASCII representation of each die. + For example, if `dice_values = [4, 1, 3, 2]` then the string + returned looks like this: + + ~~~~~~~~~~~~~~~~~~~ RESULTS ~~~~~~~~~~~~~~~~~~~ + ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ + │ ● ● │ │ │ │ ● │ │ ● │ + │ │ │ ● │ │ ● │ │ │ + │ ● ● │ │ │ │ ● │ │ ● │ + └─────────┘ └─────────┘ └─────────┘ └─────────┘ + """ + dice_faces = _get_dice_faces(dice_values) + dice_faces_rows = _generate_dice_faces_rows(dice_faces) + + # Generate header with the word "RESULTS" centered + width = len(dice_faces_rows[0]) + diagram_header = " RESULTS ".center(width, "~") + + dice_faces_diagram = "\n".join([diagram_header] + dice_faces_rows) + return dice_faces_diagram + + +def _get_dice_faces(dice_values): + dice_faces = [] + for value in dice_values: + dice_faces.append(DICE_ART[value]) + return dice_faces + + +def _generate_dice_faces_rows(dice_faces): + dice_faces_rows = [] + for row_idx in range(DIE_HEIGHT): + row_components = [] + for die in dice_faces: + row_components.append(die[row_idx]) + row_string = DIE_FACE_SEPARATOR.join(row_components) + dice_faces_rows.append(row_string) + return dice_faces_rows + + +# ~~~ App's main code block ~~~ +# 1. Get and validate user's input +num_dice_input = input("How many dice do you want to roll? [1-6] ") +num_dice = parse_input(num_dice_input) +# 2. Roll the dice +roll_results = roll_dice(num_dice) +# 3. Generate the ASCII diagram of dice faces +dice_face_diagram = generate_dice_faces_diagram(roll_results) +# 4. Display the diagram +print(f"\n{dice_face_diagram}") From 4aeba3c561ed693caf6abef7ab3f66569058799c Mon Sep 17 00:00:00 2001 From: akash18sahoo <99233511+akash18sahoo@users.noreply.github.com> Date: Mon, 10 Oct 2022 20:51:23 +0530 Subject: [PATCH 118/129] Average.py I have added a python program to calculate average of n numbers inserted by user. Average code file was not there in reposatory so I created one. Kindly have a look and add hacktober fest tag to it. --- Average.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Average.py diff --git a/Average.py b/Average.py new file mode 100644 index 00000000..da6f0da3 --- /dev/null +++ b/Average.py @@ -0,0 +1,7 @@ +n=int(input("Enter the number of elements to be inserted: ")) +a=[] +for i in range(0,n): + elem=int(input("Enter element: ")) + a.append(elem) +avg=sum(a)/n +print("Average of elements in the list",round(avg,2)) From 17a8cbee9d6ceaa45738f8691831f5f4959b922e Mon Sep 17 00:00:00 2001 From: DamyanBG Date: Mon, 10 Oct 2022 19:10:35 +0300 Subject: [PATCH 119/129] simple get coordinates program --- get_coordinates.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 get_coordinates.py diff --git a/get_coordinates.py b/get_coordinates.py new file mode 100644 index 00000000..33e634ff --- /dev/null +++ b/get_coordinates.py @@ -0,0 +1,10 @@ +from geopy.geocoders import Nominatim + +your_address = str(input()) + +geolocator = Nominatim(user_agent="basic_app") +location = geolocator.geocode(your_address) +if location: + print((location.latitude, location.longitude)) +else: + print("Can not find your address!") \ No newline at end of file From da10b5201e146849f39b490cbd8b40700cab3310 Mon Sep 17 00:00:00 2001 From: Priyanka Daryani <11776756+priyankadaryani@users.noreply.github.com> Date: Mon, 10 Oct 2022 12:43:05 -0400 Subject: [PATCH 120/129] Add a program to count the number of vowels in a text file. --- Count_Number_of_Vowels_in_a_File.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Count_Number_of_Vowels_in_a_File.py diff --git a/Count_Number_of_Vowels_in_a_File.py b/Count_Number_of_Vowels_in_a_File.py new file mode 100644 index 00000000..8fb6e6ad --- /dev/null +++ b/Count_Number_of_Vowels_in_a_File.py @@ -0,0 +1,26 @@ +######## This program counts and returns the number of vowels in a text file. ######## + +# Ask the user for the name of the file. The file should be in the same folder and should be a text file. +print("Enter the Name of File: ") + +# Convert the name to string and open the file in read mode +fileName = str(input()) +fileHandle = open(fileName, "r") + +# Declare a variable to store the number of vowels. Initally it is zero. +count = 0 + +# create an array of all the vowels (upper and lower case) that can be used to compare and determine if a character is a vowel +vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] + +# Read each character and compare it to the characters in the array. If found in the vowels array, then increase count. +for char in fileHandle.read(): + if char in vowels: + count = count+1 + +# Close the file +fileHandle.close() + +# Print the count to the screen for the user to see. +print("\nThe total number of vowels in the text are:") +print(count) From 4ee4f39d515830c380edc46d3889a0816a780ecd Mon Sep 17 00:00:00 2001 From: Musketeer Computing Date: Mon, 10 Oct 2022 17:47:07 +0100 Subject: [PATCH 121/129] Adding masking email address script --- mask_email_address.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 mask_email_address.py diff --git a/mask_email_address.py b/mask_email_address.py new file mode 100644 index 00000000..5cdbd8ea --- /dev/null +++ b/mask_email_address.py @@ -0,0 +1,42 @@ +""" Mask an email address +Search for email addresses in a string, extract the email addresses, mask them and re-insert them in the string. + +Author: Musketeer Computing +Created: 10th October 2022 +""" +import re + + +def main(): + sentence = input("Enter a sentence") + emails = re.findall(r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', sentence) + if not emails: + print(' No email address to mask') + exit() + d_emails = {} + for email in emails: + m_email = mask_email(email) + if m_email == 'error': + print('There was an error when masking the email. Stopping the program') + exit() + d_emails[email] = m_email + for k_email, v_email in d_emails.items(): + sentence = re.sub(k_email, v_email, sentence) + print(sentence) + + +def mask_email(email): + lo = email.find('@') + domain_extension = email.rfind('.') + word_count = len(email) + if lo > 0: + return "{0}#####{1}@{2}###{3}".format(email[0], + email[lo-1], + email[lo+1], + email[domain_extension:word_count]) + else: + return "error" + + +if __name__ == "__main__": + main() From 02b9891f6d9748f00d2c860f04fff043a7cc6d31 Mon Sep 17 00:00:00 2001 From: Prit Kalariya <71484962+PritKalariya@users.noreply.github.com> Date: Tue, 11 Oct 2022 00:50:07 +0530 Subject: [PATCH 122/129] Implemented an ATM machine logic using python. --- ATM.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 ATM.py diff --git a/ATM.py b/ATM.py new file mode 100644 index 00000000..da2c64ab --- /dev/null +++ b/ATM.py @@ -0,0 +1,82 @@ +#ATM Machine Using python + +print("="*30, "Welcome to Python Bank ATM", "="*30) + +restart = ("Y") +chances = 3 +balance = 999.99 + +while chances >= 0: + pin = int(input("\nPlease enter your 4 Digit pin: ")) + if pin == (1234): + print("\nCorrect pin!!") + + while restart not in ("n", "no", "N", "NO"): + print("\nPlease Press 1 For Your Balance.") + print("Please Press 2 To Make a Withdrawl.") + print("Please Press 3 To Pay in.") + print("Please Press 4 To Return Card.") + + option = int(input("\nWhat Would you like to Choose?: ")) + + if option == 1: + print(f"\nYour Balance is: ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif option == 2: + option2 = ("y") + withdrawl = float(input("\nHow Much Would you like to withdraw? 10, 20, 40, 60, 80, 100 for other enter 1: ")) + + if withdrawl in [10, 20, 40, 60, 80, 100]: + balance = balance - withdrawl + print(f"\nYour balance after the withdrawl is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif withdrawl == 1: + withdrawl = float(input("\nPlease Enter Desired amount: ")) + balance = balance - withdrawl + print(f"\nYour balance after the withdrawl is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif withdrawl != [10, 20, 40, 60, 80, 100]: + print("\nINVALID AMOUNT, Please try Again\n") + restart = ("y") + + elif option == 3: + pay_in = float(input("\nHow Much Would you like to Pay In? ")) + balance = balance + pay_in + print(f"\nYour balance after the Pay-in is ${balance}") + restart = input("\nWould You like to do something else? ") + + if restart in ("n", "no", "N", "NO"): + print("\nThank You\n") + break + + elif option == 4: + print("\nPlease wait whilst your card is Returned....") + print("\nThank you for your service") + break + + else: + print("\nPlease enter a correct number.\n") + restart = ("y") + + elif pin != (1234): + print("\nINCORRECT PIN!!\n") + chances = chances - 1 + + if chances == 0: + print("Calling the Police...\n") + break \ No newline at end of file From 26a5d70b332bdd53e000d2eaf16f6bafebd89e0e Mon Sep 17 00:00:00 2001 From: Shivam-Yogi Date: Wed, 19 Oct 2022 08:23:56 +0530 Subject: [PATCH 123/129] Added queue using LL --- Queue.py | 24 ++++++++++++++++++++++++ Queue_using_LL.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 Queue.py create mode 100644 Queue_using_LL.py diff --git a/Queue.py b/Queue.py new file mode 100644 index 00000000..a1397f65 --- /dev/null +++ b/Queue.py @@ -0,0 +1,24 @@ +class Queue: + arr = [] + def enqueue(self,item): + self.arr.append(item) + + def dequeue(self): + if len(self.arr) > 0: + ditem = self.arr[0] + del self.arr[0] + return ditem + else: + return #queue is empty + + def dispaly(self): + print(self.arr) + +x = Queue() # Creating object of queue class +x.enqueue(1) +x.enqueue(2) +x.dispaly() # arr = [1,2] +x.dequeue() # Deleting the first element of the queue. +x.dispaly() # arr = [2] +print(x.dequeue()) # 2 +print(x.dequeue()) # None(because queue is already empty) \ No newline at end of file diff --git a/Queue_using_LL.py b/Queue_using_LL.py new file mode 100644 index 00000000..0bfa00b7 --- /dev/null +++ b/Queue_using_LL.py @@ -0,0 +1,39 @@ +class Node: + def __init__(self, data = None): + self.data = data + self.next = None + +class Queue: + def __init__(self): + self.head = None + self.last = None + + def enqueue(self, data): + if not self.last: + self.head = Node(data) + self.last = self.head + else: + self.last.next = Node(data) + self.last = self.last.next + + def dequeue(self): + if not self.head: + return None + val = self.head.data + self.head = self.head.next + return val + + def display(self): + temp = self.head + while temp != None: + print(temp.data) + temp = temp.next + +x = Queue() # Creating object of queue class +x.enqueue(1) # Add 1 to the queue +x.enqueue(2)# Add 2 to the queue +x.display() # 1 => 2 +print(x.dequeue()) # Deleting the first element of the queue. +x.display() # 2 +print(x.dequeue()) # 2 +print(x.dequeue()) # None(because queue is already empty) \ No newline at end of file From 9abfd8c217ddb7ce4bde93bc6b01c6e028f08371 Mon Sep 17 00:00:00 2001 From: Shivam-Yogi Date: Wed, 19 Oct 2022 08:24:39 +0530 Subject: [PATCH 124/129] Added Radix sort --- Radix_sort.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Radix_sort.py diff --git a/Radix_sort.py b/Radix_sort.py new file mode 100644 index 00000000..0c6f84fe --- /dev/null +++ b/Radix_sort.py @@ -0,0 +1,43 @@ +# Radix sort in Python +# Using counting sort to sort the elements in the basis of significant places +def countingSort(array, place): + size = len(array) + output = [0] * size + count = [0] * 10 + + # Calculate count of elements + for i in range(0, size): + index = array[i] // place + count[index % 10] += 1 + + # Calculate cumulative count + for i in range(1, 10): + count[i] += count[i - 1] + + # Place the elements in sorted order + i = size - 1 + while i >= 0: + index = array[i] // place + output[count[index % 10] - 1] = array[i] + count[index % 10] -= 1 + i -= 1 + + for i in range(0, size): + array[i] = output[i] + + +# Main function to implement radix sort +def radixSort(array): + # Get maximum element + max_element = max(array) + + # Apply counting sort to sort elements based on place value. + place = 1 + while max_element // place > 0: + countingSort(array, place) + place *= 10 + + +data = [121, 432, 564, 23, 1, 45, 788] +radixSort(data) +print(data) \ No newline at end of file From b6e473db3996794f7130ab0c76beba958ad6a7b9 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Fri, 21 Oct 2022 17:13:38 +0530 Subject: [PATCH 125/129] Revert "Improved existing calculator" --- calculator.py | 85 ++++++++++++++++++++++----------------------------- 1 file changed, 37 insertions(+), 48 deletions(-) diff --git a/calculator.py b/calculator.py index 88bcdb35..6f0f018c 100644 --- a/calculator.py +++ b/calculator.py @@ -1,70 +1,59 @@ -while True: - # definition for operators - - #addition - def add(num1, num2): - return num1+num2 - - #substraction - def subtract(num1, num2): - return num1-num2 - - #multiplication - def multiply(num1, num2): - return num1*num2 - - #division - def divide(num1, num2): - try: - return num1/num2 - except ZeroDivisionError: - print ("WARNING: Invalid division, cannot divide by zero") - - #exponent - def exponent(num1, num2): - return num1**num2 - - while True: - try: - num1=float(input("Enter a digit: ")) - num2=float(input("Enter another digit: ")) - break - except ValueError: - print("The input was not a valid digit") +num1=int(input("eneter a digit")) +num2=int(input("eneter a another digit")) +# defination for operators + +#addition +def add(num1, num2): + return num1+num2 +#substraction +def subtract(num1, num2): + return num1-num2 +#multiply +def multiply(num1, num2): + return num1*num2 +#division +def divide(num1, num2): + return num1/num2 + +#command for operation +print("choose operation") +print("press 1 for add") +print("press 2 for subs") +print("press 3 for multiply") +print("press 4 for devision") - #command for operation - print("Choose an operation") - print("Press 1 for addition") - print("Press 2 for substraction") - print("Press 3 for multiplication") - print("Press 4 for division") - print("Press 5 for exponent") + + + +while True: # take input from the user - choice = input("Enter choice(1/2/3/4/5): ") + choice = input("Enter choice(1/2/3/4): ") - if choice in ('1', '2', '3', '4', '5'): + if choice in ('1', '2', '3', '4'): if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) + + elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) + + + + elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) - - elif choice == '5': - print(num1, "to the power of", num2, "=", exponent(num1, num2)) - # check if user wants another calculation # break the while loop if answer is no - next_calculation = input("Do you want to do another calculation? (yes/no): ") + next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: - print("Invalid input") + print("Invalid Input") From 53f57f7cb7c93e0005407ab7024b18d4363281f7 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Fri, 21 Oct 2022 17:16:27 +0530 Subject: [PATCH 126/129] Delete TicTacToe.py --- TicTacToe.py | 104 --------------------------------------------------- 1 file changed, 104 deletions(-) delete mode 100644 TicTacToe.py diff --git a/TicTacToe.py b/TicTacToe.py deleted file mode 100644 index e74c53bf..00000000 --- a/TicTacToe.py +++ /dev/null @@ -1,104 +0,0 @@ -import math -import time -from Player import SmartComputer, RandomComputer, Human - - -class TicTacToe(): - def __init__(self): - self.board = self.create_board() - self.actual_winner = None - - @staticmethod - def create_board(): - return [' ' for _ in range(9)] - - def board_show(self): - for cell in [self.board[i*3:(i+1)*3] for i in range(3)]: - print('| ' + ' | '.join(cell) + ' |') - - @staticmethod - def show_board_numbers(): - number_from_board = [[str(i + 1) for i in range(j*3, (j+1)*3)] for j in range(3)] - for cell in number_from_board: - print('| ' + ' | '.join(cell) + ' |') - - def make_a_move(self, square, player): - if self.board[square] == ' ': - self.board[square] = player - if self.winner_rules(square, player): - self.actual_winner = player - return True - return False - - def winner_rules(self, square, player): - # Checking the row - row_index = math.floor(square / 3) - row = self.board[row_index*3:(row_index+1)*3] - if all([l == player for l in row]): - return True - - # Checking the column - col_index = square % 3 - column = [self.board[col_index+i*3] for i in range(3)] - if all([l == player for l in column]): - return True - - # Checking for diagonal - if square % 2 == 0: - principal_diagonal = [self.board[i] for i in [0, 4, 8]] - if all([l == player for l in principal_diagonal]): - return True - - secondary_diagonal = [self.board[i] for i in [2, 4, 6]] - if all([l == player for l in secondary_diagonal]): - return True - - return False - - def null_squares(self): - return ' ' in self.board - - def number_null_squares(self): - return self.board.count(' ') - - def remaining_moves(self): - return [p for p, i in enumerate(self.board) if i == ' '] - - -def play(game, x_player, o_player, show_game = True): - if show_game: - game.show_board_numbers() - - player = 'X' - while game.null_squares(): - if player == '0': - square = o_player.get_move(game) - else: - square = x_player.get_move(game) - if game.make_a_move(square, player): - if show_game: - print(f'{player} makes a move to square {square}') - game.board_show() - print(' ') - - if game.actual_winner: - if show_game: - print(f'{player} wins!') - return player - player = '0' if player == 'X' else 'X' - - time.sleep(.8) - - if show_game: - print('Tie!') - - -if __name__ == '__main__': - #x_player = RandomComputer('0') - x_player = SmartComputer('0') - o_player = Human('X') - t = TicTacToe() - play(t, o_player, x_player, True) - - - From b110f5713b921907035e31f7ce994f4918731661 Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Fri, 21 Oct 2022 17:17:09 +0530 Subject: [PATCH 127/129] Delete password_generator.py --- password_generator.py | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 password_generator.py diff --git a/password_generator.py b/password_generator.py deleted file mode 100644 index b69fc98f..00000000 --- a/password_generator.py +++ /dev/null @@ -1,27 +0,0 @@ -import random -special = ["!","@","#","$","%","^","&","*"] -alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] -num = [1,2,3,4,5,6,7,8,9,0] -print("Enter length of password:") -length = int(input()) -print("Enter no of special characters:") -spec = int(input()) -rem_char = length-spec -num_num = rem_char//3 -num_alpha = rem_char-num_num -L=[] -alpha_list = random.sample(alpha,num_alpha) -num_list = random.sample(num,num_num) -spec_list = random.sample(special,spec) -for i in alpha_list: - L.append(i) -for i in num_list: - L.append(i) -for i in spec_list: - L.append(i) -random.shuffle(L) -password="" -for i in L: - password +=str(i) -print("your password is :",password) - From e446143ea52de53d325029a1c58ad47b030a986a Mon Sep 17 00:00:00 2001 From: Saurav Jain Date: Fri, 21 Oct 2022 17:18:49 +0530 Subject: [PATCH 128/129] Delete Sum_of_Digits.py --- Sum_of_Digits.py | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 Sum_of_Digits.py diff --git a/Sum_of_Digits.py b/Sum_of_Digits.py deleted file mode 100644 index 95e3c940..00000000 --- a/Sum_of_Digits.py +++ /dev/null @@ -1,11 +0,0 @@ -# Program for sum of digits - -def sumOfDigits(n): - if n == 0: # base case - return 0 # if n== 0 than return 0 - # return last digit + sum of digit of remaining number - return (n % 10 + sumOfDigits(int(n/10))) - - -n = int(input("Enter the number: ")) # taking input from user -sumOfDigits(n) # calling the function From 0f19710f1130d7fab0d2fc0835961cf50f49379a Mon Sep 17 00:00:00 2001 From: Pranita Dane Date: Sat, 12 Aug 2023 10:43:05 +0530 Subject: [PATCH 129/129] SpeedTypingTestInPython.py --- SpeedTypingTestInPython.py | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 SpeedTypingTestInPython.py diff --git a/SpeedTypingTestInPython.py b/SpeedTypingTestInPython.py new file mode 100644 index 00000000..aeb03db5 --- /dev/null +++ b/SpeedTypingTestInPython.py @@ -0,0 +1,61 @@ +### Speed Typing Test in python ### + +# Imported Library + +import time +import threading + +# Created Class + +class tester: + def __init__(self, paragraph): + self.correctWords = [] + self.incorrectWords = {} + self.typedWords = [] + self.totalWords = [] + self.input = None + self.paragraph = paragraph + self.accuracy = 0 + self.time = 0 + self.wordPermin = 0 + self.run() + +#### Defined the Variable ### + + def clock(self): + while len(self.typedWords) == 0: + self.time += 1 + time.sleep(1) + + def run(self): + threading.Thread(target=self.clock).start() + threading.Thread(target=self.testSpeed).start() + + def testSpeed(self): + print('\n\n'+self.paragraph+'\n\n') + self.input = str(input('\t\n'+'Type The Word Which You Want To Know the Speed As well as Incorrect \n\n')) + self.totalWords = self.paragraph.split(' ') + self.typedWords = self.input.split(' ') + + try: + for i in range(len(self.typedWords)): + if(self.typedWords[i] == self.totalWords[i]): + self.correctWords.append(self.typedWords[i]) + else: + self.incorrectWords.update({self.totalWords[i] : self.typedWords[i]}) + + except Exception as e: + print(e) + + + self.accuracy = len(self.correctWords)/len(self.typedWords) * 100 + self.wordPerMin = len(self.typedWords) / (self.time/60) + + print('\n\nResult :--') + print(f'Accuracy: -- {self.accuracy}') + print(f'Word Per Minute :-- {self.wordPerMin}') + print(f'Incorrect Words :-- {self.incorrectWords}') + +Mytester = tester("You know you're a programmer when you spend a day to find the problem, and then fix it with one line of code.") + +### The Code is ended, Thank You #### \ No newline at end of file