From b038606b0fffc8135f718be579f418c2654e7b1a Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Fri, 6 Feb 2026 00:14:40 +0530 Subject: [PATCH 1/6] Added changes --- Test2/P01_hello.py | 28 +++++++++ Test2/P02_VariableScope.py | 16 +++++ Test2/P03_ListsOperations.py | 48 +++++++++++++++ Test2/P04_Factorial.py | 17 ++++++ Test2/P05_Pattern.py | 112 +++++++++++++++++++++++++++++++++++ Test2/P06_CharCount.py | 18 ++++++ Test2/P07_PrimeNumber.py | 23 +++++++ 7 files changed, 262 insertions(+) create mode 100644 Test2/P01_hello.py create mode 100644 Test2/P02_VariableScope.py create mode 100644 Test2/P03_ListsOperations.py create mode 100644 Test2/P04_Factorial.py create mode 100644 Test2/P05_Pattern.py create mode 100644 Test2/P06_CharCount.py create mode 100644 Test2/P07_PrimeNumber.py diff --git a/Test2/P01_hello.py b/Test2/P01_hello.py new file mode 100644 index 0000000..2bab912 --- /dev/null +++ b/Test2/P01_hello.py @@ -0,0 +1,28 @@ +# 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)) + +if __name__ == '__main__': + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + + diff --git a/Test2/P02_VariableScope.py b/Test2/P02_VariableScope.py new file mode 100644 index 0000000..505eb22 --- /dev/null +++ b/Test2/P02_VariableScope.py @@ -0,0 +1,16 @@ +#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' + +if __name__ == '__main__': + test() + print(x) #prints 'Global x' diff --git a/Test2/P03_ListsOperations.py b/Test2/P03_ListsOperations.py new file mode 100644 index 0000000..53c5d13 --- /dev/null +++ b/Test2/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/Test2/P04_Factorial.py b/Test2/P04_Factorial.py new file mode 100644 index 0000000..f5262c3 --- /dev/null +++ b/Test2/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/Test2/P05_Pattern.py b/Test2/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/Test2/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/Test2/P06_CharCount.py b/Test2/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/Test2/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/Test2/P07_PrimeNumber.py b/Test2/P07_PrimeNumber.py new file mode 100644 index 0000000..485de60 --- /dev/null +++ b/Test2/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) From 0a1c992f4f2e4a5c00f48622daaa7f5af36057a9 Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Fri, 6 Feb 2026 13:03:30 +0530 Subject: [PATCH 2/6] Changes merged --- Test2/P05_Pattern.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Test2/P05_Pattern.py b/Test2/P05_Pattern.py index db988a0..7bf1487 100644 --- a/Test2/P05_Pattern.py +++ b/Test2/P05_Pattern.py @@ -102,7 +102,7 @@ def pattern6(userInput): ***** ''' - num = int(input('Enter number for pattern')) + num = userInput pattern = '*' string = pattern * num x = 0 From 3c336c551b7820093142e1180f4e6d8c4d800e71 Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Fri, 6 Feb 2026 15:32:13 +0530 Subject: [PATCH 3/6] 25 changes --- Test2/P01_hello.py | 28 -------- Test2/P02_VariableScope.py | 16 ----- Test2/P03_ListsOperations.py | 48 ------------- Test2/P20_OsModule.py | 13 ++++ Test2/P21_GuessTheNumber.py | 24 +++++++ Test2/P22_SequentialSearch.py | 23 ++++++ Test2/P23_BinarySearch.py | 29 ++++++++ Test2/P24_SelectionSort.py | 21 ++++++ Test2/P25_BubbleSort.py | 24 +++++++ Test2/P26_InsertionSort.py | 25 +++++++ Test2/P27_MergeSort.py | 42 +++++++++++ Test2/P28_QuickSort.py | 65 +++++++++++++++++ Test2/P29_ArgumentParser.py | 21 ++++++ Test2/P30_Array.py | 107 ++++++++++++++++++++++++++++ Test2/P31_SinglyLinkedList.py | 95 +++++++++++++++++++++++++ Test2/P32_Multithreading_Client.py | 24 +++++++ Test2/P32_Mutithreading_Server.py | 38 ++++++++++ Test2/P33_DoublyLinkedList.py | 108 +++++++++++++++++++++++++++++ Test2/P34_Stack.py | 58 ++++++++++++++++ Test2/P35_NarySearch.py | 81 ++++++++++++++++++++++ Test2/P36_SimpleReaderWriter.py | 41 +++++++++++ Test2/P37_HangmanGame.py | 76 ++++++++++++++++++++ Test2/P38_HashingFile.py | 13 ++++ Test2/P39_Queue.py | 51 ++++++++++++++ Test2/P40_CipherText.py | 59 ++++++++++++++++ 25 files changed, 1038 insertions(+), 92 deletions(-) delete mode 100644 Test2/P01_hello.py delete mode 100644 Test2/P02_VariableScope.py delete mode 100644 Test2/P03_ListsOperations.py create mode 100644 Test2/P20_OsModule.py create mode 100644 Test2/P21_GuessTheNumber.py create mode 100644 Test2/P22_SequentialSearch.py create mode 100644 Test2/P23_BinarySearch.py create mode 100644 Test2/P24_SelectionSort.py create mode 100644 Test2/P25_BubbleSort.py create mode 100644 Test2/P26_InsertionSort.py create mode 100644 Test2/P27_MergeSort.py create mode 100644 Test2/P28_QuickSort.py create mode 100644 Test2/P29_ArgumentParser.py create mode 100644 Test2/P30_Array.py create mode 100644 Test2/P31_SinglyLinkedList.py create mode 100644 Test2/P32_Multithreading_Client.py create mode 100644 Test2/P32_Mutithreading_Server.py create mode 100644 Test2/P33_DoublyLinkedList.py create mode 100644 Test2/P34_Stack.py create mode 100644 Test2/P35_NarySearch.py create mode 100644 Test2/P36_SimpleReaderWriter.py create mode 100644 Test2/P37_HangmanGame.py create mode 100644 Test2/P38_HashingFile.py create mode 100644 Test2/P39_Queue.py create mode 100644 Test2/P40_CipherText.py diff --git a/Test2/P01_hello.py b/Test2/P01_hello.py deleted file mode 100644 index 2bab912..0000000 --- a/Test2/P01_hello.py +++ /dev/null @@ -1,28 +0,0 @@ -# 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)) - -if __name__ == '__main__': - justPrint('Hello Sindhuja') - justPrint('Hello Sindhuja') - justPrint('Hello Sindhuja') - - diff --git a/Test2/P02_VariableScope.py b/Test2/P02_VariableScope.py deleted file mode 100644 index 505eb22..0000000 --- a/Test2/P02_VariableScope.py +++ /dev/null @@ -1,16 +0,0 @@ -#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' - -if __name__ == '__main__': - test() - print(x) #prints 'Global x' diff --git a/Test2/P03_ListsOperations.py b/Test2/P03_ListsOperations.py deleted file mode 100644 index 53c5d13..0000000 --- a/Test2/P03_ListsOperations.py +++ /dev/null @@ -1,48 +0,0 @@ -#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/Test2/P20_OsModule.py b/Test2/P20_OsModule.py new file mode 100644 index 0000000..3c2a771 --- /dev/null +++ b/Test2/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/Test2/P21_GuessTheNumber.py b/Test2/P21_GuessTheNumber.py new file mode 100644 index 0000000..f1f2c2d --- /dev/null +++ b/Test2/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/Test2/P22_SequentialSearch.py b/Test2/P22_SequentialSearch.py new file mode 100644 index 0000000..51a63d9 --- /dev/null +++ b/Test2/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/Test2/P23_BinarySearch.py b/Test2/P23_BinarySearch.py new file mode 100644 index 0000000..5d41162 --- /dev/null +++ b/Test2/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/Test2/P24_SelectionSort.py b/Test2/P24_SelectionSort.py new file mode 100644 index 0000000..4b2a35e --- /dev/null +++ b/Test2/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/Test2/P25_BubbleSort.py b/Test2/P25_BubbleSort.py new file mode 100644 index 0000000..4aab5da --- /dev/null +++ b/Test2/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/Test2/P26_InsertionSort.py b/Test2/P26_InsertionSort.py new file mode 100644 index 0000000..c120cc4 --- /dev/null +++ b/Test2/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/Test2/P27_MergeSort.py b/Test2/P27_MergeSort.py new file mode 100644 index 0000000..2ecf8ce --- /dev/null +++ b/Test2/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/Test2/P28_QuickSort.py b/Test2/P28_QuickSort.py new file mode 100644 index 0000000..ad11e64 --- /dev/null +++ b/Test2/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/Test2/P29_ArgumentParser.py b/Test2/P29_ArgumentParser.py new file mode 100644 index 0000000..15a5968 --- /dev/null +++ b/Test2/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/Test2/P30_Array.py b/Test2/P30_Array.py new file mode 100644 index 0000000..a4728c5 --- /dev/null +++ b/Test2/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/Test2/P31_SinglyLinkedList.py b/Test2/P31_SinglyLinkedList.py new file mode 100644 index 0000000..7654223 --- /dev/null +++ b/Test2/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/Test2/P32_Multithreading_Client.py b/Test2/P32_Multithreading_Client.py new file mode 100644 index 0000000..8e118c0 --- /dev/null +++ b/Test2/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/Test2/P32_Mutithreading_Server.py b/Test2/P32_Mutithreading_Server.py new file mode 100644 index 0000000..68639a3 --- /dev/null +++ b/Test2/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/Test2/P33_DoublyLinkedList.py b/Test2/P33_DoublyLinkedList.py new file mode 100644 index 0000000..7b16312 --- /dev/null +++ b/Test2/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/Test2/P34_Stack.py b/Test2/P34_Stack.py new file mode 100644 index 0000000..37ea8a5 --- /dev/null +++ b/Test2/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/Test2/P35_NarySearch.py b/Test2/P35_NarySearch.py new file mode 100644 index 0000000..9120fd8 --- /dev/null +++ b/Test2/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/Test2/P36_SimpleReaderWriter.py b/Test2/P36_SimpleReaderWriter.py new file mode 100644 index 0000000..d3c20d7 --- /dev/null +++ b/Test2/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/Test2/P37_HangmanGame.py b/Test2/P37_HangmanGame.py new file mode 100644 index 0000000..a55d14b --- /dev/null +++ b/Test2/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/Test2/P38_HashingFile.py b/Test2/P38_HashingFile.py new file mode 100644 index 0000000..1726f31 --- /dev/null +++ b/Test2/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/Test2/P39_Queue.py b/Test2/P39_Queue.py new file mode 100644 index 0000000..6cdec3d --- /dev/null +++ b/Test2/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/Test2/P40_CipherText.py b/Test2/P40_CipherText.py new file mode 100644 index 0000000..e092f31 --- /dev/null +++ b/Test2/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 From d5e570ce72f63350f7dbd5a478d62eb562d449fb Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Fri, 6 Feb 2026 17:15:35 +0530 Subject: [PATCH 4/6] 25 changes --- Test2/P01_hello.py | 28 ++++++++++++++++++++++++++++ Test2/P31_SinglyLinkedList.py | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 Test2/P01_hello.py diff --git a/Test2/P01_hello.py b/Test2/P01_hello.py new file mode 100644 index 0000000..2bab912 --- /dev/null +++ b/Test2/P01_hello.py @@ -0,0 +1,28 @@ +# 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)) + +if __name__ == '__main__': + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + + diff --git a/Test2/P31_SinglyLinkedList.py b/Test2/P31_SinglyLinkedList.py index 7654223..15ac75e 100644 --- a/Test2/P31_SinglyLinkedList.py +++ b/Test2/P31_SinglyLinkedList.py @@ -54,7 +54,7 @@ def remove(self,item): current = self.head previous = None found = False - while not found: + while current != None and not found: if current.getData() == item: found = True else: From cb5ae25a6d8bff788ab26315f27d1fdf52e21e44 Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Fri, 6 Feb 2026 17:23:05 +0530 Subject: [PATCH 5/6] 25 changes --- Test2/P01_hello.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Test2/P01_hello.py b/Test2/P01_hello.py index 2bab912..de722d7 100644 --- a/Test2/P01_hello.py +++ b/Test2/P01_hello.py @@ -4,8 +4,8 @@ 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: ") + first_number = input("Enter a number: ") + second_number = input("Enter another number: ") base_value = 10 increment_value=20 difference = increment_value - base_value From 48a50df5db4700073f3ba4128508b919e476773f Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Mon, 9 Feb 2026 15:45:01 +0530 Subject: [PATCH 6/6] Changes merged --- Test2/P39_Queue.py | 51 ---------- Test2/P40_CipherText copy.py | 59 ++++++++++++ Test2/P41_PortScanner.py | 26 +++++ Test2/P42_MultiprocessingPipes.py | 25 +++++ Test2/P43_BinarySearchTree.py | 145 ++++++++++++++++++++++++++++ Test2/P44_Closures.py | 21 ++++ Test2/P45_MoreOnClosures.py | 27 ++++++ Test2/P46_Decorators.py | 21 ++++ Test2/P47_MoreOnDecorators.py | 27 ++++++ Test2/P48_CountingSort.py | 52 ++++++++++ Test2/P49_RockPaperScissors.py | 51 ++++++++++ Test2/P50_ListComprehensions.py | 52 ++++++++++ Test2/P51_PythonJSON.py | 25 +++++ Test2/P52_BucketSort.py | 55 +++++++++++ Test2/P53_ShellSort.py | 28 ++++++ Test2/P54_PythonCSV.py | 30 ++++++ Test2/P55_Isogram.py | 29 ++++++ Test2/P56_Pangram.py | 36 +++++++ Test2/P57_Anagram.py | 27 ++++++ Test2/P58_PerfectNumber.py | 21 ++++ Test2/P59_PascalTriangle.py | 32 ++++++ Test2/P60_PickleModule.py | 32 ++++++ Test2/P61_AddressBook.py | 150 +++++++++++++++++++++++++++++ Test2/P62_BinaryTree.py | 82 ++++++++++++++++ Test2/P63_Graph.py | 80 +++++++++++++++ Test2/P64_DepthFirstTraversal.py | 82 ++++++++++++++++ Test2/P65_BreadthFirstTraversal.py | 51 ++++++++++ 27 files changed, 1266 insertions(+), 51 deletions(-) create mode 100644 Test2/P40_CipherText copy.py create mode 100644 Test2/P41_PortScanner.py create mode 100644 Test2/P42_MultiprocessingPipes.py create mode 100644 Test2/P43_BinarySearchTree.py create mode 100644 Test2/P44_Closures.py create mode 100644 Test2/P45_MoreOnClosures.py create mode 100644 Test2/P46_Decorators.py create mode 100644 Test2/P47_MoreOnDecorators.py create mode 100644 Test2/P48_CountingSort.py create mode 100644 Test2/P49_RockPaperScissors.py create mode 100644 Test2/P50_ListComprehensions.py create mode 100644 Test2/P51_PythonJSON.py create mode 100644 Test2/P52_BucketSort.py create mode 100644 Test2/P53_ShellSort.py create mode 100644 Test2/P54_PythonCSV.py create mode 100644 Test2/P55_Isogram.py create mode 100644 Test2/P56_Pangram.py create mode 100644 Test2/P57_Anagram.py create mode 100644 Test2/P58_PerfectNumber.py create mode 100644 Test2/P59_PascalTriangle.py create mode 100644 Test2/P60_PickleModule.py create mode 100644 Test2/P61_AddressBook.py create mode 100644 Test2/P62_BinaryTree.py create mode 100644 Test2/P63_Graph.py create mode 100644 Test2/P64_DepthFirstTraversal.py create mode 100644 Test2/P65_BreadthFirstTraversal.py diff --git a/Test2/P39_Queue.py b/Test2/P39_Queue.py index 6cdec3d..e69de29 100644 --- a/Test2/P39_Queue.py +++ b/Test2/P39_Queue.py @@ -1,51 +0,0 @@ -# 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/Test2/P40_CipherText copy.py b/Test2/P40_CipherText copy.py new file mode 100644 index 0000000..e092f31 --- /dev/null +++ b/Test2/P40_CipherText copy.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 diff --git a/Test2/P41_PortScanner.py b/Test2/P41_PortScanner.py new file mode 100644 index 0000000..f93d3ce --- /dev/null +++ b/Test2/P41_PortScanner.py @@ -0,0 +1,26 @@ +# Author: OMKAR PATHAK +# This program illustrates a simple port scanner using Python that scans for open ports + +import socket,sys + +def connect(host): + print('Scanning host:', host) + try: + for port in range(1, 1024): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + connection = s.connect_ex((host, port)) #NOTE: connect() needs a tuple! + if (connection == 0): + print('Port {} is open'.format(port)) + s.close() + except KeyboardInterrupt: + print('Exiting because you pressed Ctrl + C') + sys.exit() + + except socket.error: + print('Couldn\'t connect to Server') + +if __name__ == '__main__': + userInput = input('Enter the Server address(URL) to check for open ports: ') + remoteServerIP = socket.gethostbyname(userInput) + print('Server IP:',remoteServerIP) + connect(remoteServerIP) diff --git a/Test2/P42_MultiprocessingPipes.py b/Test2/P42_MultiprocessingPipes.py new file mode 100644 index 0000000..bc389ee --- /dev/null +++ b/Test2/P42_MultiprocessingPipes.py @@ -0,0 +1,25 @@ +# Author: OMKAR PATHAK +# This example illustrates an example for multiprocessing and synchronization using pipes + +from multiprocessing import Process, Pipe + +def parentData(parent): + ''' This function sends the data for the child process ''' + parent.send(['Hello']) + parent.close() + +def childData(child): + ''' This function sends the data for the parent process ''' + child.send(['Bye']) + child.close() + +if __name__ == '__main__': + parent, child = Pipe() # Create Pipe + process1 = Process(target = parentData, args = (parent, )) # Create a process for handling parent data + process2 = Process(target = childData, args = (child, )) # Create a process for handling child data + process1.start() # Start the parent process + process2.start() # Start the child process + print(parent.recv()) # Display data received from child (BYE) + print(child.recv()) # Display data received from parent (HELLO) + process1.join() # Wait till the process completes its execution + process2.join() diff --git a/Test2/P43_BinarySearchTree.py b/Test2/P43_BinarySearchTree.py new file mode 100644 index 0000000..eac303f --- /dev/null +++ b/Test2/P43_BinarySearchTree.py @@ -0,0 +1,145 @@ +# Author: OMKAR PATHAK +# This program illustrates an example of Binary Search Tree using Python + +class Node(object): + def __init__(self, data): + self.data = data + self.leftChild = None + self.rightChild = None + + def insert(self, data): + ''' For inserting the data in the Tree ''' + if self.data == data: + return False # As BST cannot contain duplicate data + + elif data < self.data: + ''' Data less than the root data is placed to the left of the root ''' + if self.leftChild: + return self.leftChild.insert(data) + else: + self.leftChild = Node(data) + return True + + else: + ''' Data greater than the root data is placed to the right of the root ''' + if self.rightChild: + return self.rightChild.insert(data) + else: + self.rightChild = Node(data) + return True + + + def find(self, data): + ''' This function checks whether the specified data is in tree or not ''' + if(data == self.data): + return True + elif(data < self.data): + if self.leftChild: + return self.leftChild.find(data) + else: + return False + else: + if self.rightChild: + return self.rightChild.find(data) + else: + return False + + def preorder(self): + '''For preorder traversal of the BST ''' + if self: + print(str(self.data), end = ' ') + if self.leftChild: + self.leftChild.preorder() + if self.rightChild: + self.rightChild.preorder() + + def inorder(self): + ''' For Inorder traversal of the BST ''' + if self: + if self.leftChild: + self.leftChild.inorder() + print(str(self.data), end = ' ') + if self.rightChild: + self.rightChild.inorder() + + def postorder(self): + ''' For postorder traversal of the BST ''' + if self: + if self.leftChild: + self.leftChild.postorder() + if self.rightChild: + self.rightChild.postorder() + print(str(self.data), end = ' ') + +class Tree(object): + def __init__(self, initial_data = []): + self.root = None + + # If provided, add initial data + for data in initial_data: + self.insert(data) + + def insert(self, data): + if self.root: + return self.root.insert(data) + else: + self.root = Node(data) + return True + + def find(self, data): + if self.root: + return self.root.find(data) + else: + return False + + def preorder(self): + if self.root is not None: + print() + print('Preorder: ') + self.root.preorder() + + def inorder(self): + print() + if self.root is not None: + print('Inorder: ') + self.root.inorder() + + def postorder(self): + print() + if self.root is not None: + print('Postorder: ') + self.root.postorder() + + + def pprint(self, head_node=0, _pre="", _last=True, term=False): + + head_node = self.root if head_node == 0 else head_node + + data = "*" if head_node is None else head_node.data + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + for i, child in enumerate([head_node.leftChild, head_node.rightChild]): + self.pprint(child, _pre, bool(i) ,term=not(bool(child))) + + +if __name__ == '__main__': + tree = Tree() + tree.insert(10) + tree.insert(12) + tree.insert(5) + tree.insert(4) + tree.insert(20) + tree.insert(8) + tree.insert(7) + tree.insert(15) + tree.insert(13) + tree.pprint() + print(tree.find(1)) + print(tree.find(12)) + tree.preorder() + tree.inorder() + tree.postorder() diff --git a/Test2/P44_Closures.py b/Test2/P44_Closures.py new file mode 100644 index 0000000..6f84fa8 --- /dev/null +++ b/Test2/P44_Closures.py @@ -0,0 +1,21 @@ +# Author: OMKAR PATHAK + +# Wikipedia: +# A closure is a record storing a function[a] together with an environment: +# a mapping associating each free variable of the function (variables that are used locally, but +# defined in an enclosing scope) with the value or reference to which the name was bound when +# the closure was created.A closure—unlike a plain function—allows the function to access those +# captured variables through the closure's copies of their values or references, even when the function +# is invoked outside their scope. + +def outerFunction(text): + text = text + + def innerFunction(): + print(text) + + return innerFunction + +if __name__ == '__main__': + myFunction = outerFunction('Hey!') + myFunction() diff --git a/Test2/P45_MoreOnClosures.py b/Test2/P45_MoreOnClosures.py new file mode 100644 index 0000000..9d95bf8 --- /dev/null +++ b/Test2/P45_MoreOnClosures.py @@ -0,0 +1,27 @@ +# Closures + +import logging +logging.basicConfig(filename='example.log', level=logging.INFO) + + +def logger(func): + def log_func(*args): + logging.info( + 'Running "{}" with arguments {}'.format(func.__name__, args)) + print(func(*args)) + return log_func + +def add(x, y): + return x+y + +def sub(x, y): + return x-y + +add_logger = logger(add) +sub_logger = logger(sub) + +add_logger(3, 3) +add_logger(4, 5) + +sub_logger(10, 5) +sub_logger(20, 10) diff --git a/Test2/P46_Decorators.py b/Test2/P46_Decorators.py new file mode 100644 index 0000000..b8f3469 --- /dev/null +++ b/Test2/P46_Decorators.py @@ -0,0 +1,21 @@ +# Author: OMKAR PATHAK +# In this example program we will see how decorators work in Python + +# Decorators provide a simple syntax for calling higher-order functions. By definition, +# a decorator is a function that takes another function and extends the behavior of the +# latter function without explicitly modifying it. Sounds confusing – but it's really not, +# especially after we go over a number of examples. + +def decorator(myFunc): + def insideDecorator(*args): + print('insideDecorator Function executed before {}'.format(myFunc.__name__)) + return myFunc(*args) + return insideDecorator + +@decorator # Decorator function that takes below function as an argument +def display(*args): + ''' This function is passed as an argument to the decorator function specified above after @ sign ''' + print('In display function') + print(*args) + +display('Hello','Hi',123) diff --git a/Test2/P47_MoreOnDecorators.py b/Test2/P47_MoreOnDecorators.py new file mode 100644 index 0000000..f86bb66 --- /dev/null +++ b/Test2/P47_MoreOnDecorators.py @@ -0,0 +1,27 @@ +# Author: OMKAR PATHAK +# In this example, we will be seeing some more concepts of decorators such as +# property decorator, getters and setters methods. + +class BankAccount(object): + def __init__(self, firstName, lastName): + self.firstName = firstName + self.lastName = lastName + + @property # property decorator + def fullName(self): + return self.firstName + ' ' + self.lastName + + @fullName.setter + def fullName(self, name): + firstName, lastName = name.split(' ') + self.firstName = firstName + self.lastName = lastName + +if __name__ == '__main__': + acc = BankAccount('Omkar', 'Pathak') + print(acc.fullName) # Notice that we can access the method for our class BankAccount without + # parenthesis! This is beacuse of property decorator + + # acc.fullName = 'Omkar Pathak' #This throws an error! Hence setter decorator should be used. + acc.fullName = 'Jagdish Pathak' + print(acc.fullName) diff --git a/Test2/P48_CountingSort.py b/Test2/P48_CountingSort.py new file mode 100644 index 0000000..3d914a3 --- /dev/null +++ b/Test2/P48_CountingSort.py @@ -0,0 +1,52 @@ +# Author: OMKAR PATHAK + +# Approach: +# Counting sort, like radix sort and bucket sort, +# is an integer based algorithm (i.e. the values of the input +# array are assumed to be integers). Hence counting sort is +# among the fastest sorting algorithms around, in theory. The +# particular distinction for counting sort is that it creates +# a bucket for each value and keep a counter in each bucket. +# Then each time a value is encountered in the input collection, +# the appropriate counter is incremented. Because counting sort +# creates a bucket for each value, an imposing restriction is +# that the maximum value in the input array be known beforehand. + +# Implementation notes: +# 1] Since the values range from 0 to k, create k+1 buckets. +# 2] To fill the buckets, iterate through the input list and +# each time a value appears, increment the counter in its +# bucket. +# 3] Now fill the input list with the compressed data in the +# buckets. Each bucket's key represents a value in the +# array. So for each bucket, from smallest key to largest, +# add the index of the bucket to the input array and +# decrease the counter in said bucket by one; until the +# counter is zero. + +# Best Case O(n+k); Average Case O(n+k); Worst Case O(n+k), +# where n is the size of the input array and k means the +# values range from 0 to k. + +def countingSort(myList): + maxValue = 0 + for i in range(len(myList)): + if myList[i] > maxValue: + maxValue = myList[i] + + buckets = [0] * (maxValue + 1) + + for i in myList: + buckets[i] += 1 + + i = 0 + for j in range(maxValue + 1): + for a in range(buckets[j]): + myList[i] = j + i += 1 + + return myList + +if __name__ == '__main__': + sortedList = countingSort([1,23,4,5,6,7,8]) + print(sortedList) diff --git a/Test2/P49_RockPaperScissors.py b/Test2/P49_RockPaperScissors.py new file mode 100644 index 0000000..eac20f8 --- /dev/null +++ b/Test2/P49_RockPaperScissors.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK +# This program illustrates a game of Rock Paper Scissors. +# RULES: +# Rock beats scissors +# Scissors beats paper +# Paper beats rock + +import random, time + +def rockPaperScissors(): + # R => Rock, P => Paper, S => Scissors + computerOptions = ['R', 'P', 'S'] + computer = computerOptions[random.randint(0, 2)] + + forOptions = {'R': 'Rock', 'P': 'Paper', 'S':'Scissors'} + + try: + player = input('Enter your choice [R]ock [P]aper [S]cissors: ') + player = player.upper() + if player in computerOptions: + if player == computer: + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('You both tied!') + elif player == 'R': + if computer == 'P': + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Sorry, you lose! Try again.') + else: + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Congrats, you win!') + elif player == 'S': + if computer == 'R': + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Sorry, you lose! Try again.') + else: + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Congrats, you win!') + elif player == 'P': + if computer == 'S': + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Sorry, you lose! Try again.') + else: + print('Player:',forOptions.get(player),'Computer:',forOptions.get(computer)) + print('Congrats, you win!') + else: + print('Please enter only R, P or S as your choice') + except: + exit() + +if __name__ == '__main__': + rockPaperScissors() diff --git a/Test2/P50_ListComprehensions.py b/Test2/P50_ListComprehensions.py new file mode 100644 index 0000000..a7597f1 --- /dev/null +++ b/Test2/P50_ListComprehensions.py @@ -0,0 +1,52 @@ +# Author: OMKAR PATHAK +# In this example we will see how to write list comprehensions to make our tasks easier + +# Python.org says: +# List comprehensions provide a concise way to create lists. +# Common applications are to make new lists where each element is +# the result of some operations applied to each member of another sequence +# or iterable, or to create a subsequence of those elements that satisfy a certain condition. + +numbers = [] +for i in range(10): + numbers.append(i) +print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +# Side Effect of above operation:It creates a variable(or overwrites) named 'x' +# that still exists after the loop completes. To get rid of this Side Effect we use List comprehensions. + +# List comprehension: +numbers = [i for i in range(10)] +print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +# Let us see few more examples +squares = [i * i for i in range(10)] +print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +# This is same as: +squares = [] +for i in range(10): + squares.append(i * i) + +# Some more: +odds = [i for i in numbers if i % 2 != 0] +print(odds) # [1, 3, 5, 7, 9] + +# This is same as: +odds = [] +for i in numbers: + if i % 2 != 0: + odds.append(i) + +# We can also use functions in comprehensions +def isSqaure(x): + import math + sqrt = int(math.sqrt(x)) + return x == sqrt * sqrt + +squares = [x for x in range(100) if isSqaure(x) == True] +print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +# Some Complex comprehensions: +pairs = [[x, x * x] for x in numbers] +print(pairs) # [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] diff --git a/Test2/P51_PythonJSON.py b/Test2/P51_PythonJSON.py new file mode 100644 index 0000000..363c5f8 --- /dev/null +++ b/Test2/P51_PythonJSON.py @@ -0,0 +1,25 @@ +# Author: OMKAR PATHAK +# This example shows how to use Python with JSON + +import json + +# For storing on json format +def storeJSON(fileName, data = {}): + with open(fileName, 'w') as fd: + json.dump(data, fd, indent = 4, separators = (',', ': ')) + +# For loading data from a JSON file +def loadJSON(fileName): + with open(fileName) as fd: + data = json.load(fd) + print(data) + return data + +if __name__ == '__main__': + data = loadJSON('example.json') + print(data['menu']['value']) # File + data['menu']['value'] = 'movie' + storeJSON('example.json', data) + print() + loadJSON('example.json') + print(data['menu']['value']) # movie diff --git a/Test2/P52_BucketSort.py b/Test2/P52_BucketSort.py new file mode 100644 index 0000000..a8fe614 --- /dev/null +++ b/Test2/P52_BucketSort.py @@ -0,0 +1,55 @@ +# Author: OMKAR PATHAK +# This program will illustrate how to implement bucket sort algorithm + +# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the +# elements of an array into a number of buckets. Each bucket is then sorted individually, either using +# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a +# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. +# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons +# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates +# involve the number of buckets. + +# Time Complexity of Solution: +# Best Case O(n); Average Case O(n); Worst Case O(n) + +from P26_InsertionSort import insertionSort +import math + +DEFAULT_BUCKET_SIZE = 5 + +def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): + if(len(myList) == 0): + print('You don\'t have any elements in array!') + + minValue = myList[0] + maxValue = myList[0] + + # For finding minimum and maximum values + for i in range(0, len(myList)): + if myList[i] < minValue: + minValue = myList[i] + elif myList[i] > maxValue: + maxValue = myList[i] + + # Initialize buckets + bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1 + buckets = [] + for i in range(0, bucketCount): + buckets.append([]) + + # For putting values in buckets + for i in range(0, len(myList)): + buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i]) + + # Sort buckets and place back into input array + sortedArray = [] + for i in range(0, len(buckets)): + insertionSort(buckets[i]) + for j in range(0, len(buckets[i])): + sortedArray.append(buckets[i][j]) + + return sortedArray + +if __name__ == '__main__': + sortedArray = bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95]) + print(sortedArray) diff --git a/Test2/P53_ShellSort.py b/Test2/P53_ShellSort.py new file mode 100644 index 0000000..46472d1 --- /dev/null +++ b/Test2/P53_ShellSort.py @@ -0,0 +1,28 @@ +# Author: OMKAR PATHAK +# This program illustrates the shell sort implementation in Python + +# According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort. +# It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by +# insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, +# then progressively reducing the gap between elements to be compared. Starting with far apart elements +# can move some out-of-place elements into position faster than a simple nearest neighbor exchange." + +# Best Case O(n logn); Average Case O(depends on gap sequence); Worst Case O(n) + +def shellSort(myList): + gap = len(myList) // 2 + while gap > 0: + for i in range(gap, len(myList)): + currentItem = myList[i] + j = i + while j >= gap and myList[j - gap] > currentItem: + myList[j] = myList[j - gap] + j -= gap + myList[j] = currentItem + gap //= 2 + + return myList + +if __name__ == '__main__': + myList = [12, 23, 4, 5, 3, 2, 12, 81, 56, 95] + print(shellSort(myList)) diff --git a/Test2/P54_PythonCSV.py b/Test2/P54_PythonCSV.py new file mode 100644 index 0000000..64585d7 --- /dev/null +++ b/Test2/P54_PythonCSV.py @@ -0,0 +1,30 @@ +# Author: OMKAR PATHAK +# In this example we will see how to use CSV files with Python + +# csv.QUOTE_ALL = Instructs writer objects to quote all fields. +# csv.QUOTE_MINIMAL = Instructs writer objects to only quote those fields which contain special characters such +# as delimiter, quotechar or any of the characters in lineterminator. +# csv.QUOTE_NONNUMERIC = Instructs writer objects to quote all non-numeric fields. +# Instructs the reader to convert all non-quoted fields to type float. +# csv.QUOTE_NONE = Instructs writer objects to never quote fields. + +import csv + +def csvRead(filePath): + with open(filePath) as fd: + reader = csv.reader(fd, delimiter = ',') + for row in reader: + print(row[0] + ' ' + row[1]) + +def csvWrite(filePath, data): + with open(filePath, 'a') as fd: + writer = csv.writer(fd, delimiter=',', quoting=csv.QUOTE_NONNUMERIC) + writer.writerow(data) + +if __name__ == '__main__': + # data = ['Firstname', 'Lastname'] + # csvWrite('example.csv', data) + userInput = input('What is your Fullname? ') + userInput = userInput.split(' ') + csvWrite('example.csv', userInput) + csvRead('example.csv') diff --git a/Test2/P55_Isogram.py b/Test2/P55_Isogram.py new file mode 100644 index 0000000..6c7b230 --- /dev/null +++ b/Test2/P55_Isogram.py @@ -0,0 +1,29 @@ +# Author: OMKAR PATHAK + +# ISOGRAM: An isogram (also known as a "nonpattern word") is a logological term for a word +# or phrase without a repeating letter + +def is_isogram(word): + # Convert the word or sentence in lower case letters. + clean_word = word.lower() + # Make ann empty list to append unique letters + letter_list = [] + for letter in clean_word: + # If letter is an alphabet then only check + if letter.isalpha(): + if letter in letter_list: + return False + letter_list.append(letter) + + return True + +if __name__ == '__main__': + print(is_isogram("")) # True + print(is_isogram("isogram")) # True + print(is_isogram("eleven")) # False + print(is_isogram("subdermatoglyphic")) # True + print(is_isogram("Alphabet")) # False + print(is_isogram("thumbscrew-japingly")) # True + print(is_isogram("Hjelmqvist-Gryb-Zock-Pfund-Wax")) # True + print(is_isogram("Emily Jung Schwartzkopf")) # True + print(is_isogram("accentor")) # False diff --git a/Test2/P56_Pangram.py b/Test2/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/Test2/P56_Pangram.py @@ -0,0 +1,36 @@ +# Author: OMKAR PATHAK + +# PANGRAM: A sentence containing every letter of the alphabet. + +from collections import Counter + +def pangram(sentence): + sentence = sentence.lower() + check = 'abcdefghijklmnopqrstuvwxyz' + alphabets = [] + for letter in sentence: + if letter.isalpha(): + if letter in alphabets: + pass + else: + alphabets.append(letter) + + alphabets = ''.join(alphabets) + if Counter(check) == Counter(alphabets): + return True + else: + return False + +# A short version of above function: +def pangram2(sentence): + alphabet = list(map(chr, range(97, 123))) + formattedString = ''.join(c for c in sentence if c.isalpha()).lower() + return set(alphabet) == set(formattedString) + +if __name__ == '__main__': + print(pangram('the quick brown fox jumps over the lazy dog')) # True + print(pangram('the_quick_brown_fox_jumps_over_the_lazy_dog')) # True + print(pangram('the 1 quick brown fish jumps over the 2 lazy dogs')) # False + print(pangram('Five quacking Zephyrs jolt my wax bed.')) # True + print(pangram('the quick brown fox jumped over the lazy FOX')) # False + print(pangram(' ')) # False diff --git a/Test2/P57_Anagram.py b/Test2/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/Test2/P57_Anagram.py @@ -0,0 +1,27 @@ +# Author: OMKAR PATHAK + +# ANAGRAM: An anagram is direct word switch or word play, the result of rearranging the letters +# of a word or phrase to produce a new word or phrase, using all the original letters exactly once + +# We are taking a word and a list. We return the anagrams of that word from the given list and return the +# list of anagrams else return empty list + +from collections import Counter + +def anagram(word, myList): + word = word.lower() + anagrams = [] + for words in myList: + if word != words.lower(): + if Counter(word) == Counter(words.lower()): + anagrams.append(words) + return anagrams + +if __name__ == '__main__': + print(anagram("ant", ["tan", "stand", "at"])) # ['tan'] + print(anagram("master", ["stream", "pigeon", "maters"])) # ['stream', 'maters'] + print(anagram("good", ["dog", "goody"])) # [] + print(anagram("allergy",[ + "gallery", "ballerina", "regally", "clergy", "largely", "leading" + ])) # ['gallery', 'regally', 'largely'] + print(anagram("BANANA", ["Banana"])) # [] diff --git a/Test2/P58_PerfectNumber.py b/Test2/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/Test2/P58_PerfectNumber.py @@ -0,0 +1,21 @@ +# Author: OMKAR PATHAK + +# Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of +# its proper positive divisors, that is, the sum of its positive divisors excluding the number itself +# (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all +# of its positive divisors (including itself). +# Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, +# and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: +# ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the +# perfect numbers 496 and 8128. + +def perfectNumber(number): + sum = 0 + for x in range(1, number): + if number % x == 0: + sum += x + return sum == number + +if __name__ == '__main__': + print(perfectNumber(6)) # True + print(perfectNumber(3)) # False diff --git a/Test2/P59_PascalTriangle.py b/Test2/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/Test2/P59_PascalTriangle.py @@ -0,0 +1,32 @@ +# Author: OMKAR PATHAK + +# PASCAL TRAINGLE: To build the triangle, start with "1" at the top, then continue placing numbers +# below it in a triangular pattern. Each number is the numbers directly above it added together. + +# generates the nth row of Pascal's Triangle +def pascalRow(n): + if n == 0: + return [1] + else: + N = pascalRow(n-1) + return [1] + [N[i] + N[i+1] for i in range(n-1)] + [1] + +# create a triangle of n rows +def pascalTriangle(n): + triangle = [] + for i in range(n): + triangle.append(pascalRow(i)) + return triangle + +if __name__ == '__main__': + for i in pascalTriangle(7): + print(i) + + # OUTPUT: + # [1] + # [1, 1] + # [1, 2, 1] + # [1, 3, 3, 1] + # [1, 4, 6, 4, 1] + # [1, 5, 10, 10, 5, 1] + # [1, 6, 15, 20, 15, 6, 1] diff --git a/Test2/P60_PickleModule.py b/Test2/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/Test2/P60_PickleModule.py @@ -0,0 +1,32 @@ +# Author: OMKAR PATHAK + +# In this example we will see how to use pickle module for storing the data efficiently! +# The pickle module translates an in-memory Python object into a serialized byte stream—a string of bytes +# that can be written to any file-like object. + +import pickle + +def storeData(): + # initializing data to be stored in db + Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak', 'age' : 21, 'pay' : 40000} + Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak', 'age' : 50, 'pay' : 50000} + + # database + db = {} + db['Omkar'] = Omkar + db['Jagdish'] = Jagdish + + dbfile = open('examplePickle', 'ab') # Its important to use binary mode + pickle.dump(db, dbfile) # source, destination + dbfile.close() + +def loadData(): + dbfile = open('examplePickle', 'rb') # for reading also binary mode is important + db = pickle.load(dbfile) + for keys in db: + print(keys,'=>',db[keys]) + dbfile.close() + +if __name__ == '__main__': + storeData() + loadData() diff --git a/Test2/P61_AddressBook.py b/Test2/P61_AddressBook.py new file mode 100644 index 0000000..98dec39 --- /dev/null +++ b/Test2/P61_AddressBook.py @@ -0,0 +1,150 @@ +# Author: OMKAR PATHAK + +# In this small mini project we will be creating a simple address book application that will store, search and +# delete records + +import pickle, os + +class AddressBook(object): + def __init__(self, name = None, address = None, email = None, phone = None): + self.name = name + self.address = address + self.email = email + self.phone = phone + self.contacts = {} + self.filename = 'addressbook' + + def __str__(self): + return '[Name: {0} | Address: {1} | Email: {2} | Phone: {3}]'.format(self.name, self.address, self.email, self.phone) + + def __repr__(self): + return '[Name: {0} | Address: {1} | Email: {2} | Phone: {3}]'.format(self.name, self.address, self.email, self.phone) + + # Adding details provided by the user in our Address Book + def addContacts(self): + try: + if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0: + myAddressBook = open(self.filename, 'rb') + data = pickle.load(myAddressBook) + myAddressBook.close() + else: + myAddressBook = open(self.filename, 'wb') + data = {} + + contact = self.getDetailsFromUser() + data[contact['Name']] = contact + myAddressBook = open(self.filename, 'wb') + pickle.dump(data, myAddressBook) + myAddressBook.close() + print('Contact Added Successfully!') + except: + print('There was an error! Contact was not added.') + finally: + myAddressBook.close() + + # Getting the details from the user to adding the Address Book + def getDetailsFromUser(self): + try: + self.contacts['Name'] = str(input('Enter Contact\'s Full Name: ')) + self.contacts['Address'] = str(input('Enter Contact\'s Address: ')) + self.contacts['Email'] = str(input('Enter Contact\'s Email Address: ')) + self.contacts['Phone'] = int(input('Enter Contact\'s Phone Number: ')) + return self.contacts + except KeyboardInterrupt as error: + raise error + + # To display ALL the contact in our Address Book + def displayContacts(self): + if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0: + myAddressBook = open(self.filename, 'rb') + data = pickle.load(myAddressBook) + myAddressBook.close() + if data: + for records in data.values(): + print(records) + myAddressBook.close() + else: + print('No Record in database.') + + # To search for a specific contact in our Address Book + def searchContacts(self): + if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0: + myAddressBook = open(self.filename, 'rb') + data = pickle.load(myAddressBook) + myAddressBook.close() + try: + contactToSearch = input('Enter the name of the contact to search: ') + counter = 0 + for contact in data.values(): + if contactToSearch in contact['Name']: + print(data[contact['Name']]) + counter += 1 + if counter == 0: + print('No record found whose name is:', contactToSearch) + except: + print('Error occured!') + else: + print('No Record in database.') + + # For modifying contacts + def modifyContacts(self): + if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0: + myAddressBook = open(self.filename, 'rb') + data = pickle.load(myAddressBook) + myAddressBook.close() + try: + contactToModify = input('Enter the name of the contact to modify (Only enter full name): ') + # Search for the record to update + for contact in data.values(): + if contactToModify == contact['Name']: + contact = data[contactToModify] + break + option = int(input('1. To modify name, 2. To modify address, 3. To modify email, 4. To modify phone: ')) + if option == 1: + contact['Name'] = input('Enter Name to modify: ') + del data[contactToModify] + data[contact['Name']] = contact + print('Successful') + elif option == 2: + contact['Address'] = input('Enter Address to modify: ') + del data[contactToModify] + data[contactToModify] = contact + print('Successful') + elif option == 3: + contact['Email'] = input('Enter Email to modify: ') + del data[contactToModify] + data[contactToModify] = contact + print('Successful') + elif option == 4: + contact['Phone'] = input('Enter Phone to modify: ') + del data[contactToModify] + data[contactToModify] = contact + print('Successful') + else: + print('Incorrect option selected.') + except: + print('Error occured. No such record found. Try Again!') + finally: + myAddressBook = open(self.filename, 'wb') + pickle.dump(data, myAddressBook) + myAddressBook.close() + else: + print('No Record in database.') + +if __name__ == '__main__': + myBook = AddressBook() + print('Enter 1. To Add Contacts 2. For Searching a Contact 3. For Modifying a Contact 4. To Display Contacts 5. To Exit') + while True: + choice = int(input('Enter your choice: ')) + if choice == 1: + myBook.addContacts() + elif choice == 2: + myBook.searchContacts() + elif choice == 3: + myBook.modifyContacts() + elif choice == 4: + myBook.displayContacts() + elif choice == 5: + exit() + else: + print('Invalid Option. Try Again!') diff --git a/Test2/P62_BinaryTree.py b/Test2/P62_BinaryTree.py new file mode 100644 index 0000000..56a3bc1 --- /dev/null +++ b/Test2/P62_BinaryTree.py @@ -0,0 +1,82 @@ +# Author: OMKAR PATHAK +# A data structure in which a record is linked to two successor records, usually referred to as +# the left branch when greater and the right when less than the previous record. + +class BinaryTree(object): + + def __init__(self,nodeData): + self.left = None + self.right = None + self.nodeData = nodeData + + def getLeftChild(self): + return self.left + + def getRightChild(self): + return self.right + + def setnodeDataValue(self,value): + self.nodeData = value + + def getnodeDataValue(self): + return self.nodeData + + def insertRight(self,newnodeData): + if self.right == None: + self.right = BinaryTree(newnodeData) + else: + tree = BinaryTree(newnodeData) + tree.right = self.right + self.right = tree + + def insertLeft(self,newnodeData): + if self.left == None: + self.left = BinaryTree(newnodeData) + else: + tree = BinaryTree(newnodeData) + self.left = tree + tree.left = self.left + + + + +def printTree(tree): + if tree != None: + printTree(tree.getLeftChild()) + print(tree.getnodeDataValue()) + printTree(tree.getRightChild()) + + +def pprint(head_node, _pre="", _last=True, term=False): + data = "*" if head_node is None else head_node.nodeData + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + left = head_node.getLeftChild() + right = head_node.getRightChild() + + for i, child in enumerate([left, right]): + pprint(child, _pre, bool(i) ,term=not(bool(child))) + + + + +def testTree(): + myTree = BinaryTree("1") + myTree.insertLeft("2") + myTree.insertRight("3") + myTree.insertRight("4") + printTree(myTree) + pprint(myTree) + +if __name__ == '__main__': + testTree() + + # OUTPUT + # 2 + # 1 + # 4 + # 3 diff --git a/Test2/P63_Graph.py b/Test2/P63_Graph.py new file mode 100644 index 0000000..0d562b2 --- /dev/null +++ b/Test2/P63_Graph.py @@ -0,0 +1,80 @@ +# Author: OMKAR PATHAK +# In this example, we will see how to implement graphs in Python + +class Vertex(object): + ''' This class helps to create a Vertex for our graph ''' + def __init__(self, key): + self.key = key + self.edges = {} + + def addNeighbour(self, neighbour, weight = 0): + self.edges[neighbour] = weight + + def __str__(self): + return str(self.key) + 'connected to: ' + str([x.key for x in self.edges]) + + def getEdges(self): + return self.edges.keys() + + def getKey(self): + return self.key + + def getWeight(self, neighbour): + try: + return self.edges[neighbour] + except: + return None + +class Graph(object): + ''' This class helps to create Graph with the help of created vertexes ''' + def __init__(self): + self.vertexList = {} + self.count = 0 + + def addVertex(self, key): + self.count += 1 + newVertex = Vertex(key) + self.vertexList[key] = newVertex + return newVertex + + def getVertex(self, vertex): + if vertex in self.vertexList: + return self.vertexList[vertex] + else: + return None + + def addEdge(self, fromEdge, toEdge, cost = 0): + if fromEdge not in self.vertexList: + newVertex = self.addVertex(fromEdge) + if toEdge not in self.vertexList: + newVertex = self.addVertex(toEdge) + self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost) + + def getVertices(self): + return self.vertexList.keys() + + def __iter__(self): + return iter(self.vertexList.values()) + + +if __name__ == '__main__': + graph = Graph() + graph.addVertex('A') + graph.addVertex('B') + graph.addVertex('C') + graph.addVertex('D') + + graph.addEdge('A', 'B', 5) + graph.addEdge('A', 'C', 6) + graph.addEdge('A', 'D', 2) + graph.addEdge('C', 'D', 3) + + for vertex in graph: + for vertexes in vertex.getEdges(): + print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes))) + + # OUTPUT: + # (C, D) => 3 + # (A, C) => 6 + # (A, D) => 2 + # (A, B) => 5 diff --git a/Test2/P64_DepthFirstTraversal.py b/Test2/P64_DepthFirstTraversal.py new file mode 100644 index 0000000..5cf6da8 --- /dev/null +++ b/Test2/P64_DepthFirstTraversal.py @@ -0,0 +1,82 @@ +# Author: OMKAR PATHAK + +# Depth first search is performed in three ways: +# Inorder +# Preorder +# Postorder + +class Node(object): + def __init__(self, data = None): + self.left = None + self.right = None + self.data = data + + # for setting left node + def setLeft(self, node): + self.left = node + + # for setting right node + def setRight(self, node): + self.right = node + + # for getting the left node + def getLeft(self): + return self.left + + # for getting right node + def getRight(self): + return self.right + + # for setting data of a node + def setData(self, data): + self.data = data + + # for getting data of a node + def getData(self): + return self.data + + +# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node +def inorder(Tree): + if Tree: + inorder(Tree.getLeft()) + print(Tree.getData(), end = ' ') + inorder(Tree.getRight()) + return + +# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node +def preorder(Tree): + if Tree: + print(Tree.getData(), end = ' ') + preorder(Tree.getLeft()) + preorder(Tree.getRight()) + return + +# in this we first traverse to the leftmost node and then to the rightmost node and then print the data +def postorder(Tree): + if Tree: + postorder(Tree.getLeft()) + postorder(Tree.getRight()) + print(Tree.getData(), end = ' ') + return + +if __name__ == '__main__': + root = Node(1) + root.setLeft(Node(2)) + root.setRight(Node(3)) + root.left.setLeft(Node(4)) + + print('Inorder Traversal:') + inorder(root) + print('\nPreorder Traversal:') + preorder(root) + print('\nPostorder Traversal:') + postorder(root) + + # OUTPUT: + # Inorder Traversal: + # 4 2 1 3 + # Preorder Traversal: + # 1 2 4 3 + # Postorder Traversal: + # 4 2 3 1 diff --git a/Test2/P65_BreadthFirstTraversal.py b/Test2/P65_BreadthFirstTraversal.py new file mode 100644 index 0000000..1517593 --- /dev/null +++ b/Test2/P65_BreadthFirstTraversal.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# Breadth First Traversal is the one in which we print the data level wise. Refer below code and output for more +# explanation + +class Node(object): + def __init__(self, data = None): + self.leftChild = None + self.rightChild = None + self.data = data + +def height(node): + if node is None: + return 0 + else: + leftHeight = height(node.leftChild) + rightHeight = height(node.rightChild) + + if leftHeight > rightHeight: + return leftHeight + 1 + else: + return rightHeight + 1 + +def breadthFirstTraversal(root): + if root == None: + return 0 + else: + h = height(root) + for i in range(h + 1): + printBFT(root, i) + +def printBFT(root, level): + if root is None: + return + else: + if level == 1: + print(root.data, end = ' ') + elif level > 1: + printBFT(root.leftChild, level - 1) + printBFT(root.rightChild, level - 1) + +if __name__ == '__main__': + root = Node(1) + root.leftChild = Node(2) + root.rightChild = Node(3) + root.leftChild.leftChild = Node(4) + + breadthFirstTraversal(root) + + # OUTPUT: + # 1 2 3 4