From 6e76175bd820fb9e3d59a6d191e759dbbb1f708d Mon Sep 17 00:00:00 2001 From: Vini Antunes Date: Wed, 5 Oct 2022 11:15:56 -0300 Subject: [PATCH 01/40] 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 02/40] 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 03/40] 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 04/40] 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 05/40] 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 06/40] 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 07/40] 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 08/40] 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 09/40] 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 10/40] 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 11/40] 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 12/40] 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 13/40] 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 14/40] 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 15/40] 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 16/40] 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 17/40] 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 18/40] 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 19/40] 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 20/40] 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 21/40] 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 22/40] 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 23/40] 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 24/40] 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 25/40] 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 26/40] 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 27/40] 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 28/40] 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 29/40] 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 30/40] 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 31/40] 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 32/40] 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 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 33/40] 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 34/40] 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 35/40] 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 36/40] 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 37/40] 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 38/40] 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 39/40] 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 0f19710f1130d7fab0d2fc0835961cf50f49379a Mon Sep 17 00:00:00 2001 From: Pranita Dane Date: Sat, 12 Aug 2023 10:43:05 +0530 Subject: [PATCH 40/40] 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