psf/black code formatting (#1277)

This commit is contained in:
William Zhang
2019-10-05 01:14:13 -04:00
committed by Christian Clauss
parent 07f04a2e55
commit 9eac17a408
291 changed files with 6014 additions and 4571 deletions

View File

@@ -1,71 +1,88 @@
# -*- coding: utf-8 -*-
'''
"""
An auto-balanced binary tree!
'''
"""
import math
import random
class my_queue:
def __init__(self):
self.data = []
self.head = 0
self.tail = 0
def isEmpty(self):
return self.head == self.tail
def push(self,data):
def push(self, data):
self.data.append(data)
self.tail = self.tail + 1
def pop(self):
ret = self.data[self.head]
self.head = self.head + 1
return ret
def count(self):
return self.tail - self.head
def print(self):
print(self.data)
print("**************")
print(self.data[self.head:self.tail])
print(self.data[self.head : self.tail])
class my_node:
def __init__(self,data):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.height = 1
def getdata(self):
return self.data
def getleft(self):
return self.left
def getright(self):
return self.right
def getheight(self):
return self.height
def setdata(self,data):
def setdata(self, data):
self.data = data
return
def setleft(self,node):
def setleft(self, node):
self.left = node
return
def setright(self,node):
def setright(self, node):
self.right = node
return
def setheight(self,height):
def setheight(self, height):
self.height = height
return
def getheight(node):
if node is None:
return 0
return node.getheight()
def my_max(a,b):
def my_max(a, b):
if a > b:
return a
return b
def leftrotation(node):
r'''
r"""
A B
/ \ / \
B C Bl A
@@ -75,33 +92,35 @@ def leftrotation(node):
UB
UB = unbalanced node
'''
print("left rotation node:",node.getdata())
"""
print("left rotation node:", node.getdata())
ret = node.getleft()
node.setleft(ret.getright())
ret.setright(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
h1 = my_max(getheight(node.getright()), getheight(node.getleft())) + 1
node.setheight(h1)
h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1
h2 = my_max(getheight(ret.getright()), getheight(ret.getleft())) + 1
ret.setheight(h2)
return ret
def rightrotation(node):
'''
"""
a mirror symmetry rotation of the leftrotation
'''
print("right rotation node:",node.getdata())
"""
print("right rotation node:", node.getdata())
ret = node.getright()
node.setright(ret.getleft())
ret.setleft(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
h1 = my_max(getheight(node.getright()), getheight(node.getleft())) + 1
node.setheight(h1)
h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1
h2 = my_max(getheight(ret.getright()), getheight(ret.getleft())) + 1
ret.setheight(h2)
return ret
def rlrotation(node):
r'''
r"""
A A Br
/ \ / \ / \
B C RR Br C LR B A
@@ -110,51 +129,60 @@ def rlrotation(node):
\ /
UB Bl
RR = rightrotation LR = leftrotation
'''
"""
node.setleft(rightrotation(node.getleft()))
return leftrotation(node)
def lrrotation(node):
node.setright(leftrotation(node.getright()))
return rightrotation(node)
def insert_node(node,data):
def insert_node(node, data):
if node is None:
return my_node(data)
if data < node.getdata():
node.setleft(insert_node(node.getleft(),data))
if getheight(node.getleft()) - getheight(node.getright()) == 2: #an unbalance detected
if data < node.getleft().getdata(): #new node is the left child of the left child
node.setleft(insert_node(node.getleft(), data))
if (
getheight(node.getleft()) - getheight(node.getright()) == 2
): # an unbalance detected
if (
data < node.getleft().getdata()
): # new node is the left child of the left child
node = leftrotation(node)
else:
node = rlrotation(node) #new node is the right child of the left child
node = rlrotation(node) # new node is the right child of the left child
else:
node.setright(insert_node(node.getright(),data))
node.setright(insert_node(node.getright(), data))
if getheight(node.getright()) - getheight(node.getleft()) == 2:
if data < node.getright().getdata():
node = lrrotation(node)
else:
node = rightrotation(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
h1 = my_max(getheight(node.getright()), getheight(node.getleft())) + 1
node.setheight(h1)
return node
def getRightMost(root):
while root.getright() is not None:
root = root.getright()
return root.getdata()
def getLeftMost(root):
while root.getleft() is not None:
root = root.getleft()
return root.getdata()
def del_node(root,data):
def del_node(root, data):
if root.getdata() == data:
if root.getleft() is not None and root.getright() is not None:
temp_data = getLeftMost(root.getright())
root.setdata(temp_data)
root.setright(del_node(root.getright(),temp_data))
root.setright(del_node(root.getright(), temp_data))
elif root.getleft() is not None:
root = root.getleft()
else:
@@ -164,12 +192,12 @@ def del_node(root,data):
print("No such data")
return root
else:
root.setleft(del_node(root.getleft(),data))
root.setleft(del_node(root.getleft(), data))
elif root.getdata() < data:
if root.getright() is None:
return root
else:
root.setright(del_node(root.getright(),data))
root.setright(del_node(root.getright(), data))
if root is None:
return root
if getheight(root.getright()) - getheight(root.getleft()) == 2:
@@ -182,27 +210,31 @@ def del_node(root,data):
root = leftrotation(root)
else:
root = rlrotation(root)
height = my_max(getheight(root.getright()),getheight(root.getleft())) + 1
height = my_max(getheight(root.getright()), getheight(root.getleft())) + 1
root.setheight(height)
return root
class AVLtree:
def __init__(self):
self.root = None
def getheight(self):
# print("yyy")
# print("yyy")
return getheight(self.root)
def insert(self,data):
print("insert:"+str(data))
self.root = insert_node(self.root,data)
def del_node(self,data):
print("delete:"+str(data))
def insert(self, data):
print("insert:" + str(data))
self.root = insert_node(self.root, data)
def del_node(self, data):
print("delete:" + str(data))
if self.root is None:
print("Tree is empty!")
return
self.root = del_node(self.root,data)
def traversale(self): #a level traversale, gives a more intuitive look on the tree
self.root = del_node(self.root, data)
def traversale(self): # a level traversale, gives a more intuitive look on the tree
q = my_queue()
q.push(self.root)
layer = self.getheight()
@@ -211,21 +243,21 @@ class AVLtree:
cnt = 0
while not q.isEmpty():
node = q.pop()
space = " "*int(math.pow(2,layer-1))
print(space,end = "")
space = " " * int(math.pow(2, layer - 1))
print(space, end="")
if node is None:
print("*",end = "")
print("*", end="")
q.push(None)
q.push(None)
else:
print(node.getdata(),end = "")
print(node.getdata(), end="")
q.push(node.getleft())
q.push(node.getright())
print(space,end = "")
print(space, end="")
cnt = cnt + 1
for i in range(100):
if cnt == math.pow(2,i) - 1:
layer = layer -1
if cnt == math.pow(2, i) - 1:
layer = layer - 1
if layer == 0:
print()
print("*************************************")
@@ -235,11 +267,13 @@ class AVLtree:
print()
print("*************************************")
return
def test(self):
getheight(None)
print("****")
self.getheight()
if __name__ == "__main__":
t = AVLtree()
t.traversale()
@@ -248,7 +282,7 @@ if __name__ == "__main__":
for i in l:
t.insert(i)
t.traversale()
random.shuffle(l)
for i in l:
t.del_node(i)

View File

@@ -1,12 +1,13 @@
class Node: # This is the Class Node with constructor that contains data variable to type data and left,right pointers.
class Node: # This is the Class Node with constructor that contains data variable to type data and left,right pointers.
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def display(tree): #In Order traversal of the tree
if tree is None:
def display(tree): # In Order traversal of the tree
if tree is None:
return
if tree.left is not None:
@@ -19,7 +20,10 @@ def display(tree): #In Order traversal of the tree
return
def depth_of_tree(tree): #This is the recursive function to find the depth of binary tree.
def depth_of_tree(
tree
): # This is the recursive function to find the depth of binary tree.
if tree is None:
return 0
else:
@@ -31,18 +35,20 @@ def depth_of_tree(tree): #This is the recursive function to find the depth of bi
return 1 + depth_r_tree
def is_full_binary_tree(tree): # This functions returns that is it full binary tree or not?
def is_full_binary_tree(
tree
): # This functions returns that is it full binary tree or not?
if tree is None:
return True
if (tree.left is None) and (tree.right is None):
return True
if (tree.left is not None) and (tree.right is not None):
return (is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right))
return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right)
else:
return False
def main(): # Main func for testing.
def main(): # Main func for testing.
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
@@ -59,5 +65,5 @@ def main(): # Main func for testing.
display(tree)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View File

@@ -1,13 +1,14 @@
'''
"""
A binary search Tree
'''
class Node:
"""
class Node:
def __init__(self, label, parent):
self.label = label
self.left = None
self.right = None
#Added in order to delete a node easier
# Added in order to delete a node easier
self.parent = parent
def getLabel(self):
@@ -34,8 +35,8 @@ class Node:
def setParent(self, parent):
self.parent = parent
class BinarySearchTree:
class BinarySearchTree:
def __init__(self):
self.root = None
@@ -46,90 +47,90 @@ class BinarySearchTree:
if self.empty():
self.root = new_node
else:
#If Tree is not empty
# If Tree is not empty
curr_node = self.root
#While we don't get to a leaf
# While we don't get to a leaf
while curr_node is not None:
#We keep reference of the parent node
# We keep reference of the parent node
parent_node = curr_node
#If node label is less than current node
# If node label is less than current node
if new_node.getLabel() < curr_node.getLabel():
#We go left
# We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
# Else we go right
curr_node = curr_node.getRight()
#We insert the new node in a leaf
# We insert the new node in a leaf
if new_node.getLabel() < parent_node.getLabel():
parent_node.setLeft(new_node)
else:
parent_node.setRight(new_node)
#Set parent to the new node
# Set parent to the new node
new_node.setParent(parent_node)
def delete(self, label):
if (not self.empty()):
#Look for the node with that label
if not self.empty():
# Look for the node with that label
node = self.getNode(label)
#If the node exists
if(node is not None):
#If it has no children
if(node.getLeft() is None and node.getRight() is None):
# If the node exists
if node is not None:
# If it has no children
if node.getLeft() is None and node.getRight() is None:
self.__reassignNodes(node, None)
node = None
#Has only right children
elif(node.getLeft() is None and node.getRight() is not None):
# Has only right children
elif node.getLeft() is None and node.getRight() is not None:
self.__reassignNodes(node, node.getRight())
#Has only left children
elif(node.getLeft() is not None and node.getRight() is None):
# Has only left children
elif node.getLeft() is not None and node.getRight() is None:
self.__reassignNodes(node, node.getLeft())
#Has two children
# Has two children
else:
#Gets the max value of the left branch
# Gets the max value of the left branch
tmpNode = self.getMax(node.getLeft())
#Deletes the tmpNode
# Deletes the tmpNode
self.delete(tmpNode.getLabel())
#Assigns the value to the node to delete and keesp tree structure
# Assigns the value to the node to delete and keesp tree structure
node.setLabel(tmpNode.getLabel())
def getNode(self, label):
curr_node = None
#If the tree is not empty
if(not self.empty()):
#Get tree root
# If the tree is not empty
if not self.empty():
# Get tree root
curr_node = self.getRoot()
#While we don't find the node we look for
#I am using lazy evaluation here to avoid NoneType Attribute error
# While we don't find the node we look for
# I am using lazy evaluation here to avoid NoneType Attribute error
while curr_node is not None and curr_node.getLabel() is not label:
#If node label is less than current node
# If node label is less than current node
if label < curr_node.getLabel():
#We go left
# We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
# Else we go right
curr_node = curr_node.getRight()
return curr_node
def getMax(self, root = None):
if(root is not None):
def getMax(self, root=None):
if root is not None:
curr_node = root
else:
#We go deep on the right branch
# We go deep on the right branch
curr_node = self.getRoot()
if(not self.empty()):
while(curr_node.getRight() is not None):
if not self.empty():
while curr_node.getRight() is not None:
curr_node = curr_node.getRight()
return curr_node
def getMin(self, root = None):
if(root is not None):
def getMin(self, root=None):
if root is not None:
curr_node = root
else:
#We go deep on the left branch
# We go deep on the left branch
curr_node = self.getRoot()
if(not self.empty()):
if not self.empty():
curr_node = self.getRoot()
while(curr_node.getLeft() is not None):
while curr_node.getLeft() is not None:
curr_node = curr_node.getLeft()
return curr_node
@@ -150,34 +151,34 @@ class BinarySearchTree:
return self.root
def __isRightChildren(self, node):
if(node == node.getParent().getRight()):
if node == node.getParent().getRight():
return True
return False
def __reassignNodes(self, node, newChildren):
if(newChildren is not None):
if newChildren is not None:
newChildren.setParent(node.getParent())
if(node.getParent() is not None):
#If it is the Right Children
if(self.__isRightChildren(node)):
if node.getParent() is not None:
# If it is the Right Children
if self.__isRightChildren(node):
node.getParent().setRight(newChildren)
else:
#Else it is the left children
# Else it is the left children
node.getParent().setLeft(newChildren)
#This function traversal the tree. By default it returns an
#In order traversal list. You can pass a function to traversal
#The tree as needed by client code
def traversalTree(self, traversalFunction = None, root = None):
if(traversalFunction is None):
#Returns a list of nodes in preOrder by default
# This function traversal the tree. By default it returns an
# In order traversal list. You can pass a function to traversal
# The tree as needed by client code
def traversalTree(self, traversalFunction=None, root=None):
if traversalFunction is None:
# Returns a list of nodes in preOrder by default
return self.__InOrderTraversal(self.root)
else:
#Returns a list of nodes in the order that the users wants to
# Returns a list of nodes in the order that the users wants to
return traversalFunction(self.root)
#Returns an string of all the nodes labels in the list
#In Order Traversal
# Returns an string of all the nodes labels in the list
# In Order Traversal
def __str__(self):
list = self.__InOrderTraversal(self.root)
str = ""
@@ -185,6 +186,7 @@ class BinarySearchTree:
str = str + " " + x.getLabel().__str__()
return str
def InPreOrder(curr_node):
nodeList = []
if curr_node is not None:
@@ -193,8 +195,9 @@ def InPreOrder(curr_node):
nodeList = nodeList + InPreOrder(curr_node.getRight())
return nodeList
def testBinarySearchTree():
r'''
r"""
Example
8
/ \
@@ -203,15 +206,15 @@ def testBinarySearchTree():
1 6 14
/ \ /
4 7 13
'''
"""
r'''
r"""
Example After Deletion
7
/ \
1 4
'''
"""
t = BinarySearchTree()
t.insert(8)
t.insert(3)
@@ -223,20 +226,20 @@ def testBinarySearchTree():
t.insert(4)
t.insert(7)
#Prints all the elements of the list in order traversal
# Prints all the elements of the list in order traversal
print(t.__str__())
if(t.getNode(6) is not None):
if t.getNode(6) is not None:
print("The label 6 exists")
else:
print("The label 6 doesn't exist")
if(t.getNode(-1) is not None):
if t.getNode(-1) is not None:
print("The label -1 exists")
else:
print("The label -1 doesn't exist")
if(not t.empty()):
if not t.empty():
print(("Max Value: ", t.getMax().getLabel()))
print(("Min Value: ", t.getMin().getLabel()))
@@ -247,11 +250,12 @@ def testBinarySearchTree():
t.delete(6)
t.delete(14)
#Gets all the elements of the tree In pre order
#And it prints them
# Gets all the elements of the tree In pre order
# And it prints them
list = t.traversalTree(InPreOrder, t.root)
for x in list:
print(x)
if __name__ == "__main__":
testBinarySearchTree()

View File

@@ -1,28 +1,28 @@
class FenwickTree:
def __init__(self, SIZE): # create fenwick tree with size SIZE
def __init__(self, SIZE): # create fenwick tree with size SIZE
self.Size = SIZE
self.ft = [0 for i in range (0,SIZE)]
self.ft = [0 for i in range(0, SIZE)]
def update(self, i, val): # update data (adding) in index i in O(lg N)
while (i < self.Size):
def update(self, i, val): # update data (adding) in index i in O(lg N)
while i < self.Size:
self.ft[i] += val
i += i & (-i)
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
ret = 0
while (i > 0):
while i > 0:
ret += self.ft[i]
i -= i & (-i)
return ret
if __name__ == '__main__':
if __name__ == "__main__":
f = FenwickTree(100)
f.update(1,20)
f.update(4,4)
f.update(1, 20)
f.update(4, 4)
print(f.query(1))
print(f.query(3))
print(f.query(4))
f.update(2,-5)
f.update(2, -5)
print(f.query(1))
print(f.query(3))

View File

@@ -1,34 +1,38 @@
import math
class SegmentTree:
class SegmentTree:
def __init__(self, N):
self.N = N
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
self.flag = [0 for i in range(0,4*N)] # flag for lazy update
self.st = [
0 for i in range(0, 4 * N)
] # approximate the overall size of segment tree with array N
self.lazy = [0 for i in range(0, 4 * N)] # create array to store lazy update
self.flag = [0 for i in range(0, 4 * N)] # flag for lazy update
def left(self, idx):
return idx*2
return idx * 2
def right(self, idx):
return idx*2 + 1
return idx * 2 + 1
def build(self, idx, l, r, A):
if l==r:
self.st[idx] = A[l-1]
else :
mid = (l+r)//2
self.build(self.left(idx),l,mid, A)
self.build(self.right(idx),mid+1,r, A)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
if l == r:
self.st[idx] = A[l - 1]
else:
mid = (l + r) // 2
self.build(self.left(idx), l, mid, A)
self.build(self.right(idx), mid + 1, r, A)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
# update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
def update(
self, idx, l, r, a, b, val
): # update(1, 1, N, a, b, v) for update val v to [a,b]
if self.flag[idx] == True:
self.st[idx] = self.lazy[idx]
self.flag[idx] = False
if l!=r:
if l != r:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
@@ -36,22 +40,22 @@ class SegmentTree:
if r < a or l > b:
return True
if l >= a and r <= b :
if l >= a and r <= b:
self.st[idx] = val
if l!=r:
if l != r:
self.lazy[self.left(idx)] = val
self.lazy[self.right(idx)] = val
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
return True
mid = (l+r)//2
self.update(self.left(idx),l,mid,a,b,val)
self.update(self.right(idx),mid+1,r,a,b,val)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
mid = (l + r) // 2
self.update(self.left(idx), l, mid, a, b, val)
self.update(self.right(idx), mid + 1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
return True
# query with O(lg N)
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
def query(self, idx, l, r, a, b): # query(1, 1, N, a, b) for query max of [a,b]
if self.flag[idx] == True:
self.st[idx] = self.lazy[idx]
self.flag[idx] = False
@@ -64,27 +68,27 @@ class SegmentTree:
return -math.inf
if l >= a and r <= b:
return self.st[idx]
mid = (l+r)//2
q1 = self.query(self.left(idx),l,mid,a,b)
q2 = self.query(self.right(idx),mid+1,r,a,b)
return max(q1,q2)
mid = (l + r) // 2
q1 = self.query(self.left(idx), l, mid, a, b)
q2 = self.query(self.right(idx), mid + 1, r, a, b)
return max(q1, q2)
def showData(self):
showList = []
for i in range(1,N+1):
for i in range(1, N + 1):
showList += [self.query(1, 1, self.N, i, i)]
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
N = 15
segt = SegmentTree(N)
segt.build(1,1,N,A)
print(segt.query(1,1,N,4,6))
print(segt.query(1,1,N,7,11))
print(segt.query(1,1,N,7,12))
segt.update(1,1,N,1,3,111)
print(segt.query(1,1,N,1,15))
segt.update(1,1,N,7,8,235)
segt.build(1, 1, N, A)
print(segt.query(1, 1, N, 4, 6))
print(segt.query(1, 1, N, 7, 11))
print(segt.query(1, 1, N, 7, 12))
segt.update(1, 1, N, 1, 3, 111)
print(segt.query(1, 1, N, 1, 15))
segt.update(1, 1, N, 7, 8, 235)
segt.showData()

View File

@@ -75,7 +75,7 @@ def main():
10: [],
11: [],
12: [],
13: []
13: [],
}
level, parent = bfs(level, parent, max_node, graph, 1)
parent = creatSparse(max_node, parent)

View File

@@ -700,7 +700,6 @@ def main():
print_results("Tree traversal", test_tree_chaining())
print("Testing tree balancing...")
print("This should only be a few seconds.")
test_insertion_speed()

View File

@@ -1,10 +1,12 @@
import math
class SegmentTree:
class SegmentTree:
def __init__(self, A):
self.N = len(A)
self.st = [0] * (4 * self.N) # approximate the overall size of segment tree with array N
self.st = [0] * (
4 * self.N
) # approximate the overall size of segment tree with array N
self.build(1, 0, self.N - 1)
def left(self, idx):
@@ -20,51 +22,55 @@ class SegmentTree:
mid = (l + r) // 2
self.build(self.left(idx), l, mid)
self.build(self.right(idx), mid + 1, r)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
def update(self, a, b, val):
return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
def update_recursive(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
def update_recursive(
self, idx, l, r, a, b, val
): # update(1, 1, N, a, b, v) for update val v to [a,b]
if r < a or l > b:
return True
if l == r :
if l == r:
self.st[idx] = val
return True
mid = (l+r)//2
mid = (l + r) // 2
self.update_recursive(self.left(idx), l, mid, a, b, val)
self.update_recursive(self.right(idx), mid+1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
self.update_recursive(self.right(idx), mid + 1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
return True
def query(self, a, b):
return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)
def query_recursive(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
def query_recursive(
self, idx, l, r, a, b
): # query(1, 1, N, a, b) for query max of [a,b]
if r < a or l > b:
return -math.inf
if l >= a and r <= b:
return self.st[idx]
mid = (l+r)//2
mid = (l + r) // 2
q1 = self.query_recursive(self.left(idx), l, mid, a, b)
q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b)
return max(q1, q2)
def showData(self):
showList = []
for i in range(1,N+1):
for i in range(1, N + 1):
showList += [self.query(i, i)]
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
if __name__ == "__main__":
A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
N = 15
segt = SegmentTree(A)
print(segt.query(4, 6))
print(segt.query(7, 11))
print(segt.query(7, 12))
segt.update(1,3,111)
segt.update(1, 3, 111)
print(segt.query(1, 15))
segt.update(7,8,235)
segt.update(7, 8, 235)
segt.showData()

View File

@@ -7,6 +7,7 @@ class Node:
Treap's node
Treap is a binary tree by key and heap by priority
"""
def __init__(self, key: int):
self.key = key
self.prior = random()

View File

@@ -8,13 +8,17 @@ class DoubleHash(HashTable):
"""
Hash Table example with open addressing and Double Hash
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = next_prime(value % self.size_table) \
if not check_prime(value % self.size_table) else value % self.size_table #gt = bigger than
next_prime_gt = (
next_prime(value % self.size_table)
if not check_prime(value % self.size_table)
else value % self.size_table
) # gt = bigger than
return next_prime_gt - (data % next_prime_gt)
def __hash_double_function(self, key, data, increment):
@@ -25,9 +29,14 @@ class DoubleHash(HashTable):
new_key = self.hash_function(data)
while self.values[new_key] is not None and self.values[new_key] != key:
new_key = self.__hash_double_function(key, data, i) if \
self.balanced_factor() >= self.lim_charge else None
if new_key is None: break
else: i += 1
new_key = (
self.__hash_double_function(key, data, i)
if self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break
else:
i += 1
return new_key

View File

@@ -19,8 +19,9 @@ class HashTable:
return self._keys
def balanced_factor(self):
return sum([1 for slot in self.values
if slot is not None]) / (self.size_table * self.charge_factor)
return sum([1 for slot in self.values if slot is not None]) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
@@ -46,8 +47,7 @@ class HashTable:
def _colision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None \
and self.values[new_key] != key:
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
@@ -61,7 +61,7 @@ class HashTable:
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table #hell's pointers D: don't DRY ;/
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
map(self.insert_data, survivor_values)
def insert_data(self, data):
@@ -80,5 +80,3 @@ class HashTable:
else:
self.rehashing()
self.insert_data(data)

View File

@@ -7,18 +7,20 @@ class HashTableWithLinkedList(HashTable):
super().__init__(*args, **kwargs)
def _set_value(self, key, data):
self.values[key] = deque([]) if self.values[key] is None else self.values[key]
self.values[key] = deque([]) if self.values[key] is None else self.values[key]
self.values[key].appendleft(data)
self._keys[key] = self.values[key]
def balanced_factor(self):
return sum([self.charge_factor - len(slot) for slot in self.values])\
/ self.size_table * self.charge_factor
return (
sum([self.charge_factor - len(slot) for slot in self.values])
/ self.size_table
* self.charge_factor
)
def _colision_resolution(self, key, data=None):
if not (len(self.values[key]) == self.charge_factor
and self.values.count(None) == 0):
if not (
len(self.values[key]) == self.charge_factor and self.values.count(None) == 0
):
return key
return super()._colision_resolution(key, data)

View File

@@ -5,25 +5,25 @@
def check_prime(number):
"""
"""
it's not the best solution
"""
special_non_primes = [0,1,2]
if number in special_non_primes[:2]:
return 2
elif number == special_non_primes[-1]:
return 3
return all([number % i for i in range(2, number)])
special_non_primes = [0, 1, 2]
if number in special_non_primes[:2]:
return 2
elif number == special_non_primes[-1]:
return 3
return all([number % i for i in range(2, number)])
def next_prime(value, factor=1, **kwargs):
value = factor * value
first_value_val = value
while not check_prime(value):
value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **kwargs)
return value

View File

@@ -7,18 +7,21 @@ class QuadraticProbing(HashTable):
"""
Basic Hash Table example with open addressing using Quadratic Probing
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _colision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(key + i*i)
new_key = self.hash_function(key + i * i)
while self.values[new_key] is not None \
and self.values[new_key] != key:
while self.values[new_key] is not None and self.values[new_key] != key:
i += 1
new_key = self.hash_function(key + i*i) if not \
self.balanced_factor() >= self.lim_charge else None
new_key = (
self.hash_function(key + i * i)
if not self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break

View File

@@ -26,9 +26,7 @@ class Node:
In-place merge of two binomial trees of equal size.
Returns the root of the resulting tree
"""
assert (
self.left_tree_size == other.left_tree_size
), "Unequal Sizes of Blocks"
assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks"
if self.val < other.val:
other.left = self.right
@@ -36,9 +34,7 @@ class Node:
if self.right:
self.right.parent = other
self.right = other
self.left_tree_size = (
self.left_tree_size * 2 + 1
)
self.left_tree_size = self.left_tree_size * 2 + 1
return self
else:
self.left = other.right
@@ -46,9 +42,7 @@ class Node:
if other.right:
other.right.parent = self
other.right = self
other.left_tree_size = (
other.left_tree_size * 2 + 1
)
other.left_tree_size = other.left_tree_size * 2 + 1
return other
@@ -132,9 +126,7 @@ class BinomialHeap:
"""
def __init__(
self, bottom_root=None, min_node=None, heap_size=0
):
def __init__(self, bottom_root=None, min_node=None, heap_size=0):
self.size = heap_size
self.bottom_root = bottom_root
self.min_node = min_node
@@ -165,10 +157,7 @@ class BinomialHeap:
combined_roots_list = []
i, j = self.bottom_root, other.bottom_root
while i or j:
if i and (
(not j)
or i.left_tree_size < j.left_tree_size
):
if i and ((not j) or i.left_tree_size < j.left_tree_size):
combined_roots_list.append((i, True))
i = i.parent
else:
@@ -176,29 +165,17 @@ class BinomialHeap:
j = j.parent
# Insert links between them
for i in range(len(combined_roots_list) - 1):
if (
combined_roots_list[i][1]
!= combined_roots_list[i + 1][1]
):
combined_roots_list[i][
0
].parent = combined_roots_list[i + 1][0]
combined_roots_list[i + 1][
0
].left = combined_roots_list[i][0]
if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:
combined_roots_list[i][0].parent = combined_roots_list[i + 1][0]
combined_roots_list[i + 1][0].left = combined_roots_list[i][0]
# Consecutively merge roots with same left_tree_size
i = combined_roots_list[0][0]
while i.parent:
if (
(
i.left_tree_size
== i.parent.left_tree_size
)
and (not i.parent.parent)
(i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)
) or (
i.left_tree_size == i.parent.left_tree_size
and i.left_tree_size
!= i.parent.parent.left_tree_size
and i.left_tree_size != i.parent.parent.left_tree_size
):
# Neighbouring Nodes
@@ -264,9 +241,7 @@ class BinomialHeap:
next_node = self.bottom_root.parent.parent
# Merge
self.bottom_root = self.bottom_root.mergeTrees(
self.bottom_root.parent
)
self.bottom_root = self.bottom_root.mergeTrees(self.bottom_root.parent)
# Update Links
self.bottom_root.parent = next_node
@@ -337,9 +312,7 @@ class BinomialHeap:
if bottom_of_new.val < min_of_new.val:
min_of_new = bottom_of_new
# Corner case of single root on top left path
if (not self.min_node.left) and (
not self.min_node.parent
):
if (not self.min_node.left) and (not self.min_node.parent):
self.size = size_of_new
self.bottom_root = bottom_of_new
self.min_node = min_of_new
@@ -348,9 +321,7 @@ class BinomialHeap:
# Remaining cases
# Construct heap of right subtree
newHeap = BinomialHeap(
bottom_root=bottom_of_new,
min_node=min_of_new,
heap_size=size_of_new,
bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new
)
# Update size
@@ -411,12 +382,8 @@ class BinomialHeap:
"""
if curr_node:
preorder.append((curr_node.val, level))
self.__traversal(
curr_node.left, preorder, level + 1
)
self.__traversal(
curr_node.right, preorder, level + 1
)
self.__traversal(curr_node.left, preorder, level + 1)
self.__traversal(curr_node.right, preorder, level + 1)
else:
preorder.append(("#", level))
@@ -429,10 +396,7 @@ class BinomialHeap:
return ""
preorder_heap = self.preOrder()
return "\n".join(
("-" * level + str(value))
for value, level in preorder_heap
)
return "\n".join(("-" * level + str(value)) for value, level in preorder_heap)
# Unit Tests

View File

@@ -2,83 +2,85 @@
# This heap class start from here.
class Heap:
def __init__(self): # Default constructor of heap class.
self.h = []
self.currsize = 0
def __init__(self): # Default constructor of heap class.
self.h = []
self.currsize = 0
def leftChild(self,i):
if 2*i+1 < self.currsize:
return 2*i+1
return None
def leftChild(self, i):
if 2 * i + 1 < self.currsize:
return 2 * i + 1
return None
def rightChild(self,i):
if 2*i+2 < self.currsize:
return 2*i+2
return None
def rightChild(self, i):
if 2 * i + 2 < self.currsize:
return 2 * i + 2
return None
def maxHeapify(self,node):
if node < self.currsize:
m = node
lc = self.leftChild(node)
rc = self.rightChild(node)
if lc is not None and self.h[lc] > self.h[m]:
m = lc
if rc is not None and self.h[rc] > self.h[m]:
m = rc
if m!=node:
temp = self.h[node]
self.h[node] = self.h[m]
self.h[m] = temp
self.maxHeapify(m)
def maxHeapify(self, node):
if node < self.currsize:
m = node
lc = self.leftChild(node)
rc = self.rightChild(node)
if lc is not None and self.h[lc] > self.h[m]:
m = lc
if rc is not None and self.h[rc] > self.h[m]:
m = rc
if m != node:
temp = self.h[node]
self.h[node] = self.h[m]
self.h[m] = temp
self.maxHeapify(m)
def buildHeap(self,a): #This function is used to build the heap from the data container 'a'.
self.currsize = len(a)
self.h = list(a)
for i in range(self.currsize//2,-1,-1):
self.maxHeapify(i)
def buildHeap(
self, a
): # This function is used to build the heap from the data container 'a'.
self.currsize = len(a)
self.h = list(a)
for i in range(self.currsize // 2, -1, -1):
self.maxHeapify(i)
def getMax(self): #This function is used to get maximum value from the heap.
if self.currsize >= 1:
me = self.h[0]
temp = self.h[0]
self.h[0] = self.h[self.currsize-1]
self.h[self.currsize-1] = temp
self.currsize -= 1
self.maxHeapify(0)
return me
return None
def getMax(self): # This function is used to get maximum value from the heap.
if self.currsize >= 1:
me = self.h[0]
temp = self.h[0]
self.h[0] = self.h[self.currsize - 1]
self.h[self.currsize - 1] = temp
self.currsize -= 1
self.maxHeapify(0)
return me
return None
def heapSort(self): #This function is used to sort the heap.
size = self.currsize
while self.currsize-1 >= 0:
temp = self.h[0]
self.h[0] = self.h[self.currsize-1]
self.h[self.currsize-1] = temp
self.currsize -= 1
self.maxHeapify(0)
self.currsize = size
def heapSort(self): # This function is used to sort the heap.
size = self.currsize
while self.currsize - 1 >= 0:
temp = self.h[0]
self.h[0] = self.h[self.currsize - 1]
self.h[self.currsize - 1] = temp
self.currsize -= 1
self.maxHeapify(0)
self.currsize = size
def insert(self,data): #This function is used to insert data in the heap.
self.h.append(data)
curr = self.currsize
self.currsize+=1
while self.h[curr] > self.h[curr/2]:
temp = self.h[curr/2]
self.h[curr/2] = self.h[curr]
self.h[curr] = temp
curr = curr/2
def insert(self, data): # This function is used to insert data in the heap.
self.h.append(data)
curr = self.currsize
self.currsize += 1
while self.h[curr] > self.h[curr / 2]:
temp = self.h[curr / 2]
self.h[curr / 2] = self.h[curr]
self.h[curr] = temp
curr = curr / 2
def display(self): # This function is used to print the heap.
print(self.h)
def display(self): #This function is used to print the heap.
print(self.h)
def main():
l = list(map(int, input().split()))
h = Heap()
h.buildHeap(l)
h.heapSort()
h.display()
if __name__=='__main__':
main()
l = list(map(int, input().split()))
h = Heap()
h.buildHeap(l)
h.heapSort()
h.display()
if __name__ == "__main__":
main()

View File

@@ -3,6 +3,7 @@ class Node:
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None

View File

@@ -1,76 +1,81 @@
'''
"""
- A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
- This is an example of a double ended, doubly linked list.
- Each link references the next link and the previous one.
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent'''
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent"""
class LinkedList: #making main class named linked list
class LinkedList: # making main class named linked list
def __init__(self):
self.head = None
self.tail = None
def insertHead(self, x):
newLink = Link(x) #Create a new link with a value attached to it
if(self.isEmpty() == True): #Set the first element added to be the tail
newLink = Link(x) # Create a new link with a value attached to it
if self.isEmpty() == True: # Set the first element added to be the tail
self.tail = newLink
else:
self.head.previous = newLink # newLink <-- currenthead(head)
newLink.next = self.head # newLink <--> currenthead(head)
self.head = newLink # newLink(head) <--> oldhead
self.head.previous = newLink # newLink <-- currenthead(head)
newLink.next = self.head # newLink <--> currenthead(head)
self.head = newLink # newLink(head) <--> oldhead
def deleteHead(self):
temp = self.head
self.head = self.head.next # oldHead <--> 2ndElement(head)
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
if(self.head is None):
self.tail = None #if empty linked list
self.head = self.head.next # oldHead <--> 2ndElement(head)
self.head.previous = (
None
) # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
if self.head is None:
self.tail = None # if empty linked list
return temp
def insertTail(self, x):
newLink = Link(x)
newLink.next = None # currentTail(tail) newLink -->
self.tail.next = newLink # currentTail(tail) --> newLink -->
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
self.tail = newLink # oldTail <--> newLink(tail) -->
newLink.next = None # currentTail(tail) newLink -->
self.tail.next = newLink # currentTail(tail) --> newLink -->
newLink.previous = self.tail # currentTail(tail) <--> newLink -->
self.tail = newLink # oldTail <--> newLink(tail) -->
def deleteTail(self):
temp = self.tail
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
self.tail.next = None # 2ndlast(tail) --> None
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
self.tail.next = None # 2ndlast(tail) --> None
return temp
def delete(self, x):
current = self.head
while(current.value != x): # Find the position to delete
while current.value != x: # Find the position to delete
current = current.next
if(current == self.head):
if current == self.head:
self.deleteHead()
elif(current == self.tail):
elif current == self.tail:
self.deleteTail()
else: #Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next # 1 --> 3
current.next.previous = current.previous # 1 <--> 3
else: # Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next # 1 --> 3
current.next.previous = current.previous # 1 <--> 3
def isEmpty(self): #Will return True if the list is empty
return(self.head is None)
def isEmpty(self): # Will return True if the list is empty
return self.head is None
def display(self): #Prints contents of the list
def display(self): # Prints contents of the list
current = self.head
while(current != None):
while current != None:
current.displayLink()
current = current.next
print()
class Link:
next = None #This points to the link in front of the new link
previous = None #This points to the link behind the new link
next = None # This points to the link in front of the new link
previous = None # This points to the link behind the new link
def __init__(self, x):
self.value = x
def displayLink(self):
print("{}".format(self.value), end=" ")

View File

@@ -6,21 +6,22 @@ class Node: # create a Node
class Linked_List:
def __init__(self):
self.Head = None # Initialize Head to None
self.Head = None # Initialize Head to None
def insert_tail(self, data):
if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head
if self.Head is None:
self.insert_head(data) # If this is first node, call insert_head
else:
temp = self.Head
while(temp.next != None): #traverse to last node
while temp.next != None: # traverse to last node
temp = temp.next
temp.next = Node(data) #create node & link to tail
temp.next = Node(data) # create node & link to tail
def insert_head(self, data):
newNod = Node(data) # create a new node
newNod = Node(data) # create a new node
if self.Head != None:
newNod.next = self.Head # link newNode to head
self.Head = newNod # make NewNode as Head
newNod.next = self.Head # link newNode to head
self.Head = newNod # make NewNode as Head
def printList(self): # print every node data
tamp = self.Head
@@ -38,12 +39,15 @@ class Linked_List:
def delete_tail(self): # delete from tail
tamp = self.Head
if self.Head != None:
if(self.Head.next is None): # if Head is the only Node in the Linked List
if self.Head.next is None: # if Head is the only Node in the Linked List
self.Head = None
else:
while tamp.next.next is not None: # find the 2nd last element
tamp = tamp.next
tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element
tamp.next, tamp = (
None,
tamp.next,
) # (2nd last element).next = None and tamp = last element
return tamp
def isEmpty(self):
@@ -65,21 +69,22 @@ class Linked_List:
# Return prev in order to put the head at the end
self.Head = prev
def main():
A = Linked_List()
print("Inserting 1st at Head")
a1=input()
a1 = input()
A.insert_head(a1)
print("Inserting 2nd at Head")
a2=input()
a2 = input()
A.insert_head(a2)
print("\nPrint List : ")
A.printList()
print("\nInserting 1st at Tail")
a3=input()
a3 = input()
A.insert_tail(a3)
print("Inserting 2nd at Tail")
a4=input()
a4 = input()
A.insert_tail(a4)
print("\nPrint List : ")
A.printList()
@@ -94,5 +99,6 @@ def main():
print("\nPrint List : ")
A.printList()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -1,6 +1,6 @@
class Node:
def __init__(self, data):
self.data = data;
self.data = data
self.next = None
@@ -14,13 +14,13 @@ class Linkedlist:
print(temp.data)
temp = temp.next
# adding nodes
# adding nodes
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# swapping nodes
# swapping nodes
def swapNodes(self, d1, d2):
prevD1 = None
prevD2 = None
@@ -53,11 +53,11 @@ class Linkedlist:
D1.next = D2.next
D2.next = temp
# swapping code ends here
if __name__ == '__main__':
if __name__ == "__main__":
list = Linkedlist()
list.push(5)
list.push(4)
@@ -70,6 +70,3 @@ if __name__ == '__main__':
list.swapNodes(1, 4)
print("After swapping")
list.print_list()

View File

@@ -5,11 +5,11 @@
import collections
# initializing deque
de = collections.deque([1, 2, 3,])
de = collections.deque([1, 2, 3])
# using extend() to add numbers to right end
# adds 4,5,6 to right end
de.extend([4,5,6])
de.extend([4, 5, 6])
# printing modified deque
print("The deque after extending deque at end is : ")
@@ -17,7 +17,7 @@ print(de)
# using extendleft() to add numbers to left end
# adds 7,8,9 to right end
de.extendleft([7,8,9])
de.extendleft([7, 8, 9])
# printing modified deque
print("The deque after extending deque at beginning is : ")

View File

@@ -1,46 +1,52 @@
"""Queue represented by a python list"""
class Queue():
class Queue:
def __init__(self):
self.entries = []
self.length = 0
self.front=0
self.front = 0
def __str__(self):
printed = '<' + str(self.entries)[1:-1] + '>'
printed = "<" + str(self.entries)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.entries.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.length = self.length - 1
dequeued = self.entries[self.front]
#self.front-=1
#self.entries = self.entries[self.front:]
# self.front-=1
# self.entries = self.entries[self.front:]
self.entries = self.entries[1:]
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
self.put(self.get())
"""Enqueues {@code item}
@return item at front of self.entries"""
def front(self):
return self.entries[0]
"""Returns the length of this.entries"""
def size(self):
return self.length

View File

@@ -1,16 +1,19 @@
"""Queue represented by a pseudo stack (represented by a list with pop and append)"""
class Queue():
class Queue:
def __init__(self):
self.stack = []
self.length = 0
def __str__(self):
printed = '<' + str(self.stack)[1:-1] + '>'
printed = "<" + str(self.stack)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.stack.append(item)
self.length = self.length + 1
@@ -19,17 +22,19 @@ class Queue():
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.rotate(1)
dequeued = self.stack[self.length-1]
dequeued = self.stack[self.length - 1]
self.stack = self.stack[:-1]
self.rotate(self.length-1)
self.length = self.length -1
self.rotate(self.length - 1)
self.length = self.length - 1
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
temp = self.stack[0]
@@ -39,12 +44,14 @@ class Queue():
"""Reports item at the front of self
@return item at front of self.stack"""
def front(self):
front = self.get()
self.put(front)
self.rotate(self.length-1)
self.rotate(self.length - 1)
return front
"""Returns the length of this.stack"""
def size(self):
return self.length

View File

@@ -1,23 +1,22 @@
class Stack:
def __init__(self):
self.stack = []
self.top = 0
def __init__(self):
self.stack = []
self.top = 0
def is_empty(self):
return self.top == 0
def is_empty(self):
return (self.top == 0)
def push(self, item):
if self.top < len(self.stack):
self.stack[self.top] = item
else:
self.stack.append(item)
def push(self, item):
if self.top < len(self.stack):
self.stack[self.top] = item
else:
self.stack.append(item)
self.top += 1
self.top += 1
def pop(self):
if self.is_empty():
return None
else:
self.top -= 1
return self.stack[self.top]
def pop(self):
if self.is_empty():
return None
else:
self.top -= 1
return self.stack[self.top]

View File

@@ -1,23 +1,23 @@
from .stack import Stack
__author__ = 'Omkar Pathak'
__author__ = "Omkar Pathak"
def balanced_parentheses(parentheses):
""" Use a stack to check if a string of parentheses is balanced."""
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
if parenthesis == "(":
stack.push(parenthesis)
elif parenthesis == ')':
elif parenthesis == ")":
if stack.is_empty():
return False
stack.pop()
return stack.is_empty()
if __name__ == '__main__':
examples = ['((()))', '((())', '(()))']
print('Balanced parentheses demonstration:\n')
if __name__ == "__main__":
examples = ["((()))", "((())", "(()))"]
print("Balanced parentheses demonstration:\n")
for example in examples:
print(example + ': ' + str(balanced_parentheses(example)))
print(example + ": " + str(balanced_parentheses(example)))

View File

@@ -2,7 +2,7 @@ import string
from .stack import Stack
__author__ = 'Omkar Pathak'
__author__ = "Omkar Pathak"
def is_operand(char):
@@ -15,9 +15,7 @@ def precedence(char):
https://en.wikipedia.org/wiki/Order_of_operations
"""
dictionary = {'+': 1, '-': 1,
'*': 2, '/': 2,
'^': 3}
dictionary = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
return dictionary.get(char, -1)
@@ -34,29 +32,28 @@ def infix_to_postfix(expression):
for char in expression:
if is_operand(char):
postfix.append(char)
elif char not in {'(', ')'}:
while (not stack.is_empty()
and precedence(char) <= precedence(stack.peek())):
elif char not in {"(", ")"}:
while not stack.is_empty() and precedence(char) <= precedence(stack.peek()):
postfix.append(stack.pop())
stack.push(char)
elif char == '(':
elif char == "(":
stack.push(char)
elif char == ')':
while not stack.is_empty() and stack.peek() != '(':
elif char == ")":
while not stack.is_empty() and stack.peek() != "(":
postfix.append(stack.pop())
# Pop '(' from stack. If there is no '(', there is a mismatched
# parentheses.
if stack.peek() != '(':
raise ValueError('Mismatched parentheses')
if stack.peek() != "(":
raise ValueError("Mismatched parentheses")
stack.pop()
while not stack.is_empty():
postfix.append(stack.pop())
return ' '.join(postfix)
return " ".join(postfix)
if __name__ == '__main__':
expression = 'a+b*(c^d-e)^(f+g*h)-i'
if __name__ == "__main__":
expression = "a+b*(c^d-e)^(f+g*h)-i"
print('Infix to Postfix Notation demonstration:\n')
print('Infix notation: ' + expression)
print('Postfix notation: ' + infix_to_postfix(expression))
print("Infix to Postfix Notation demonstration:\n")
print("Infix notation: " + expression)
print("Postfix notation: " + infix_to_postfix(expression))

View File

@@ -14,48 +14,82 @@ Enter an Infix Equation = a + b ^c
a+b^c (Infix) -> +a^bc (Prefix)
"""
def infix_2_postfix(Infix):
Stack = []
Postfix = []
priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator
print_width = len(Infix) if(len(Infix)>7) else 7
priority = {
"^": 3,
"*": 2,
"/": 2,
"%": 2,
"+": 1,
"-": 1,
} # Priority of each operator
print_width = len(Infix) if (len(Infix) > 7) else 7
# Print table header for output
print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ")
print('-'*(print_width*3+7))
print(
"Symbol".center(8),
"Stack".center(print_width),
"Postfix".center(print_width),
sep=" | ",
)
print("-" * (print_width * 3 + 7))
for x in Infix:
if(x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif(x == '('): Stack.append(x) # if x is "(" push to Stack
elif(x == ')'): # if x is ")" pop stack until "(" is encountered
while(Stack[-1] != '('):
Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix
if x.isalpha() or x.isdigit():
Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
Stack.append(x) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while Stack[-1] != "(":
Postfix.append(Stack.pop()) # Pop stack & add the content to Postfix
Stack.pop()
else:
if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack
if len(Stack) == 0:
Stack.append(x) # If stack is empty, push x to stack
else:
while( len(Stack) > 0 and priority[x] <= priority[Stack[-1]]): # while priority of x is not greater than priority of element in the stack
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
Stack.append(x) # push x to stack
while (
len(Stack) > 0 and priority[x] <= priority[Stack[-1]]
): # while priority of x is not greater than priority of element in the stack
Postfix.append(Stack.pop()) # pop stack & add to Postfix
Stack.append(x) # push x to stack
print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format
print(
x.center(8),
("".join(Stack)).ljust(print_width),
("".join(Postfix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
while(len(Stack) > 0): # while stack is not empty
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format
while len(Stack) > 0: # while stack is not empty
Postfix.append(Stack.pop()) # pop stack & add to Postfix
print(
" ".center(8),
("".join(Stack)).ljust(print_width),
("".join(Postfix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
return "".join(Postfix) # return Postfix as str
return "".join(Postfix) # return Postfix as str
def infix_2_prefix(Infix):
Infix = list(Infix[::-1]) # reverse the infix equation
Infix = list(Infix[::-1]) # reverse the infix equation
for i in range(len(Infix)):
if(Infix[i] == '('): Infix[i] = ')' # change "(" to ")"
elif(Infix[i] == ')'): Infix[i] = '(' # change ")" to "("
return (infix_2_postfix("".join(Infix)))[::-1] # call infix_2_postfix on Infix, return reverse of Postfix
if Infix[i] == "(":
Infix[i] = ")" # change "(" to ")"
elif Infix[i] == ")":
Infix[i] = "(" # change ")" to "("
return (infix_2_postfix("".join(Infix)))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
Infix = input("\nEnter an Infix Equation = ") #Input an Infix equation
Infix = "".join(Infix.split()) #Remove spaces from the input
Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation
Infix = "".join(Infix.split()) # Remove spaces from the input
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")

View File

@@ -4,13 +4,14 @@ def printNGE(arr):
for i in range(0, len(arr), 1):
next = -1
for j in range(i+1, len(arr), 1):
for j in range(i + 1, len(arr), 1):
if arr[i] < arr[j]:
next = arr[j]
break
print(str(arr[i]) + " -- " + str(next))
# Driver program to test above function
arr = [11,13,21,3]
arr = [11, 13, 21, 3]
printNGE(arr)

View File

@@ -19,32 +19,52 @@ Enter a Postfix Equation (space separated) = 5 6 9 * +
import operator as op
def Solve(Postfix):
Stack = []
Div = lambda x, y: int(x/y) # integer division operation
Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation
Div = lambda x, y: int(x / y) # integer division operation
Opr = {
"^": op.pow,
"*": op.mul,
"/": Div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ")
print('-'*(30+len(Postfix)))
print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ")
print("-" * (30 + len(Postfix)))
for x in Postfix:
if( x.isdigit() ): # if x in digit
Stack.append(x) # append x to stack
print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
if x.isdigit(): # if x in digit
Stack.append(x) # append x to stack
print(
x.rjust(8), ("push(" + x + ")").ljust(12), ",".join(Stack), sep=" | "
) # output in tabular format
else:
B = Stack.pop() # pop stack
print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
B = Stack.pop() # pop stack
print(
"".rjust(8), ("pop(" + B + ")").ljust(12), ",".join(Stack), sep=" | "
) # output in tabular format
A = Stack.pop() # pop stack
print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
A = Stack.pop() # pop stack
print(
"".rjust(8), ("pop(" + A + ")").ljust(12), ",".join(Stack), sep=" | "
) # output in tabular format
Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack
print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
Stack.append(
str(Opr[x](int(A), int(B)))
) # evaluate the 2 values poped from stack & push result to stack
print(
x.rjust(8),
("push(" + A + x + B + ")").ljust(12),
",".join(Stack),
sep=" | ",
) # output in tabular format
return int(Stack[0])
if __name__ == "__main__":
Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(' ')
Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", Solve(Postfix))

View File

@@ -1,4 +1,4 @@
__author__ = 'Omkar Pathak'
__author__ = "Omkar Pathak"
class Stack(object):
@@ -32,7 +32,7 @@ class Stack(object):
if self.stack:
return self.stack.pop()
else:
raise IndexError('pop from an empty stack')
raise IndexError("pop from an empty stack")
def peek(self):
""" Peek at the top-most element of the stack."""
@@ -52,17 +52,17 @@ class StackOverflowError(BaseException):
pass
if __name__ == '__main__':
if __name__ == "__main__":
stack = Stack()
for i in range(10):
stack.push(i)
print('Stack demonstration:\n')
print('Initial stack: ' + str(stack))
print('pop(): ' + str(stack.pop()))
print('After pop(), the stack is now: ' + str(stack))
print('peek(): ' + str(stack.peek()))
print("Stack demonstration:\n")
print("Initial stack: " + str(stack))
print("pop(): " + str(stack.pop()))
print("After pop(), the stack is now: " + str(stack))
print("peek(): " + str(stack.peek()))
stack.push(100)
print('After push(100), the stack is now: ' + str(stack))
print('is_empty(): ' + str(stack.is_empty()))
print('size(): ' + str(stack.size()))
print("After push(100), the stack is now: " + str(stack))
print("is_empty(): " + str(stack.is_empty()))
print("size(): " + str(stack.size()))

View File

@@ -1,11 +1,13 @@
'''
"""
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.
The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
'''
"""
def calculateSpan(price, S):
n = len(price)
@@ -21,14 +23,14 @@ def calculateSpan(price, S):
# Pop elements from stack whlie stack is not
# empty and top of stack is smaller than price[i]
while( len(st) > 0 and price[st[0]] <= price[i]):
while len(st) > 0 and price[st[0]] <= price[i]:
st.pop()
# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
S[i] = i+1 if len(st) <= 0 else (i - st[0])
S[i] = i + 1 if len(st) <= 0 else (i - st[0])
# Push this element to stack
st.append(i)
@@ -36,13 +38,13 @@ def calculateSpan(price, S):
# A utility function to print elements of array
def printArray(arr, n):
for i in range(0,n):
print(arr[i],end =" ")
for i in range(0, n):
print(arr[i], end=" ")
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price)+1)]
S = [0 for i in range(len(price) + 1)]
# Fill the span values in array S[]
calculateSpan(price, S)