├── 8queens.py ├── ASCIIValue.py ├── Add_Binary.py ├── Addition.py ├── Anagram.py ├── AnagramString.py ├── Arithmetic Operations.py ├── Array Partition.py ├── Atharva_35.py ├── BinaryInsertionSort.py ├── BinarySearch.py ├── BitwiseOperators.py ├── BubbleSort.py ├── Calculator.py ├── Calender.py ├── Coin_Flipper.py ├── CountLettersInAWordUsingDictionary.py ├── Dheeraj.py ├── Dice_Rolling_Simulator.py ├── Fibonacci Number.py ├── Fibonacci.py ├── FloydsTriangle.py ├── Hangman.py ├── HelloWorld ├── InsertionSort.py ├── ListToFile.py ├── LostCardProblem.py ├── MatrixMultiplication.py ├── Merge Sort.py ├── MergeSort.py ├── MinMaxNumbers.py ├── Pascal's Triangle.py ├── PrimeCheck.py ├── Python program ├── PythonProgramtoAddTwoNumbers.py ├── PythonProgramtoFindNumbersDivisiblebyAnotherNumber ├── PythonProgramtoFindtheLargestAmongThreeNumbers ├── QueueUsingList.py ├── Quick_sort.py ├── Quicksort.py ├── README.md ├── RSA_algorithm.py ├── ReverseString.py ├── SelectionSort.py ├── ShellSort.py ├── Silver_Project_RockPaperSciss.py ├── Simple_Calculator.py ├── SineTaylorSeries.py ├── Stack.py ├── StackUsingList.py ├── TimSort.py ├── Transpose_Matrix.py ├── UppertoLower and LowertoUppercase.py ├── WakeOnLan.py ├── age_in_days.py ├── algorithms ├── LinkedList.py ├── Queues.py ├── README.md └── Stack.py ├── dice_roller.py ├── djikstras_shortest_path.py ├── factorial.py ├── gcdOfTwoNumbers.py ├── greet.py ├── guess_number.py ├── helloworld ├── helloworld.py ├── kadanealgorithm.cpp ├── linear_search.py ├── optimized Bubble Sort.py ├── palindrome_and_armstrong_check.py ├── rock.py ├── say_name_name.py ├── spam.py ├── strongNumber.py ├── temperature.py └── tranaslator_gui.py /8queens.py: -------------------------------------------------------------------------------- 1 | BOARD_SIZE = 8 2 | 3 | class BailOut(Exception): 4 | pass 5 | 6 | def validate(queens): 7 | left = right = col = queens[-1] 8 | for r in reversed(queens[:-1]): 9 | left, right = left-1, right+1 10 | if r in (left, col, right): 11 | raise BailOut 12 | 13 | def add_queen(queens): 14 | for i in range(BOARD_SIZE): 15 | test_queens = queens + [i] 16 | try: 17 | validate(test_queens) 18 | if len(test_queens) == BOARD_SIZE: 19 | return test_queens 20 | else: 21 | return add_queen(test_queens) 22 | except BailOut: 23 | pass 24 | raise BailOut 25 | 26 | queens = add_queen([]) 27 | print (queens) 28 | print ("\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)) 29 | -------------------------------------------------------------------------------- /ASCIIValue.py: -------------------------------------------------------------------------------- 1 | c = 'p' 2 | print("The ASCII value is ", ord(c)) -------------------------------------------------------------------------------- /Add_Binary.py: -------------------------------------------------------------------------------- 1 | 2 | def addBinary(num1: str, num2: str) -> str: 3 | """ 4 | Method to add to binary numbers 5 | Parameters: Two binary numbers num1 and num2 (string) 6 | Output: Addition in binary 7 | """ 8 | sumnum = int(num1,2) + int(num2,2) 9 | print(bin(sumnum)[2:]) 10 | 11 | addBinary("11", "1") -------------------------------------------------------------------------------- /Addition.py: -------------------------------------------------------------------------------- 1 | a=12 2 | b=20 3 | print(a+b) 4 | -------------------------------------------------------------------------------- /Anagram.py: -------------------------------------------------------------------------------- 1 | def is_anagram(str1, str2): 2 | list_str1 = list(str1) 3 | list_str1.sort() 4 | list_str2 = list(str2) 5 | list_str2.sort() 6 | 7 | return (list_str1 == list_str2) 8 | 9 | print(is_anagram(input(),input())) 10 | -------------------------------------------------------------------------------- /AnagramString.py: -------------------------------------------------------------------------------- 1 | #a word, phrase, or name formed by rearranging the letters of another 2 | #example silent and listen 3 | #a good additionalitt to this program would be to check whether they are actuallly words or not :) 4 | 5 | def mysort(s): #function that splits the letters 6 | d=sorted(s) 7 | s=''.join(d) 8 | return s 9 | 10 | s1=input("enter first string") 11 | n1=mysort(s1) #function invocation /calling the function 12 | 13 | s2=input("enter second string") 14 | n2=mysort(s2) 15 | 16 | if n1==n2: 17 | print("anagram") 18 | else: 19 | print("not an anangram") -------------------------------------------------------------------------------- /Arithmetic Operations.py: -------------------------------------------------------------------------------- 1 | number1=75 2 | number2=2 3 | print('Addition=', number1+number2) 4 | print('Subtraction=', number1-number2) 5 | print('product=', number1*number2) 6 | print('Division=', number1/number2) 7 | print('number1^number2=', number1**number2) 8 | -------------------------------------------------------------------------------- /Array Partition.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayPairSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | z = len(nums) 9 | sum1 = 0 10 | for i in range(0,z): 11 | if (i%2 == 0): 12 | sum1 += nums[i] 13 | return sum1 14 | -------------------------------------------------------------------------------- /Atharva_35.py: -------------------------------------------------------------------------------- 1 | # Simple program in python for checking for armstrong number 2 | # Python program to check if the number is an Armstrong number or not 3 | 4 | y='y' 5 | 6 | while y == 'y': # while loop 7 | # take input from the user 8 | x = int(input("Enter a number: ")) 9 | 10 | sum = 0 11 | 12 | temp = x 13 | while temp > 0: #loop for checking armstrong number 14 | digit = temp % 10 15 | sum += digit ** 3 16 | temp //= 10 17 | 18 | if x == sum: 19 | print(x,"is an Armstrong number") 20 | else: 21 | print(x,"is not an Armstrong number") 22 | 23 | y=input("WNamt to continue?(y/n)") #Condition for multiple run 24 | 25 | -------------------------------------------------------------------------------- /BinaryInsertionSort.py: -------------------------------------------------------------------------------- 1 | class Sort: 2 | def __init__(self, array): 3 | self.array = array 4 | 5 | def binary_insertion_sort(self): 6 | for i in range(1, len(self.array)): 7 | key = self.array[i] 8 | pos = self.binary_search(key, 0, i) + 1 9 | for k in range(i, pos, -1): 10 | self.array[k] = self.array[k - 1] 11 | self.array[pos] = key 12 | return self.array 13 | 14 | def binary_search(self, element, first, last): 15 | if last - first <= 1: 16 | if element < self.array[first]: 17 | return first - 1 18 | else: 19 | return first 20 | mid = (first + last)//2 21 | if self.array[mid] < element: 22 | return self.binary_search(element, mid, last) 23 | elif self.array[mid] > element: 24 | return self.binary_search(element, first, mid) 25 | else: 26 | return mid 27 | 28 | def main(): 29 | array = list(map(int, input("Enter unsorted array: ").split(' '))) 30 | obj = Sort(array) 31 | sorted_array = obj.binary_insertion_sort() 32 | print("Sorted Array: ", end = '') 33 | print(*sorted_array) 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /BinarySearch.py: -------------------------------------------------------------------------------- 1 | # Iterative Binary Search Function 2 | # It returns index of x in given array arr if present, 3 | # else returns -1 4 | def binary_search(arr, x): 5 | low = 0 6 | high = len(arr) - 1 7 | mid = 0 8 | 9 | while low <= high: 10 | 11 | mid = (high + low) // 2 12 | 13 | # Check if x is present at mid 14 | if arr[mid] < x: 15 | low = mid + 1 16 | 17 | # If x is greater, ignore left half 18 | elif arr[mid] > x: 19 | high = mid - 1 20 | 21 | # If x is smaller, ignore right half 22 | else: 23 | return mid 24 | 25 | # If we reach here, then the element was not present 26 | return -1 27 | 28 | 29 | # Test array 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binary_search(arr, x) 35 | 36 | if result != -1: 37 | print("Element is present at index", str(result)) 38 | else: 39 | print("Element is not present in array") 40 | -------------------------------------------------------------------------------- /BitwiseOperators.py: -------------------------------------------------------------------------------- 1 | a=5 2 | c=int(input("Enter a num")) 3 | print(a&c, a|c) #bitwise and, bitwise or 4 | b=a>>c #Right shift 5 | d=a< ar[j+1] : 9 | ar[j], ar[j+1] = ar[j+1], ar[j] 10 | # Driver code to test above 11 | ar = ['t','u','t','o','r','i','a','l'] 12 | bubbleSort(ar) 13 | print ("Sorted array is:") 14 | for i in range(len(ar)): 15 | print (ar[i]) 16 | -------------------------------------------------------------------------------- /Calculator.py: -------------------------------------------------------------------------------- 1 | def calc(choice, first_num, second_num): 2 | # Python does not have switch case 3 | # There are other ways to implement this, dictionary mapping for example, but I started off with this 4 | if(choice=='addition' or choice=='add'): 5 | return first_num+second_num 6 | elif (choice=='subtraction' or choice=='subtract'): 7 | return first_num-second_num 8 | elif(choice=='multiplication' or choice=='multiply'): 9 | return first_num*second_num 10 | elif (choice=='division' or choice=='divide'): 11 | return first_num/second_num 12 | 13 | print("This is the Basic Calculator Program") 14 | start=input("Do you wish to start? Type 1 for YES and 0 for NO: ") 15 | st=int(start) 16 | if(st!=1 and st!=0): 17 | print("I'm going to take that as a YES") 18 | while (st==1): 19 | num1=input("Enter the first number: ") 20 | first_num=int(num1) 21 | # I could use some thing like 22 | # Press the corresponing number to perform the operation 23 | # 1. Addition 24 | # 2. Subtraction 25 | # And so on, but I wanted to attempt taking a word input 26 | choice=input("Addition, subtraction, multiplication or division? ") 27 | choice=choice.lower() 28 | num2=input("Enter the second number: ") 29 | second_num=int(num2) 30 | answer=calc(first_num, choice, second_num) 31 | a=int(answer) 32 | print("The answer is "+str(a)) 33 | continue_=input("Do you want to continue? Press 1 for YES and 0 for NO: ") 34 | st=int(continue_) 35 | if(st!=1 and st!=0): 36 | print("I'm going to take that as a no...") 37 | 38 | print("Thank you for trying out the Bacic Calculator Program!") 39 | -------------------------------------------------------------------------------- /Calender.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | yy = int(input("Enter year: ")) 3 | mm = int(input("Enter month: ")) 4 | 5 | print(calendar.month(yy, mm)) -------------------------------------------------------------------------------- /Coin_Flipper.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def flip(): 4 | n = random.randint(0,1) 5 | if n == 1: 6 | return True 7 | else: 8 | return False 9 | 10 | def user_prompt(): 11 | while True: 12 | try: 13 | userInput = input("Please enter a number of flips: ") 14 | userInput = int(userInput) 15 | if num_validity(userInput): 16 | break 17 | else: 18 | print("Please Enter a valid Number which is more than 0") 19 | except ValueError: 20 | print("Please Enter a valid Number") 21 | 22 | return userInput 23 | 24 | def num_validity(flips): 25 | return flips > 0 26 | 27 | def main(num): 28 | heads_count = 0 29 | tails_count = 0 30 | result= "" 31 | 32 | for i in range(int(num)): 33 | if (flip()): 34 | heads_count+=1 35 | result += "H " 36 | else: 37 | tails_count+=1 38 | result += "T " 39 | 40 | print("Number of Heads: %i" % (heads_count)) 41 | print("Number of Tails: %i" % (tails_count)) 42 | print(result) 43 | 44 | Input = user_prompt() 45 | main(Input) -------------------------------------------------------------------------------- /CountLettersInAWordUsingDictionary.py: -------------------------------------------------------------------------------- 1 | word=input("enter a word ") 2 | 3 | dict={} 4 | 5 | for c in word: 6 | co = dict.get(c,0) 7 | if co == 0: 8 | dict[c]=1 9 | else: 10 | dict[c]=co+1 11 | print(dict) 12 | -------------------------------------------------------------------------------- /Dheeraj.py: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | -------------------------------------------------------------------------------- /Dice_Rolling_Simulator.py: -------------------------------------------------------------------------------- 1 | import random 2 | print("This is a dice stimulator") 3 | x = "y" 4 | 5 | while x == "y": 6 | number = random.randint(1,6) 7 | 8 | if number == 1: 9 | print("----------") 10 | print("| |") 11 | print("| O |") 12 | print("| |") 13 | print("----------") 14 | if number == 2: 15 | print("----------") 16 | print("| |") 17 | print("| O O |") 18 | print("| |") 19 | print("----------") 20 | if number == 3: 21 | print("----------") 22 | print("| O |") 23 | print("| O |") 24 | print("| O |") 25 | print("----------") 26 | if number == 4: 27 | print("----------") 28 | print("| O O |") 29 | print("| |") 30 | print("| O O |") 31 | print("----------") 32 | if number == 5: 33 | print("----------") 34 | print("| O O |") 35 | print("| O |") 36 | print("| O O |") 37 | print("----------") 38 | if number == 6: 39 | print("----------") 40 | print("| O O |") 41 | print("| O O |") 42 | print("| O O |") 43 | print("----------") 44 | x = input("Press y to roll again") 45 | 46 | -------------------------------------------------------------------------------- /Fibonacci Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fib(self, N): 3 | """ 4 | :type N: int 5 | :rtype: int 6 | """ 7 | a,b = 0,1 8 | for i in range(N): 9 | a,b = b,b+a 10 | return a 11 | -------------------------------------------------------------------------------- /Fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibSequence(): 2 | # Generates a fibonacci sequence with the size of ngi 3 | runFib = True 4 | while(runFib): 5 | n = int(input('How many numbers do you need? ')) 6 | if n > 0 : 7 | runFib = False 8 | series = [1] 9 | 10 | while len(series) < n: 11 | if len(series) == 1: 12 | series.append(1) 13 | else: 14 | series.append(series[-1] + series[-2]) 15 | 16 | for i in range(len(series)): # Convert the numbers to strings 17 | series[i] = str(series[i]) 18 | else: 19 | print('enter a valid number') 20 | 21 | return(', '.join(series)) # Return the sequence seperated by commas 22 | 23 | print(fibSequence()) -------------------------------------------------------------------------------- /FloydsTriangle.py: -------------------------------------------------------------------------------- 1 | size = int(input("Enter the range: \t ")) 2 | print("\nFLOYD'S TRIANGLE \n") 3 | k = 1 4 | # 2 for loops, one for column looping another for row looping 5 | # i loop for column looping and j loop for row looping 6 | for i in range(1, size + 1): 7 | for j in range(1, i + 1): 8 | print(k, end=" ") 9 | k = k + 1 10 | print() 11 | print("\n") 12 | -------------------------------------------------------------------------------- /Hangman.py: -------------------------------------------------------------------------------- 1 | import random 2 | def hangman(): 3 | 4 | word = random.choice(["pugger" , "littlepugger" , "tiger" , "superman" , "thor" , "pokemon" , "avengers" , "savewater" , "earth" , "annable" ]) 5 | validLetters = 'abcdefghijklmnopqrstuvwxyz' 6 | turns = 10 7 | guessmade = '' 8 | 9 | while len(word) > 0: 10 | main = "" 11 | missed = 0 12 | 13 | for letter in word: 14 | if letter in guessmade: 15 | main = main + letter 16 | else: 17 | main = main + "_" + " " 18 | if main == word: 19 | print(main) 20 | print("You win!") 21 | break 22 | 23 | print("Guess the word:" , main) 24 | guess = input() 25 | 26 | if guess in validLetters: 27 | guessmade = guessmade + guess 28 | else: 29 | print("Enter a valid character") 30 | guess = input() 31 | 32 | if guess not in word: 33 | turns = turns - 1 34 | if turns == 9: 35 | print("9 turns left") 36 | print(" -------- ") 37 | if turns == 8: 38 | print("8 turns left") 39 | print(" -------- ") 40 | print(" O ") 41 | if turns == 7: 42 | print("7 turns left") 43 | print(" -------- ") 44 | print(" O ") 45 | print(" | ") 46 | if turns == 6: 47 | print("6 turns left") 48 | print(" -------- ") 49 | print(" O ") 50 | print(" | ") 51 | print(" / ") 52 | if turns == 5: 53 | print("5 turns left") 54 | print(" -------- ") 55 | print(" O ") 56 | print(" | ") 57 | print(" / \ ") 58 | if turns == 4: 59 | print("4 turns left") 60 | print(" -------- ") 61 | print(" \ O ") 62 | print(" | ") 63 | print(" / \ ") 64 | if turns == 3: 65 | print("3 turns left") 66 | print(" -------- ") 67 | print(" \ O / ") 68 | print(" | ") 69 | print(" / \ ") 70 | if turns == 2: 71 | print("2 turns left") 72 | print(" -------- ") 73 | print(" \ O /| ") 74 | print(" | ") 75 | print(" / \ ") 76 | if turns == 1: 77 | print("1 turns left") 78 | print("Last breaths counting, Take care!") 79 | print(" -------- ") 80 | print(" \ O_|/ ") 81 | print(" | ") 82 | print(" / \ ") 83 | if turns == 0: 84 | print("You loose") 85 | print("You let a kind man die") 86 | print(" -------- ") 87 | print(" O_| ") 88 | print(" /|\ ") 89 | print(" / \ ") 90 | break 91 | 92 | 93 | name = input("Enter your name") 94 | print("Welcome" , name ) 95 | print("-------------------") 96 | print("try to guess the word in less than 10 attempts") 97 | hangman() 98 | print() 99 | -------------------------------------------------------------------------------- /HelloWorld: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | -------------------------------------------------------------------------------- /InsertionSort.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raviprakashdev/simplePythonProgram/f776628c7282a775f7663c2ecfc7d2817a8ed863/InsertionSort.py -------------------------------------------------------------------------------- /ListToFile.py: -------------------------------------------------------------------------------- 1 | #write a list to file 2 | color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] 3 | with open('abc.txt', "w") as myfile: 4 | myfile.write("\n".join(color)) 5 | 6 | content = open('abc.txt') 7 | print(content.read()) 8 | -------------------------------------------------------------------------------- /LostCardProblem.py: -------------------------------------------------------------------------------- 1 | for _ in range(int(input("Enter the number of testcases: "))): 2 | print("\n\n\nWelcome, We will find one of your lost card...") 3 | print("\n1. Series Cards\n2. Random Cards\n3. Exit\n\n") 4 | ch=4 5 | a=0 6 | sum=0 7 | while(ch!=1 and ch!=2 and ch!=3): 8 | print("Please, Press 1, 2 or 3... ") 9 | ch=input() 10 | try: 11 | ch=int(ch) 12 | except: 13 | pass 14 | if(ch==3): 15 | exit() 16 | else: 17 | n=int(input("Enter the total number of cards you had: ")) 18 | if(ch==1): 19 | a=n*(n+1)//2 20 | else: 21 | print("Enter all the",n,"cards you had: ") 22 | for i in range(1,n+1): 23 | a=a+int(input()) 24 | print("Now, enter",n-1,"cards you have now: ") 25 | for i in range(n-1): 26 | sum=sum+int(input()) 27 | print("Lost Card: ",a-sum) 28 | -------------------------------------------------------------------------------- /MatrixMultiplication.py: -------------------------------------------------------------------------------- 1 | # Program to multiply two matrices using nested loops 2 | 3 | # take a 3 by 3 matrix 4 | A = [[1, 2, 3], 5 | [4, 5, 6], 6 | [7, 8, 9]] 7 | 8 | # take a 3 by 4 matrix 9 | B = [[100, 200, 300, 400], 10 | [500, 600, 700, 800], 11 | [900, 1000, 1100, 1200]] 12 | 13 | result = [[0, 0, 0, 0], 14 | [0, 0, 0, 0], 15 | [0, 0, 0, 0]] 16 | 17 | # iterating by row of A 18 | for i in range(len(A)): 19 | 20 | # iterating by coloum by B 21 | for j in range(len(B[0])): 22 | 23 | # iterating by rows of B 24 | for k in range(len(B)): 25 | result[i][j] += A[i][k] * B[k][j] 26 | 27 | for r in result: 28 | print(r) 29 | -------------------------------------------------------------------------------- /Merge Sort.py: -------------------------------------------------------------------------------- 1 | # Merge Sort implementation 2 | # Average Time Complexity is O(nlog(n)) 3 | 4 | # Merges two subarrays of arr[] 5 | # First subarray is arr[l..n] 6 | # Second subarray is arr[n+1..r] 7 | 8 | def merge(arr, l, n, r): 9 | n1 = n - l + 1 10 | n2 = r - n 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays 17 | for i in range(0 , n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0 , n2): 21 | R[j] = arr[n + 1 + j] 22 | 23 | # Merge the temp back into arr[l..r] 24 | i = 0 25 | j = 0 26 | k = l 27 | 28 | while i < n1 and j < n2 : 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | while i < n1: 38 | arr[k] = L[i] 39 | i += 1 40 | k += 1 41 | 42 | # Copy the remaining elements of R[] 43 | while j < n2: 44 | arr[k] = R[j] 45 | j += 1 46 | k += 1 47 | 48 | def mergeSort(arr,l,r): 49 | if l < r: 50 | 51 | # Same as (l+r)//2, but avoids overflow for 52 | # large l and n 53 | n = (l+(r-1))//2 54 | 55 | # Sort first and second halves 56 | mergeSort(arr, l, n) 57 | mergeSort(arr, n+1, r) 58 | merge(arr, l, n, r) 59 | 60 | # Receiving an input from the user 61 | arr = [] 62 | n = int(input("Enter number of elements : ")) 63 | for i in range(0, n): 64 | ele = int(input()) 65 | arr.append(ele) 66 | 67 | # Calling mergeSort function 68 | mergeSort(arr,0,n-1) 69 | print ("\n\nSorted array is") 70 | for i in range(n): 71 | print ("%d" %arr[i]) 72 | -------------------------------------------------------------------------------- /MergeSort.py: -------------------------------------------------------------------------------- 1 | def merge(left_list, right_list): 2 | sorted_list = [] 3 | left_list_index = right_list_index = 0 4 | 5 | left_list_length, right_list_length = len(left_list), len(right_list) 6 | 7 | for _ in range(left_list_length + right_list_length): 8 | if left_list_index < left_list_length and right_list_index < right_list_length: 9 | if left_list[left_list_index] <= right_list[right_list_index]: 10 | sorted_list.append(left_list[left_list_index]) 11 | left_list_index += 1 12 | else: 13 | sorted_list.append(right_list[right_list_index]) 14 | right_list_index += 1 15 | 16 | elif left_list_index == left_list_length: 17 | sorted_list.append(right_list[right_list_index]) 18 | right_list_index += 1 19 | 20 | elif right_list_index == right_list_length: 21 | sorted_list.append(left_list[left_list_index]) 22 | left_list_index += 1 23 | 24 | return sorted_list 25 | 26 | 27 | def merge_sort(nums): 28 | 29 | if len(nums) <= 1: 30 | return nums 31 | 32 | mid = len(nums) // 2 33 | 34 | left_list = merge_sort(nums[:mid]) 35 | right_list = merge_sort(nums[mid:]) 36 | 37 | return merge(left_list, right_list) 38 | A=[] 39 | B=int(input("enter B-")) 40 | n=int(input("enter the number of houses ")) 41 | for i in range(n): 42 | A.append(int(input("enter the cost of the house-"))) 43 | C = merge_sort(A) 44 | su=0 45 | ct=0 46 | while(su 1 : 10 | # check for factors 11 | for x in range(2, user_number): 12 | if (user_number % x) == 0: 13 | print(user_number, "is not a prime number") 14 | print(x, "is a factor of", user_number) 15 | break 16 | else: 17 | print(user_number, "is a prime number!") 18 | 19 | # if entered number is less than or equal to 1, it is not prime 20 | else: 21 | print(user_number, "is not a prime number") -------------------------------------------------------------------------------- /Python program: -------------------------------------------------------------------------------- 1 | #THIS PROGRAMME PRINT HELLO WORLD 2 | print('Hello,World!') 3 | -------------------------------------------------------------------------------- /PythonProgramtoAddTwoNumbers.py: -------------------------------------------------------------------------------- 1 | # Store input numbers 2 | num1 = input('Enter first number: ') 3 | num2 = input('Enter second number: ') 4 | 5 | # Add two numbers 6 | sum = float(num1) + float(num2) 7 | 8 | # Display the sum 9 | print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) 10 | -------------------------------------------------------------------------------- /PythonProgramtoFindNumbersDivisiblebyAnotherNumber: -------------------------------------------------------------------------------- 1 | # Take a list of numbers 2 | my_list = [12, 65, 54, 39, 102, 339, 221,] 3 | 4 | # use anonymous function to filter 5 | result = list(filter(lambda x: (x % 13 == 0), my_list)) 6 | 7 | # display the result 8 | print("Numbers divisible by 13 are",result) 9 | -------------------------------------------------------------------------------- /PythonProgramtoFindtheLargestAmongThreeNumbers: -------------------------------------------------------------------------------- 1 | # Python program to find the largest number among the three input numbers 2 | 3 | # change the values of num1, num2 and num3 4 | # for a different result 5 | num1 = 10 6 | num2 = 14 7 | num3 = 12 8 | 9 | # uncomment following lines to take three numbers from user 10 | #num1 = float(input("Enter first number: ")) 11 | #num2 = float(input("Enter second number: ")) 12 | #num3 = float(input("Enter third number: ")) 13 | 14 | if (num1 >= num2) and (num1 >= num3): 15 | largest = num1 16 | elif (num2 >= num1) and (num2 >= num3): 17 | largest = num2 18 | else: 19 | largest = num3 20 | 21 | print("The largest number is", largest) 22 | -------------------------------------------------------------------------------- /QueueUsingList.py: -------------------------------------------------------------------------------- 1 | try: #try catch so that the program does not crash 2 | queue=[] 3 | 4 | while True: 5 | op = int(input("Press--> 1 to insert into queue | 2 to remove from queue | 3 to display values of queue | 4 to reverse the exisiting queue| 5 to exit ")) 6 | if op==1: #to insert an elelment in the queue 7 | ele = int(input("enter elem to insert ")) 8 | queue.append(ele) 9 | elif op==2: #to remove an element from the queue 10 | if len(queue) ==0: 11 | print("The queue is empty, insert values if required") 12 | else: 13 | ele=queue.pop(0) 14 | print(ele) 15 | elif op==3: #to display the elements in the queue 16 | print(queue) 17 | elif op==4: #to reverse queue 18 | queue.reverse() 19 | elif op==5: #to exit 20 | break 21 | else: 22 | print("invalid option") 23 | 24 | except ValueError: 25 | print("Please enter integer only") #If user inputs an alphabet or string the program should not crash 26 | except: 27 | print("There's been some issue please check the data you've entered") 28 | 29 | -------------------------------------------------------------------------------- /Quick_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Quicksort Sort 2 | 3 | # This function takes last element as pivot, places 4 | # the pivot element at its correct position in sorted 5 | # array, and places all smaller (smaller than pivot) 6 | # to left of pivot and all greater elements to right 7 | # of pivot 8 | 9 | 10 | def partition(arr, low, high): 11 | i = (low-1) # index of smaller element 12 | pivot = arr[high] # pivot 13 | 14 | for j in range(low, high): 15 | 16 | # If current element is smaller than or 17 | # equal to pivot 18 | if arr[j] <= pivot: 19 | 20 | # increment index of smaller element 21 | i = i+1 22 | arr[i], arr[j] = arr[j], arr[i] 23 | 24 | arr[i+1], arr[high] = arr[high], arr[i+1] 25 | return (i+1) 26 | 27 | # The main function that implements QuickSort 28 | # arr[] --> Array to be sorted, 29 | # low --> Starting index, 30 | # high --> Ending index 31 | 32 | # Function to do Quick sort 33 | 34 | 35 | def quickSort(arr, low, high): 36 | if len(arr) == 1: 37 | return arr 38 | if low < high: 39 | 40 | # pi is partitioning index, arr[p] is now 41 | # at right place 42 | pi = partition(arr, low, high) 43 | 44 | # Separately sort elements before 45 | # partition and after partition 46 | quickSort(arr, low, pi-1) 47 | quickSort(arr, pi+1, high) 48 | 49 | 50 | # Driver code to test above 51 | arr = [10, 7, 8, 9, 1, 5] 52 | n = len(arr) 53 | quickSort(arr, 0, n-1) 54 | print("Sorted array is:") 55 | for i in range(n): 56 | print("%d" % arr[i]), 57 | 58 | # This code is contributed by Mohit Kumra 59 | #This code in improved by https://github.com/anushkrishnav 60 | -------------------------------------------------------------------------------- /Quicksort.py: -------------------------------------------------------------------------------- 1 | # function to partition the list 2 | def partition(arr, low, high): 3 | i = low - 1 4 | pivot = arr[high] # pivot element 5 | 6 | for j in range(low, high): 7 | # If current element is smaller than the pivot, swap the element with pivot 8 | if arr[j] <= pivot: 9 | i = i + 1 10 | # swapping the elements 11 | arr[i], arr[j] = arr[j], arr[i] 12 | 13 | arr[i + 1], arr[high] = arr[high], arr[i + 1] 14 | return i + 1 15 | 16 | 17 | # sorting the partitioned lists 18 | def quickSort(arr, low, high): 19 | if low < high: 20 | # pi is partitioning index, arr[pi] is now at correct place in sorted array 21 | pi = partition(arr, low, high) 22 | # sort the partitions 23 | 24 | quickSort(arr, low, pi - 1) 25 | quickSort(arr, pi + 1, high) 26 | 27 | 28 | # driver function 29 | if __name__ == "__main__": 30 | arr = [12, 5, 30, 8, 16, 3, 14, 7] 31 | n = len(arr) 32 | quickSort(arr, 0, n - 1) 33 | print("Sorted array is:") 34 | for i in range(n): 35 | print(arr[i], end=" ") 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simplePythonProgram 2 | 3 | This repo contains the following files: 4 | - `Bubble Sort_2.py`: a bubble sort program. 5 | - `BubbleSort.py`: another bubble sort program. 6 | - `Merge Sort.py`: a merge sort implementation program with user-received input. 7 | - `Fibonacci.py`: a program that takes number of digits given as input and generates a Fibonacci Sequence based on input. 8 | - `README.md`: this file. 9 | - `helloworld.py`: a simple hello world program. 10 | - `greet.py` : a simple program that requests user name and greets them with a specfic message. 11 | - `spam.py`: a simple program to give spam message to anyone 12 | - `Quick_sort.py`: quick sort program 13 | 14 | 15 | To run spam.py install pyautogui 16 |
17 | pip install pyautogui
18 | 
19 | -------------------------------------------------------------------------------- /RSA_algorithm.py: -------------------------------------------------------------------------------- 1 | from decimal import Decimal 2 | 3 | def gcd(a,b): 4 | if b==0: 5 | return a 6 | else: 7 | return gcd(b,a%b) 8 | p = int(input('Enter the value of p = ')) 9 | q = int(input('Enter the value of q = ')) 10 | no = int(input('Enter the value of text = ')) 11 | n = p*q 12 | t = (p-1)*(q-1) 13 | 14 | for e in range(2,t): 15 | if gcd(e,t)== 1: 16 | break 17 | 18 | 19 | for i in range(1,10): 20 | x = 1 + i*t 21 | if x % e == 0: 22 | d = int(x/e) 23 | break 24 | ctt = Decimal(0) 25 | ctt =pow(no,e) 26 | ct = ctt % n 27 | 28 | dtt = Decimal(0) 29 | dtt = pow(ct,d) 30 | dt = dtt % n 31 | 32 | print('n = '+str(n)+' e = '+str(e)+' t = '+str(t)+' d = '+str(d)+' cipher text = '+str(ct)+' decrypted text = '+str(dt)) 33 | -------------------------------------------------------------------------------- /ReverseString.py: -------------------------------------------------------------------------------- 1 | def rev_string(s): 2 | a=s[::-1] 3 | return a 4 | 5 | s1=input("enter the string ") 6 | r1=rev_string(s1) 7 | 8 | print(r1) -------------------------------------------------------------------------------- /SelectionSort.py: -------------------------------------------------------------------------------- 1 | # Selection sort is a sorting function that finds the minimum element 2 | # from the unsorted part of the array(i.e right) and moves it to the 3 | # sorted part the array(i.e left) 4 | 5 | def selectionSort(arr): 6 | for i in range(len(arr)-1): 7 | #initially we take i as index that has the minimum value 8 | min = i 9 | #then we search the part of the array after this index 10 | for j in range(i+1, len(arr)): 11 | #if we find an index whose value is less than that at min then 12 | if arr[j] 0: 6 | 7 | for i in range(gap, len(inpList)): 8 | temp = inpList[i] 9 | j = i 10 | 11 | while j >= gap and inpList[j - gap] > temp: 12 | inpList[j] = inpList[j - gap] 13 | j = j-gap 14 | inpList[j] = temp 15 | 16 | gap = gap//2 17 | 18 | 19 | -------------------------------------------------------------------------------- /Silver_Project_RockPaperSciss.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def getUserInput(): 5 | player = 'blank' 6 | while player.lower() != 'r' and player.lower() != 'p' and player.lower() != 's': 7 | player = input("\n\nEnter your valid choice from R,P or S: ").lower() 8 | return player 9 | 10 | 11 | def getSystemInput(): 12 | lst = ['r', 'p', 's'] 13 | bot = random.choice(lst) 14 | return bot 15 | 16 | 17 | def checkWinner(player, bot): 18 | if player == bot: # If both player and bot choose the same 19 | return 'draw' 20 | elif player == 'r' and bot == 'p': 21 | return 'bot' 22 | elif player == 'r' and bot == 's': 23 | return 'player' 24 | elif player == 'p' and bot == 'r': 25 | return 'player' 26 | elif player == 'p' and bot == 's': 27 | return 'bot' 28 | elif player == 's' and bot == 'r': 29 | return 'bot' 30 | elif player == 's' and bot == 'p': 31 | return 'player' 32 | 33 | 34 | def rockPaperScissor(): 35 | resume = 'y' 36 | player_score = 0 37 | bot_score = 0 38 | while resume.lower() == 'y': 39 | ply = getUserInput() 40 | bt = getSystemInput() 41 | print('Bot Entered - ', bt) 42 | print('You Entered - ', ply) 43 | winner = checkWinner(ply, bt) 44 | print('Winner is - ', winner) 45 | if winner == 'player': 46 | player_score += 1 47 | elif winner == 'bot': 48 | bot_score += 1 49 | print("\n\n------ScoreCard------") 50 | print("Player:", player_score) 51 | print("Bot:", bot_score) 52 | resume = input("\n\nDO YOU WANT TO CONTINUE THE GAME!? Press y : ") 53 | 54 | 55 | rockPaperScissor() 56 | -------------------------------------------------------------------------------- /Simple_Calculator.py: -------------------------------------------------------------------------------- 1 | # Program make a simple calculator 2 | 3 | # This function adds two numbers 4 | def add(x, y): 5 | return x + y 6 | 7 | # This function subtracts two numbers 8 | def subtract(x, y): 9 | return x - y 10 | 11 | # This function multiplies two numbers 12 | def multiply(x, y): 13 | return x * y 14 | 15 | # This function divides two numbers 16 | def divide(x, y): 17 | return x / y 18 | 19 | 20 | print("Select operation.") 21 | print("1.Add") 22 | print("2.Subtract") 23 | print("3.Multiply") 24 | print("4.Divide") 25 | 26 | while True: 27 | # Take input from the user 28 | choice = input("Enter choice(1/2/3/4): ") 29 | 30 | # Check if choice is one of the four options 31 | if choice in ('1', '2', '3', '4'): 32 | num1 = float(input("Enter first number: ")) 33 | num2 = float(input("Enter second number: ")) 34 | 35 | if choice == '1': 36 | print(num1, "+", num2, "=", add(num1, num2)) 37 | 38 | elif choice == '2': 39 | print(num1, "-", num2, "=", subtract(num1, num2)) 40 | 41 | elif choice == '3': 42 | print(num1, "*", num2, "=", multiply(num1, num2)) 43 | 44 | elif choice == '4': 45 | print(num1, "/", num2, "=", divide(num1, num2)) 46 | break 47 | else: 48 | print("Invalid Input") 49 | 50 | -------------------------------------------------------------------------------- /SineTaylorSeries.py: -------------------------------------------------------------------------------- 1 | def fact(x): 2 | if x==0 or x==1: 3 | return 1 4 | else: 5 | return x*fact(x-1) 6 | def sin(x,n): 7 | power=1 8 | sign=1 9 | s=0 10 | for i in range(n): 11 | s=s+(sign*(x**power)/fact(power)) 12 | power=power+2 13 | sign=sign*-1 14 | return s 15 | print("This program will calculate value of sinx using taylor series upto n terms: ") 16 | x=float(input("Enter the value of x: ")) 17 | n=int(input("Enter the value of n: ")) 18 | print("Calculating...") 19 | print("Value of sinx upto n-terms using taylor series is: ",sin(x,n)) 20 | -------------------------------------------------------------------------------- /Stack.py: -------------------------------------------------------------------------------- 1 | stack=[] 2 | try: 3 | while True: 4 | op = int(input("1 push 2 pop 3 display 4 exit")) 5 | if op==1: 6 | ele = int(input("enter elem to push ")) 7 | stack.append(ele) 8 | elif op==2: 9 | if len(stack) ==0: 10 | print("empty hai stack ") 11 | else: 12 | ele=stack.pop() 13 | print("popped elements ") 14 | elif op==3: 15 | print(stack) 16 | elif op==4: 17 | break 18 | else: 19 | print("invalid option") 20 | -------------------------------------------------------------------------------- /StackUsingList.py: -------------------------------------------------------------------------------- 1 | #LIFO 2 | 3 | stack=[] 4 | try: #try except so that the program does not crash[optional] 5 | while True: 6 | op = int(input("Select---> 1 to push, 2 to pop top most element, 3 to display elements in stack,4 to peek,5 to exit ")) 7 | if op==1: #to push into stack 8 | ele = int(input("enter elem to push ")) 9 | stack.append(ele) 10 | elif op==2: #to pop from stack. If stack is empty it will display "Stack is empty" 11 | if len(stack) ==0: 12 | print("Stack is empty ") 13 | else: 14 | ele=stack.pop() 15 | print("popped element ",ele) 16 | elif op==3: #TO display stack elements and print "Stack is empty " if there are no elements 17 | if len(stack) ==0: 18 | print("Stack is empty ") 19 | else: 20 | print(stack) 21 | elif op==4: #To peek at stack top. i.e see the topmost element 22 | if len(stack) ==0: 23 | print("Stack is empty ") 24 | else: 25 | print(stack[-1]) 26 | elif op==5: #To exit from loop 27 | break 28 | else: 29 | print("invalid option") 30 | except ValueError: 31 | print("Please enter integer only") #If user inputs an alphabet or string the program should not crash 32 | except: 33 | print("There's been some issue please check the data you've entered") -------------------------------------------------------------------------------- /TimSort.py: -------------------------------------------------------------------------------- 1 | def timsort(array): 2 | min_run = 32 3 | n = len(array) 4 | 5 | # Start by slicing and sorting small portions of the 6 | # input array. The size of these slices is defined by 7 | # your `min_run` size. 8 | for i in range(0, n, min_run): 9 | insertion_sort(array, i, min((i + min_run - 1), n - 1)) 10 | 11 | # Now you can start merging the sorted slices. 12 | # Start from `min_run`, doubling the size on 13 | # each iteration until you surpass the length of 14 | # the array. 15 | size = min_run 16 | while size < n: 17 | # Determine the arrays that will 18 | # be merged together 19 | for start in range(0, n, size * 2): 20 | # Compute the `midpoint` (where the first array ends 21 | # and the second starts) and the `endpoint` (where 22 | # the second array ends) 23 | midpoint = start + size - 1 24 | end = min((start + size * 2 - 1), (n-1)) 25 | 26 | # Merge the two subarrays. 27 | # The `left` array should go from `start` to 28 | # `midpoint + 1`, while the `right` array should 29 | # go from `midpoint + 1` to `end + 1`. 30 | merged_array = merge( 31 | left=array[start:midpoint + 1], 32 | right=array[midpoint + 1:end + 1]) 33 | 34 | # Finally, put the merged array back into 35 | # your array 36 | array[start:start + len(merged_array)] = merged_array 37 | 38 | # Each iteration should double the size of your arrays 39 | size *= 2 40 | 41 | return array 42 | -------------------------------------------------------------------------------- /Transpose_Matrix.py: -------------------------------------------------------------------------------- 1 | rows = int(input("Enter the Number of rows : " )) 2 | column = int(input("Enter the Number of Columns: ")) 3 | 4 | print("Enter the elements of Matrix:") 5 | matrix= [[int(input()) for i in range(column)] for i in range(rows)] 6 | print("Matrix") 7 | for n in matrix: 8 | print(n) 9 | 10 | 11 | result =[[0 for i in range(rows)] for j in range(column)] 12 | 13 | for r in range(rows): 14 | for c in range(column): 15 | result[c][r] = matrix[r][c] 16 | 17 | print("Transpose matrix is: ") 18 | for r in result: 19 | print(r) 20 | -------------------------------------------------------------------------------- /UppertoLower and LowertoUppercase.py: -------------------------------------------------------------------------------- 1 | s = "Hello" 2 | for x in range(len(s)): 3 | if(s[x].isupper()): 4 | print(s[x].lower()) 5 | else: 6 | print(s[x].upper()) 7 | -------------------------------------------------------------------------------- /WakeOnLan.py: -------------------------------------------------------------------------------- 1 | """" 2 | Send Magic Package for Wake on Lan 3 | """" 4 | 5 | import socket 6 | import struct 7 | 8 | # insert correct MAC address 9 | MAC = 'FF:FF:FF:FF:FF:FF' 10 | 11 | MAC = MAC.replace(':','') 12 | 13 | magic_packet = ''.join(['FF' * 6, MAC * 16]) 14 | 15 | send_data = b'' 16 | for i in range(0, len(magic_packet), 2): 17 | send_data = b''.join([send_data, struct.pack('B', int(magic_packet[i: i + 2], 16))]) 18 | 19 | soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 20 | soc.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 21 | soc.sendto(send_data, ("255.255.255.255", 9)) 22 | 23 | 24 | -------------------------------------------------------------------------------- /age_in_days.py: -------------------------------------------------------------------------------- 1 | """ project for final week done with basic course """ 2 | import datetime 3 | # would help in finding no.of days 4 | def days_in_month(yeara,montha): 5 | if(montha==2 and yeara%4==0): 6 | days=29 7 | elif(montha==2 and yeara%4!=0): 8 | days=28 9 | elif(montha<=7 and montha%2 !=0): 10 | days=31 11 | elif(montha<=7 and montha%2 ==0): 12 | days=30 13 | elif(montha>7 and montha%2 ==0): 14 | days=31 15 | else: 16 | days=30 17 | return days 18 | def is_valid_date(yearb,monthb,dateb): # help in checking a valid date 19 | 20 | if( 1<=yearb<=9999)and(1<=monthb<=12)and(1<=dateb <= days_in_month(yearb,monthb)): 21 | return True 22 | else : 23 | return False 24 | def days_between(year,month,date,year1,month1,date1): 25 | # help in checking a valid date 26 | if(is_valid_date(year,month,date))and(is_valid_date(year1,month1,date1)) : 27 | difference=0 28 | else : 29 | return 0 30 | date11=datetime.date(year,month,date) 31 | date22=datetime.date(year1,month1,date1) 32 | difference = date22-date11 33 | if(difference.days>0): 34 | return difference.days 35 | else: 36 | return 0 37 | def age_in_days(yearc,monthc,datec): 38 | # help in checking a valid date 39 | if(is_valid_date(yearc,monthc,datec)): 40 | difference=0 41 | else: 42 | return 0 43 | todays_date=datetime.date.today() 44 | date33=datetime.date(yearc,monthc,datec) 45 | difference=todays_date-date33 46 | if(difference.days>0): 47 | age=difference.days 48 | else : 49 | age= 0 50 | return age -------------------------------------------------------------------------------- /algorithms/LinkedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Tanseer Saji 3 | Desc: An Implementation of Linked List Data Structure 4 | """ 5 | 6 | 7 | class Node: 8 | def __init__(self, val=0, next=None) -> None: 9 | self.val = val 10 | self.next = next 11 | 12 | 13 | def search(root, val) -> bool: 14 | ptr = root 15 | while ptr: 16 | if ptr.val == val: 17 | return True 18 | ptr = ptr.next 19 | return False 20 | 21 | 22 | def traverse(root) -> None: 23 | ptr = root 24 | while ptr: 25 | print(ptr.val) 26 | ptr = ptr.next 27 | 28 | 29 | def insert(root, val) -> None: 30 | ptr = root 31 | while ptr.next: 32 | ptr = ptr.next 33 | ptr.next = Node(val) 34 | 35 | 36 | def delete(root, val) -> None: 37 | ptr = root 38 | if ptr.val == val: 39 | root = ptr.next 40 | ptr = None 41 | return 42 | 43 | prev = None 44 | while ptr: 45 | if ptr.val == val: 46 | break 47 | prev = ptr 48 | ptr = ptr.next 49 | if not ptr: 50 | return 51 | 52 | prev.next = ptr.next 53 | ptr = None 54 | 55 | 56 | if __name__ == "__main__": 57 | llist = Node(0) 58 | for i in range(1, 10): 59 | insert(llist, i) 60 | delete(llist, 1) 61 | traverse(llist) 62 | -------------------------------------------------------------------------------- /algorithms/Queues.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Jay Paliwal 3 | Desc: And implementation of the Queue data structure using arrays. 4 | """ 5 | class Queue: 6 | def __init__(self,size): 7 | self.size=size 8 | self.q=[] 9 | self.front=-1 10 | self.rear=-1 11 | def enqueue(self): 12 | if self.rear==(self.size-1): 13 | print("Queue Full") 14 | else: 15 | val=int(input("Enter the value to be enqueued: ")) 16 | self.q.append(val) 17 | self.rear+=1 18 | if self.front==-1: 19 | self.front=0 20 | 21 | def dequeue(self): 22 | if self.rear<0 or self.rear=self.size-1: 15 | print("Stack overflow") 16 | else: 17 | val=int(input("Enter the value to be pushed: ")) 18 | self.top+=1 19 | self.stack.insert(0,val) 20 | 21 | def pop(self): 22 | if self.top<=-1: 23 | print("Stack underflow") 24 | else: 25 | self.top-=1 26 | print("Popped element: ",self.stack.pop(0)) 27 | 28 | def peek(self): 29 | if self.top==-1: 30 | print("Stack empty") 31 | else: 32 | print("Elemet at the top is: ",self.stack[0]) 33 | 34 | def display(self): 35 | if self.top==-1: 36 | print("Stack emppty.") 37 | else: 38 | print("The stack elements are: ",*self.stack) 39 | 40 | def empty(self): 41 | if self. top==-1: 42 | print("Stack is already empty") 43 | else: 44 | print("The elements deleted from the stack are: ",*self.stack) 45 | self.top=-1 46 | 47 | 48 | stack_size=int(input("Enter the size of the Stack: ")) 49 | stk=Stack(stack_size) 50 | while True: 51 | fn=input("\nMenu:\n1. Enter 'push' to push new element\n2. Enter 'pop' to pop top element\n3. Enter 'peek' to view top elemnt\n4. Enter 'display' to display all elemts of stack\n5 Enter 'empty' to display current stack elemets and clear the stack\n6. Enter 'exit' to end program\n") 52 | print("\n") 53 | if fn=="exit": 54 | break 55 | elif fn=="push": 56 | stk.push() 57 | elif fn=="pop": 58 | stk.pop() 59 | elif fn=="peek": 60 | stk.peek() 61 | elif fn=="display": 62 | stk.display() 63 | elif fn=="empty": 64 | stk.empty() 65 | else: 66 | print("Enter a valid input") 67 | 68 | 69 | -------------------------------------------------------------------------------- /dice_roller.py: -------------------------------------------------------------------------------- 1 | """The purpose of this program is to roll a quantity number of die type dice and provide the user with the results""" 2 | import random 3 | 4 | die = input("What die type (default is d6): ") or "d6" #Promtps user for the type of die to roll or defaults to a six sided die 5 | quantity = input("How many (default is 1): ") or 1 #Prompts user for the number of dice to roll or defaults to 1 6 | quantity = int(quantity) #Changes the user provided information (a string) into an integer for use in the range call in the for loop. 7 | total = 0 #Set total to 0 8 | 9 | #There is probably a more eliegant way to do this but I don't know how 10 | if die == "d4": 11 | sides = 4 12 | elif die == "d6": 13 | sides = 6 14 | elif die == "d10": 15 | sides = 10 16 | elif die == "d12": 17 | sides = 12 18 | elif die == "d20": 19 | sides = 20 20 | elif die == "d100": 21 | sides = 100 22 | else: 23 | print("That is not a die type") 24 | 25 | for i in range(0, quantity): #Iterates through the quantity of dice to be rolled and dieplays their individual results 26 | result = (random.randint(1, sides)) 27 | print(i+1, die, " = ", result) 28 | total += result 29 | print("This is the result of your roll: ", total) 30 | -------------------------------------------------------------------------------- /djikstras_shortest_path.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Jay Paliwal 3 | Desc: Implementation fo graph using adjecency matrix and calculation 4 | of the length of the shortest path using dijkstra's algorithm 5 | """ 6 | 7 | import sys 8 | 9 | class Graph: 10 | def __init__(self,vertices): 11 | self.vertices=vertices 12 | self.graph=[[0]*vertices]*vertices 13 | 14 | def add_edge(self,v1,v2,wt): 15 | self.graph[v1][v2]=wt 16 | self.graph[v2][v1]=wt 17 | 18 | def dijkstra(self,src,dest): 19 | d=[sys.maxsize]*self.vertices 20 | d[src]=0 21 | shrtst_pth=[False]*self.vertices 22 | for _ in range(self.vertices): 23 | min=sys.maxsize 24 | for i in range(self.vertices): 25 | if d[i]0 and shrtst_pth[v2]==False and d[v2]>(d[v1]+self.graph[v1][v2]): 31 | d[v2]=d[v1]+self.graph[v1][v2] 32 | print("The length of the shortest path between ",src," and ",dest," is: ",d[dest] 33 | 34 | v=int(input("Enter the number of vertices: ")) 35 | g=Graph(v) 36 | c='1' 37 | while True: 38 | c=input("Enter '1' to add a new edge, enter '0' if you are done adding edges: ") 39 | if c!='0' or c!='1': 40 | print("Invalid input") 41 | continue 42 | elif c=='0': 43 | break 44 | a=int(input("Enter first vertex: ")) 45 | b=int(input("Enter second vertex: ")) 46 | if a>=v or a<0: 47 | print("Invalid value entered for first vertex") 48 | continue 49 | if b>=v or b<0: 50 | print("Invalid value entered for second vertex") 51 | continue 52 | wt=int(input("Enter the weight of the edge: ")) 53 | g.add_edge(a,b,wt) 54 | 55 | while True: 56 | src,dest=map(int,input("Enter the source and destination vertex to calculate the shorthest path (source followed by destination): ").rstrip().split()) 57 | if (src>=0 and src=0 and dest guess: 14 | print("You guessed too small!") 15 | elif x < guess: 16 | print("You Guessed too high!") 17 | 18 | if count >= 5: 19 | print("\nThe number is %d"%x) 20 | print("\tBetter Luck Next time!") 21 | -------------------------------------------------------------------------------- /helloworld: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | -------------------------------------------------------------------------------- /helloworld.py: -------------------------------------------------------------------------------- 1 | # Print Condition 2 | print("Hello World") 3 | 4 | 5 | -------------------------------------------------------------------------------- /kadanealgorithm.cpp: -------------------------------------------------------------------------------- 1 | /*Implementing Kadane's algorithm -finding the largest sum of a subarray in an array*/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int n;//to store array size 8 | int s=0;//storing sum of a subarray 9 | int max=-2147483648;//storing maximum sum of a subarray 10 | cin>>n; //Entering array size 11 | int a[n+1]; 12 | for(int i=0;i>a[i];} 14 | 15 | for(int i=0;imax) 20 | max=s; 21 | } 22 | cout< to < in this line. 12 | if array[j] > array[j + 1]: 13 | 14 | # Swap if greater is at the rear position 15 | (array[j], array[j + 1]) = (array[j + 1], array[j]) 16 | swapped = False 17 | 18 | # If there is not swapping in the last swap, then the array is already sorted. 19 | if swapped: 20 | break 21 | 22 | 23 | data = [-2, 45, 0, 11, -9] 24 | bubbleSort(data) 25 | print('Sorted Array in Ascending Order:') 26 | print(data) 27 | -------------------------------------------------------------------------------- /palindrome_and_armstrong_check.py: -------------------------------------------------------------------------------- 1 | def palindrome(inp): 2 | if inp==inp[::-1]: #reverse the string and check 3 | print("Yes, {} is palindrome ".format(inp)) 4 | else: 5 | print("No, {} is not palindrome ".format(inp)) 6 | 7 | 8 | def armstrong(number): 9 | num=number 10 | length=len(str(num)) 11 | total=0 12 | while num>0: 13 | temp=num%10 14 | total=total+(temp**length) #powering each digit with length of number and adding 15 | num=num//10 16 | if total==number: 17 | print("{} is Armstrong number".format(number) ) 18 | else: 19 | print("{} is not an Armstrong number".format(number) ) 20 | 21 | palindrome('qwerewq') 22 | armstrong(407) 23 | -------------------------------------------------------------------------------- /rock.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | gameplay=['Rock','Paper','scissors'] 3 | n=3 4 | Computer=gameplay[randint(0,2)] 5 | Player=False 6 | YourScore=0 7 | ComputerScore=0 8 | i=0 9 | while i 0): 8 | d = temp % 10 9 | f = 1 10 | while(d > 0): 11 | f = f * d 12 | d -= 1 13 | sum += f 14 | temp = temp // 10 15 | if sum == num: 16 | print("%d is a Strong Number" %(num)) 17 | else: 18 | print("%d is NOT a Strong Number" %(num)) 19 | -------------------------------------------------------------------------------- /temperature.py: -------------------------------------------------------------------------------- 1 | celsius = 37.5 2 | fahrenheit = (celsius*1.8)+32 3 | print('%0.1f degree Celsius is equal to %0.1f degree fahrenheit'%(celsius,fahrenheit)) -------------------------------------------------------------------------------- /tranaslator_gui.py: -------------------------------------------------------------------------------- 1 | 2 | from googletrans import Translator 3 | import pyttsx3 4 | import tkinter as tk 5 | 6 | root=tk.Tk() 7 | root.geometry("800*400") 8 | root.title("Translator") 9 | en=tk.StringVar() 10 | 11 | def trans(): 12 | global speech 13 | x=en.get() 14 | translator = Translator() 15 | translated = translator.translate(x) 16 | speech = translated.text 17 | T.insert('end',speech) 18 | 19 | def speak(): 20 | engine = pyttsx3.init() 21 | engine.say(speech) 22 | engine.runAndWait() 23 | label = tk.Label(root,text="Text").grid(row=0,column=0) 24 | label2 = tk.Label(root,text="Output:").grid(row=3,column=0) 25 | entry = tk.Entry(root,textvariable=en).grid(row=0,column=1,padx=5,pady=10,ipadx=150,ipady=20) 26 | 27 | 28 | T = tk.Text(root, height=30,width=30) 29 | T.grid(row=4,column=1,padx=5,pady=10,ipadx=30,ipady=10) 30 | button=tk.Button(root,text="Translate",fg="Red",bg="Black",command=tran).grid(row=1,column=0,padx=10,pady=10,ipadx=30,ipady=10) 31 | button2=tk.Button(root,text="Speak",fg="Red",bg="Black",command=speak).grid(row=4,column=1,padx=10,pady=10,ipadx=30,ipady=10) 32 | root.mainloop() 33 | --------------------------------------------------------------------------------