From d7952f2d0809f628034f99d5c87807d0b6627377 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 11 Mar 2026 18:46:56 +0530 Subject: [PATCH 01/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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!') From 79200c8c9e267af53506d4fc17e235529dd6888a Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Mon, 18 May 2026 17:24:54 +0530 Subject: [PATCH 12/14] Deleted files --- python/P02_VariableScope.py | 16 -- python/P03_ListsOperations.py | 47 ------ python/P04_Factorial copy.py | 16 -- python/P04_Factorial.py | 16 -- python/P05_Pattern copy.py | 112 ------------- python/P05_Pattern.py | 112 ------------- python/P06_CharCount.py | 18 --- 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/P59_PascalTriangle.py | 32 ---- python/P60_PickleModule copy.py | 32 ---- python/P60_PickleModule.py | 32 ---- python/P61_AddressBook copy.py | 150 ------------------ python/P61_AddressBook.py | 150 ------------------ python/P70_SimpleProgressBar copy.py | 18 --- python/P70_SimpleProgressBar.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 ------ python/p123/P55_Isogram copy.py | 29 ---- python/p123/P55_Isogram.py | 29 ---- python/p123/P56_Pangram copy.py | 36 ----- python/p123/P56_Pangram.py | 34 ---- python/p123/P57_Anagram copy.py | 27 ---- python/p123/P57_Anagram.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 ------------------ python/p123/P74_PythonGenerators.py | 18 --- python/p123/P75_TicTacToe.py | 75 --------- python/p123/P77_FileSearching.py | 51 ------ {python => python123}/P01_hello.py | 0 {python => python123}/P02_InstanceMethods.py | 0 .../P02_VariableScope copy.py | 0 44 files changed, 1817 deletions(-) delete mode 100644 python/P02_VariableScope.py delete mode 100644 python/P03_ListsOperations.py delete mode 100644 python/P04_Factorial copy.py delete mode 100644 python/P04_Factorial.py delete mode 100644 python/P05_Pattern copy.py delete mode 100644 python/P05_Pattern.py delete mode 100644 python/P06_CharCount.py delete mode 100644 python/P54_PythonCSV.py delete mode 100644 python/P55_Isogram.py delete mode 100644 python/P56_Pangram.py delete mode 100644 python/P57_Anagram.py delete mode 100644 python/P58_PerfectNumber.py delete mode 100644 python/P59_PascalTriangle copy.py delete mode 100644 python/P59_PascalTriangle.py delete mode 100644 python/P60_PickleModule copy.py delete mode 100644 python/P60_PickleModule.py delete mode 100644 python/P61_AddressBook copy.py delete mode 100644 python/P61_AddressBook.py delete mode 100644 python/P70_SimpleProgressBar copy.py delete mode 100644 python/P70_SimpleProgressBar.py delete mode 100644 python/P71_PythonUnittest.py delete mode 100644 python/P72_PythonLambda.py delete mode 100644 python/P73_SimplePythonEncryption.py delete mode 100644 python/P74_PythonGenerators.py delete mode 100644 python/P75_TicTacToe.py delete mode 100644 python/P77_FileSearching.py delete mode 100644 python/p123/P55_Isogram copy.py delete mode 100644 python/p123/P55_Isogram.py delete mode 100644 python/p123/P56_Pangram copy.py delete mode 100644 python/p123/P56_Pangram.py delete mode 100644 python/p123/P57_Anagram copy.py delete mode 100644 python/p123/P57_Anagram.py delete mode 100644 python/p123/P58_PerfectNumber.py delete mode 100644 python/p123/P59_PascalTriangle copy.py delete mode 100644 python/p123/P59_PascalTriangle.py delete mode 100644 python/p123/P60_PickleModule copy.py delete mode 100644 python/p123/P60_PickleModule.py delete mode 100644 python/p123/P61_AddressBook copy.py delete mode 100644 python/p123/P74_PythonGenerators.py delete mode 100644 python/p123/P75_TicTacToe.py delete mode 100644 python/p123/P77_FileSearching.py rename {python => python123}/P01_hello.py (100%) rename {python => python123}/P02_InstanceMethods.py (100%) rename {python => python123}/P02_VariableScope copy.py (100%) diff --git a/python/P02_VariableScope.py b/python/P02_VariableScope.py deleted file mode 100644 index 6286822..0000000 --- a/python/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 = '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 deleted file mode 100644 index f2d5dfc..0000000 --- a/python/P03_ListsOperations.py +++ /dev/null @@ -1,47 +0,0 @@ -#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) diff --git a/python/P04_Factorial copy.py b/python/P04_Factorial copy.py deleted file mode 100644 index fb29789..0000000 --- a/python/P04_Factorial copy.py +++ /dev/null @@ -1,16 +0,0 @@ -#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/P04_Factorial.py b/python/P04_Factorial.py deleted file mode 100644 index fb29789..0000000 --- a/python/P04_Factorial.py +++ /dev/null @@ -1,16 +0,0 @@ -#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 deleted file mode 100644 index db988a0..0000000 --- a/python/P05_Pattern copy.py +++ /dev/null @@ -1,112 +0,0 @@ -#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/P05_Pattern.py b/python/P05_Pattern.py deleted file mode 100644 index db988a0..0000000 --- a/python/P05_Pattern.py +++ /dev/null @@ -1,112 +0,0 @@ -#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 deleted file mode 100644 index 010151a..0000000 --- a/python/P06_CharCount.py +++ /dev/null @@ -1,18 +0,0 @@ -#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: - if char in dict: - 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/python/P54_PythonCSV.py b/python/P54_PythonCSV.py deleted file mode 100644 index 64585d7..0000000 --- a/python/P54_PythonCSV.py +++ /dev/null @@ -1,30 +0,0 @@ -# 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 deleted file mode 100644 index 6c7b230..0000000 --- a/python/P55_Isogram.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 deleted file mode 100644 index be2f31d..0000000 --- a/python/P56_Pangram.py +++ /dev/null @@ -1,36 +0,0 @@ -# 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 deleted file mode 100644 index 4d282d0..0000000 --- a/python/P57_Anagram.py +++ /dev/null @@ -1,27 +0,0 @@ -# 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 deleted file mode 100644 index bcce192..0000000 --- a/python/P58_PerfectNumber.py +++ /dev/null @@ -1,21 +0,0 @@ -# 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 deleted file mode 100644 index 8a84384..0000000 --- a/python/P59_PascalTriangle copy.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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/P59_PascalTriangle.py b/python/P59_PascalTriangle.py deleted file mode 100644 index 8a84384..0000000 --- a/python/P59_PascalTriangle.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index b0c68e4..0000000 --- a/python/P60_PickleModule copy.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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/P60_PickleModule.py b/python/P60_PickleModule.py deleted file mode 100644 index b0c68e4..0000000 --- a/python/P60_PickleModule.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index 98dec39..0000000 --- a/python/P61_AddressBook copy.py +++ /dev/null @@ -1,150 +0,0 @@ -# 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/P61_AddressBook.py b/python/P61_AddressBook.py deleted file mode 100644 index 98dec39..0000000 --- a/python/P61_AddressBook.py +++ /dev/null @@ -1,150 +0,0 @@ -# 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 deleted file mode 100644 index 3cdd8a6..0000000 --- a/python/P70_SimpleProgressBar copy.py +++ /dev/null @@ -1,18 +0,0 @@ -# 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/P70_SimpleProgressBar.py b/python/P70_SimpleProgressBar.py deleted file mode 100644 index 3cdd8a6..0000000 --- a/python/P70_SimpleProgressBar.py +++ /dev/null @@ -1,18 +0,0 @@ -# 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 deleted file mode 100644 index b5ef685..0000000 --- a/python/P71_PythonUnittest.py +++ /dev/null @@ -1,44 +0,0 @@ -# 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 deleted file mode 100644 index 67fc881..0000000 --- a/python/P72_PythonLambda.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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 deleted file mode 100644 index f898416..0000000 --- a/python/P73_SimplePythonEncryption.py +++ /dev/null @@ -1,27 +0,0 @@ -# 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 deleted file mode 100644 index 16333bf..0000000 --- a/python/P74_PythonGenerators.py +++ /dev/null @@ -1,18 +0,0 @@ -# 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 deleted file mode 100644 index a8dcee4..0000000 --- a/python/P75_TicTacToe.py +++ /dev/null @@ -1,75 +0,0 @@ -# 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 deleted file mode 100644 index a651b5c..0000000 --- a/python/P77_FileSearching.py +++ /dev/null @@ -1,51 +0,0 @@ -# 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') diff --git a/python/p123/P55_Isogram copy.py b/python/p123/P55_Isogram copy.py deleted file mode 100644 index 6c7b230..0000000 --- a/python/p123/P55_Isogram copy.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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/P55_Isogram.py b/python/p123/P55_Isogram.py deleted file mode 100644 index 7c98b28..0000000 --- a/python/p123/P55_Isogram.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 = 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.add(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 deleted file mode 100644 index be2f31d..0000000 --- a/python/p123/P56_Pangram copy.py +++ /dev/null @@ -1,36 +0,0 @@ -# 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/P56_Pangram.py b/python/p123/P56_Pangram.py deleted file mode 100644 index 8be9cf5..0000000 --- a/python/p123/P56_Pangram.py +++ /dev/null @@ -1,34 +0,0 @@ -# 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 = set() - for letter in sentence: - if letter.isalpha(): - alphabets.add(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 deleted file mode 100644 index 4d282d0..0000000 --- a/python/p123/P57_Anagram copy.py +++ /dev/null @@ -1,27 +0,0 @@ -# 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/P57_Anagram.py b/python/p123/P57_Anagram.py deleted file mode 100644 index cd1f6f4..0000000 --- a/python/p123/P57_Anagram.py +++ /dev/null @@ -1,27 +0,0 @@ -# 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.lower() != 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 deleted file mode 100644 index bcce192..0000000 --- a/python/p123/P58_PerfectNumber.py +++ /dev/null @@ -1,21 +0,0 @@ -# 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 deleted file mode 100644 index 8a84384..0000000 --- a/python/p123/P59_PascalTriangle copy.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index 8a84384..0000000 --- a/python/p123/P59_PascalTriangle.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index b0c68e4..0000000 --- a/python/p123/P60_PickleModule copy.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index b0c68e4..0000000 --- a/python/p123/P60_PickleModule.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 deleted file mode 100644 index 98dec39..0000000 --- a/python/p123/P61_AddressBook copy.py +++ /dev/null @@ -1,150 +0,0 @@ -# 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/p123/P74_PythonGenerators.py b/python/p123/P74_PythonGenerators.py deleted file mode 100644 index 16333bf..0000000 --- a/python/p123/P74_PythonGenerators.py +++ /dev/null @@ -1,18 +0,0 @@ -# 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 deleted file mode 100644 index a8dcee4..0000000 --- a/python/p123/P75_TicTacToe.py +++ /dev/null @@ -1,75 +0,0 @@ -# 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 deleted file mode 100644 index a651b5c..0000000 --- a/python/p123/P77_FileSearching.py +++ /dev/null @@ -1,51 +0,0 @@ -# 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') diff --git a/python/P01_hello.py b/python123/P01_hello.py similarity index 100% rename from python/P01_hello.py rename to python123/P01_hello.py diff --git a/python/P02_InstanceMethods.py b/python123/P02_InstanceMethods.py similarity index 100% rename from python/P02_InstanceMethods.py rename to python123/P02_InstanceMethods.py diff --git a/python/P02_VariableScope copy.py b/python123/P02_VariableScope copy.py similarity index 100% rename from python/P02_VariableScope copy.py rename to python123/P02_VariableScope copy.py From 769a4ff2d3f9b1ff50796845aa9dd284a2234421 Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Mon, 18 May 2026 17:50:22 +0530 Subject: [PATCH 13/14] Added changes --- python123/P01_hello.py | 4 +- python123/P02_InstanceMethods.py | 2 +- python123/P05_Pattern.py | 112 ++++++++++++++++++++++++++++ python123/P06_CharCount.py | 18 +++++ python123/P06_Inheritance.py | 20 +++++ python123/P07_MoreOnInheritance.py | 26 +++++++ python123/P07_PrimeNumber.py | 23 ++++++ python123/P50_ListComprehensions.py | 52 +++++++++++++ python123/P51_PythonJSON.py | 25 +++++++ python123/P52_BucketSort.py | 55 ++++++++++++++ python123/P53_ShellSort.py | 28 +++++++ python123/P56_Pangram.py | 36 +++++++++ python123/P57_Anagram.py | 27 +++++++ python123/P58_PerfectNumber.py | 21 ++++++ python123/P59_PascalTriangle.py | 32 ++++++++ python123/P60_PickleModule.py | 32 ++++++++ 16 files changed, 510 insertions(+), 3 deletions(-) create mode 100644 python123/P05_Pattern.py create mode 100644 python123/P06_CharCount.py create mode 100644 python123/P06_Inheritance.py create mode 100644 python123/P07_MoreOnInheritance.py create mode 100644 python123/P07_PrimeNumber.py create mode 100644 python123/P50_ListComprehensions.py create mode 100644 python123/P51_PythonJSON.py create mode 100644 python123/P52_BucketSort.py create mode 100644 python123/P53_ShellSort.py create mode 100644 python123/P56_Pangram.py create mode 100644 python123/P57_Anagram.py create mode 100644 python123/P58_PerfectNumber.py create mode 100644 python123/P59_PascalTriangle.py create mode 100644 python123/P60_PickleModule.py diff --git a/python123/P01_hello.py b/python123/P01_hello.py index fa97a01..0add5a0 100644 --- a/python123/P01_hello.py +++ b/python123/P01_hello.py @@ -1,9 +1,9 @@ # Author: OMKAR PATHAK # This program prints the entered message -def justPrint(text): +def print_text(text): '''This function prints the text passed as argument to this function''' print(text) if __name__ == '__main__': - justPrint('Hello01 appmod') + print_text('Hello01 appmod') diff --git a/python123/P02_InstanceMethods.py b/python123/P02_InstanceMethods.py index 78c12ac..eae3555 100644 --- a/python123/P02_InstanceMethods.py +++ b/python123/P02_InstanceMethods.py @@ -6,7 +6,7 @@ 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 + def get_vehicle_type(self): print(self) print('I have a type') diff --git a/python123/P05_Pattern.py b/python123/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/python123/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/python123/P06_CharCount.py b/python123/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/python123/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/python123/P06_Inheritance.py b/python123/P06_Inheritance.py new file mode 100644 index 0000000..072464c --- /dev/null +++ b/python123/P06_Inheritance.py @@ -0,0 +1,20 @@ +#Author: OMKAR PATHAK +#This program illustrates the concept of inheritance +#Python looks up for method in following order: Instance attributes, class attributes and the +#from the base class + +class Data(object): + def getData(self): + print('In data!') + +class Time(Data): #Inheriting from Data class + def getTime(self): + print('In Time!') + +if __name__ == '__main__': + data = Data() + time = Time() + + data.getData() + time.getTime() + time.getData() #Inherited Data method diff --git a/python123/P07_MoreOnInheritance.py b/python123/P07_MoreOnInheritance.py new file mode 100644 index 0000000..61182e5 --- /dev/null +++ b/python123/P07_MoreOnInheritance.py @@ -0,0 +1,26 @@ +#Author: OMKAR PATHAK +#This program illustrates the advanced concepts of inheritance +#Python looks up for method in following order: Instance attributes, class attributes and the +#from the base class +#mro: Method Resolution order + +class Data(object): + def __init__(self, data): + self.data = data + + def getData(self): + print('Data:',self.data) + +class Time(Data): #Inhertiting from Data class + def getTime(self): + print('Time:',self.data) + +if __name__ == '__main__': + data = Data(10) + time = Time(20) #inherited Class -> Value passed to __init__of Data (Base class) + + time.getTime() + data.getData() + time.getData() + + print(Time.mro()) diff --git a/python123/P07_PrimeNumber.py b/python123/P07_PrimeNumber.py new file mode 100644 index 0000000..485de60 --- /dev/null +++ b/python123/P07_PrimeNumber.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program checks whether the entered number is prime or not + +def checkPrime(number): + '''This function checks for prime number''' + isPrime = False + if number == 2: + print(number, 'is a Prime Number') + if number > 1: + for i in range(2, number): + if number % i == 0: + print(number, 'is not a Prime Number') + isPrime = False + break + else: + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') + +if __name__ == '__main__': + userInput = int(input('Enter a number to check: ')) + checkPrime(userInput) diff --git a/python123/P50_ListComprehensions.py b/python123/P50_ListComprehensions.py new file mode 100644 index 0000000..a7597f1 --- /dev/null +++ b/python123/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/python123/P51_PythonJSON.py b/python123/P51_PythonJSON.py new file mode 100644 index 0000000..363c5f8 --- /dev/null +++ b/python123/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/python123/P52_BucketSort.py b/python123/P52_BucketSort.py new file mode 100644 index 0000000..a8fe614 --- /dev/null +++ b/python123/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/python123/P53_ShellSort.py b/python123/P53_ShellSort.py new file mode 100644 index 0000000..46472d1 --- /dev/null +++ b/python123/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/python123/P56_Pangram.py b/python123/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/python123/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/python123/P57_Anagram.py b/python123/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/python123/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/python123/P58_PerfectNumber.py b/python123/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/python123/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/python123/P59_PascalTriangle.py b/python123/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python123/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/python123/P60_PickleModule.py b/python123/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python123/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() From 88bc93ff8cee8da712a54334322822ec5ec0706f Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Mon, 18 May 2026 18:37:35 +0530 Subject: [PATCH 14/14] add changes --- python123/P51_PythonJSON.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python123/P51_PythonJSON.py b/python123/P51_PythonJSON.py index 363c5f8..4f2677a 100644 --- a/python123/P51_PythonJSON.py +++ b/python123/P51_PythonJSON.py @@ -4,7 +4,7 @@ import json # For storing on json format -def storeJSON(fileName, data = {}): +def storeJSON(fileName, data=None): with open(fileName, 'w') as fd: json.dump(data, fd, indent = 4, separators = (',', ': '))