diff --git a/.github/ISSUE_TEMPLATE/create-an-issue.md b/.github/ISSUE_TEMPLATE/create-an-issue.md new file mode 100644 index 0000000..22b0276 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/create-an-issue.md @@ -0,0 +1,25 @@ +--- +name: Create an Issue +about: For creating isssue for HacktoberFest +title: '' +labels: Hacktoberfest +assignees: '' + +--- + +**Title** - + +**what will change** - + +**Assignees** - + +### Type of Issue +Please add/delete options that are not relevant. +- [x] Improving Code +- [x] Improving Documentation +- [x] Adding New Code + +### Programming Language +Please add/delete options that are not relevant. +- [x] Python +- [x] C++ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..05003b2 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "C:\\Users\\VISWANADH\\miniconda3\\python.exe" +} \ No newline at end of file diff --git a/Python/Base Convertor Number System.py b/Python/Base Convertor Number System.py new file mode 100644 index 0000000..b4c8baf --- /dev/null +++ b/Python/Base Convertor Number System.py @@ -0,0 +1,73 @@ +def base_check(xnumber, xbase): + for char in xnumber[len(xnumber ) -1]: + if int(char) >= int(xbase): + return False + return True + +def convert_from_10(xnumber, xbase, arr, ybase): + if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8: + + if xnumber == 0: + return arr + else: + quotient = int(xnumber) // int(xbase) + remainder = int(xnumber) % int(xbase) + arr.append(remainder) + dividend = quotient + convert_from_10(dividend, xbase, arr, base) + elif int(xbase) == 16: + if int(xnumber) == 0: + return arr + else: + quotient = int(xnumber) // int(xbase) + remainder = int(xnumber) % int(xbase) + if remainder > 9: + if remainder == 10: remainder = 'A' + if remainder == 11: remainder = 'B' + if remainder == 12: remainder = 'C' + if remainder == 13: remainder = 'D' + if remainder == 14: remainder = 'E' + if remainder == 15: remainder = 'F' + arr.append(remainder) + dividend = quotient + convert_from_10(dividend, xbase, arr, ybase) +def convert_to_10(xnumber, xbase, arr, ybase): + if int(xbase) == 10: + for char in xnumber: + arr.append(char) + flipped = arr[::-1] + ans = 0 + j = 0 + + for i in flipped: + ans = ans + (int(i) * (int(ybase) ** j)) + j = j + 1 + return ans +arrayfrom = [] +arrayto = [] +is_base_possible = False +number = input("Enter the number you would like to convert: ") + +while not is_base_possible: + base = input("What is the base of this number? ") + is_base_possible = base_check(number, base) + if not is_base_possible: + print(f"The number {number} is not a base {base} number") + base = input + else: + break +dBase = input("What is the base you would like to convert to? ") +if int(base) == 10: + convert_from_10(number, dBase, arrayfrom, base) + answer = arrayfrom[::-1] # reverses the array + print(f"In base {dBase} this number is: ") + print(*answer, sep='') +elif int(dBase) == 10: + answer = convert_to_10(number, dBase, arrayto, base) + print(f"In base {dBase} this number is: {answer} ") +else: + number = convert_to_10(number, 10, arrayto, base) + convert_from_10(number, dBase, arrayfrom, base) + answer = arrayfrom[::-1] + print(f"In base {dBase} this number is: ") + print(*answer, sep='') \ No newline at end of file diff --git a/Python/BasicCalculator.py b/Python/BasicCalculator.py index 819204d..c85ac9a 100644 --- a/Python/BasicCalculator.py +++ b/Python/BasicCalculator.py @@ -11,6 +11,9 @@ def mul(num1, num2): return num1 * num2 def div(num1, num2): + if num2 == 0: + print("Can't divide a number by 0") + exit() return num1 / num2 print("Please Select Operations\n "\ @@ -23,7 +26,7 @@ def div(num1, num2): select = input("Press\n" "1 " "2 " "3 " "4 \n") number_1 = int(input("Type Your First Number :")) -number_2 = int(input("Type YOur Second Number :")) +number_2 = int(input("Type Your Second Number :")) if select == '1': @@ -45,4 +48,4 @@ def div(num1, num2): else: print('Invalid Input ! Try aagian ') -print('Thanks for Using Calculator') \ No newline at end of file +print('Thanks for Using Calculator') diff --git a/Python/Binary_Tree_algo.py b/Python/Binary_Tree_algo.py new file mode 100644 index 0000000..95c26ea --- /dev/null +++ b/Python/Binary_Tree_algo.py @@ -0,0 +1,55 @@ +class Node: + + def __init__(self, data): + + self.left = None + self.right = None + self.data = data + + + def PrintTree(self): + print(self.data) + +root = Node(10) + +root.PrintTree() + +class Node: + + def __init__(self, data): + + self.left = None + self.right = None + self.data = data + + def insert(self, data): +# Compare the new value with the parent node + if self.data: + if data < self.data: + if self.left is None: + self.left = Node(data) + else: + self.left.insert(data) + elif data > self.data: + if self.right is None: + self.right = Node(data) + else: + self.right.insert(data) + else: + self.data = data + +# Print the tree + def PrintTree(self): + if self.left: + self.left.PrintTree() + print( self.data), + if self.right: + self.right.PrintTree() + +# Use the insert method to add nodes +root = Node(12) +root.insert(6) +root.insert(14) +root.insert(3) + +root.PrintTree() diff --git a/Python/BinarytreeClassbased.py b/Python/BinarytreeClassbased.py new file mode 100644 index 0000000..29eb8e8 --- /dev/null +++ b/Python/BinarytreeClassbased.py @@ -0,0 +1,24 @@ +def binarytree(r): + return[r,[],[]] +def insertleft(root,newbranch): + t=root.pop(1) + if len(t)>1: + root.insert(1,[newbranch,t,[]]) + else: + root.insert(1,[newbranch,[],[]]) + return root +def insertright(root,newbranch): + t=root.pop(2) + if len(t)>1: + root.insert(2,[newbranch,[],t]) + else: + root.insert(2,[newbranch,[],[]]) + return root +def getroot(root,new): + root[0]=new +def setnew(root): + return root[0] +def getleft(root): + return root[1] +def getright(root): + return root[2] diff --git a/Python/BlackJack_Game.py b/Python/BlackJack_Game.py new file mode 100644 index 0000000..fd6e71c --- /dev/null +++ b/Python/BlackJack_Game.py @@ -0,0 +1,143 @@ +import random as rn +deck = [2,3,4,5,6,7,8,9,10,'J','Q','K','A'] +suit = ['spade' , 'heart' , 'diamond' , 'club'] +arr = [] +pl = [] +dl = [] + +# Check Blackjack__________________________________________ +def BlackJack(s): + if s==21: + return True + else: + return False + +# Check Bust_______________________________________________ +def Bust(s): + if s>21: + return True + else: + return False + +# Check Ace is 1 or 11_____________________________________ +def check_For_Ace(s): + if (s+11)<=21: + return 11 + else: + return 1 + +# Adjust the sum___________________________________________ +def check_sum(s): + if s < 21: + return s + + for i in range(len(pl)-1,-1,-1): + if pl[i] == 'A': + s -= 10 + break + return s + +# creating a well shuffled pack of cards___________________ +def startGame(): + print("Welcome to the BlackJack Game:\n") + for i in suit: + for j in deck: + arr.append([i,j]) + rn.shuffle(arr) + + pl.append(arr[0]) + pl.append(arr[1]) + dl.append(arr[2]) + dl.append(arr[3]) + + print(f'\nDealer draws {dl[0]} and [xxxxxx,xx]\n') + s = 0 + for i in range(0,2): + if arr[i][1] == 'J' or arr[i][1] == 'K' or arr[i][1] == 'Q': + s += 10 + elif arr[i][1] == 'A': + s += check_For_Ace(s) + else: + s += arr[i][1] + return s + +# player's chance__________________________________________ +def playersTurn(s): + print("You are currently at " + str(s)) + print(f'Current Hand: {pl}') + + s = check_sum(s) + + if (BlackJack(s)): + print("Hurray......It's a BLACKJACK....You Won\n") + return 2 + elif (Bust(s)): + print("You got Bust.....You Lost\n") + return 3 + + while(1): + i = int(input("\nHit(Press 1) or Stay(Press 0): ")) + if i==1 or i==0: + return i + else: + print("Enter a valid number....\n") + +if __name__ == '__main__': + s = startGame() + c = j = 0 + for i in range(4,len(arr)): + + j = playersTurn(s) + if j == 2 or j == 3: + j = i + break + elif j == 0: + j = i + c = 100 + break + print(f'You draw {arr[i]}\n') + + if arr[i][1] == 'J' or arr[i][1] == 'K' or arr[i][1] == 'Q': + c = 10 + elif arr[i][1] == 'A': + c = check_For_Ace(s) + else: + c = arr[i][1] + s += c + pl.append(arr[i]) + + if c == 100: + sp = s + s = 0 + for i in range(2,4): + if arr[i][1] == 'J' or arr[i][1] == 'K' or arr[i][1] == 'Q': + s += 10 + elif arr[i][1] == 'A': + s += check_For_Ace(s) + else: + s += arr[i][1] + print(f"\nDealer's second card was {dl[1]}") + + for i in range(j,len(arr)): + print(f"\nDealer is at {s}") + print(f"\nDealer's current hand: {dl}\n") + + s = check_sum(s) + if (BlackJack(s)): + print("Dealer got a BlackJack and won the Game\nYou Lost\n") + break + elif (Bust(s)): + print("Dealer got Busted\nYou Won\n") + break + elif (sp < s): + print("Dealer Won the Game\n") + break + + print(f"Dealer draws {arr[i]}") + dl.append(arr[i]) + if arr[i][1] == 'J' or arr[i][1] == 'K' or arr[i][1] == 'Q': + s += 10 + elif arr[i][1] == 'A': + s += check_For_Ace(s) + else: + s += arr[i][1] diff --git a/Python/Bubble-Sort-algo.py b/Python/Bubble-Sort-algo.py index 473dc33..322b04b 100644 --- a/Python/Bubble-Sort-algo.py +++ b/Python/Bubble-Sort-algo.py @@ -18,9 +18,16 @@ def bubbleSort(arr): # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] - +#for dynamic list input +'''n=int(input('total elements of list')) +arr=[] +while (n>=1): + i=int(input('enter element')) + arr.append(i) + return (arr) +''' bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): - print ("%d" %arr[i]), + print (arr[i]), diff --git a/Python/Check for URL in a String b/Python/Check for URL in a String new file mode 100644 index 0000000..c704f68 --- /dev/null +++ b/Python/Check for URL in a String @@ -0,0 +1,15 @@ +# Python code to find the URL from an input string +# Using the regular expression +import re + +def Find(string): + + # findall() has been used + # with valid conditions for urls in string + regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" + url = re.findall(regex,string) + return [x[0] for x in url] + +# Driver Code +string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/' +print("Urls: ", Find(string)) diff --git a/Python/Extract Unique values dictionary values b/Python/Extract Unique values dictionary values new file mode 100644 index 0000000..81b412a --- /dev/null +++ b/Python/Extract Unique values dictionary values @@ -0,0 +1,19 @@ +# Python3 code to demonstrate working of +# Extract Unique values dictionary values +# Using set comprehension + values() + sorted() + +# initializing dictionary +test_dict = {'gfg' : [5, 6, 7, 8], + 'is' : [10, 11, 7, 5], + 'best' : [6, 12, 10, 8], + 'for' : [1, 2, 5]} + +# printing original dictionary +print("The original dictionary is : " + str(test_dict)) + +# Extract Unique values dictionary values +# Using set comprehension + values() + sorted() +res = list(sorted({ele for val in test_dict.values() for ele in val})) + +# printing result +print("The unique values list is : " + str(res)) diff --git a/Python/FriendshipCalculator.py b/Python/FriendshipCalculator.py new file mode 100644 index 0000000..cb9cbf8 --- /dev/null +++ b/Python/FriendshipCalculator.py @@ -0,0 +1,18 @@ +#python code to find the friendship value between two friends just for fun +alphabet = 'bcghjklmpqtvwxyz' +score = 0 +name = input("Enter first name and second name with space in between:-") +for character in name: + if character in 'aeiou': + score+=5 + if character in 'friends': + score+=10 + if character in alphabet: + score+=alphabet.find(character) + else: + score+=0 +if score>100: + print('Your friendship score is :', score) + print('Congratulations! you both are best friends') +else: + print('Your friendship score is', score) diff --git a/Python/KMPstringmatchalgorithm.py b/Python/KMPstringmatchalgorithm.py new file mode 100644 index 0000000..3726bb4 --- /dev/null +++ b/Python/KMPstringmatchalgorithm.py @@ -0,0 +1,60 @@ +# Python program for KMP Algorithm +def KMPSearch(pat, txt): + M = len(pat) + N = len(txt) + + # create lps[] that will hold the longest prefix suffix + # values for pattern + lps = [0]*M + j = 0 # index for pat[] + + # Preprocess the pattern (calculate lps[] array) + computeLPSArray(pat, M, lps) + + i = 0 # index for txt[] + while i < N: + if pat[j] == txt[i]: + i += 1 + j += 1 + + if j == M: + print ("Found pattern at index " + str(i-j)) + j = lps[j-1] + + # mismatch after j matches + elif i < N and pat[j] != txt[i]: + # Do not match lps[0..lps[j-1]] characters, + # they will match anyway + if j != 0: + j = lps[j-1] + else: + i += 1 + +def computeLPSArray(pat, M, lps): + len = 0 # length of the previous longest prefix suffix + + lps[0] # lps[0] is always 0 + i = 1 + + # the loop calculates lps[i] for i = 1 to M-1 + while i < M: + if pat[i]== pat[len]: + len += 1 + lps[i] = len + i += 1 + else: + # This is tricky. Consider the example. + # AAACAAAA and i = 7. The idea is similar + # to search step. + if len != 0: + len = lps[len-1] + # Also, note that we do not increment i here + else: + lps[i] = 0 + i += 1 + +txt = "ABABDABACDABABCABAB" +pat = "ABABCABAB" +KMPSearch(pat, txt) + +# This code is contributed by Bhavya Jain \ No newline at end of file diff --git a/Python/LongestIncreasingSubsequence.py b/Python/LongestIncreasingSubsequence.py new file mode 100644 index 0000000..82fc4e6 --- /dev/null +++ b/Python/LongestIncreasingSubsequence.py @@ -0,0 +1,19 @@ +def lis(arr): + t = [0]*len(arr) + t[0]=1 + j=1 + while jarr[i] and t[j]= 8): + for i in s: + + # counting lowercase alphabets + if (i.islower()): + l+=1 + + # counting uppercase alphabets + if (i.isupper()): + u+=1 + + # counting digits + if (i.isdigit()): + d+=1 + + # counting the mentioned special characters + if(i=='@'or i=='$' or i=='_'): + p+=1 +if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)): + print("Valid Password") +else: + print("Invalid Password") diff --git a/Python/Prime Number From Digit Words.py b/Python/Prime Number From Digit Words.py new file mode 100644 index 0000000..e6a24c9 --- /dev/null +++ b/Python/Prime Number From Digit Words.py @@ -0,0 +1,67 @@ +import math +myDictionary= { + "one":1, + "two":2, + "three":3, + "four":4, + "five":5, + "six":6, + "seven":7, + "eight":8, + "nine":9, + "ten":10, + "eleven":11, + "twelve":12, + "thirteen":13, + "fourteen":14, + "fifteen":15, + "sixteen":16, + "seventeen":17, + "eighteen":18, + "nineteen":19, + "twenty":20, + "thirty":30, + "forty":40, + "fifty":50, + "sixty":60, + "seventy":70, + "eighty":80, + "ninety":90, + "hundred":100, + } + +def Print_Prime_Numbers(number_in_text): + text=number_in_text.strip().split(" ") + num=0 + if len(text)<=2 and "hundred" not in text: + for i in text: + num+=myDictionary[i] + else: + num=myDictionary[text[0]]*myDictionary[text[1]] + text=text[2:] + + for i in text: + num+=myDictionary[i] + + print(num) + primes=[] + for i in range(2,num+1): + primes.append(i) + + i = 2 + #from 2 to sqrt(number) + while(i <= int(math.sqrt(num))): + #if i is in list + #then we gotta delete its multiples + if i in primes: + #j will give multiples of i, + #starting from 2*i + for j in range(i*2, num+1, i): + if j in primes: + #deleting the multiple if found in list + primes.remove(j) + i = i+1 + + return primes + +print(Print_Prime_Numbers("nine hundred ninety nine")) diff --git a/Python/TicTacToe.py b/Python/TicTacToe.py new file mode 100644 index 0000000..bd28530 --- /dev/null +++ b/Python/TicTacToe.py @@ -0,0 +1,171 @@ +import random + + #to print out the board +def drawBoard (board): + print (' | |') + print (' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) + print (' | |') + print ('------------') + print (' | |') + print (' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) + print (' | |') + print ('------------') + print (' | |') + print (' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) + print (' | |') + +def inputPlayerLetter(): + letter = '' + while not (letter == 'X' or letter == 'O'): + print('Do you want to be X or O?') + letter = input().upper() + + if letter == 'X': + return ['X','O'] + else: + return ['O','X'] + +def whoGoesFirst(): + if random.randint(0,1) == 0: + return 'computer' + else: + return 'player' + +def playAgain(): + print ('Do you want to play again?') + return input().lower().startswith('y') + +def makeMove(board , letter , move): + board[move] = letter + +def isWinner(bo,le): + return ((bo[7]==le and bo[8]==le and bo[9]==le) or + (bo[4]==le and bo[5]==le and bo[6]==le) or + (bo[1]==le and bo[2]==le and bo[3]==le) or + (bo[7]==le and bo[4]==le and bo[1]==le) or + (bo[8]==le and bo[5]==le and bo[2]==le) or + (bo[9]==le and bo[6]==le and bo[3]==le) or + (bo[9]==le and bo[5]==le and bo[1]==le) or + (bo[7]==le and bo[5]==le and bo[3]==le)) + +def getBoardCopy(board): + dupeBoard = [] + + for i in board: + dupeBoard.append(i) + + return dupeBoard + +def isSpaceFree(board, move): + return board[move] == ' ' + +def getPlayerMove(board): + + move = ' ' + while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,int(move)): + print ('What is your next move? (1-9)') + move = input() + return int (move) + +def chooseRandomMoveFromList (board,movesList): + possibleMoves = [] + for i in movesList: + if isSpaceFree(board,i): + possibleMoves.append(i) + + if len(possibleMoves) != 0: + return random.choice(possibleMoves) + else: + return None + +def getComputerMove(board,computerLetter): + + if computerLetter == 'X': + playerLetter == 'O' + else: + playerLetter == 'X' + + #to check if we can the next move + for i in range(1,10): + copy = getBoardCopy(board) + if isSpaceFree(copy,i): + makeMove(copy, computerLetter , i) + if isWinner(copy, computerLetter): + return i + + #to check if player can win in their next move and block them + for i in range(1,10): + copy = getBoardCopy(board) + if isSpaceFree(copy,i): + makeMove(copy, playerLetter , i) + if isWinner(copy, playerLetter): + return i + + #try to take one of the corners if they are free + move = chooseRandomMoveFromList (board, [1, 3, 7, 9]) + if move != None: + return move + + #try to take the centre, if it is free + if isSpaceFree(board, [5]): + return 5 + + #move on one of the sides + return chooseRandomMoveFromList (board, [2, 4, 6, 8]) + +def isBoardFull (board): + #return true if every space is full, otherwise false + for i in range(1, 10): + if isSpaceFree(board, i): + return False + return True + + +print ('Welcome to Tic Tac Toe') + +while True: + #reset the board + theBoard = [' '] * 10 + playerLetter, computerLetter = inputPlayerLetter() + turn = whoGoesFirst() + print ('The ' + turn + ' will go first. ') + gameIsPlaying = True + + while gameIsPlaying: + if turn == 'player': + #Player's turn + drawBoard(theBoard) + move = getPlayerMove(theBoard) + makeMove (theBoard , playerLetter , move) + + if isWinner (theBoard, playerLetter): + drawBoard(theBoard) + print('You have won the game!!') + gameIsPlaying = False + else: + if isBoardFull(theBoard): + drawBoard(theBoard) + print('The game is a Tie!!') + break + else: + turn = 'computer' + + else: + #Computer's turn + move = getComputerMove(theBoard, computerLetter) + makeMove(theBoard, computerLetter, move) + + if isWinner(theBoard, computerLetter): + drawBoard(theBoard) + print('The computer has won!! You lose!') + gameIsPlaying = False + else: + if isBoardFull(theBoard): + drawBoard(theBoard) + print('The game is a Tie!!') + break + else: + turn = 'player' + + if not playAgain(): + break diff --git a/Python/TowerOfHanoi.py b/Python/TowerOfHanoi.py new file mode 100644 index 0000000..dfc3a9d --- /dev/null +++ b/Python/TowerOfHanoi.py @@ -0,0 +1,34 @@ +# Implement Code to Solve Tower of Hanoi Problem (Issue #38) +# https://github.com/Py-Contributors/Hacktoberfest-2020/issues/38 +# Contributed by @tauseefmohammed2 : https://github.com/tauseefmohammed2 + +def TowerOfHanoi(numDisks, source, intermediate, destination): + if(numDisks == 1): + print("Move Disk 1 From Pole {} to Pole {}".format(source, destination)) + return + TowerOfHanoi(numDisks - 1, source, destination, intermediate) + print("Move Disk {} From Pole {} to Pole {}".format(numDisks, source, destination)) + TowerOfHanoi(numDisks - 1, intermediate, source, destination) + +numDisks = int(input("Enter Number of Disks: ")) + +# Source : A, Intermediate : B, Destination : C +TowerOfHanoi(numDisks, 'A', 'B', 'C') + +# Input : 3 +# Output : +# Enter Number of Disks: 3 +# Move Disk 1 From Pole A to Pole C +# Move Disk 2 From Pole A to Pole B +# Move Disk 1 From Pole C to Pole B +# Move Disk 3 From Pole A to Pole C +# Move Disk 1 From Pole B to Pole A +# Move Disk 2 From Pole B to Pole C +# Move Disk 1 From Pole A to Pole C + +# Input : 2 +# Output : +# Enter Number of Disks: 2 +# Move Disk 1 From Pole A to Pole B +# Move Disk 2 From Pole A to Pole C +# Move Disk 1 From Pole B to Pole C diff --git a/Python/__pycache__/speedtest.cpython-37.pyc b/Python/__pycache__/speedtest.cpython-37.pyc new file mode 100644 index 0000000..8ca1455 Binary files /dev/null and b/Python/__pycache__/speedtest.cpython-37.pyc differ diff --git a/Python/binarynumbers_stack.py b/Python/binarynumbers_stack.py new file mode 100644 index 0000000..5dbfde3 --- /dev/null +++ b/Python/binarynumbers_stack.py @@ -0,0 +1,30 @@ +class Stack(object): + def __init__(self): + self.items = [] + def isEmpty(self): + return self.items == [] + def push(self,item): + self.items.append(item) + def pop(self): + return self.items.pop() + def peek(self): + return self.items[len(self.items)-1] + def size(self): + return len(self.items) + def binary(self): + return self.items + +def divby2(numb): + + s=Stack() + while numb>0: + rem = numb%2 + s.push(rem) + numb = numb//2 + binstring = '' + while not s.isEmpty: + binstring = binstring + str(s.pop()) + return binstring + +c = divby2(42) +print(c) \ No newline at end of file diff --git a/Python/binarysearch.py b/Python/binarysearch.py new file mode 100644 index 0000000..3bba443 --- /dev/null +++ b/Python/binarysearch.py @@ -0,0 +1,14 @@ +from bisect import bisect_left,bisect + +def binsearchright(a,k): + c = bisect(a, k) + return c + +def binsearchleft(a,k): + b = bisect_left(a,k) + return b +a = [1,1,2,2,2,4,4,4,4,4,4,8,8] +k = int(8) +res = binsearchleft(a, k) +res1 = binsearchright(a,k) +print("{} is present {} times in the array".format(k,abs(res-res1))) \ No newline at end of file diff --git a/Python/coins.py b/Python/coins.py new file mode 100644 index 0000000..9d3a1f8 --- /dev/null +++ b/Python/coins.py @@ -0,0 +1,14 @@ +money = 63 +denom = [1,5,10,12,25] +i = len(denom)-1 +count=0 +count1 = 9999999999 +for n in range(len(denom)-1,-1,-1): + if money%denom[n] == 0: + count1 = min(count1,money//denom[n]) +while money: + count+=money//denom[i] + money = money%denom[i] + #print('Used {} coin {} times'.format(denom[i],max(money,count))) + i-=1 +print(min(count,count1)) \ No newline at end of file diff --git a/Python/even-odd.py b/Python/even-odd.py new file mode 100644 index 0000000..dbf4716 --- /dev/null +++ b/Python/even-odd.py @@ -0,0 +1,5 @@ +num = int(input("Enter a number: ")) +if (num % 2) == 0: + print("{0} is Even".format(num)) +else: + print("{0} is Odd".format(num)) diff --git a/Python/insertionsort.py b/Python/insertionsort.py new file mode 100644 index 0000000..b0d5c5b --- /dev/null +++ b/Python/insertionsort.py @@ -0,0 +1,13 @@ +print("Enter the numbers: ") +arr = list(map(int,input().split(' '))) + +for i in range(1,len(arr)): + temp = arr[i] + j = i-1 + while(j>=0 and arr[j]>temp): + arr[j+1] = arr[j] + j = j-1 + arr[j+1] = temp + +print("After insertion sort : ",arr) + diff --git a/Python/kadane'salgorithm.py b/Python/kadane'salgorithm.py new file mode 100644 index 0000000..d659fb3 --- /dev/null +++ b/Python/kadane'salgorithm.py @@ -0,0 +1,14 @@ +def maxi(s): + max_sum = s[0] + cur_sum = s[0] + + for i in range(1,len(s)): + cur_sum = max(s[i],cur_sum+s[i]) + max_sum = max(max_sum,cur_sum) + return max_sum + +t = int(input()) +for i in range(t): + n = input() + s = list(map(int,input().split())) + print(maxi(s)) diff --git a/Python/longestcommonsubsequence.py b/Python/longestcommonsubsequence.py new file mode 100644 index 0000000..0acd344 --- /dev/null +++ b/Python/longestcommonsubsequence.py @@ -0,0 +1,14 @@ +def lcs(s1,s2): + dp = [[0]*(len(s2)+1)]*(len(s1)+1) + print(dp) + maxi = 0 + for i in range(len(s1)): + for j in range(len(s2)): + if s1[i] == s2[j]: + dp[i+1][j+1] = 1 + dp[i][j] + else: + dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]) + maxi = max(maxi, dp[i+1][j+1]) + print(maxi) + +lcs('ABC','AE') \ No newline at end of file diff --git a/Python/longestpalindromicsubstring.py b/Python/longestpalindromicsubstring.py new file mode 100644 index 0000000..462b27e --- /dev/null +++ b/Python/longestpalindromicsubstring.py @@ -0,0 +1,20 @@ + +reslen=float("-infinity") +resstart = None +def asd(s='aaababaaa'): + if len(s)<2: + return s + for i in range(len(s)-1): + expand(s,i,i) + expand(s,i,i+1) + return s[resstart:resstart+reslen] + +def expand(string,begin,end): + while begin>=0 and end2: + value = fib(n-1) + fib(n-2) + known[n] = value + return value + +print(fib(1000)) \ No newline at end of file diff --git a/Python/mergesort.py b/Python/mergesort.py new file mode 100644 index 0000000..489a26b --- /dev/null +++ b/Python/mergesort.py @@ -0,0 +1,37 @@ +'''merge has complexity of (6n*log n base 2) + 6n big Oh of nlog n it better than insertion sort for higher range +it sort by sorting sub parts of given array and then merge them''' + + +def merge(L,R): + (ll,lr)=(len(L),len(R)) + (i,j,t)=(0,0,[]) + while i+j1: + mid=(r+l)//2 + L=mergesort(arr,l,mid) + R=mergesort(arr,mid,r) + return merge(L,R) + +print("enter") +arr=list(map(int,input().split())) +pp=mergesort(arr,0,len(arr)) +print(pp) diff --git a/Python/minplatforms.py b/Python/minplatforms.py new file mode 100644 index 0000000..b05bfdb --- /dev/null +++ b/Python/minplatforms.py @@ -0,0 +1,24 @@ +def mp(s1,s2): + count= 0 + s2.sort() + plat_needed = 1 + result = 1 + first = 1 + second = 0 + while first result: + result = plat_needed + else: + plat_needed-=1 + second+=1 + return result + +#code +for i in range(int(input())): + n = int(input()) + s1 = list(map(int,input().split())) + s2 = list(map(int,input().split())) + print(mp(s1,s2)) \ No newline at end of file diff --git a/Python/musicPlayer.py b/Python/musicPlayer.py new file mode 100644 index 0000000..44d48c8 --- /dev/null +++ b/Python/musicPlayer.py @@ -0,0 +1,45 @@ +from tkinter import * +import pygame +import os + +window=Tk() +window.geometry("400x150") + +pygame.mixer.init() + +n=0 + +def start_stop(): + global n + n=n+1 + + if n==1: + song_name=songs_listbox.get() + pygame.mixer.music.load(song_name) + pygame.mixer.music.play(0) + print("music started ") + elif (n%2)==0: + pygame.mixer.music.pause() + print("paused ") + + elif (n%2)!=0: + pygame.mixer.music.unpause() + print("unPaused") + + + + +l1=Label(window,text="MUSIC PLAYER",font="times 20") +l1.grid(row=1,column=1) + +b2=Button(window,text='o',width=20,command=start_stop) +b2.grid(row=4,column=1) + + +songs_list=os.listdir() +songs_listbox=StringVar(window) +songs_listbox.set("select songs") +menu=OptionMenu(window,songs_listbox,*songs_list) +menu.grid(row=4,column=4) + +window.mainloop() \ No newline at end of file diff --git a/Python/password_manager.py b/Python/password_manager.py new file mode 100644 index 0000000..74a1f8f --- /dev/null +++ b/Python/password_manager.py @@ -0,0 +1,64 @@ +import sqlite3 +from hashlib import sha256 + + +ADMIN_PASSWORD = "123456" + +connect = input("What is your password?\n") + +while connect != ADMIN_PASSWORD: + connect = input("What is your password?\n") + if connect == "q": + break + +conn = sqlite3.connect('pass_manager.db') + +def create_password(pass_key, service, admin_pass): + return sha256(admin_pass.encode('utf-8') + service.lower().encode('utf-8') + pass_key.encode('utf-8')).hexdigest()[:15] + +def get_hex_key(admin_pass, service): + return sha256(admin_pass.encode('utf-8') + service.lower().encode('utf-8')).hexdigest() + +def get_password(admin_pass, service): + secret_key = get_hex_key(admin_pass, service) + cursor = conn.execute("SELECT * from KEYS WHERE PASS_KEY=" + '"' + secret_key + '"') + + file_string = "" + for row in cursor: + file_string = row[0] + return create_password(file_string, service, admin_pass) + +def add_password(service, admin_pass): + secret_key = get_hex_key(admin_pass, service) + + command = 'INSERT INTO KEYS (PASS_KEY) VALUES (%s);' %('"' + secret_key +'"') + conn.execute(command) + conn.commit() + return create_password(secret_key, service, admin_pass) + +if connect == ADMIN_PASSWORD: + try: + conn.execute('''CREATE TABLE KEYS + (PASS_KEY TEXT PRIMARY KEY NOT NULL);''') + print("Your safe has been created!\nWhat would you like to store in it today?") + except: + print("You have a safe, what would you like to do today?") + + + while True: + print("\n"+ "*"*15) + print("Commands:") + print("q = quit program") + print("gp = get password") + print("sp = store password") + print("*"*15) + input_ = input(":") + + if input_ == "q": + break + if input_ == "sp": + service = input("What is the name of the service?\n") + print("\n" + service.capitalize() + " password created:\n" + add_password(service, ADMIN_PASSWORD)) + if input_ == "gp": + service = input("What is the name of the service?\n") + print("\n" + service.capitalize() + " password:\n"+get_password(ADMIN_PASSWORD, service)) diff --git a/Python/quicksort.py b/Python/quicksort.py new file mode 100644 index 0000000..539a99c --- /dev/null +++ b/Python/quicksort.py @@ -0,0 +1,17 @@ +def quicksort(arr): + if len(arr)>=1: + pivot = arr.pop(len(arr)//2) + else: + return arr + items_greater = [] + items_lesser = [] + for ele in arr: + if ele>=pivot: + items_greater.append(ele) + else: + items_lesser.append(ele) + + return quicksort(items_lesser) + [pivot] + quicksort(items_greater) + +arr = list(map(int,input().split())) +print(quicksort(arr)) \ No newline at end of file diff --git a/Python/reverse palindrome.py b/Python/reverse palindrome.py index 352c8ec..0ebb0cc 100644 --- a/Python/reverse palindrome.py +++ b/Python/reverse palindrome.py @@ -2,22 +2,22 @@ Python Programe To Check if a String is Palindrome or Not ''' -check1 = input("Choose Your Input For Check Palindrome\n For Integer Type --> i \n For Word Type -->s\n").lower() -for i range(1,3): - if check1 == 's': - x = input("Enter Your Word Here :\n").lower() - elif check1 == 'i': - x = input("Enter Your Number Here :\n") - else: - print("Please Enter I or S only") +for i in range(1,3): + check1 = input("Choose Your Input For Check Palindrome\n For Integer Type --> i \n For Word Type -->s\n").lower() + if check1 == 's': + x = input("Enter Your Word Here :\n").lower() + elif check1 == 'i': + x = input("Enter Your Number Here :\n") + else: + print("Please Enter I or S only") + break + reverse = "" # Empty String to save Reverse value in it. - w = "" # Empty String to save Reverse value in it. - -#save string x to a new new variable and compare them - for i in x: - w = i + w # save new value to w - if (x==w): - print("Yes") - break - else: - print("No") \ No newline at end of file + #Construct the reverse value/string + for i in x: + reverse = i + reverse + #Compare the string and its reverse + if (x==reverse): + print("Yes") + else: + print("No") \ No newline at end of file diff --git a/Python/reverse_name.py b/Python/reverse_name.py new file mode 100644 index 0000000..c87f79a --- /dev/null +++ b/Python/reverse_name.py @@ -0,0 +1,3 @@ +first = input("Enter first name") +last = input("Enter last name") +print(first[::-1]+" " +last[::-1]) diff --git a/Python/rodcutter.py b/Python/rodcutter.py new file mode 100644 index 0000000..d99e81c --- /dev/null +++ b/Python/rodcutter.py @@ -0,0 +1,10 @@ +def rodcutter(cost): + rod = [0]*len(cost) + rod[0] = 0 + for i in range(1,len(rod)): + max_pro = float('-infinity') + for j in range(1,i+1): + max_pro = max(max_pro,cost[j]+rod[i-j]) + rod[i] = max_pro + return rod[-1] +print(rodcutter([0,2,4,5,7])) \ No newline at end of file diff --git a/Python/screenRecorder.py b/Python/screenRecorder.py new file mode 100644 index 0000000..b4cc36b --- /dev/null +++ b/Python/screenRecorder.py @@ -0,0 +1,47 @@ +import cv2 +import numpy as np +from PIL import ImageGrab + + +def screenRec(): + + # defining the codec + fourcc = cv2.VideoWriter_fourcc(*'XVID') + + # defining frame rate of the output video + fps = 8.0 + + # outout video + out = cv2.VideoWriter('output.avi', fourcc, fps, (1366, 768)) + + while(True): + + # take a snapshot of the screen using imagegrab + img = ImageGrab.grab() + + # convert this image to numpy array + img_np = np.array(img) + + # reads colors as BGR + frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) + + # DISPLAY this frames as video + win_title = "Screen Recorder" + cv2.imshow(win_title, frame) + + # output the frame + out.write(frame) + + # wait for 'q' key to stop recording (program) + if(cv2.waitKey(1) & 0XFF == ord('q')): + break + + # close the window and release recording + out.release() + + # de-allocate any associated memory usage + cv2.destroyAllWindows() + + +# call screenrec function +screenRec() \ No newline at end of file diff --git a/Python/speedtest.py b/Python/speedtest.py new file mode 100644 index 0000000..04b3c2b --- /dev/null +++ b/Python/speedtest.py @@ -0,0 +1,16 @@ +import speedtest +try: + st = speedtest.Speedtest() + server_names = [] + st.get_servers(server_names) + downlink_bps = st.download() + uplink_bps = st.upload() + ping = st.results.ping + up_mbps = round(uplink_bps/1000000,2) + down_mbps = round(downlink_bps/1000000,2) + print('speed test results:') + print('ping: {} ms'.format(ping)) + print('upling: {} Mbps'.format(up_mbps)) + print('downling: {} Mbps'.format(down_mbps)) +except: + print("Speed test can't perform right now!") \ No newline at end of file diff --git a/Python/stairwaystoheaven.py b/Python/stairwaystoheaven.py new file mode 100644 index 0000000..adb0431 --- /dev/null +++ b/Python/stairwaystoheaven.py @@ -0,0 +1,13 @@ +known = {} +def stariways(n): + if n in known: + return known[n] + if n==1: + value = 1 + elif n==2: + value = 2 + elif n>2: + value = stariways(n-1)+stariways(n-2) + known[n] = value + return value +print(stariways(3)) \ No newline at end of file diff --git a/Python/stockpriceprofit.py b/Python/stockpriceprofit.py new file mode 100644 index 0000000..7ce79f4 --- /dev/null +++ b/Python/stockpriceprofit.py @@ -0,0 +1,9 @@ +def stockprice(price): + minuptil = [0]*len(price) + profit = [0]*len(price) + minuptil[0] = price[0] + for i in range(1,len(price)): + minuptil[i] = min(price[i],minuptil[i-1]) + profit[i] = price[i] - minuptil[i] + return max(profit) +print(stockprice([8,1,2,4,6,3])) \ No newline at end of file diff --git a/Python/sum of square of n natural number.py b/Python/sum of square of n natural number.py index 12639f7..4c481f6 100644 --- a/Python/sum of square of n natural number.py +++ b/Python/sum of square of n natural number.py @@ -11,5 +11,21 @@ def squaresum(n): sum += (i * i) return sum +n = int(input("Enter Number to Print Sum Of square of N Natural Number :\n")) +print(squaresum(n)) + + +''' +The above approach takes linear time to compute the squaresum however we can solve +this in constant time using the formula: + Σn^2 = [n(n+1)(2n+1)]/6 + +Source : https://en.wikipedia.org/wiki/Square_pyramidal_number +''' + +def squaresum(n): + sum = (n*(n+1)*(2*n+1))//6 + return sum + n = int(input("Enter Number to Print Sum Of square of N Natural Number :\n")) print(squaresum(n)) \ No newline at end of file diff --git a/Python/sumoftherange.py b/Python/sumoftherange.py new file mode 100644 index 0000000..21daabf --- /dev/null +++ b/Python/sumoftherange.py @@ -0,0 +1,10 @@ +def sumofrange(arr): + sumarr = [0]*(len(arr)) + sumarr[0] = arr[0] + for i in range(1,len(arr)): + sumarr[i] = arr[i]+sumarr[i-1] + return sumarr +print(sumofrange([1,-2,3,10,-8,0])) +#Then give the query like sum in the range(2,4) +# the answer will be => sum(2,4) = sum(0,4) - sum(0,1) +# i.e., sum(i,j) = sum(0,j) - sum(0,i-1) \ No newline at end of file diff --git a/Python/towerofhonai.py b/Python/towerofhonai.py new file mode 100644 index 0000000..eeb97c0 --- /dev/null +++ b/Python/towerofhonai.py @@ -0,0 +1,10 @@ +def movetower(height, fromtower, totower, withtower): + if height == 1: + print(fromtower + '-->' + totower) + return True + print('Executing 1, height of tower: {}'.format(height)) + movetower(height-1, fromtower,withtower,totower) + print(fromtower + '-->' + totower) + print('Executing 2, height of tower: {}'.format(height)) + movetower(height-1, withtower, totower, fromtower) +print(movetower(3,'a','c','b')) \ No newline at end of file diff --git a/README.md b/README.md index a33ef7b..7326388 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # HacktoberFest-2020 +### Disclaimer :- This Repository is for learning purpose, how to create issue and Pull request on github during HacktoberFest.Contributions on this repository will not count for HacktoberFest. We are not adding this repository for HacktoberFest. We support real motive of Open Source contributions. you can check out our other [Repository](https://github.com/py-contributors/) which are participating in Hacktober. Check [here](https://github.com/py-contributors/) + pycontributors logo -Open source is changing the world - one pull request at a time. +Open source is changing the world - one pull request at a time. - [HacktoberFest-2020](#hacktoberfest-2020)