Sorted Linked List to Balanced Binary search tree

class LNode :

def __init__(self):

self.data = None

self.next = None

class TNode :

def __init__(self):

self.data = None

self.left = None

self.right = None

head = None

def sortedListToBST():

global head

n = countLNodes(head)

return sortedListToBSTRecur(n)

def sortedListToBSTRecur( n) :

global head

if (n <= 0) :

return None

left = sortedListToBSTRecur( int(n/2))

root = newNode((head).data)

root.left = left

head = (head).next

root.right = sortedListToBSTRecur( n - int(n/2) - 1)

return root

def countLNodes(head) :

count = 0

temp = head

while(temp != None):

temp = temp.next

count = count + 1

return count

def push(head, new_data) :

new_node = LNode()

new_node.data = new_data

new_node.next = (head)

(head) = new_node

return head

def printList(node):

while(node != None):

print( node.data ,end= " ")

node = node.next

def newNode(data) :

node = TNode()

node.data = data

node.left = None

node.right = None

return node

def preOrder( node) :

if (node == None) :

return

print(node.data, end = " " )

preOrder(node.left)

preOrder(node.right)

head = None

head = push(head, 7)

head = push(head, 6)

head = push(head, 5)

head = push(head, 4)

head = push(head, 3)

head = push(head, 2)

head = push(head, 1)

print("Given Linked List " )

printList(head)

root = sortedListToBST()

print("\nPreOrder Traversal of constructed BST ")

preOrder(root)

Python Logo Using Turtle in Python

import turtle

turtle_cursor = turtle.Turtle()

turtle_screen = turtle.Screen()

def pause():

    turtle_cursor.speed(2)

    for i in range(100):

        turtle_cursor.left(90)

def upper_dot_of_python_logo():

    turtle_cursor.penup()

    turtle_cursor.right(90)

    turtle_cursor.forward(160)

    turtle_cursor.left(90)

    turtle_cursor.forward(70)

    turtle_cursor.pencolor("white")

    turtle_cursor.dot(35)

def second_position():

    turtle_cursor.penup()

    turtle_cursor.forward(20)

    turtle_cursor.right(90)

    turtle_cursor.forward(10)

    turtle_cursor.right(90)

    turtle_cursor.pendown()

def half():

    turtle_cursor.forward(50)

    draw_side_curve_of_python_logo()

    turtle_cursor.forward(90)

    draw_first_left_curve_of_python_logo()

    turtle_cursor.forward(40)

    turtle_cursor.left(90)

    turtle_cursor.forward(80)

    turtle_cursor.right(90)

    turtle_cursor.forward(10)

    turtle_cursor.right(90)

    turtle_cursor.forward(120)  

    draw_second_left_curve_of_python_logo()

    turtle_cursor.forward(30)

    turtle_cursor.left(90)

    turtle_cursor.forward(50)

    draw_right_curve_of_python_logo()

    turtle_cursor.forward(40)

    turtle_cursor.end_fill()

def lower_dot_of_python_logo():

    turtle_cursor.left(90)

    turtle_cursor.penup()

    turtle_cursor.forward(310)

    turtle_cursor.left(90)

    turtle_cursor.forward(120)

    turtle_cursor.pendown()

    turtle_cursor.dot(35)

def draw_first_left_curve_of_python_logo():

    draw_side_curve_of_python_logo()

    turtle_cursor.forward(80)

    draw_side_curve_of_python_logo()

def draw_second_left_curve_of_python_logo():

    draw_side_curve_of_python_logo()

    turtle_cursor.forward(90)

    draw_side_curve_of_python_logo()

def draw_side_curve_of_python_logo():

    for i in range(90):

        turtle_cursor.left(1)

        turtle_cursor.forward(1)

def draw_right_curve_of_python_logo():

    for i in range(90):

        turtle_cursor.right(1)

        turtle_cursor.forward(1)

turtle_cursor.pensize(2)

turtle_cursor.speed(10)

turtle_cursor.pensize(2)

turtle_cursor.pencolor("black")

turtle_screen.bgcolor("white")

turtle_cursor.fillcolor("#306998")

turtle_cursor.begin_fill()

half()

turtle_cursor.end_fill()

second_position()

turtle_cursor.fillcolor("#FFD43B")

turtle_cursor.begin_fill()

half()

turtle_cursor.end_fill()

upper_dot_of_python_logo()

lower_dot_of_python_logo()

pause

Volume and Surface area of Hemisphere

import math

def volume(r):

volume = 2 * math.pi * math.pow(r, 3) / 3

print("Volume = ", '%.4f' %volume)

def surface_area(r):

s_area = 2 * math.pi * math.pow(r, 2)

print("Surface Area = ", '%.4f' %s_area)

r = 11

volume(r)

surface_area(r)


Dyck path

def countDyckPaths(n):

res = 1

for i in range(0, n):

res *= (2 * n - i)

res /= (i + 1)

return res / (n+1)

n = 4

print("Number of Dyck Paths is ",

str(int(countDyckPaths(n))))


Longest path between any pair of vertices

def DFS(graph, src, prev_len,

max_len, visited):

visited[src] = 1

curr_len = 0

adjacent = None

for i in range(len(graph[src])):

adjacent = graph[src][i]

if (not visited[adjacent[0]]):

curr_len = prev_len + adjacent[1]

DFS(graph, adjacent[0], curr_len,

max_len, visited)

if (max_len[0] < curr_len):

