Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Numpy/P40_CipherText.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Author: OMKAR PATHAK
# This program illustrates a simple example for encrypting/ decrypting your text

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS = LETTERS.lower()

def encrypt(message, key):
''' This function lets you to encrypt your message based on a key '''
encrypted = ''
for chars in message:
if chars in LETTERS:
num = LETTERS.find(chars)
num += key
if num>25:
num=num%25
num=num-1
encrypted =encrypted + LETTERS[num]

return encrypted

def decrypt(message, key):
''' This function lets you to decrypt your message based on a key '''
decrypted = ''
for chars in message:
if chars in LETTERS:
num = LETTERS.find(chars)
if num>25:
num=num%25
num=num-1
num = num -key
decrypted =decrypted+LETTERS[num]

return decrypted

def main():
message = str(input('Enter your message: '))
key = int(input('Enter you key [1 - 26]: '))
choice = input('Encrypt or Decrypt? [E/D]: ')

if choice.lower().startswith('e'):
print(encrypt(message, key))
else:
print(decrypt(message, key))

if __name__ == '__main__':
main()

# OUTPUT:
# omkarpathak@omkarpathak-Inspiron-3542:~/Documents/GITs/Python-Programs/Programs$ python P40_CipherText.py
# Enter your message: omkar
# Enter you key [1 - 26]: 2
# Encrypt or Decrypt? [E/D]: e
# qomct
#
# omkarpathak@omkarpathak-Inspiron-3542:~/Documents/GITs/Python-Programs/Programs$ python P40_CipherText.py
# Enter your message: qomct
# Enter you key [1 - 26]: 2
# Encrypt or Decrypt? [E/D]: d
# omkar
26 changes: 26 additions & 0 deletions Numpy/P41_PortScanner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Author: OMKAR PATHAK
# This program illustrates a simple port scanner using Python that scans for open ports

import socket,sys

