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) 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/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]