max_len[0] = curr_len

curr_len = 0

def longestCable(graph, n):

max_len = [-999999999999]

for i in range(1, n + 1):

visited = [False] * (n + 1)

DFS(graph, i, 0, max_len, visited)

return max_len[0]

if __name__ == '__main__':

n = 6

graph = [[] for i in range(n + 1)]

graph[1].append([2, 3])

graph[2].append([1, 3])

graph[2].append([3, 4])

graph[3].append([2, 4])

graph[2].append([6, 2])

graph[6].append([2, 2])

graph[4].append([6, 6])

graph[6].append([4, 6])

graph[5].append([6, 5])

graph[6].append([5, 5])

print("Maximum length of cable =",

longestCable(graph, n))


Reverse a path in Binary search tree using queue

class Node:

def __init__(self, data):

self.key = data

self.left = None

self.right = None

def inorder(root):

if root != None:

inorder(root.left)

print(root.key, end = " ")

inorder(root.right)

def reversePath(node, key, q1):

if node == None:

return

if node.key == key:

q1.insert(0, node.key)

node.key = q1[-1]

q1.pop()

return

elif key < node.key:

q1.insert(0, node.key)

reversePath(node.left, key, q1)

node.key = q1[-1]

q1.pop()

elif (key > node.key):

q1.insert(0, node.key)

reversePath(node.right, key, q1)

node.key = q1[-1]

q1.pop()

return

def insert(node, key):

if node == None:

return Node(key)

if key < node.key:

node.left = insert(node.left, key)

elif key > node.key:

node.right = insert(node.right, key)

return node

if __name__ == '__main__':

root = None

q1 = []

k = 80;

root = insert(root, 50)

insert(root, 30)

insert(root, 20)

insert(root, 40)

insert(root, 70)

insert(root, 60)

insert(root, 80)

print("Before Reverse :")

inorder(root)

reversePath(root, k, q1)

print()

print("After Reverse :")

inorder(root)

Python for Engineers featured in Feedspot Top 60 Python Blogs

Python for Engineers has been selected by Feedspot as one of the Top 60 Python Blogs on the web 

https://blog.feedspot.com/python_blogs/





creating mergeable stack

class Node():

def __init__(self,data):

self.next = None

self.prev = None

self.data = data

class Stack():

def __init__(self):

self.head = None

self.tail = None

def push(self, data):

new_node = Node(data)

if (self.head == None):

self.head = new_node

self.head.next= None

self.head.prev = None

self.tail = new_node

else:

new_node.prev = self.tail

self.tail.next = new_node

self.tail = new_node

def pop(self):

if (self.head == None):

print("Stack underflow")

if (self.head == self.tail):

self.head = None

self.tail = None

else:

node = self.tail

self.tail = self.tail.prev

del node

self.tail.next = None

def merge(self, stack):

if stack.head == None: return 

if self.head == None:

self.head = stack.head

self.tail = stack.tail

return

self.head.prev = stack.tail 

stack.tail.nxt = self.head

self.head = stack.head

def display(self):

if (self.tail != None):

n = self.tail

while (n != None):

print(n.data, end = " ")

n = n.prev

print()

else:

print("Stack Underflow")

ms1 = Stack()

ms2 = Stack()

ms1.push(6)

ms1.push(5)

ms1.push(4)

ms2.push(9)

ms2.push(8)

ms2.push(7)

ms1.merge(ms2)

ms1.display()

while ms1.head != ms1.tail:

ms1.pop ()

print ("check pop all elements until head == tail (one element left)")

print ("on merged stack: ", end = "")

ms1.display()


Find all triplets with zero sum

def triplets(arr, n):

f = False

for i in range(0, n-2):

for j in range(i+1, n-1):

for k in range(j+1, n):

if (arr[i] + arr[j] + arr[k] == 0):

print(arr[i], arr[j], arr[k])

f = True

if (f == False):

print(" not exist ")

arr = [0, -1, 2, -3, 1]

n = len(arr)

triplets(arr, n)


Interleave the first half of the queue with second half

from queue import Queue

def interLeaveQueue(q):

if (q.qsize() % 2 != 0):

print("Input even number of integers.")

s = []

size = int(q.qsize() / 2)

for i in range(size):

s.append(q.queue[0])

q.get()

while len(s) != 0:

q.put(s[-1])

s.pop()

for i in range(size):

q.put(q.queue[0])

q.get()

for i in range(size):

s.append(q.queue[0])

q.get()

while len(s) != 0:

q.put(s[-1])

s.pop()

q.put(q.queue[0])

q.get()

if __name__ == '__main__':

q = Queue()

q.put(11)

q.put(12)

q.put(13)

q.put(14)

q.put(15)

q.put(16)

q.put(17)

q.put(18)

q.put(19)

q.put(20)

interLeaveQueue(q)

length = q.qsize()

for i in range(length):

print(q.queue[0], end=" ")

q.get()


Find size of Doubly Linked List

class Nodes:

def __init__(self):

self.data = None

self.next = None

self.prev = None

def push( ref, new_data):

new_node = Nodes()

new_node.data = new_data

new_node.next = (ref)

new_node.prev = None

if ((ref) != None):

(ref).prev = new_node

(ref) = new_node

return ref

def findSize(node):

res = 0

while (node != None):

res = res + 1

node = node.next

return res

head = None

head = push(head, 4)

head = push(head, 3)

head = push(head, 2)

head = push(head, 1)

print(findSize(head))