def connect(host):
print('Scanning host:', host)
try:
for port in range(1, 1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = s.connect_ex((host, port)) #NOTE: connect() needs a tuple!
if (connection == 0):
print('Port {} is open'.format(port))
s.close()
except KeyboardInterrupt:
print('Exiting because you pressed Ctrl + C')
sys.exit()

except socket.error:
print('Couldn\'t connect to Server')

if __name__ == '__main__':
userInput = input('Enter the Server address(URL) to check for open ports: ')
remoteServerIP = socket.gethostbyname(userInput)
print('Server IP:',remoteServerIP)
connect(remoteServerIP)
25 changes: 25 additions & 0 deletions Numpy/P42_MultiprocessingPipes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Author: OMKAR PATHAK
# This example illustrates an example for multiprocessing and synchronization using pipes

from multiprocessing import Process, Pipe

def parentData(parent):
''' This function sends the data for the child process '''
parent.send(['Hello'])
parent.close()

def childData(child):
''' This function sends the data for the parent process '''
child.send(['Bye'])
child.close()

if __name__ == '__main__':
parent, child = Pipe() # Create Pipe
process1 = Process(target = parentData, args = (parent, )) # Create a process for handling parent data
process2 = Process(target = childData, args = (child, )) # Create a process for handling child data
process1.start() # Start the parent process
process2.start() # Start the child process
print(parent.recv()) # Display data received from child (BYE)
print(child.recv()) # Display data received from parent (HELLO)
process1.join() # Wait till the process completes its execution
process2.join()
145 changes: 145 additions & 0 deletions Numpy/P43_BinarySearchTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# Author: OMKAR PATHAK
# This program illustrates an example of Binary Search Tree using Python

class Node(object):
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None

def insert(self, data):
''' For inserting the data in the Tree '''
if self.data == data:
return False # As BST cannot contain duplicate data

elif data < self.data:
''' Data less than the root data is placed to the left of the root '''
if self.leftChild:
return self.leftChild.insert(data)
else:
self.leftChild = Node(data)
return True

else:
''' Data greater than the root data is placed to the right of the root '''
if self.rightChild:
return self.rightChild.insert(data)
else:
self.rightChild = Node(data)
return True


def find(self, data):
''' This function checks whether the specified data is in tree or not '''
if(data == self.data):
return True
elif(data < self.data):
if self.leftChild:
return self.leftChild.find(data)
else:
return False
else:
if self.rightChild:
return self.rightChild.find(data)
else:
return False

def preorder(self):
'''For preorder traversal of the BST '''
if self:
print(str(self.data), end = ' ')
if self.leftChild:
self.leftChild.preorder()
if self.rightChild:
self.rightChild.preorder()

def inorder(self):
''' For Inorder traversal of the BST '''
if self:
if self.leftChild:
self.leftChild.inorder()
print(str(self.data), end = ' ')
if self.rightChild:
self.rightChild.inorder()

def postorder(self):
''' For postorder traversal of the BST '''
if self:
if self.leftChild:
self.leftChild.postorder()
if self.rightChild:
self.rightChild.postorder()
print(str(self.data), end = ' ')

class Tree(object):
def __init__(self, initial_data = []):
self.root = None

# If provided, add initial data
for data in initial_data:
self.insert(data)

def insert(self, data):
if self.root:
return self.root.insert(data)
else:
self.root = Node(data)
return True

def find(self, data):
if self.root:
return self.root.find(data)
else:
return False

def preorder(self):
if self.root is not None:
print()
print('Preorder: ')
self.root.preorder()

def inorder(self):
print()
if self.root is not None:
print('Inorder: ')
self.root.inorder()

def postorder(self):
print()
if self.root is not None:
print('Postorder: ')
self.root.postorder()


def pprint(self, head_node=0, _pre="", _last=True, term=False):

head_node = self.root if head_node == 0 else head_node

data = "*" if head_node is None else head_node.data

print(_pre, "`- " if _last else "|- ", data, sep="")
_pre += " " if _last else "| "

if term: return

for i, child in enumerate([head_node.leftChild, head_node.rightChild]):
self.pprint(child, _pre, bool(i) ,term=not(bool(child)))


if __name__ == '__main__':
tree = Tree()
tree.insert(10)
tree.insert(12)
tree.insert(5)
tree.insert(4)
tree.insert(20)
tree.insert(8)
tree.insert(7)
tree.insert(15)
tree.insert(13)
tree.pprint()
print(tree.find(1))
print(tree.find(12))
tree.preorder()
tree.inorder()
tree.postorder()
21 changes: 21 additions & 0 deletions Numpy/P44_Closures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Author: OMKAR PATHAK

# Wikipedia:
# A closure is a record storing a function[a] together with an environment:
# a mapping associating each free variable of the function (variables that are used locally, but
# defined in an enclosing scope) with the value or reference to which the name was bound when
# the closure was created.A closure—unlike a plain function—allows the function to access those
# captured variables through the closure's copies of their values or references, even when the function
# is invoked outside their scope.

def outerFunction(text):
text = text

def innerFunction():
print(text)

return innerFunction

if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
27 changes: 27 additions & 0 deletions Numpy/P45_MoreOnClosures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Closures

import logging
logging.basicConfig(filename='example.log', level=logging.INFO)


def logger(func):
def log_func(*args):
logging.info(
'Running "{}" with arguments {}'.format(func.__name__, args))
print(func(*args))
return log_func

def add(x, y):
return x+y

def sub(x, y):
return x-y

add_logger = logger(add)
sub_logger = logger(sub)

add_logger(3, 3)
add_logger(4, 5)

sub_logger(10, 5)
sub_logger(20, 10)
21 changes: 21 additions & 0 deletions Numpy/P46_Decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Author: OMKAR PATHAK
# In this example program we will see how decorators work in Python

# Decorators provide a simple syntax for calling higher-order functions. By definition,
# a decorator is a function that takes another function and extends the behavior of the
# latter function without explicitly modifying it. Sounds confusing – but it's really not,
# especially after we go over a number of examples.

def decorator(myFunc):
def insideDecorator(*args):
print('insideDecorator Function executed before {}'.format(myFunc.__name__))
return myFunc(*args)
return insideDecorator

@decorator # Decorator function that takes below function as an argument
def display(*args):
''' This function is passed as an argument to the decorator function specified above after @ sign '''
print('In display function')
print(*args)

display('Hello','Hi',123)
27 changes: 27 additions & 0 deletions Numpy/P47_MoreOnDecorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Author: OMKAR PATHAK
# In this example, we will be seeing some more concepts of decorators such as
# property decorator, getters and setters methods.

class BankAccount(object):
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName

@property # property decorator
def fullName(self):
return self.firstName + ' ' + self.lastName

@fullName.setter
def fullName(self, name):
firstName, lastName = name.split(' ')
self.firstName = firstName
self.lastName = lastName

if __name__ == '__main__':
acc = BankAccount('Omkar', 'Pathak')
print(acc.fullName) # Notice that we can access the method for our class BankAccount without
# parenthesis! This is beacuse of property decorator

# acc.fullName = 'Omkar Pathak' #This throws an error! Hence setter decorator should be used.
acc.fullName = 'Jagdish Pathak'
print(acc.fullName)
Loading
Loading