From d7952f2d0809f628034f99d5c87807d0b6627377 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 11 Mar 2026 18:46:56 +0530 Subject: [PATCH 01/11] Added python fils --- python/P01_hello.py | 9 +++++++ python/P02_VariableScope.py | 16 ++++++++++++ python/P03_ListsOperations.py | 47 +++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 python/P01_hello.py create mode 100644 python/P02_VariableScope.py create mode 100644 python/P03_ListsOperations.py diff --git a/python/P01_hello.py b/python/P01_hello.py new file mode 100644 index 0000000..fa97a01 --- /dev/null +++ b/python/P01_hello.py @@ -0,0 +1,9 @@ +# 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) + +if __name__ == '__main__': + justPrint('Hello01 appmod') diff --git a/python/P02_VariableScope.py b/python/P02_VariableScope.py new file mode 100644 index 0000000..6286822 --- /dev/null +++ b/python/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 = 'Global x' + +def test(): + #global x + y = 'Local y' + x = 'Local x' + print(x +', '+ y) #prints 'Local x' and 'Local y' + +if __name__ == '__main__': + test() + print(x) #prints 'Global x' diff --git a/python/P03_ListsOperations.py b/python/P03_ListsOperations.py new file mode 100644 index 0000000..f2d5dfc --- /dev/null +++ b/python/P03_ListsOperations.py @@ -0,0 +1,47 @@ +#Author: OMKAR PATHAK +#This program gives examples about various list operations + +#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) From 17cf43a2c40fd5d8fefadec0ec3f15a37e9c637c Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 11 Mar 2026 19:06:10 +0530 Subject: [PATCH 02/11] Added changes --- .gitignore | 1 + python/P02_InstanceMethods.py | 15 +++++++++++++++ python/P02_VariableScope copy.py | 16 ++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 python/P02_InstanceMethods.py create mode 100644 python/P02_VariableScope copy.py diff --git a/.gitignore b/.gitignore index 4d29575..e982eb3 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ npm-debug.log* yarn-debug.log* yarn-error.log* +.appmodconfig diff --git a/python/P02_InstanceMethods.py b/python/P02_InstanceMethods.py new file mode 100644 index 0000000..78c12ac --- /dev/null +++ b/python/P02_InstanceMethods.py @@ -0,0 +1,15 @@ +#Author: OMKAR PATHAK +#In this example we will be seeing how instance methods are used +#Instance methods are accessed by: instance.method() + +class Vehicle(): + #Class Methods/ Attributes + + #Here self is passed as an argument because instance is passed as first argument + def type(self): #Without self it throws an error + print(self) + print('I have a type') + +car = Vehicle() +print(car) +car.type() diff --git a/python/P02_VariableScope copy.py b/python/P02_VariableScope copy.py new file mode 100644 index 0000000..505eb22 --- /dev/null +++ b/python/P02_VariableScope copy.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' From 57e3ebaa86856f466936eea8e784ecb395a16221 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Mon, 6 Apr 2026 15:18:42 +0530 Subject: [PATCH 03/11] Added changed --- python/P04_Factorial.py | 16 ++++++ python/P05_Pattern.py | 112 ++++++++++++++++++++++++++++++++++++++++ python/P06_CharCount.py | 18 +++++++ 3 files changed, 146 insertions(+) create mode 100644 python/P04_Factorial.py create mode 100644 python/P05_Pattern.py create mode 100644 python/P06_CharCount.py diff --git a/python/P04_Factorial.py b/python/P04_Factorial.py new file mode 100644 index 0000000..fb29789 --- /dev/null +++ b/python/P04_Factorial.py @@ -0,0 +1,16 @@ +#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: + 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/python/P05_Pattern.py b/python/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/python/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/python/P06_CharCount.py b/python/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/python/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)) From b3156cd1bce5951cfa64d7136fa7a08745684cc1 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Mon, 20 Apr 2026 23:26:57 +0530 Subject: [PATCH 04/11] Added changes --- python/P04_Factorial copy.py | 16 +++++ python/P05_Pattern copy.py | 112 +++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 python/P04_Factorial copy.py create mode 100644 python/P05_Pattern copy.py diff --git a/python/P04_Factorial copy.py b/python/P04_Factorial copy.py new file mode 100644 index 0000000..fb29789 --- /dev/null +++ b/python/P04_Factorial copy.py @@ -0,0 +1,16 @@ +#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: + 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/python/P05_Pattern copy.py b/python/P05_Pattern copy.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/python/P05_Pattern copy.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]) From 3b0c036fc3637d69ed7f53631b78efc1de12dbbe Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 22 Apr 2026 14:43:58 +0530 Subject: [PATCH 05/11] Added changes --- python/P60_PickleModule.py | 32 +++++++ python/P61_AddressBook.py | 150 ++++++++++++++++++++++++++++++++ python/P70_SimpleProgressBar.py | 18 ++++ 3 files changed, 200 insertions(+) create mode 100644 python/P60_PickleModule.py create mode 100644 python/P61_AddressBook.py create mode 100644 python/P70_SimpleProgressBar.py diff --git a/python/P60_PickleModule.py b/python/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python/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/python/P61_AddressBook.py b/python/P61_AddressBook.py new file mode 100644 index 0000000..98dec39 --- /dev/null +++ b/python/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/python/P70_SimpleProgressBar.py b/python/P70_SimpleProgressBar.py new file mode 100644 index 0000000..3cdd8a6 --- /dev/null +++ b/python/P70_SimpleProgressBar.py @@ -0,0 +1,18 @@ +# This is the program for creating a simple progress bar. You may need this in many of your projects. +# You can install a module for progress bar by 'pip3 install progressbar2' + +import sys, time + +def progressBar(count, total, suffix=''): + barLength = 60 + filledLength = int(round(barLength * count / float(total))) + + percent = round(100.0 * count / float(total), 1) + bar = '=' * filledLength + '-' * (barLength - filledLength) + + sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percent, '%', suffix)) + sys.stdout.flush() + +for i in range(1,11): + time.sleep(1) + progressBar(i, 10) From 3575e236345fd4e6235a07f213a1213cf532ff91 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 22 Apr 2026 15:56:27 +0530 Subject: [PATCH 06/11] Added changes --- python/P06_CharCount.py | 2 +- python/P59_PascalTriangle.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 python/P59_PascalTriangle.py diff --git a/python/P06_CharCount.py b/python/P06_CharCount.py index ae13486..010151a 100644 --- a/python/P06_CharCount.py +++ b/python/P06_CharCount.py @@ -6,7 +6,7 @@ def charFrequency(userInput): userInput = userInput.lower() #covert to lowercase dict = {} for char in userInput: - keys = dict.keys() + if char in dict: if char in keys: dict[char] += 1 else: diff --git a/python/P59_PascalTriangle.py b/python/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python/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] From 93c94ade6ee280c55f8cc840db59c99e942f1817 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 22 Apr 2026 17:00:46 +0530 Subject: [PATCH 07/11] Commit changes --- python/P54_PythonCSV.py | 30 ++++++ python/P55_Isogram.py | 29 ++++++ python/P56_Pangram.py | 36 +++++++ python/P57_Anagram.py | 27 +++++ python/P58_PerfectNumber.py | 21 ++++ python/P59_PascalTriangle copy.py | 32 ++++++ python/P60_PickleModule copy.py | 32 ++++++ python/P61_AddressBook copy.py | 150 +++++++++++++++++++++++++++ python/P70_SimpleProgressBar copy.py | 18 ++++ python/P71_PythonUnittest.py | 44 ++++++++ python/P72_PythonLambda.py | 33 ++++++ python/P73_SimplePythonEncryption.py | 27 +++++ python/P74_PythonGenerators.py | 18 ++++ python/P75_TicTacToe.py | 75 ++++++++++++++ python/P77_FileSearching.py | 51 +++++++++ 15 files changed, 623 insertions(+) create mode 100644 python/P54_PythonCSV.py create mode 100644 python/P55_Isogram.py create mode 100644 python/P56_Pangram.py create mode 100644 python/P57_Anagram.py create mode 100644 python/P58_PerfectNumber.py create mode 100644 python/P59_PascalTriangle copy.py create mode 100644 python/P60_PickleModule copy.py create mode 100644 python/P61_AddressBook copy.py create mode 100644 python/P70_SimpleProgressBar copy.py create mode 100644 python/P71_PythonUnittest.py create mode 100644 python/P72_PythonLambda.py create mode 100644 python/P73_SimplePythonEncryption.py create mode 100644 python/P74_PythonGenerators.py create mode 100644 python/P75_TicTacToe.py create mode 100644 python/P77_FileSearching.py diff --git a/python/P54_PythonCSV.py b/python/P54_PythonCSV.py new file mode 100644 index 0000000..64585d7 --- /dev/null +++ b/python/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/python/P55_Isogram.py b/python/P55_Isogram.py new file mode 100644 index 0000000..6c7b230 --- /dev/null +++ b/python/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/python/P56_Pangram.py b/python/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/python/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/python/P57_Anagram.py b/python/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/python/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/python/P58_PerfectNumber.py b/python/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/python/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/python/P59_PascalTriangle copy.py b/python/P59_PascalTriangle copy.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python/P59_PascalTriangle copy.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/python/P60_PickleModule copy.py b/python/P60_PickleModule copy.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python/P60_PickleModule copy.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/python/P61_AddressBook copy.py b/python/P61_AddressBook copy.py new file mode 100644 index 0000000..98dec39 --- /dev/null +++ b/python/P61_AddressBook copy.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/python/P70_SimpleProgressBar copy.py b/python/P70_SimpleProgressBar copy.py new file mode 100644 index 0000000..3cdd8a6 --- /dev/null +++ b/python/P70_SimpleProgressBar copy.py @@ -0,0 +1,18 @@ +# This is the program for creating a simple progress bar. You may need this in many of your projects. +# You can install a module for progress bar by 'pip3 install progressbar2' + +import sys, time + +def progressBar(count, total, suffix=''): + barLength = 60 + filledLength = int(round(barLength * count / float(total))) + + percent = round(100.0 * count / float(total), 1) + bar = '=' * filledLength + '-' * (barLength - filledLength) + + sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percent, '%', suffix)) + sys.stdout.flush() + +for i in range(1,11): + time.sleep(1) + progressBar(i, 10) diff --git a/python/P71_PythonUnittest.py b/python/P71_PythonUnittest.py new file mode 100644 index 0000000..b5ef685 --- /dev/null +++ b/python/P71_PythonUnittest.py @@ -0,0 +1,44 @@ +# Author: OMKAR PATHAK + +# This module helps to build the testcases for a particular program to test its integrity and overall execution + +import unittest + +def checkPrime(number): + '''This function checks if the number is a prime number''' + if number == 2: + return True + if number > 2: + for i in range(2, number): + if number % i == 0: + return False + break + else: + return True + break + else: + return False + +# Class for providing test cases +class CheckPrime(unittest.TestCase): + + def test_checkPrime(self): + self.assertEqual(checkPrime(3), True) # Check if the function returns the value specified in the second argument + + def test_checkPrime2(self): + self.assertTrue(checkPrime(5)) # Check if the function returns True + self.assertFalse(checkPrime(4)) # Check if the function returns False + + def test_checkPrime3(self): + # Check that providing a string input produces an error + with self.assertRaises(TypeError): + checkPrime('1') + +if __name__ == '__main__': + unittest.main() + + # OUTPUT: + # ---------------------------------------------------------------------- + # Ran 3 tests in 0.000s + #   + # OK diff --git a/python/P72_PythonLambda.py b/python/P72_PythonLambda.py new file mode 100644 index 0000000..67fc881 --- /dev/null +++ b/python/P72_PythonLambda.py @@ -0,0 +1,33 @@ +# Author: OMKAR PATHAK + +# In this program we will learn what Python lambda is. +# The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without +# a name. These functions are throw-away functions, i.e. they are just needed where they have been created. +# Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda +# feature was added to Python due to the demand from Lisp programmers. + +# The argument list consists of a comma separated list of arguments and the expression is an arithmetic +# expression using these arguments. You can assign the function to a variable to give it a name. +# The following example of a lambda function returns the sum of its two arguments: + +myFunc = lambda x, y: x * y + +print(myFunc(2, 3)) #output: 6 + +#Here we are directly creating the function and passing the arguments +print((lambda x, y: x * y)(2, 3)) #same output i.e 6 + +print(type(lambda x, y: x * y)) #Output: + +# example to find squares of all numbers of a list +myList = [i for i in range(10)] + +# returns square of each number +myFunc2 = lambda x: x * x + +squares = list(map(myFunc2, myList)) +print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +print(list(map(lambda x: x * x, myList))) #same as above + + diff --git a/python/P73_SimplePythonEncryption.py b/python/P73_SimplePythonEncryption.py new file mode 100644 index 0000000..f898416 --- /dev/null +++ b/python/P73_SimplePythonEncryption.py @@ -0,0 +1,27 @@ +# Author: OMKAR PATHAK + +# This program illustrates a simple Python encryption example using the RSA Algotrithm + +# RSA is an algorithm used by modern computers to encrypt and decrypt messages. It is an asymmetric +# cryptographic algorithm. Asymmetric means that there are two different keys (public and private). + +# For installation: sudo pip3 install pycrypto + +from Crypto.PublicKey import RSA +from Crypto import Random + +randomGenerator = Random.new().read +# Generating a private key and a public key +# key stores both the keys +key = RSA.generate(1024, randomGenerator) # 1024 is the size of the key in bits +print(key) # Prints private key +print(key.publickey()) # Prints public key + +# Encryption using Public Key +publicKey = key.publickey() +encryptedData = publicKey.encrypt('My name is Omkar Pathak'.encode('utf-8'), 32) +print(encryptedData) + +# Decryption using Private Key +decryptedData = key.decrypt(encryptedData) +print(decryptedData) diff --git a/python/P74_PythonGenerators.py b/python/P74_PythonGenerators.py new file mode 100644 index 0000000..16333bf --- /dev/null +++ b/python/P74_PythonGenerators.py @@ -0,0 +1,18 @@ +# Author: OMKAR PATHAK + +# A Python generator is a function which returns a generator iterator (just an object we can iterate over) +# by calling yield + +def simpleGenerator(numbers): + i = 0 + while True: + check = input('Wanna generate a number? (If yes, press y else n): ') + if check in ('Y', 'y') and len(numbers) > i: + yield numbers[i] + i += 1 + else: + print('Bye!') + break + +for number in simpleGenerator([10, 11, 12, 14]): + print(number) diff --git a/python/P75_TicTacToe.py b/python/P75_TicTacToe.py new file mode 100644 index 0000000..a8dcee4 --- /dev/null +++ b/python/P75_TicTacToe.py @@ -0,0 +1,75 @@ +# Author: OMKAR PATHAK + +# A simple example of tic tac toe game + +# For storing user choices +choices = [] + +# For initializing the board with numbers +for i in range(0, 9): + choices.append(str(i)) + +firstPlayer = True +winner = False +iterations = 0 # To terminate the loop + +# For drawing board on to the terminal +def printBoard(): + print('\n=============') + print('| ' + choices[0] + ' | ' + choices[1] + ' | ' + choices[2] + ' |') + print('=============') + print('| ' + choices[3] + ' | ' + choices[4] + ' | ' + choices[5] + ' |') + print('=============') + print('| ' + choices[6] + ' | ' + choices[7] + ' | ' + choices[8] + ' |') + print('=============\n') + +# Play the game while the winner is not decided or the game is drawn +while not winner and iterations < 9: + printBoard() + + iterations += 1 + + if firstPlayer == True: + print('Player 1: ', end = '') + else: + print('Player 2: ', end = '') + + try: + playerInput = int(input()) + except: + print('Please enter a valid number from the board') + continue + + # Check if userInput already has 'X' or 'O' + if choices[playerInput] == 'X' or choices[playerInput] == 'O': + print('Illegal move, try again!') + continue + + if firstPlayer: + choices[playerInput] = 'X' + else: + choices[playerInput] = 'O' + + firstPlayer = not firstPlayer + + # Winning conditions + for index in range(0, 3): + # For [0,1,2], [3,4,5], [6,7,8] + if (choices[index * 3] == choices[((index * 3) + 1)] and choices[index * 3] == choices[((index * 3) + 2)]): + winner = True + printBoard() + + # For [0,3,6], [1,4,7], [2,5,8] + if(choices[index] == choices[index + 3] and choices[index + 3] == choices[index + 6]): + winner = True + printBoard() + + if((choices[0] == choices[4] and choices[4] == choices[8]) or + (choices[2] == choices[4] and choices[4] == choices[6])): + winner = True + printBoard() + +if winner: + print('Player ' + str(int(firstPlayer + 1)) + ' wins!') +else: + print('Game drawn') diff --git a/python/P77_FileSearching.py b/python/P77_FileSearching.py new file mode 100644 index 0000000..a651b5c --- /dev/null +++ b/python/P77_FileSearching.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# This program will help us implement concepts such as binary searching, operating system. +# P.S: Dont run this on root. That is dont give the DIRECTORY path as root else the program might +# consume all your resources and your system might get crashed + +import os +from pathlib import Path + +DIRECTORY = '/home/omkarpathak/Desktop' + +# List all the directories in the DIRECTORY +dirs = [name for name in os.listdir(DIRECTORY) if os.path.isdir(os.path.join(DIRECTORY, name))] + +# List all the files in the DIRECTORY +# files = [name for name in os.listdir(DIRECTORY) if os.path.isfile(os.path.join(DIRECTORY, name))] +files = [] + +for root, dirs, files in os.walk(DIRECTORY): + for File in files: + files.append(root + File) + +dirs.sort() +files.sort() + +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, List[mid] + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +print(dirs) +print(files) + +try: + result, filePath = binarySearch('server.py', files) + print(os.path.abspath(filePath)) +except: + print('File not found') From 08e64c53d96638406416e665d76d93fb350479e2 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Thu, 23 Apr 2026 17:43:39 +0530 Subject: [PATCH 08/11] Added changes --- python/p123/P74_PythonGenerators.py | 18 +++++++ python/p123/P75_TicTacToe.py | 75 +++++++++++++++++++++++++++++ python/p123/P77_FileSearching.py | 51 ++++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 python/p123/P74_PythonGenerators.py create mode 100644 python/p123/P75_TicTacToe.py create mode 100644 python/p123/P77_FileSearching.py diff --git a/python/p123/P74_PythonGenerators.py b/python/p123/P74_PythonGenerators.py new file mode 100644 index 0000000..16333bf --- /dev/null +++ b/python/p123/P74_PythonGenerators.py @@ -0,0 +1,18 @@ +# Author: OMKAR PATHAK + +# A Python generator is a function which returns a generator iterator (just an object we can iterate over) +# by calling yield + +def simpleGenerator(numbers): + i = 0 + while True: + check = input('Wanna generate a number? (If yes, press y else n): ') + if check in ('Y', 'y') and len(numbers) > i: + yield numbers[i] + i += 1 + else: + print('Bye!') + break + +for number in simpleGenerator([10, 11, 12, 14]): + print(number) diff --git a/python/p123/P75_TicTacToe.py b/python/p123/P75_TicTacToe.py new file mode 100644 index 0000000..a8dcee4 --- /dev/null +++ b/python/p123/P75_TicTacToe.py @@ -0,0 +1,75 @@ +# Author: OMKAR PATHAK + +# A simple example of tic tac toe game + +# For storing user choices +choices = [] + +# For initializing the board with numbers +for i in range(0, 9): + choices.append(str(i)) + +firstPlayer = True +winner = False +iterations = 0 # To terminate the loop + +# For drawing board on to the terminal +def printBoard(): + print('\n=============') + print('| ' + choices[0] + ' | ' + choices[1] + ' | ' + choices[2] + ' |') + print('=============') + print('| ' + choices[3] + ' | ' + choices[4] + ' | ' + choices[5] + ' |') + print('=============') + print('| ' + choices[6] + ' | ' + choices[7] + ' | ' + choices[8] + ' |') + print('=============\n') + +# Play the game while the winner is not decided or the game is drawn +while not winner and iterations < 9: + printBoard() + + iterations += 1 + + if firstPlayer == True: + print('Player 1: ', end = '') + else: + print('Player 2: ', end = '') + + try: + playerInput = int(input()) + except: + print('Please enter a valid number from the board') + continue + + # Check if userInput already has 'X' or 'O' + if choices[playerInput] == 'X' or choices[playerInput] == 'O': + print('Illegal move, try again!') + continue + + if firstPlayer: + choices[playerInput] = 'X' + else: + choices[playerInput] = 'O' + + firstPlayer = not firstPlayer + + # Winning conditions + for index in range(0, 3): + # For [0,1,2], [3,4,5], [6,7,8] + if (choices[index * 3] == choices[((index * 3) + 1)] and choices[index * 3] == choices[((index * 3) + 2)]): + winner = True + printBoard() + + # For [0,3,6], [1,4,7], [2,5,8] + if(choices[index] == choices[index + 3] and choices[index + 3] == choices[index + 6]): + winner = True + printBoard() + + if((choices[0] == choices[4] and choices[4] == choices[8]) or + (choices[2] == choices[4] and choices[4] == choices[6])): + winner = True + printBoard() + +if winner: + print('Player ' + str(int(firstPlayer + 1)) + ' wins!') +else: + print('Game drawn') diff --git a/python/p123/P77_FileSearching.py b/python/p123/P77_FileSearching.py new file mode 100644 index 0000000..a651b5c --- /dev/null +++ b/python/p123/P77_FileSearching.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# This program will help us implement concepts such as binary searching, operating system. +# P.S: Dont run this on root. That is dont give the DIRECTORY path as root else the program might +# consume all your resources and your system might get crashed + +import os +from pathlib import Path + +DIRECTORY = '/home/omkarpathak/Desktop' + +# List all the directories in the DIRECTORY +dirs = [name for name in os.listdir(DIRECTORY) if os.path.isdir(os.path.join(DIRECTORY, name))] + +# List all the files in the DIRECTORY +# files = [name for name in os.listdir(DIRECTORY) if os.path.isfile(os.path.join(DIRECTORY, name))] +files = [] + +for root, dirs, files in os.walk(DIRECTORY): + for File in files: + files.append(root + File) + +dirs.sort() +files.sort() + +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, List[mid] + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +print(dirs) +print(files) + +try: + result, filePath = binarySearch('server.py', files) + print(os.path.abspath(filePath)) +except: + print('File not found') From b77abac7861f344f5463624fd8775554601ff0cc Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Thu, 23 Apr 2026 17:46:33 +0530 Subject: [PATCH 09/11] Added changes --- python/p123/P55_Isogram.py | 29 +++++++++++++++++++++++++++++ python/p123/P56_Pangram.py | 36 ++++++++++++++++++++++++++++++++++++ python/p123/P57_Anagram.py | 27 +++++++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 python/p123/P55_Isogram.py create mode 100644 python/p123/P56_Pangram.py create mode 100644 python/p123/P57_Anagram.py diff --git a/python/p123/P55_Isogram.py b/python/p123/P55_Isogram.py new file mode 100644 index 0000000..6c7b230 --- /dev/null +++ b/python/p123/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/python/p123/P56_Pangram.py b/python/p123/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/python/p123/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/python/p123/P57_Anagram.py b/python/p123/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/python/p123/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"])) # [] From ded422e45e6ef0bbc46e0f3702cd1c5e155e6813 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Thu, 23 Apr 2026 18:09:16 +0530 Subject: [PATCH 10/11] Added changes --- python/p123/P55_Isogram.py | 4 ++-- python/p123/P56_Pangram.py | 8 +++----- python/p123/P57_Anagram.py | 2 +- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/python/p123/P55_Isogram.py b/python/p123/P55_Isogram.py index 6c7b230..7c98b28 100644 --- a/python/p123/P55_Isogram.py +++ b/python/p123/P55_Isogram.py @@ -7,13 +7,13 @@ 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 = [] + letter_list = set() 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) + letter_list.add(letter) return True diff --git a/python/p123/P56_Pangram.py b/python/p123/P56_Pangram.py index be2f31d..8be9cf5 100644 --- a/python/p123/P56_Pangram.py +++ b/python/p123/P56_Pangram.py @@ -7,13 +7,11 @@ def pangram(sentence): sentence = sentence.lower() check = 'abcdefghijklmnopqrstuvwxyz' - alphabets = [] + alphabets = set() for letter in sentence: if letter.isalpha(): - if letter in alphabets: - pass - else: - alphabets.append(letter) + alphabets.add(letter) + alphabets = ''.join(alphabets) if Counter(check) == Counter(alphabets): diff --git a/python/p123/P57_Anagram.py b/python/p123/P57_Anagram.py index 4d282d0..cd1f6f4 100644 --- a/python/p123/P57_Anagram.py +++ b/python/p123/P57_Anagram.py @@ -12,7 +12,7 @@ def anagram(word, myList): word = word.lower() anagrams = [] for words in myList: - if word != words.lower(): + if word.lower() != words.lower(): if Counter(word) == Counter(words.lower()): anagrams.append(words) return anagrams From a46d0534ebba3e9af53b267eadb91ebd7e41a6a7 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Thu, 23 Apr 2026 18:25:42 +0530 Subject: [PATCH 11/11] Added changes --- python/p123/P55_Isogram copy.py | 29 +++++ python/p123/P56_Pangram copy.py | 36 ++++++ python/p123/P57_Anagram copy.py | 27 +++++ python/p123/P58_PerfectNumber.py | 21 ++++ python/p123/P59_PascalTriangle copy.py | 32 ++++++ python/p123/P59_PascalTriangle.py | 32 ++++++ python/p123/P60_PickleModule copy.py | 32 ++++++ python/p123/P60_PickleModule.py | 32 ++++++ python/p123/P61_AddressBook copy.py | 150 +++++++++++++++++++++++++ 9 files changed, 391 insertions(+) create mode 100644 python/p123/P55_Isogram copy.py create mode 100644 python/p123/P56_Pangram copy.py create mode 100644 python/p123/P57_Anagram copy.py create mode 100644 python/p123/P58_PerfectNumber.py create mode 100644 python/p123/P59_PascalTriangle copy.py create mode 100644 python/p123/P59_PascalTriangle.py create mode 100644 python/p123/P60_PickleModule copy.py create mode 100644 python/p123/P60_PickleModule.py create mode 100644 python/p123/P61_AddressBook copy.py diff --git a/python/p123/P55_Isogram copy.py b/python/p123/P55_Isogram copy.py new file mode 100644 index 0000000..6c7b230 --- /dev/null +++ b/python/p123/P55_Isogram copy.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/python/p123/P56_Pangram copy.py b/python/p123/P56_Pangram copy.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/python/p123/P56_Pangram copy.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/python/p123/P57_Anagram copy.py b/python/p123/P57_Anagram copy.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/python/p123/P57_Anagram copy.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/python/p123/P58_PerfectNumber.py b/python/p123/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/python/p123/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/python/p123/P59_PascalTriangle copy.py b/python/p123/P59_PascalTriangle copy.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python/p123/P59_PascalTriangle copy.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/python/p123/P59_PascalTriangle.py b/python/p123/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python/p123/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/python/p123/P60_PickleModule copy.py b/python/p123/P60_PickleModule copy.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python/p123/P60_PickleModule copy.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/python/p123/P60_PickleModule.py b/python/p123/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python/p123/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/python/p123/P61_AddressBook copy.py b/python/p123/P61_AddressBook copy.py new file mode 100644 index 0000000..98dec39 --- /dev/null +++ b/python/p123/P61_AddressBook copy.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!')