Solve Problems by Coding Solutions - A Complete solution for python programming
The Story of Python, by Its Creator, Guido van Rossum
Iterative Method to find Height of Binary Tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def treeHeight(root):
if root is None:
return 0
q = []
q.append(root)
height = 0
while(True):
nodeCount = len(q)
if nodeCount == 0 :
return height
height += 1
while(nodeCount > 0):
node = q[0]
q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
nodeCount -= 1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Height of tree is", treeHeight(root))
Split a Circular Linked List into two halves
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def push(self, data):
ptr1 = Node(data)
temp = self.head
ptr1.next = self.head
if self.head is not None:
while(temp.next != self.head):
temp = temp.next
temp.next = ptr1
else:
ptr1.next = ptr1
self.head = ptr1
def printList(self):
temp = self.head
if self.head is not None:
while(True):
print ("%d" %(temp.data),end=' ')
temp = temp.next
if (temp == self.head):
break
def splitList(self, head1, head2):
slow_ptr = self.head
fast_ptr = self.head
if self.head is None:
return
while(fast_ptr.next != self.head and
fast_ptr.next.next != self.head ):
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
if fast_ptr.next.next == self.head:
fast_ptr = fast_ptr.next
head1.head = self.head
if self.head.next != self.head:
head2.head = slow_ptr.next
fast_ptr.next = slow_ptr.next
slow_ptr.next = self.head
head = CircularLinkedList()
head1 = CircularLinkedList()
head2 = CircularLinkedList()
head.push(12)
head.push(56)
head.push(2)
head.push(11)
print ("Original Circular Linked List")
head.printList()
head.splitList(head1 , head2)
print ("\nFirst Circular Linked List")
head1.printList()
print ("\nSecond Circular Linked List")
head2.printList()
Group Shifted String
ALPHA = 26
def getDiffString(str):
shift=""
for i in range(1, len(str)):
dif = (ord(str[i]) -
ord(str[i - 1]))
if(dif < 0):
dif += ALPHA
shift += chr(dif + ord('a'))
return shift
def groupShiftedString(str,n):
groupMap = {}
for i in range(n):
diffStr = getDiffString(str[i])
if diffStr not in groupMap:
groupMap[diffStr] = [i]
else:
groupMap[diffStr].append(i)
for it in groupMap:
v = groupMap[it]
for i in range(len(v)):
print(str[v[i]], end = " ")
print()
str = ["acd", "dfg", "wyz",
"yab", "mop","bdfh",
"a", "x", "moqs"]
n = len(str)
groupShiftedString(str, n)
Moser-de Bruijn Sequence
def gen(n):
if n == 0:
return 0
elif n ==1:
return 1
elif n % 2 ==0:
return 4 * gen(n // 2)
elif n % 2 == 1:
return 4 * gen(n // 2) +1
def moserDeBruijn(n):
for i in range(n):
print(gen(i), end = " ")
n = 15
print("First", n, "terms of ",
"Moser-de Bruijn Sequence:")
moserDeBruijn(n)