diff --git a/Programs/P02_VariableScope.py b/Programs/P02_VariableScope.py index 505eb22..a85c8bd 100644 --- a/Programs/P02_VariableScope.py +++ b/Programs/P02_VariableScope.py @@ -10,7 +10,9 @@ def test(): y = 100 # Local y x = 20 print(x + y) #prints 'Local x' and 'Local y' + print("Variable scope") if __name__ == '__main__': test() print(x) #prints 'Global x' + \ No newline at end of file diff --git a/Test001/P10_LCM.py b/Test001/P10_LCM.py new file mode 100644 index 0000000..aa1f5bd --- /dev/null +++ b/Test001/P10_LCM.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program calculates the LCM of the two numbers entered by the user + +def LCM(number1, number2): + '''This function calculates LCM of two numbers inputed by the user''' + maximum = max(number1, number2) + i = maximum + while True: + if (i % number1 == 0 and i % number2 == 0): + lcm = i + break + i += maximum + + return lcm + +if __name__ == '__main__': + userInput1 = int(input('Enter first number: ')) + userInput2 = int(input('Enter second number: ')) + print('LCM of {} and {} is {}'.format( userInput1, userInput2, LCM(userInput1, userInput2))) diff --git a/Test001/P11_BinaryToDecimal.py b/Test001/P11_BinaryToDecimal.py new file mode 100644 index 0000000..7304c79 --- /dev/null +++ b/Test001/P11_BinaryToDecimal.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program converts the given binary number to its decimal equivalent + +def binaryToDecimal(binary): + '''This function calculates the decimal equivalent to given binary number''' + binary1 = binary + decimal, i, n = 0, 0, 0 + while(binary != 0): + dec = binary % 10 + decimal = decimal + dec * pow(2, i) + binary = binary//10 + i += 1 + print('Decimal equivalent of {} is {}'.format(binary1, decimal)) + +if __name__ == '__main__': + userInput = int(input('Enter the binary number to check its decimal equivalent: ')) + binaryToDecimal(userInput) diff --git a/Test001/P12_DecimalToBinary.py b/Test001/P12_DecimalToBinary.py new file mode 100644 index 0000000..c1be53c --- /dev/null +++ b/Test001/P12_DecimalToBinary.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#Program to convert decimal to its equivalent binary + +def decimalToBinary(n): + '''Function to print binary number for the input decimal using recursion''' + if n > 1: + decimalToBinary(n//2) + print(n % 2,end = '') + +if __name__ == '__main__': + userInput = int(input('Enter the decimal number to find its binary equivalent: ')) + decimalToBinary(userInput) + print() diff --git a/Test001/P13_Palindrome.py b/Test001/P13_Palindrome.py new file mode 100644 index 0000000..6d5aba8 --- /dev/null +++ b/Test001/P13_Palindrome.py @@ -0,0 +1,14 @@ +#Author: OMKAR PATHAK +#This program checks for the palindrome + +def palindrome(string): + '''This function checks the string for palindrome''' + revString = string[::-1] + if string == revString: + print('String is Palindrome') + else: + print('String is not Palindrome') + +if __name__ == '__main__': + userInput = str(input('Enter a string to check for Palindrome: ')) + palindrome(userInput) diff --git a/Test001/P14_CheckGreater.py b/Test001/P14_CheckGreater.py new file mode 100644 index 0000000..88f74b6 --- /dev/null +++ b/Test001/P14_CheckGreater.py @@ -0,0 +1,15 @@ +#Author: OMKAR PATHAK +#This prpgram checks that the given number is greater than all those numbers in th list + +def checkGreater(number): + '''This function checks whether the entered number is greater than those in the list''' + original = [1,2,3,4,5] + original.sort() + if number > original[-1]: + print('Yes, the entered number is greater than those in the list') + else: + print('No, entered number is less than those in the list') + +if __name__ == '__main__': + userInput = int(input('Enter the number to check: ')) + checkGreater(userInput) diff --git a/Test001/P15_Arguments.py b/Test001/P15_Arguments.py new file mode 100644 index 0000000..cd51cf3 --- /dev/null +++ b/Test001/P15_Arguments.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program gives a demo of how can you pass arguments while running python programs +#Run the program as: python P15_Arguments.py Omkar Pathak + +import sys + +def arguments(): + '''This function prints the argruments passed while running the python program''' + try: + print('This is the name of the script:', sys.argv[0]) + print('First argument:', sys.argv[1]) + print('Second argument:', sys.argv[2]) + except IndexError: + print('Give only two arguments') + +if __name__ == '__main__': + arguments() diff --git a/Test001/P16_CountVowels.py b/Test001/P16_CountVowels.py new file mode 100644 index 0000000..9b0c691 --- /dev/null +++ b/Test001/P16_CountVowels.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program counts the vowels present in the user input + +def countVowels(sentence): + '''This function counts the vowels''' + count = 0 + sentence = sentence.lower() + for c in sentence: + if c in ['a', 'e', 'i', 'o', 'u']: + count += 1 + return count + + +if __name__ == '__main__': + userInput = str(input("Enter the string to check for vowels: ")) + count = countVowels(userInput) + print('Vowel Count: ',count) diff --git a/Test001/P17_EvenOdd.py b/Test001/P17_EvenOdd.py new file mode 100644 index 0000000..b69a47f --- /dev/null +++ b/Test001/P17_EvenOdd.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program takes input from user and sorts the numbers in two arrays, one of even and other of odd + +def evenOdd(numbers): + '''This function divides the numbers in two arrays one of even and other of odd''' + even = [] + odd = [] + for number in numbers: + if int(number) % 2 == 0: + even.append(number) + else: + odd.append(number) + return even, odd + +if __name__ == '__main__': + userInput = input("Enter the numbers (space separated) to check: ") + userInput = list(userInput.split()) + even, odd = evenOdd(userInput) + print('Even Nos: ', ','.join(even), '\n', 'Odd Nos: ', ','.join(odd)) diff --git a/Test001/P18_Logging.py b/Test001/P18_Logging.py new file mode 100644 index 0000000..64acae3 --- /dev/null +++ b/Test001/P18_Logging.py @@ -0,0 +1,22 @@ +#Author: OMKAR PATHAK +#This program illustrates a logging example +import logging + +def log(number): + ''' This function creates a log file if any error is reported ''' + logging.basicConfig(filename = 'P18-logfile.txt', level = logging.INFO) + try: + if int(number) % 2 == 0: + print('Successful') + else: + print('Unsuccessful, this instance will be reported, check the log file') + logging.info('Invalid Entry') + except: + print('Please enter a valid integer') + +if __name__ == '__main__': + try: + userInput = int(input('Enter a number: ')) + log(userInput) + except: + print('Please enter a valid integer') diff --git a/Test001/P19_SimpleStopWatch.py b/Test001/P19_SimpleStopWatch.py new file mode 100644 index 0000000..bbbff67 --- /dev/null +++ b/Test001/P19_SimpleStopWatch.py @@ -0,0 +1,45 @@ +#Author: OMKAR PATHAK +#This program illustrates a stopwatch + +import time + +print('Press ENTER to begin, Press Ctrl + C to stop') +while True: + try: + input() #For ENTER + starttime = time.time() + print('Started') + except KeyboardInterrupt: + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break +# Press enter to start and stop the watch +""" +import time + +print('Press Enter to begin, Press Enter again to stop') +if input()=='': + starttime = time.time() + print('Started') + while True: + val=input() #For ENTER + if val=='': + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break + +""" + +""" +Output: +Press Enter to begin, Press Enter again to stop + +Started + +Stopped +Total Time: 1.05 secs + +""" + diff --git a/Test001/P20_OsModule.py b/Test001/P20_OsModule.py new file mode 100644 index 0000000..3c2a771 --- /dev/null +++ b/Test001/P20_OsModule.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#This program illustrates the example for os module in short + +import os +import time + +print(os.getcwd()) #Prints the current working directory + +os.mkdir('newDir1') +for i in range(1,10): + print('Here i is',i) + os.rename('newDir' + str(i),'newDir' + str(i + 1)) + time.sleep(2) diff --git a/Test001/P21_GuessTheNumber.py b/Test001/P21_GuessTheNumber.py new file mode 100644 index 0000000..f1f2c2d --- /dev/null +++ b/Test001/P21_GuessTheNumber.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program guesses the randomnly generated number + + +import random + +def guess(): + ''' This function guesses the randomnly generated number ''' + randomNumber = random.randint(0, 21) + count = 0 + + while True: + count += 1 + number = int(input('Enter the number between 0 to 20: ')) + if number < randomNumber: + print('Too small') + elif number > randomNumber: + print('Too large') + else: + print('You have got it in', count, 'tries') + break + +if __name__ == '__main__': + guess() diff --git a/Test001/P22_SequentialSearch.py b/Test001/P22_SequentialSearch.py new file mode 100644 index 0000000..51a63d9 --- /dev/null +++ b/Test001/P22_SequentialSearch.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program is an example for sequential search + +def sequentialSearch(target, List): + '''This function returns the position of the target if found else returns -1''' + position = 0 + global iterations + iterations = 0 + while position < len(List): + iterations += 1 + if target == List[position]: + return position + position += 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8] + target = 3 + ans = sequentialSearch(target, List) + if ans != -1: + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found in the list') diff --git a/Test001/P23_BinarySearch.py b/Test001/P23_BinarySearch.py new file mode 100644 index 0000000..5d41162 --- /dev/null +++ b/Test001/P23_BinarySearch.py @@ -0,0 +1,29 @@ +#Author: OMKAR PATHAK +#This programs give an example of binary search algorithm + +def binarySearch(target, List): + '''This function performs a binary search on a sorted list and returns the position if successful else returns -1''' + left = 0 #First position of the list + right = len(List) - 1 #Last position of the list + global iterations + iterations = 0 + + while left <= right: #U can also write while True condition + iterations += 1 + mid = (left + right) // 2 + if target == List[mid]: + return mid + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] + target = 2 + ans = binarySearch(target, List) + if(ans != -1): + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found') diff --git a/Test001/P24_SelectionSort.py b/Test001/P24_SelectionSort.py new file mode 100644 index 0000000..4b2a35e --- /dev/null +++ b/Test001/P24_SelectionSort.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#This program shows an example of selection sort + +#Selection sort iterates all the elements and if the smallest element in the list is found then that number +#is swapped with the first + +#Best O(n^2); Average O(n^2); Worst O(n^2) + +def selectionSort(List): + for i in range(len(List) - 1): #For iterating n - 1 times + minimum = i + for j in range( i + 1, len(List)): # Compare i and i + 1 element + if(List[j] < List[minimum]): + minimum = j + if(minimum != i): + List[i], List[minimum] = List[minimum], List[i] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',selectionSort(List)) diff --git a/Test001/P25_BubbleSort.py b/Test001/P25_BubbleSort.py new file mode 100644 index 0000000..4aab5da --- /dev/null +++ b/Test001/P25_BubbleSort.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program shows an example of bubble sort using Python + +# Bubblesort is an elementary sorting algorithm. The idea is to +# imagine bubbling the smallest elements of a (vertical) array to the +# top; then bubble the next smallest; then so on until the entire +# array is sorted. Bubble sort is worse than both insertion sort and +# selection sort. It moves elements as many times as insertion sort +# (bad) and it takes as long as selection sort (bad). On the positive +# side, bubble sort is easy to understand. Also there are highly +# improved variants of bubble sort. + +# Best O(n^2); Average O(n^2); Worst O(n^2) + +def bubbleSort(List): + for i in range(len(List)): + for j in range(len(List) - 1, i, -1): + if List[j] < List[j - 1]: + List[j], List[j - 1] = List[j - 1], List[j] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',bubbleSort(List)) diff --git a/Test001/P26_InsertionSort.py b/Test001/P26_InsertionSort.py new file mode 100644 index 0000000..c120cc4 --- /dev/null +++ b/Test001/P26_InsertionSort.py @@ -0,0 +1,25 @@ +#Author: OMKAR PATHAK +#This program shows an example of insertion sort using Python + +# Insertion sort is good for collections that are very small +# or nearly sorted. Otherwise it's not a good sorting algorithm: +# it moves data around too much. Each time an insertion is made, +# all elements in a greater position are shifted. + +# Best O(n); Average O(n^2); Worst O(n^2) + +def insertionSort(List): + for i in range(1, len(List)): + currentNumber = List[i] + for j in range(i - 1, -1, -1): + if List[j] > currentNumber : + List[j], List[j + 1] = List[j + 1], List[j] + else: + List[j + 1] = currentNumber + break + + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',insertionSort(List)) diff --git a/Test001/P27_MergeSort.py b/Test001/P27_MergeSort.py new file mode 100644 index 0000000..2ecf8ce --- /dev/null +++ b/Test001/P27_MergeSort.py @@ -0,0 +1,42 @@ +#Author: OMKAR PATHAK +#This program gives an example of Merge sort + +# Merge sort is a divide and conquer algorithm. In the divide and +# conquer paradigm, a problem is broken into pieces where each piece +# still retains all the properties of the larger problem -- except +# its size. To solve the original problem, each piece is solved +# individually; then the pieces are merged back together. + +# Best = Average = Worst = O(nlog(n)) + +def merge(a,b): + """ Function to merge two arrays """ + c = [] + while len(a) != 0 and len(b) != 0: + if a[0] < b[0]: + c.append(a[0]) + a.remove(a[0]) + else: + c.append(b[0]) + b.remove(b[0]) + if len(a) == 0: + c += b + else: + c += a + return c + +# Code for merge sort + +def mergeSort(x): + """ Function to sort an array using merge sort algorithm """ + if len(x) == 0 or len(x) == 1: + return x + else: + middle = len(x)//2 + a = mergeSort(x[:middle]) + b = mergeSort(x[middle:]) + return merge(a,b) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',mergeSort(List)) diff --git a/Test001/P28_QuickSort.py b/Test001/P28_QuickSort.py new file mode 100644 index 0000000..ad11e64 --- /dev/null +++ b/Test001/P28_QuickSort.py @@ -0,0 +1,65 @@ +#Author: OMKAR PATHAK +#This program illustrates an example of quick sort + +# Quicksort works by selecting an element called a pivot and splitting +# the array around that pivot such that all the elements in, say, the +# left sub-array are less than pivot and all the elements in the right +# sub-array are greater than pivot. The splitting continues until the +# array can no longer be broken into pieces. That's it. Quicksort is +# done. + +# Best = Average = O(nlog(n)); Worst = O(n^2 +import time + +def quickSort(myList, start, end): + if start < end: + # partition the list + pivot = partition(myList, start, end) + # sort both halves + quickSort(myList, start, pivot-1) + quickSort(myList, pivot+1, end) + return myList + +def partition(myList, start, end): + pivot = myList[start] + left = start+1 + right = end + done = False + while not done: + while left <= right and myList[left] <= pivot: + left = left + 1 + while myList[right] >= pivot and right >=left: + right = right -1 + if right < left: + done= True + else: + # swap places + temp=myList[left] + myList[left]=myList[right] + myList[right]=temp + # swap start with myList[right] + temp=myList[start] + myList[start]=myList[right] + myList[right]=temp + return right + +# A more efficient solution +def quicksortBetter(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quicksortBetter(left) + middle + quicksortBetter(right) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + start = time.time() + print('Sorted List:',quickSort(List, 0, len(List) - 1)) + stop = time.time() + print('Time Required:', (stop - start)) + start = time.time() + print('Sorted List:', quicksortBetter(List)) + stop = time.time() + print('Time Required:', (stop - start)) diff --git a/Test001/P29_ArgumentParser.py b/Test001/P29_ArgumentParser.py new file mode 100644 index 0000000..15a5968 --- /dev/null +++ b/Test001/P29_ArgumentParser.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#In this example w will see the example for Python argument parser + +import argparse + +def argumentParser(): + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--slowbros', help = 'Names of Slowbros', action = 'store_true') + arg = parser.parse_args() + if(arg.slowbros): + slowBros() + else: + print('Dude give some arguments! Type ArgumentParser -h for more details') + + +def slowBros(): + print('SLOWBROS MEMBERS: \nOmkar Pathak\nChinmaya Kaundanya\nAkash Nalawade\nSanket Parode') + + +if __name__ == '__main__': + argumentParser() diff --git a/Test001/P30_Array.py b/Test001/P30_Array.py new file mode 100644 index 0000000..a4728c5 --- /dev/null +++ b/Test001/P30_Array.py @@ -0,0 +1,107 @@ +#Author: OMKAR PATHAK +#This example illustrates how an array can be implemened using Python + +class Array(object): + def __init__(self, size, defaultValue = None): + ''' + size: indicates the static size of the Array + defaultValue indicates the default value that Array takes while creation, you can also + pass preinitialized list to set the values of the array elements + ''' + self.size = size + # If only array size is initialized then, initialize all the elements as None type + if(defaultValue == None): + self.items = list() + for i in range(size): + self.items.append(defaultValue) + else: + # If user has given the default values for the array + self.items = list() + + if(len(defaultValue) == size or len(defaultValue) < size): + for j in range(len(defaultValue)): + if(defaultValue[j]): + self.items.append(defaultValue[j]) + for i in range(len(defaultValue), size): + self.items.append(None) + else: + print('Elements are more than the size specified') + + def myLen(self): + ''' This function returns the length of the Array (Only initialised number of elements)''' + length = 0 + for i in self.items: + if i == None: + continue + else: + length += 1 + return length + + def insertFirst(self, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), 0, -1): + self.items[i] = self.items[i - 1] + self.items[0] = element + else: + print('Element index out of range') + + def insertAtIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index, -1): + self.items[i] = self.items[i - 1] + self.items[index] = element + else: + print('Element index out of range') + + def insertAfterIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index + 1, -1): + self.items[i] = self.items[i - 1] + self.items[index + 1] = element + else: + print('Element index out of range') + + def insertBeforeIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index - 1, -1): + self.items[i] = self.items[i - 1] + self.items[index - 1] = element + else: + print('Element index out of range') + + def delete(self, element): + if element in self.items: + Index = self.items.index(element) + self.items[Index] = None + else: + print('This element is not in the Array!') + + def search(self, element): + if element in self.items: + position = 0 + for i in range(self.myLen()): + if(self.items[i] == element): + break + else: + position += 1 + + print('Element {} found at position {}'.format(element, position)) + else: + print('This element is not in the Array!') + +if __name__ == '__main__': + myArray = Array(5, [1]) + print(myArray.items, myArray.myLen()) # [1, None, None, None, None] 1 + myArray.insertFirst(3) + print(myArray.items, myArray.myLen()) # [3, 1, None, None, None] 2 + myArray.insertAfterIndex(1,4) + print(myArray.items, myArray.myLen()) # [3, 1, 4, None, None] 3 + myArray.insertBeforeIndex(3,5) + print(myArray.items, myArray.myLen()) # [3, 1, 5, 4, None] 4 + myArray.delete(5) + print(myArray.items, myArray.myLen()) # [3, 1, None, 4, None] 3 + myArray.search(4) # Element 4 found at position 3 diff --git a/Test002/P01_hello.py b/Test002/P01_hello.py new file mode 100644 index 0000000..8bf2bd6 --- /dev/null +++ b/Test002/P01_hello.py @@ -0,0 +1,29 @@ +# Author: OMKAR PATHAK +# This program prints the entered message + +def justPrint(text): + '''This function prints the text passed as argument to this function''' + print(text) + a=input("Enter a number: ") + b=input("Enter another number: ") + base_value = 10 + increment_value=20 + difference = increment_value - base_value + divide_value = increment_value / base_value + multiply_value = increment_value * base_value + floor_division = increment_value // base_value # // -> integer division + + print("Floor Division:", floor_division) + # print("Difference is:", increment_value - base_value) + print("Divide value is:", divide_value) + print("Multiply value is:", multiply_value) + print("Modulus:", increment_value % base_value ) # % -> remainder + print('Addition is:', int(a) + int(b)) + print("All the arthemitic operations are covered") + +if __name__ == '__main__': + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + + diff --git a/Test002/P02_VariableScope.py b/Test002/P02_VariableScope.py new file mode 100644 index 0000000..a85c8bd --- /dev/null +++ b/Test002/P02_VariableScope.py @@ -0,0 +1,18 @@ +#Author: OMKAR PATHAK +#This programs shows the rules for variable scope + +# LEGB Rule: Local, Enclosing, Global, Built-in + +x = 80 # Global x + +def test(): + #global x + y = 100 # Local y + x = 20 + print(x + y) #prints 'Local x' and 'Local y' + print("Variable scope") + +if __name__ == '__main__': + test() + print(x) #prints 'Global x' + \ No newline at end of file diff --git a/Test002/P03_ListsOperations.py b/Test002/P03_ListsOperations.py new file mode 100644 index 0000000..53c5d13 --- /dev/null +++ b/Test002/P03_ListsOperations.py @@ -0,0 +1,48 @@ +#Author: OMKAR PATHAK +#This program gives examples about various list operations +# User story id : Prod - PYTH-003 + +#Syntax: list[start: end: step] + +myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] +#index 0 1 2 3 4 5 6 7 8 +# -9 -8 -7 -6 -5 -4 -3 -2 -1 + +#List Slicing +print('Original List:',myList) +print('First Element:',myList[0]) #Prints the first element of the list or 0th element of the list +print('Element at 2nd Index position:',myList[2]) #Prints the 2nd element of the list +print('Elements from 0th Index to 4th Index:',myList[0: 5]) #Prints elements of the list from 0th index to 4th index. IT DOESN'T INCLUDE THE LAST INDEX +print('Element at -7th Index:',myList[-7]) #Prints the -7th or 3rd element of the list + +#To append an element to a list +myList.append(10) +print('Append:',myList) + +#To find the index of a particular element +print('Index of element \'6\':',myList.index(6)) #returns index of element '6' + +#To sort the list +myList.sort() + +#To pop last element +print('Poped Element:',myList.pop()) + +#To remove a particular element from the lsit BY NAME +myList.remove(6) +print('After removing \'6\':',myList) + +#To insert an element at a specified Index +myList.insert(5, 6) +print('Inserting \'6\' at 5th index:',myList) + +#To count number of occurences of a element in the list +print('No of Occurences of \'1\':',myList.count(1)) + +#To extend a list that is insert multiple elemets at once at the end of the list +myList.extend([11,0]) +print('Extending list:',myList) + +#To reverse a list +myList.reverse() +print('Reversed list:',myList) diff --git a/Test002/P04_Factorial.py b/Test002/P04_Factorial.py new file mode 100644 index 0000000..f5262c3 --- /dev/null +++ b/Test002/P04_Factorial.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program finds the favtorial of the specified numbers +#For example, factorial of 5 = 5*4*3*2*1 = 120 + +def factorial(number): + '''This function finds the factorial of the number passed as argument''' + if number < 0: + print('Invalid entry! Cannot find factorial of a negative number') + if number == 0 or number == 1: + print("Hello") + return 1 + else: + return number * factorial(number - 1) + +if __name__ == '__main__': + userInput = int(input('Enter the Number to find the factorial of: ')) + print(factorial(userInput)) diff --git a/Test002/P05_Pattern.py b/Test002/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/Test002/P05_Pattern.py @@ -0,0 +1,112 @@ +#Author: OMKAR PATHAK +#This program prints various patterns + +def pattern1(level): + '''This function prints the following pattern: + + * + ** + *** + **** + + ''' + for i in range(1, level + 1): + print() + for j in range(i): + print('*', end = '') + +def pattern2(level): + '''This function prints the following pattern: + + **** + *** + ** + * + + ''' + for i in range(level, 0, -1): + print() + for j in range(i): + print('*', end = '') + +def pattern3(level): + '''This function prints the following pattern: + + * + ** + *** + **** + + ''' + counter = level + for i in range(level + 1): + print(' ' * counter + '*' * i) + counter -= 1 + +def pattern4(level): + '''This function prints the following pattern: + + **** + *** + ** + * + + ''' + counter = 0 + for i in range(level, 0 ,-1): + print(' ' * counter + '*' * i) + counter += 1 + +def pattern5(level): + '''This function prints the following pattern: + + * + *** + ***** + + ''' + # first loop for number of lines + for i in range(level + 1): + #second loop for spaces + for j in range(level - i): + print (" ",end='') + # this loop is for printing stars + for k in range(2 * i - 1): + print("*", end='') + print() + + +if __name__ == '__main__': + userInput = int(input('Enter the level: ')) + pattern1(userInput) + print() + pattern2(userInput) + print() + pattern3(userInput) + print() + pattern4(userInput) + print() + pattern5(userInput) + print() + + def pattern6(userInput): + ''' + following is the another approach to solve pattern problems with reduced time complexity + + for + + * + ** + *** + **** + ***** + ''' + + num = int(input('Enter number for pattern')) + pattern = '*' + string = pattern * num + x = 0 + + for i in string: + x = x + 1 + print(string[0:x]) diff --git a/Test002/P06_CharCount.py b/Test002/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/Test002/P06_CharCount.py @@ -0,0 +1,18 @@ +#Author: OMKAR PATHAK +#This program checks for the character frequency in the given string + +def charFrequency(userInput): + '''This fuction helps to count the char frequency in the given string ''' + userInput = userInput.lower() #covert to lowercase + dict = {} + for char in userInput: + keys = dict.keys() + if char in keys: + dict[char] += 1 + else: + dict[char] = 1 + return dict + +if __name__ == '__main__': + userInput = str(input('Enter a string: ')) + print(charFrequency(userInput)) diff --git a/Test002/P07_PrimeNumber.py b/Test002/P07_PrimeNumber.py new file mode 100644 index 0000000..485de60 --- /dev/null +++ b/Test002/P07_PrimeNumber.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program checks whether the entered number is prime or not + +def checkPrime(number): + '''This function checks for prime number''' + isPrime = False + if number == 2: + print(number, 'is a Prime Number') + if number > 1: + for i in range(2, number): + if number % i == 0: + print(number, 'is not a Prime Number') + isPrime = False + break + else: + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') + +if __name__ == '__main__': + userInput = int(input('Enter a number to check: ')) + checkPrime(userInput) diff --git a/Test002/P08_Fibonacci.py b/Test002/P08_Fibonacci.py new file mode 100644 index 0000000..67133a1 --- /dev/null +++ b/Test002/P08_Fibonacci.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program calculates the fibonacci series till the n-th term + +def fibonacci(number): + '''This function calculates the fibonacci series till the n-th term''' + if number <= 1: + return number + else: + return (fibonacci(number - 1) + fibonacci(number - 2)) + +def fibonacci_without_recursion(number): + if number == 0: return 0 + fibonacci0, fibonacci1 = 0, 1 + for i in range(2, number + 1): + fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1 + return fibonacci1 + +if __name__ == '__main__': + userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: ')) + for i in range(userInput + 1): + print(fibonacci(i),end=' ') + + print("\nUsing LOOP:") + print(fibonacci_without_recursion(userInput)) diff --git a/Test002/P09_Factorial.py b/Test002/P09_Factorial.py new file mode 100644 index 0000000..37b8dbc --- /dev/null +++ b/Test002/P09_Factorial.py @@ -0,0 +1,22 @@ +#Author: OMKAR PATHAK +#This program calculates the factorial of a given number + +def factorial(number): + '''This function calculates the factorial of a number''' + if number == 1 or number == 0: + return 1 + else: + return number * factorial(number - 1) + +def factorial_without_recursion(number): + fact = 1 + while(number > 0): + fact = fact * number + number = number - 1 + print('Factorial of', number,'is: ') + print(fact) + +if __name__ == '__main__': + userInput = int(input('Enter the number to find its factorial: ')) + print('Factorial of', userInput, 'is:', factorial(userInput)) + factorial_without_recursion(userInput) diff --git a/Test002/P10_LCM.py b/Test002/P10_LCM.py new file mode 100644 index 0000000..aa1f5bd --- /dev/null +++ b/Test002/P10_LCM.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program calculates the LCM of the two numbers entered by the user + +def LCM(number1, number2): + '''This function calculates LCM of two numbers inputed by the user''' + maximum = max(number1, number2) + i = maximum + while True: + if (i % number1 == 0 and i % number2 == 0): + lcm = i + break + i += maximum + + return lcm + +if __name__ == '__main__': + userInput1 = int(input('Enter first number: ')) + userInput2 = int(input('Enter second number: ')) + print('LCM of {} and {} is {}'.format( userInput1, userInput2, LCM(userInput1, userInput2))) diff --git a/Test002/P11_BinaryToDecimal.py b/Test002/P11_BinaryToDecimal.py new file mode 100644 index 0000000..7304c79 --- /dev/null +++ b/Test002/P11_BinaryToDecimal.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program converts the given binary number to its decimal equivalent + +def binaryToDecimal(binary): + '''This function calculates the decimal equivalent to given binary number''' + binary1 = binary + decimal, i, n = 0, 0, 0 + while(binary != 0): + dec = binary % 10 + decimal = decimal + dec * pow(2, i) + binary = binary//10 + i += 1 + print('Decimal equivalent of {} is {}'.format(binary1, decimal)) + +if __name__ == '__main__': + userInput = int(input('Enter the binary number to check its decimal equivalent: ')) + binaryToDecimal(userInput) diff --git a/Test002/P12_DecimalToBinary.py b/Test002/P12_DecimalToBinary.py new file mode 100644 index 0000000..c1be53c --- /dev/null +++ b/Test002/P12_DecimalToBinary.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#Program to convert decimal to its equivalent binary + +def decimalToBinary(n): + '''Function to print binary number for the input decimal using recursion''' + if n > 1: + decimalToBinary(n//2) + print(n % 2,end = '') + +if __name__ == '__main__': + userInput = int(input('Enter the decimal number to find its binary equivalent: ')) + decimalToBinary(userInput) + print() diff --git a/Test002/P13_Palindrome.py b/Test002/P13_Palindrome.py new file mode 100644 index 0000000..6d5aba8 --- /dev/null +++ b/Test002/P13_Palindrome.py @@ -0,0 +1,14 @@ +#Author: OMKAR PATHAK +#This program checks for the palindrome + +def palindrome(string): + '''This function checks the string for palindrome''' + revString = string[::-1] + if string == revString: + print('String is Palindrome') + else: + print('String is not Palindrome') + +if __name__ == '__main__': + userInput = str(input('Enter a string to check for Palindrome: ')) + palindrome(userInput) diff --git a/Test002/P14_CheckGreater.py b/Test002/P14_CheckGreater.py new file mode 100644 index 0000000..88f74b6 --- /dev/null +++ b/Test002/P14_CheckGreater.py @@ -0,0 +1,15 @@ +#Author: OMKAR PATHAK +#This prpgram checks that the given number is greater than all those numbers in th list + +def checkGreater(number): + '''This function checks whether the entered number is greater than those in the list''' + original = [1,2,3,4,5] + original.sort() + if number > original[-1]: + print('Yes, the entered number is greater than those in the list') + else: + print('No, entered number is less than those in the list') + +if __name__ == '__main__': + userInput = int(input('Enter the number to check: ')) + checkGreater(userInput) diff --git a/Test002/P15_Arguments.py b/Test002/P15_Arguments.py new file mode 100644 index 0000000..cd51cf3 --- /dev/null +++ b/Test002/P15_Arguments.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program gives a demo of how can you pass arguments while running python programs +#Run the program as: python P15_Arguments.py Omkar Pathak + +import sys + +def arguments(): + '''This function prints the argruments passed while running the python program''' + try: + print('This is the name of the script:', sys.argv[0]) + print('First argument:', sys.argv[1]) + print('Second argument:', sys.argv[2]) + except IndexError: + print('Give only two arguments') + +if __name__ == '__main__': + arguments() diff --git a/Test002/P16_CountVowels.py b/Test002/P16_CountVowels.py new file mode 100644 index 0000000..9b0c691 --- /dev/null +++ b/Test002/P16_CountVowels.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program counts the vowels present in the user input + +def countVowels(sentence): + '''This function counts the vowels''' + count = 0 + sentence = sentence.lower() + for c in sentence: + if c in ['a', 'e', 'i', 'o', 'u']: + count += 1 + return count + + +if __name__ == '__main__': + userInput = str(input("Enter the string to check for vowels: ")) + count = countVowels(userInput) + print('Vowel Count: ',count) diff --git a/Test002/P17_EvenOdd.py b/Test002/P17_EvenOdd.py new file mode 100644 index 0000000..b69a47f --- /dev/null +++ b/Test002/P17_EvenOdd.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program takes input from user and sorts the numbers in two arrays, one of even and other of odd + +def evenOdd(numbers): + '''This function divides the numbers in two arrays one of even and other of odd''' + even = [] + odd = [] + for number in numbers: + if int(number) % 2 == 0: + even.append(number) + else: + odd.append(number) + return even, odd + +if __name__ == '__main__': + userInput = input("Enter the numbers (space separated) to check: ") + userInput = list(userInput.split()) + even, odd = evenOdd(userInput) + print('Even Nos: ', ','.join(even), '\n', 'Odd Nos: ', ','.join(odd)) diff --git a/Test002/P18_Logging.py b/Test002/P18_Logging.py new file mode 100644 index 0000000..64acae3 --- /dev/null +++ b/Test002/P18_Logging.py @@ -0,0 +1,22 @@ +#Author: OMKAR PATHAK +#This program illustrates a logging example +import logging + +def log(number): + ''' This function creates a log file if any error is reported ''' + logging.basicConfig(filename = 'P18-logfile.txt', level = logging.INFO) + try: + if int(number) % 2 == 0: + print('Successful') + else: + print('Unsuccessful, this instance will be reported, check the log file') + logging.info('Invalid Entry') + except: + print('Please enter a valid integer') + +if __name__ == '__main__': + try: + userInput = int(input('Enter a number: ')) + log(userInput) + except: + print('Please enter a valid integer') diff --git a/Test002/P19_SimpleStopWatch.py b/Test002/P19_SimpleStopWatch.py new file mode 100644 index 0000000..bbbff67 --- /dev/null +++ b/Test002/P19_SimpleStopWatch.py @@ -0,0 +1,45 @@ +#Author: OMKAR PATHAK +#This program illustrates a stopwatch + +import time + +print('Press ENTER to begin, Press Ctrl + C to stop') +while True: + try: + input() #For ENTER + starttime = time.time() + print('Started') + except KeyboardInterrupt: + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break +# Press enter to start and stop the watch +""" +import time + +print('Press Enter to begin, Press Enter again to stop') +if input()=='': + starttime = time.time() + print('Started') + while True: + val=input() #For ENTER + if val=='': + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break + +""" + +""" +Output: +Press Enter to begin, Press Enter again to stop + +Started + +Stopped +Total Time: 1.05 secs + +""" + diff --git a/Test002/P20_OsModule.py b/Test002/P20_OsModule.py new file mode 100644 index 0000000..3c2a771 --- /dev/null +++ b/Test002/P20_OsModule.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#This program illustrates the example for os module in short + +import os +import time + +print(os.getcwd()) #Prints the current working directory + +os.mkdir('newDir1') +for i in range(1,10): + print('Here i is',i) + os.rename('newDir' + str(i),'newDir' + str(i + 1)) + time.sleep(2) diff --git a/Test002/P21_GuessTheNumber.py b/Test002/P21_GuessTheNumber.py new file mode 100644 index 0000000..f1f2c2d --- /dev/null +++ b/Test002/P21_GuessTheNumber.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program guesses the randomnly generated number + + +import random + +def guess(): + ''' This function guesses the randomnly generated number ''' + randomNumber = random.randint(0, 21) + count = 0 + + while True: + count += 1 + number = int(input('Enter the number between 0 to 20: ')) + if number < randomNumber: + print('Too small') + elif number > randomNumber: + print('Too large') + else: + print('You have got it in', count, 'tries') + break + +if __name__ == '__main__': + guess() diff --git a/Test002/P22_SequentialSearch.py b/Test002/P22_SequentialSearch.py new file mode 100644 index 0000000..51a63d9 --- /dev/null +++ b/Test002/P22_SequentialSearch.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program is an example for sequential search + +def sequentialSearch(target, List): + '''This function returns the position of the target if found else returns -1''' + position = 0 + global iterations + iterations = 0 + while position < len(List): + iterations += 1 + if target == List[position]: + return position + position += 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8] + target = 3 + ans = sequentialSearch(target, List) + if ans != -1: + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found in the list') diff --git a/Test002/P23_BinarySearch.py b/Test002/P23_BinarySearch.py new file mode 100644 index 0000000..5d41162 --- /dev/null +++ b/Test002/P23_BinarySearch.py @@ -0,0 +1,29 @@ +#Author: OMKAR PATHAK +#This programs give an example of binary search algorithm + +def binarySearch(target, List): + '''This function performs a binary search on a sorted list and returns the position if successful else returns -1''' + left = 0 #First position of the list + right = len(List) - 1 #Last position of the list + global iterations + iterations = 0 + + while left <= right: #U can also write while True condition + iterations += 1 + mid = (left + right) // 2 + if target == List[mid]: + return mid + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] + target = 2 + ans = binarySearch(target, List) + if(ans != -1): + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found') diff --git a/Test002/P24_SelectionSort.py b/Test002/P24_SelectionSort.py new file mode 100644 index 0000000..4b2a35e --- /dev/null +++ b/Test002/P24_SelectionSort.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#This program shows an example of selection sort + +#Selection sort iterates all the elements and if the smallest element in the list is found then that number +#is swapped with the first + +#Best O(n^2); Average O(n^2); Worst O(n^2) + +def selectionSort(List): + for i in range(len(List) - 1): #For iterating n - 1 times + minimum = i + for j in range( i + 1, len(List)): # Compare i and i + 1 element + if(List[j] < List[minimum]): + minimum = j + if(minimum != i): + List[i], List[minimum] = List[minimum], List[i] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',selectionSort(List)) diff --git a/Test002/P25_BubbleSort.py b/Test002/P25_BubbleSort.py new file mode 100644 index 0000000..4aab5da --- /dev/null +++ b/Test002/P25_BubbleSort.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program shows an example of bubble sort using Python + +# Bubblesort is an elementary sorting algorithm. The idea is to +# imagine bubbling the smallest elements of a (vertical) array to the +# top; then bubble the next smallest; then so on until the entire +# array is sorted. Bubble sort is worse than both insertion sort and +# selection sort. It moves elements as many times as insertion sort +# (bad) and it takes as long as selection sort (bad). On the positive +# side, bubble sort is easy to understand. Also there are highly +# improved variants of bubble sort. + +# Best O(n^2); Average O(n^2); Worst O(n^2) + +def bubbleSort(List): + for i in range(len(List)): + for j in range(len(List) - 1, i, -1): + if List[j] < List[j - 1]: + List[j], List[j - 1] = List[j - 1], List[j] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',bubbleSort(List)) diff --git a/Test002/P26_InsertionSort.py b/Test002/P26_InsertionSort.py new file mode 100644 index 0000000..c120cc4 --- /dev/null +++ b/Test002/P26_InsertionSort.py @@ -0,0 +1,25 @@ +#Author: OMKAR PATHAK +#This program shows an example of insertion sort using Python + +# Insertion sort is good for collections that are very small +# or nearly sorted. Otherwise it's not a good sorting algorithm: +# it moves data around too much. Each time an insertion is made, +# all elements in a greater position are shifted. + +# Best O(n); Average O(n^2); Worst O(n^2) + +def insertionSort(List): + for i in range(1, len(List)): + currentNumber = List[i] + for j in range(i - 1, -1, -1): + if List[j] > currentNumber : + List[j], List[j + 1] = List[j + 1], List[j] + else: + List[j + 1] = currentNumber + break + + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',insertionSort(List)) diff --git a/Test002/P27_MergeSort.py b/Test002/P27_MergeSort.py new file mode 100644 index 0000000..2ecf8ce --- /dev/null +++ b/Test002/P27_MergeSort.py @@ -0,0 +1,42 @@ +#Author: OMKAR PATHAK +#This program gives an example of Merge sort + +# Merge sort is a divide and conquer algorithm. In the divide and +# conquer paradigm, a problem is broken into pieces where each piece +# still retains all the properties of the larger problem -- except +# its size. To solve the original problem, each piece is solved +# individually; then the pieces are merged back together. + +# Best = Average = Worst = O(nlog(n)) + +def merge(a,b): + """ Function to merge two arrays """ + c = [] + while len(a) != 0 and len(b) != 0: + if a[0] < b[0]: + c.append(a[0]) + a.remove(a[0]) + else: + c.append(b[0]) + b.remove(b[0]) + if len(a) == 0: + c += b + else: + c += a + return c + +# Code for merge sort + +def mergeSort(x): + """ Function to sort an array using merge sort algorithm """ + if len(x) == 0 or len(x) == 1: + return x + else: + middle = len(x)//2 + a = mergeSort(x[:middle]) + b = mergeSort(x[middle:]) + return merge(a,b) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',mergeSort(List)) diff --git a/Test002/P28_QuickSort.py b/Test002/P28_QuickSort.py new file mode 100644 index 0000000..ad11e64 --- /dev/null +++ b/Test002/P28_QuickSort.py @@ -0,0 +1,65 @@ +#Author: OMKAR PATHAK +#This program illustrates an example of quick sort + +# Quicksort works by selecting an element called a pivot and splitting +# the array around that pivot such that all the elements in, say, the +# left sub-array are less than pivot and all the elements in the right +# sub-array are greater than pivot. The splitting continues until the +# array can no longer be broken into pieces. That's it. Quicksort is +# done. + +# Best = Average = O(nlog(n)); Worst = O(n^2 +import time + +def quickSort(myList, start, end): + if start < end: + # partition the list + pivot = partition(myList, start, end) + # sort both halves + quickSort(myList, start, pivot-1) + quickSort(myList, pivot+1, end) + return myList + +def partition(myList, start, end): + pivot = myList[start] + left = start+1 + right = end + done = False + while not done: + while left <= right and myList[left] <= pivot: + left = left + 1 + while myList[right] >= pivot and right >=left: + right = right -1 + if right < left: + done= True + else: + # swap places + temp=myList[left] + myList[left]=myList[right] + myList[right]=temp + # swap start with myList[right] + temp=myList[start] + myList[start]=myList[right] + myList[right]=temp + return right + +# A more efficient solution +def quicksortBetter(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quicksortBetter(left) + middle + quicksortBetter(right) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + start = time.time() + print('Sorted List:',quickSort(List, 0, len(List) - 1)) + stop = time.time() + print('Time Required:', (stop - start)) + start = time.time() + print('Sorted List:', quicksortBetter(List)) + stop = time.time() + print('Time Required:', (stop - start)) diff --git a/Test002/P29_ArgumentParser.py b/Test002/P29_ArgumentParser.py new file mode 100644 index 0000000..15a5968 --- /dev/null +++ b/Test002/P29_ArgumentParser.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#In this example w will see the example for Python argument parser + +import argparse + +def argumentParser(): + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--slowbros', help = 'Names of Slowbros', action = 'store_true') + arg = parser.parse_args() + if(arg.slowbros): + slowBros() + else: + print('Dude give some arguments! Type ArgumentParser -h for more details') + + +def slowBros(): + print('SLOWBROS MEMBERS: \nOmkar Pathak\nChinmaya Kaundanya\nAkash Nalawade\nSanket Parode') + + +if __name__ == '__main__': + argumentParser() diff --git a/Test002/P30_Array.py b/Test002/P30_Array.py new file mode 100644 index 0000000..a4728c5 --- /dev/null +++ b/Test002/P30_Array.py @@ -0,0 +1,107 @@ +#Author: OMKAR PATHAK +#This example illustrates how an array can be implemened using Python + +class Array(object): + def __init__(self, size, defaultValue = None): + ''' + size: indicates the static size of the Array + defaultValue indicates the default value that Array takes while creation, you can also + pass preinitialized list to set the values of the array elements + ''' + self.size = size + # If only array size is initialized then, initialize all the elements as None type + if(defaultValue == None): + self.items = list() + for i in range(size): + self.items.append(defaultValue) + else: + # If user has given the default values for the array + self.items = list() + + if(len(defaultValue) == size or len(defaultValue) < size): + for j in range(len(defaultValue)): + if(defaultValue[j]): + self.items.append(defaultValue[j]) + for i in range(len(defaultValue), size): + self.items.append(None) + else: + print('Elements are more than the size specified') + + def myLen(self): + ''' This function returns the length of the Array (Only initialised number of elements)''' + length = 0 + for i in self.items: + if i == None: + continue + else: + length += 1 + return length + + def insertFirst(self, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), 0, -1): + self.items[i] = self.items[i - 1] + self.items[0] = element + else: + print('Element index out of range') + + def insertAtIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index, -1): + self.items[i] = self.items[i - 1] + self.items[index] = element + else: + print('Element index out of range') + + def insertAfterIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index + 1, -1): + self.items[i] = self.items[i - 1] + self.items[index + 1] = element + else: + print('Element index out of range') + + def insertBeforeIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index - 1, -1): + self.items[i] = self.items[i - 1] + self.items[index - 1] = element + else: + print('Element index out of range') + + def delete(self, element): + if element in self.items: + Index = self.items.index(element) + self.items[Index] = None + else: + print('This element is not in the Array!') + + def search(self, element): + if element in self.items: + position = 0 + for i in range(self.myLen()): + if(self.items[i] == element): + break + else: + position += 1 + + print('Element {} found at position {}'.format(element, position)) + else: + print('This element is not in the Array!') + +if __name__ == '__main__': + myArray = Array(5, [1]) + print(myArray.items, myArray.myLen()) # [1, None, None, None, None] 1 + myArray.insertFirst(3) + print(myArray.items, myArray.myLen()) # [3, 1, None, None, None] 2 + myArray.insertAfterIndex(1,4) + print(myArray.items, myArray.myLen()) # [3, 1, 4, None, None] 3 + myArray.insertBeforeIndex(3,5) + print(myArray.items, myArray.myLen()) # [3, 1, 5, 4, None] 4 + myArray.delete(5) + print(myArray.items, myArray.myLen()) # [3, 1, None, 4, None] 3 + myArray.search(4) # Element 4 found at position 3 diff --git a/Test002/P31_SinglyLinkedList.py b/Test002/P31_SinglyLinkedList.py new file mode 100644 index 0000000..7654223 --- /dev/null +++ b/Test002/P31_SinglyLinkedList.py @@ -0,0 +1,95 @@ +#This program illustrates an example of singly linked list +#Linked lists do NOT support random access hence only sequential search can be carried out + +class Node(object): + def __init__(self, data, Next = None): + self.data = data + self.next = Next + + def getData(self): + return self.data + + def setData(self, data): + self.data = data + + def getNext(self): + return self.next + + def setNext(self, newNext): + self.next = newNext + +class LinkedList(object): + def __init__(self): + self.head = None + + def isEmpty(self): + return self.head == None + + def add(self, element): + temp = Node(element) + temp.setNext(self.head) + self.head = temp + + def size(self): + current = self.head + count = 0 + while current != None: + count = count + 1 + current = current.getNext() + + return count + + def search(self,item): + current = self.head + found = False + while current != None and not found: + if current.getData() == item: + found = True + else: + current = current.getNext() + + return found + + def remove(self,item): + current = self.head + previous = None + found = False + while not found: + if current.getData() == item: + found = True + else: + previous = current + current = current.getNext() + + if previous == None: + self.head = current.getNext() + else: + previous.setNext(current.getNext()) + + def getAllData(self): + current = self.head + elements = [] + while current: + elements.append(current.getData()) + current = current.getNext() + + return elements + +if __name__ == '__main__': + myList = LinkedList() + + print(myList.head) # None + + myList.add(12) + myList.add(2) + myList.add(22) + myList.add(32) + myList.add(42) + + print(myList.size()) # 5 + + print(myList.search(93)) # False + print(myList.search(12)) # True + print(myList.getAllData()) + myList.remove(12) + print(myList.getAllData()) diff --git a/Test002/P32_Multithreading_Client.py b/Test002/P32_Multithreading_Client.py new file mode 100644 index 0000000..8e118c0 --- /dev/null +++ b/Test002/P32_Multithreading_Client.py @@ -0,0 +1,24 @@ +#This program illustrates the client-server model using multithreading. +#Multiole clients can connect to server and each time a client connects a corresponding +#thread is created for handling client requests + +import socket + +ClientSocket = socket.socket() +host = '127.0.0.1' +port = 1233 + +print('Waiting for connection') +try: + ClientSocket.connect((host, port)) +except socket.error as e: + print(str(e)) + +Response = ClientSocket.recv(1024) +while True: + Input = input('Say Something: ') + ClientSocket.send(str.encode(Input)) + Response = ClientSocket.recv(1024) + print(Response.decode('utf-8')) + +ClientSocket.close() diff --git a/Test002/P32_Mutithreading_Server.py b/Test002/P32_Mutithreading_Server.py new file mode 100644 index 0000000..68639a3 --- /dev/null +++ b/Test002/P32_Mutithreading_Server.py @@ -0,0 +1,38 @@ +#This program illustrates the client-server model using multithreading. +#Multiole clients can connect to server and each time a client connects a corresponding +#thread is created for handling client requests + +import socket +import os +from _thread import * + +ServerSocket = socket.socket() +host = '127.0.0.1' +port = 1233 +ThreadCount = 0 +try: + ServerSocket.bind((host, port)) +except socket.error as e: + print(str(e)) + +print('Waitiing for a Connection..') +ServerSocket.listen(5) + +#Function for handling requests by a thread +def threaded_client(connection): + connection.send(str.encode('Welcome to the Server\n')) + while True: + data = connection.recv(2048) + reply = 'Server Says: ' + data.decode('utf-8') + if not data: + break + connection.sendall(str.encode(reply)) + connection.close() + +while True: + Client, address = ServerSocket.accept() + print('Connected to: ' + address[0] + ':' + str(address[1])) + start_new_thread(threaded_client, (Client, )) + ThreadCount += 1 + print('Thread Number: ' + str(ThreadCount)) +ServerSocket.close() diff --git a/Test002/P33_DoublyLinkedList.py b/Test002/P33_DoublyLinkedList.py new file mode 100644 index 0000000..7b16312 --- /dev/null +++ b/Test002/P33_DoublyLinkedList.py @@ -0,0 +1,108 @@ +#Author: OMKAR PATHAK +#This program illustrates an example of singly linked list + +class Node(object): + def __init__(self, data, Next = None, Previous = None): + self.data = data + self.next = Next + self.previous = Previous + + def getNext(self): + return self.next + + def getPrevious(self): + return self.previous + + def getData(self): + return self.data + + def setData(self, newData): + self.data = newData + + def setNext(self, newNext): + self.next = newNext + + def setPrevious(self, newPrevious): + self.previous = newPrevious + + +class LinkedList(object): + def __init__(self): + self.head = None + + def isEmpty(self): + ''' This function checks whether the list is empty''' + return self.head == None + + def insertFirst(self, data): + ''' This function inserts a new node in the Linked List ''' + newNode = Node(data) + if self.head: + self.head.setPrevious(newNode) + newNode.setNext(self.head) + self.head = newNode + + def insertLast(self, data): + newNode = Node(data) + current = self.head + while current.getNext() != None: + current = current.getNext() + current.setNext(newNode) + newNode.setPrevious(current) + + # def insertBetween(self, newItem, item): + # current = self.head + # newNode = Node(newItem) + # previous = None + # found = False + # while not found: + # if current.getData() == item: + # found = True + # else: + # previous = current + # current = current.getNext() + # + # if previous == None: + # self.head = current.getPrevious() + # else: + # previous.setNext(newNode) + # newNode.setPrevious(previous) + + def getAllData(self): + ''' This function displays the data elements of the Linked List ''' + current = self.head + elements = [] + while current: + elements.append(current.getData()) + current = current.getNext() + + return elements + + def remove(self,item): + current = self.head + previous = None + found = False + while not found: + if current.getData() == item: + found = True + else: + previous = current + current = current.getNext() + + if previous == None: + self.head = current.getNext() + else: + previous.setNext(current.getNext()) + +if __name__ == '__main__': + myList = LinkedList() + myList.insertFirst(1) + myList.insertFirst(12) + myList.insertFirst(32) + myList.insertFirst(22) + myList.insertLast(2) + myList.remove(12) + # myList.insertBetween(12, 22) + # for i in range(0, 10): + # myList.insertFirst(i) + print(myList.getAllData()) diff --git a/Test002/P34_Stack.py b/Test002/P34_Stack.py new file mode 100644 index 0000000..37ea8a5 --- /dev/null +++ b/Test002/P34_Stack.py @@ -0,0 +1,58 @@ +#Author: OMKAR PATHAK + +#This program illustrates an example of Stack implementation +#Stack Operations: push(), pop(), isEmpty(), peek(), stackSize() + +class Stack(object): + def __init__(self, size): + self.index = [] + self.size = size + + def __str__(self): + myString = ' '.join(str(i) for i in self.index) + return myString + + def push(self, data): + ''' Pushes a element to top of the stack ''' + if(self.isFull() != True): + self.index.append(data) + else: + print('Stack overflow') + + def pop(self): + ''' Pops the top element ''' + if(self.isEmpty() != True): + return self.index.pop() + else: + print('Stack is already empty!') + + def isEmpty(self): + ''' Checks whether the stack is empty ''' + return len(self.index) == [] + + def isFull(self): + ''' Checks whether the stack if full ''' + return len(self.index) == self.size + + def peek(self): + ''' Returns the top element of the stack ''' + if(self.isEmpty() != True): + return self.index[-1] + else: + print('Stack is already empty!') + + def stackSize(self): + ''' Returns the current stack size ''' + return len(self.index) + +if __name__ == '__main__': + myStack = Stack(10) + for i in range(0, 10): + myStack.push(i) + print(myStack.isEmpty()) # False + print(myStack.isFull()) # True + print(myStack) # 0 1 2 3 4 5 6 7 8 9 + print(myStack.stackSize()) # 10 + print(myStack.pop()) # 9 + print(myStack) # 0 1 2 3 4 5 6 7 8 + print(myStack.peek()) # 8 diff --git a/Test002/P35_NarySearch.py b/Test002/P35_NarySearch.py new file mode 100644 index 0000000..9120fd8 --- /dev/null +++ b/Test002/P35_NarySearch.py @@ -0,0 +1,81 @@ +#Author: OMKAR PATHAK + +#This program illsutrates an example of N-ary search + +ARRAY_SIZE = 10000000 # Size of our array +DIVISIONS = 10 # N-ary count + +def Main(): + myArray = [] + for i in range(0, ARRAY_SIZE + 1): + myArray.insert(i, i) + + key = int(input('Enter the key to search:')) + + low = 0 + high = ARRAY_SIZE + found = 0 + + if(key < myArray[low] or key > myArray[high - 1]): + print('Key is out of range!') + else: + while(low < high): + if(key == myArray[low] or key == myArray[high]): + found = 1 + break + else: + partitionSize = (high - low) // DIVISIONS + print('Searching from {} to {}'.format(low, high)) + print('Array Size is: ',(high - low)) + + mid = [0] + for i in range(1, DIVISIONS + 1): + mid.insert(i,low + partitionSize * i) + if(key == myArray[mid[i]]): + found = 1 + print() + if(found): + break + + if(key < myArray[mid[1]]): + high = mid[1] - 1 + elif(key > myArray[mid[DIVISIONS - 1]]): + low = mid[DIVISIONS - 1] + 1 + else: + for i in range(2, DIVISIONS + 1): + if(key < myArray[mid[i]]): + low = mid[i - 1] + 1 + high = mid[i]; + break; + + if(found): + print('Element Found!') + else: + print('Not Found!') + +if __name__ == '__main__': + Main() + + + # OUTPUT: + # omkarpathak@omkarpathak-Inspiron-3542:~/Documents/GITs/Python-Programs/Programs$ python P35_NarySearch.py + # Enter the key to search:433 + # Searching from 0 to 10000000 + # Array Size is:  10000000 + #   + # Searching from 0 to 999999 + # Array Size is:  999999 + #   + # Searching from 0 to 99998 + # Array Size is:  99998 + #   + # Searching from 0 to 9998 + # Array Size is:  9998 + #   + # Searching from 0 to 998 + # Array Size is:  998 + #   + # Searching from 397 to 495 + # Array Size is:  98 + #   + # Element Found! diff --git a/Test002/P36_SimpleReaderWriter.py b/Test002/P36_SimpleReaderWriter.py new file mode 100644 index 0000000..d3c20d7 --- /dev/null +++ b/Test002/P36_SimpleReaderWriter.py @@ -0,0 +1,41 @@ +#Author: OMKAR PATHAK +#In this example, we will see how to implement a simple reader Writer program using Python (Mutex) + +import threading as thread +import random + +global x #Shared Data +x = 0 +lock = thread.Lock() #Lock for synchronising access + +def Reader(): + global x + print('Reader is Reading!') + lock.acquire() #Acquire the lock before Reading (mutex approach) + print('Shared Data:', x) + lock.release() #Release the lock after Reading + print() + +def Writer(): + global x + print('Writer is Writing!') + lock.acquire() #Acquire the lock before Writing + x += 1 #Write on the shared memory + print('Writer is Releasing the lock!') + lock.release() #Release the lock after Writing + print() + +if __name__ == '__main__': + for i in range(0, 10): + randomNumber = random.randint(0, 100) #Generate a Random number between 0 to 100 + if(randomNumber > 50): + Thread1 = thread.Thread(target = Reader) + Thread1.start() + else: + Thread2 = thread.Thread(target = Writer) + Thread2.start() + +Thread1.join() +Thread2.join() + +# print(x) diff --git a/Test002/P37_HangmanGame.py b/Test002/P37_HangmanGame.py new file mode 100644 index 0000000..a55d14b --- /dev/null +++ b/Test002/P37_HangmanGame.py @@ -0,0 +1,76 @@ +# Author: Omkar Pathak +# This is just an example of how we can use Python for some gaming problems. + +import random +from collections import Counter + +someWords = '''apple banana mango strawberry orange grape pineapple apricot lemon coconut watermelon +cherry papaya berry peach lychee muskmelon''' + +someWords = someWords.split(' ') +word = random.choice(someWords) + +if __name__ == '__main__': + print('Guess the word! HINT: word is a name of a fruit') + for i in word: + print('_', end = ' ') + print() + + playing = True + letterGuessed = '' + chances = len(word) + 2 + correct = 0 + + try: + while (chances != 0): + print() + chances -= 1 + + try: + guess = str(input('Enter a letter to guess: ')) + except: + print('Enter only a letter!') + continue + + # Validation of the guess + if not guess.isalpha(): + print('Enter only a LETTER') + continue + elif len(guess) > 1: + print('Enter only a SINGLE letter') + continue + elif guess in letterGuessed: + print('You have already guessed that letter') + continue + + + # If letter is guessed correcly + if guess in word: + letterGuessed += guess + + # Print the word + for char in word: + if char in letterGuessed: + print(char, end = ' ') + correct += 1 + else: + print('_', end = ' ') + + # If user has guessed all the letters + if (Counter(letterGuessed) == Counter(word)): + print() + print('Congratulations, You won!') + break + + # If user has used all of his chances + if chances == 0: + print() + print('You lost! Try again..') + print('The word was {}'.format(word)) + + except KeyboardInterrupt: + print() + print('Bye! Try again.') + exit() + + # print(letterGuessed) diff --git a/Test002/P38_HashingFile.py b/Test002/P38_HashingFile.py new file mode 100644 index 0000000..1726f31 --- /dev/null +++ b/Test002/P38_HashingFile.py @@ -0,0 +1,13 @@ +# Author: OMKAR PATHAK +# This example illustrates an example to calculate a hash of a file + +import hashlib +BLOCKSIZE = 65536 # Block read size if file is big enough +fileToOpen = '/home/omkarpathak/Documents/GITs/Python-Programs/Scripts/howto.txt' +hasher = hashlib.md5() +with open(fileToOpen, 'rb') as afile: + buf = afile.read(BLOCKSIZE) + while len(buf) > 0: + hasher.update(buf) + buf = afile.read(BLOCKSIZE) +print(hasher.hexdigest()) diff --git a/Test002/P39_Queue.py b/Test002/P39_Queue.py new file mode 100644 index 0000000..6cdec3d --- /dev/null +++ b/Test002/P39_Queue.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# This program illustrates an example of Queue implementation in Python +# Stack Operations: enqueue(), dequeue(), isFull(), isEmpty, peek() + +class Queue(object): + def __init__(self, size): + self.queue = [] + self.size = size + + def __str__(self): + myString = ' '.join(str(i) for i in self.queue) + return myString + + def enqueue(self, item): + '''This function adds an item to the rear end of the queue ''' + if(self.isFull() != True): + self.queue.insert(0, item) + else: + print('Queue is Full!') + + def dequeue(self): + ''' This function removes an item from the front end of the queue ''' + if(self.isEmpty() != True): + return self.queue.pop() + else: + print('Queue is Empty!') + + def isEmpty(self): + ''' This function checks if the queue is empty ''' + return self.queue == [] + + def isFull(self): + ''' This function checks if the queue is full ''' + return len(self.queue) == self.size + + def peek(self): + ''' This function helps to see the first element at the fron end of the queue ''' + if(self.isEmpty() != True): + return self.queue[-1] + else: + print('Queue is Empty!') + +if __name__ == '__main__': + myQueue = Queue(10) + myQueue.enqueue(1) + myQueue.enqueue(2) + myQueue.enqueue(3) + print(myQueue) + myQueue.dequeue() + print(myQueue) diff --git a/Test002/P40_CipherText.py b/Test002/P40_CipherText.py new file mode 100644 index 0000000..e092f31 --- /dev/null +++ b/Test002/P40_CipherText.py @@ -0,0 +1,59 @@ +# Author: OMKAR PATHAK +# This program illustrates a simple example for encrypting/ decrypting your text + +LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +LETTERS = LETTERS.lower() + +def encrypt(message, key): + ''' This function lets you to encrypt your message based on a key ''' + encrypted = '' + for chars in message: + if chars in LETTERS: + num = LETTERS.find(chars) + num += key + if num>25: + num=num%25 + num=num-1 + encrypted =encrypted + LETTERS[num] + + return encrypted + +def decrypt(message, key): + ''' This function lets you to decrypt your message based on a key ''' + decrypted = '' + for chars in message: + if chars in LETTERS: + num = LETTERS.find(chars) + if num>25: + num=num%25 + num=num-1 + num = num -key + decrypted =decrypted+LETTERS[num] + + return decrypted + +def main(): + message = str(input('Enter your message: ')) + key = int(input('Enter you key [1 - 26]: ')) + choice = input('Encrypt or Decrypt? [E/D]: ') + + if choice.lower().startswith('e'): + print(encrypt(message, key)) + else: + print(decrypt(message, key)) + +if __name__ == '__main__': + main() + + # OUTPUT: + # omkarpathak@omkarpathak-Inspiron-3542:~/Documents/GITs/Python-Programs/Programs$ python P40_CipherText.py + # Enter your message: omkar + # Enter you key [1 - 26]: 2 + # Encrypt or Decrypt? [E/D]: e + # qomct + # + # omkarpathak@omkarpathak-Inspiron-3542:~/Documents/GITs/Python-Programs/Programs$ python P40_CipherText.py + # Enter your message: qomct + # Enter you key [1 - 26]: 2 + # Encrypt or Decrypt? [E/D]: d + # omkar