diff --git a/.gitignore b/.gitignore index 4d29575..e982eb3 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ npm-debug.log* yarn-debug.log* yarn-error.log* +.appmodconfig diff --git a/python123/P01_hello.py b/python123/P01_hello.py new file mode 100644 index 0000000..0add5a0 --- /dev/null +++ b/python123/P01_hello.py @@ -0,0 +1,9 @@ +# Author: OMKAR PATHAK +# This program prints the entered message + +def print_text(text): + '''This function prints the text passed as argument to this function''' + print(text) + +if __name__ == '__main__': + print_text('Hello01 appmod') diff --git a/python123/P02_InstanceMethods.py b/python123/P02_InstanceMethods.py new file mode 100644 index 0000000..eae3555 --- /dev/null +++ b/python123/P02_InstanceMethods.py @@ -0,0 +1,15 @@ +#Author: OMKAR PATHAK +#In this example we will be seeing how instance methods are used +#Instance methods are accessed by: instance.method() + +class Vehicle(): + #Class Methods/ Attributes + + #Here self is passed as an argument because instance is passed as first argument + def get_vehicle_type(self): + print(self) + print('I have a type') + +car = Vehicle() +print(car) +car.type() diff --git a/python123/P02_VariableScope copy.py b/python123/P02_VariableScope copy.py new file mode 100644 index 0000000..505eb22 --- /dev/null +++ b/python123/P02_VariableScope copy.py @@ -0,0 +1,16 @@ +#Author: OMKAR PATHAK +#This programs shows the rules for variable scope + +# LEGB Rule: Local, Enclosing, Global, Built-in + +x = 80 # Global x + +def test(): + #global x + y = 100 # Local y + x = 20 + print(x + y) #prints 'Local x' and 'Local y' + +if __name__ == '__main__': + test() + print(x) #prints 'Global x' diff --git a/python123/P05_Pattern.py b/python123/P05_Pattern.py new file mode 100644 index 0000000..db988a0 --- /dev/null +++ b/python123/P05_Pattern.py @@ -0,0 +1,112 @@ +#Author: OMKAR PATHAK +#This program prints various patterns + +def pattern1(level): + '''This function prints the following pattern: + + * + ** + *** + **** + + ''' + for i in range(1, level + 1): + print() + for j in range(i): + print('*', end = '') + +def pattern2(level): + '''This function prints the following pattern: + + **** + *** + ** + * + + ''' + for i in range(level, 0, -1): + print() + for j in range(i): + print('*', end = '') + +def pattern3(level): + '''This function prints the following pattern: + + * + ** + *** + **** + + ''' + counter = level + for i in range(level + 1): + print(' ' * counter + '*' * i) + counter -= 1 + +def pattern4(level): + '''This function prints the following pattern: + + **** + *** + ** + * + + ''' + counter = 0 + for i in range(level, 0 ,-1): + print(' ' * counter + '*' * i) + counter += 1 + +def pattern5(level): + '''This function prints the following pattern: + + * + *** + ***** + + ''' + # first loop for number of lines + for i in range(level + 1): + #second loop for spaces + for j in range(level - i): + print (" ",end='') + # this loop is for printing stars + for k in range(2 * i - 1): + print("*", end='') + print() + + +if __name__ == '__main__': + userInput = int(input('Enter the level: ')) + pattern1(userInput) + print() + pattern2(userInput) + print() + pattern3(userInput) + print() + pattern4(userInput) + print() + pattern5(userInput) + print() + + def pattern6(userInput): + ''' + following is the another approach to solve pattern problems with reduced time complexity + + for + + * + ** + *** + **** + ***** + ''' + + num = int(input('Enter number for pattern')) + pattern = '*' + string = pattern * num + x = 0 + + for i in string: + x = x + 1 + print(string[0:x]) diff --git a/python123/P06_CharCount.py b/python123/P06_CharCount.py new file mode 100644 index 0000000..ae13486 --- /dev/null +++ b/python123/P06_CharCount.py @@ -0,0 +1,18 @@ +#Author: OMKAR PATHAK +#This program checks for the character frequency in the given string + +def charFrequency(userInput): + '''This fuction helps to count the char frequency in the given string ''' + userInput = userInput.lower() #covert to lowercase + dict = {} + for char in userInput: + keys = dict.keys() + if char in keys: + dict[char] += 1 + else: + dict[char] = 1 + return dict + +if __name__ == '__main__': + userInput = str(input('Enter a string: ')) + print(charFrequency(userInput)) diff --git a/python123/P06_Inheritance.py b/python123/P06_Inheritance.py new file mode 100644 index 0000000..072464c --- /dev/null +++ b/python123/P06_Inheritance.py @@ -0,0 +1,20 @@ +#Author: OMKAR PATHAK +#This program illustrates the concept of inheritance +#Python looks up for method in following order: Instance attributes, class attributes and the +#from the base class + +class Data(object): + def getData(self): + print('In data!') + +class Time(Data): #Inheriting from Data class + def getTime(self): + print('In Time!') + +if __name__ == '__main__': + data = Data() + time = Time() + + data.getData() + time.getTime() + time.getData() #Inherited Data method diff --git a/python123/P07_MoreOnInheritance.py b/python123/P07_MoreOnInheritance.py new file mode 100644 index 0000000..61182e5 --- /dev/null +++ b/python123/P07_MoreOnInheritance.py @@ -0,0 +1,26 @@ +#Author: OMKAR PATHAK +#This program illustrates the advanced concepts of inheritance +#Python looks up for method in following order: Instance attributes, class attributes and the +#from the base class +#mro: Method Resolution order + +class Data(object): + def __init__(self, data): + self.data = data + + def getData(self): + print('Data:',self.data) + +class Time(Data): #Inhertiting from Data class + def getTime(self): + print('Time:',self.data) + +if __name__ == '__main__': + data = Data(10) + time = Time(20) #inherited Class -> Value passed to __init__of Data (Base class) + + time.getTime() + data.getData() + time.getData() + + print(Time.mro()) diff --git a/python123/P07_PrimeNumber.py b/python123/P07_PrimeNumber.py new file mode 100644 index 0000000..485de60 --- /dev/null +++ b/python123/P07_PrimeNumber.py @@ -0,0 +1,23 @@ +#Author: OMKAR PATHAK +#This program checks whether the entered number is prime or not + +def checkPrime(number): + '''This function checks for prime number''' + isPrime = False + if number == 2: + print(number, 'is a Prime Number') + if number > 1: + for i in range(2, number): + if number % i == 0: + print(number, 'is not a Prime Number') + isPrime = False + break + else: + isPrime = True + + if isPrime: + print(number, 'is a Prime Number') + +if __name__ == '__main__': + userInput = int(input('Enter a number to check: ')) + checkPrime(userInput) diff --git a/python123/P50_ListComprehensions.py b/python123/P50_ListComprehensions.py new file mode 100644 index 0000000..a7597f1 --- /dev/null +++ b/python123/P50_ListComprehensions.py @@ -0,0 +1,52 @@ +# Author: OMKAR PATHAK +# In this example we will see how to write list comprehensions to make our tasks easier + +# Python.org says: +# List comprehensions provide a concise way to create lists. +# Common applications are to make new lists where each element is +# the result of some operations applied to each member of another sequence +# or iterable, or to create a subsequence of those elements that satisfy a certain condition. + +numbers = [] +for i in range(10): + numbers.append(i) +print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +# Side Effect of above operation:It creates a variable(or overwrites) named 'x' +# that still exists after the loop completes. To get rid of this Side Effect we use List comprehensions. + +# List comprehension: +numbers = [i for i in range(10)] +print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +# Let us see few more examples +squares = [i * i for i in range(10)] +print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +# This is same as: +squares = [] +for i in range(10): + squares.append(i * i) + +# Some more: +odds = [i for i in numbers if i % 2 != 0] +print(odds) # [1, 3, 5, 7, 9] + +# This is same as: +odds = [] +for i in numbers: + if i % 2 != 0: + odds.append(i) + +# We can also use functions in comprehensions +def isSqaure(x): + import math + sqrt = int(math.sqrt(x)) + return x == sqrt * sqrt + +squares = [x for x in range(100) if isSqaure(x) == True] +print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +# Some Complex comprehensions: +pairs = [[x, x * x] for x in numbers] +print(pairs) # [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] diff --git a/python123/P51_PythonJSON.py b/python123/P51_PythonJSON.py new file mode 100644 index 0000000..4f2677a --- /dev/null +++ b/python123/P51_PythonJSON.py @@ -0,0 +1,25 @@ +# Author: OMKAR PATHAK +# This example shows how to use Python with JSON + +import json + +# For storing on json format +def storeJSON(fileName, data=None): + with open(fileName, 'w') as fd: + json.dump(data, fd, indent = 4, separators = (',', ': ')) + +# For loading data from a JSON file +def loadJSON(fileName): + with open(fileName) as fd: + data = json.load(fd) + print(data) + return data + +if __name__ == '__main__': + data = loadJSON('example.json') + print(data['menu']['value']) # File + data['menu']['value'] = 'movie' + storeJSON('example.json', data) + print() + loadJSON('example.json') + print(data['menu']['value']) # movie diff --git a/python123/P52_BucketSort.py b/python123/P52_BucketSort.py new file mode 100644 index 0000000..a8fe614 --- /dev/null +++ b/python123/P52_BucketSort.py @@ -0,0 +1,55 @@ +# Author: OMKAR PATHAK +# This program will illustrate how to implement bucket sort algorithm + +# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the +# elements of an array into a number of buckets. Each bucket is then sorted individually, either using +# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a +# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. +# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons +# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates +# involve the number of buckets. + +# Time Complexity of Solution: +# Best Case O(n); Average Case O(n); Worst Case O(n) + +from P26_InsertionSort import insertionSort +import math + +DEFAULT_BUCKET_SIZE = 5 + +def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): + if(len(myList) == 0): + print('You don\'t have any elements in array!') + + minValue = myList[0] + maxValue = myList[0] + + # For finding minimum and maximum values + for i in range(0, len(myList)): + if myList[i] < minValue: + minValue = myList[i] + elif myList[i] > maxValue: + maxValue = myList[i] + + # Initialize buckets + bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1 + buckets = [] + for i in range(0, bucketCount): + buckets.append([]) + + # For putting values in buckets + for i in range(0, len(myList)): + buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i]) + + # Sort buckets and place back into input array + sortedArray = [] + for i in range(0, len(buckets)): + insertionSort(buckets[i]) + for j in range(0, len(buckets[i])): + sortedArray.append(buckets[i][j]) + + return sortedArray + +if __name__ == '__main__': + sortedArray = bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95]) + print(sortedArray) diff --git a/python123/P53_ShellSort.py b/python123/P53_ShellSort.py new file mode 100644 index 0000000..46472d1 --- /dev/null +++ b/python123/P53_ShellSort.py @@ -0,0 +1,28 @@ +# Author: OMKAR PATHAK +# This program illustrates the shell sort implementation in Python + +# According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort. +# It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by +# insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, +# then progressively reducing the gap between elements to be compared. Starting with far apart elements +# can move some out-of-place elements into position faster than a simple nearest neighbor exchange." + +# Best Case O(n logn); Average Case O(depends on gap sequence); Worst Case O(n) + +def shellSort(myList): + gap = len(myList) // 2 + while gap > 0: + for i in range(gap, len(myList)): + currentItem = myList[i] + j = i + while j >= gap and myList[j - gap] > currentItem: + myList[j] = myList[j - gap] + j -= gap + myList[j] = currentItem + gap //= 2 + + return myList + +if __name__ == '__main__': + myList = [12, 23, 4, 5, 3, 2, 12, 81, 56, 95] + print(shellSort(myList)) diff --git a/python123/P56_Pangram.py b/python123/P56_Pangram.py new file mode 100644 index 0000000..be2f31d --- /dev/null +++ b/python123/P56_Pangram.py @@ -0,0 +1,36 @@ +# Author: OMKAR PATHAK + +# PANGRAM: A sentence containing every letter of the alphabet. + +from collections import Counter + +def pangram(sentence): + sentence = sentence.lower() + check = 'abcdefghijklmnopqrstuvwxyz' + alphabets = [] + for letter in sentence: + if letter.isalpha(): + if letter in alphabets: + pass + else: + alphabets.append(letter) + + alphabets = ''.join(alphabets) + if Counter(check) == Counter(alphabets): + return True + else: + return False + +# A short version of above function: +def pangram2(sentence): + alphabet = list(map(chr, range(97, 123))) + formattedString = ''.join(c for c in sentence if c.isalpha()).lower() + return set(alphabet) == set(formattedString) + +if __name__ == '__main__': + print(pangram('the quick brown fox jumps over the lazy dog')) # True + print(pangram('the_quick_brown_fox_jumps_over_the_lazy_dog')) # True + print(pangram('the 1 quick brown fish jumps over the 2 lazy dogs')) # False + print(pangram('Five quacking Zephyrs jolt my wax bed.')) # True + print(pangram('the quick brown fox jumped over the lazy FOX')) # False + print(pangram(' ')) # False diff --git a/python123/P57_Anagram.py b/python123/P57_Anagram.py new file mode 100644 index 0000000..4d282d0 --- /dev/null +++ b/python123/P57_Anagram.py @@ -0,0 +1,27 @@ +# Author: OMKAR PATHAK + +# ANAGRAM: An anagram is direct word switch or word play, the result of rearranging the letters +# of a word or phrase to produce a new word or phrase, using all the original letters exactly once + +# We are taking a word and a list. We return the anagrams of that word from the given list and return the +# list of anagrams else return empty list + +from collections import Counter + +def anagram(word, myList): + word = word.lower() + anagrams = [] + for words in myList: + if word != words.lower(): + if Counter(word) == Counter(words.lower()): + anagrams.append(words) + return anagrams + +if __name__ == '__main__': + print(anagram("ant", ["tan", "stand", "at"])) # ['tan'] + print(anagram("master", ["stream", "pigeon", "maters"])) # ['stream', 'maters'] + print(anagram("good", ["dog", "goody"])) # [] + print(anagram("allergy",[ + "gallery", "ballerina", "regally", "clergy", "largely", "leading" + ])) # ['gallery', 'regally', 'largely'] + print(anagram("BANANA", ["Banana"])) # [] diff --git a/python123/P58_PerfectNumber.py b/python123/P58_PerfectNumber.py new file mode 100644 index 0000000..bcce192 --- /dev/null +++ b/python123/P58_PerfectNumber.py @@ -0,0 +1,21 @@ +# Author: OMKAR PATHAK + +# Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of +# its proper positive divisors, that is, the sum of its positive divisors excluding the number itself +# (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all +# of its positive divisors (including itself). +# Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, +# and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: +# ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the +# perfect numbers 496 and 8128. + +def perfectNumber(number): + sum = 0 + for x in range(1, number): + if number % x == 0: + sum += x + return sum == number + +if __name__ == '__main__': + print(perfectNumber(6)) # True + print(perfectNumber(3)) # False diff --git a/python123/P59_PascalTriangle.py b/python123/P59_PascalTriangle.py new file mode 100644 index 0000000..8a84384 --- /dev/null +++ b/python123/P59_PascalTriangle.py @@ -0,0 +1,32 @@ +# Author: OMKAR PATHAK + +# PASCAL TRAINGLE: To build the triangle, start with "1" at the top, then continue placing numbers +# below it in a triangular pattern. Each number is the numbers directly above it added together. + +# generates the nth row of Pascal's Triangle +def pascalRow(n): + if n == 0: + return [1] + else: + N = pascalRow(n-1) + return [1] + [N[i] + N[i+1] for i in range(n-1)] + [1] + +# create a triangle of n rows +def pascalTriangle(n): + triangle = [] + for i in range(n): + triangle.append(pascalRow(i)) + return triangle + +if __name__ == '__main__': + for i in pascalTriangle(7): + print(i) + + # OUTPUT: + # [1] + # [1, 1] + # [1, 2, 1] + # [1, 3, 3, 1] + # [1, 4, 6, 4, 1] + # [1, 5, 10, 10, 5, 1] + # [1, 6, 15, 20, 15, 6, 1] diff --git a/python123/P60_PickleModule.py b/python123/P60_PickleModule.py new file mode 100644 index 0000000..b0c68e4 --- /dev/null +++ b/python123/P60_PickleModule.py @@ -0,0 +1,32 @@ +# Author: OMKAR PATHAK + +# In this example we will see how to use pickle module for storing the data efficiently! +# The pickle module translates an in-memory Python object into a serialized byte stream—a string of bytes +# that can be written to any file-like object. + +import pickle + +def storeData(): + # initializing data to be stored in db + Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak', 'age' : 21, 'pay' : 40000} + Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak', 'age' : 50, 'pay' : 50000} + + # database + db = {} + db['Omkar'] = Omkar + db['Jagdish'] = Jagdish + + dbfile = open('examplePickle', 'ab') # Its important to use binary mode + pickle.dump(db, dbfile) # source, destination + dbfile.close() + +def loadData(): + dbfile = open('examplePickle', 'rb') # for reading also binary mode is important + db = pickle.load(dbfile) + for keys in db: + print(keys,'=>',db[keys]) + dbfile.close() + +if __name__ == '__main__': + storeData() + loadData()