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))


Spiral Square Mania with Turtle

import turtle as t

pen = t.Turtle()

pen.color("cyan")

pen.speed(0)

colors = ["green","black","orange","navy","green","black","orange","navy"]

def draw_square(color):

        for side in range(4):

                pen.forward(100)

                pen.right(90)

                for side in range(4):

                        pen.forward(50)

                        pen.right(90)

pen.penup()

pen.back(40)

pen.pendown()

for color in colors:

        pen.color(color)

        draw_square(color)

        pen.forward(50)

        pen.left(45)

pen.hideturtle()

t.done()

Chess-Board using Turtle

import turtle

sc = turtle.Screen()

cb = turtle.Turtle()

def draw():

    for i in range(4):

        cb.forward(30)

        cb.left(90)

    cb.forward(30)

if __name__ == "__main__":

    sc.setup(400, 600)

    cb.speed(100)

    for i in range(8):

        cb.up()

        cb.setpos(-100, 30 * i)

        cb.down()

        for j in range(8):

            if (i + j) % 2 == 0:

                col = 'black'

            else:

                col = 'white'

            cb.fillcolor(col)

            cb.begin_fill()

            draw()

            cb.end_fill()

    cb.hideturtle()

    turtle.done()


The Story of Python, by Its Creator, Guido van Rossum

Guido van Rossum  is a Dutch programmer best known as the creator of the Python programming language, for which he was the "benevolent dictator for life" (BDFL) until he stepped down from the position on 12 July 2018. He remained a member of the Python Steering Council through 2019, and withdrew from nominations for the 2020 election.

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)


Calculate City Block Distance

import numpy as np

def cityblock_distance(A, B):

result = np.sum([abs(a - b) for (a, b) in zip(A, B)])

return result

if __name__== "__main__":

arr1 = [5,2]

arr2 = [1,5]

result = cityblock_distance(arr1, arr2)

print(result)


Calculate the Euclidean distance using NumPy

 Using square() and sum() 


import numpy as np

point1 = np.array((5,2))

point2 = np.array((1,5))

sum_sq = np.sum(np.square(point1 - point2))

print(np.sqrt(sum_sq))


Finite Automata algorithm for Pattern Searching

NO_OF_CHARS = 256

def getNextState(pat, M, state, x):

if state < M and x == ord(pat[state]):

return state+1

i=0

for ns in range(state,0,-1):

if ord(pat[ns-1]) == x:

while(i<ns-1):

if pat[i] != pat[state-ns+1+i]:

break

i+=1

if i == ns-1:

return ns

return 0

def computeTF(pat, M):

global NO_OF_CHARS

TF = [[0 for i in range(NO_OF_CHARS)]\

for _ in range(M+1)]


for state in range(M+1):

for x in range(NO_OF_CHARS):

z = getNextState(pat, M, state, x)

TF[state][x] = z

return TF

def search(pat, txt):

global NO_OF_CHARS

M = len(pat)

N = len(txt)

TF = computeTF(pat, M)

state=0

for i in range(N):

state = TF[state][ord(txt[i])]

if state == M:

print("Pattern found at index: {}".\

format(i-M+1))

def main():

txt = "AABAACAADAABAAABAA"

pat = "AABA"

search(pat, txt)

if __name__ == '__main__':

main()


TOP 10 INDIAN CITIES PAYING A FORTUNE FOR PYTHON DEVELOPERS IN 2022

Bengaluru, Karnataka

New Delhi, India

Gurgaon, Haryana

Hyderabad, Telangana

Pune, Maharashtra

Chennai, Tamil Nadu

Noida, Uttar Pradesh

Mumbai, Maharashtra

Kolkata, West Bengal

Lucknow, Uttar Pradesh


For more details 

Reservoir Sampling

import random

def printArray(stream,n):

for i in range(n):

print(stream[i],end=" ");

print();

def selectKItems(stream, n, k):

i=0;

reservoir = [0]*k;

for i in range(k):

reservoir[i] = stream[i];

while(i < n):

j = random.randrange(i+1);

if(j < k):

reservoir[j] = stream[i];

i+=1;

print("Following are k randomly selected items");

printArray(reservoir, k);

if __name__ == "__main__":

stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

n = len(stream);

k = 5;

selectKItems(stream, n, k);


Program to print Lower triangular and Upper triangular matrix of an array

def lower(matrix, row, col):

for i in range(0, row):

for j in range(0, col):

if (i < j):

print("0", end = " ");

else:

print(matrix[i][j],

end = " " );

print(" ");

def upper(matrix, row, col):

for i in range(0, row):

for j in range(0, col):

if (i > j):

print("0", end = " ");

else:

print(matrix[i][j],

end = " " );

print(" ");

matrix = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]];

row = 3;

col = 3;

print("Lower triangular matrix: ");

lower(matrix, row, col);

print("Upper triangular matrix: ");

upper(matrix, row, col);


Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed

def maxSum(arr):

arrSum = 0

currVal = 0

n = len(arr)

for i in range(0, n):

arrSum = arrSum + arr[i]

currVal = currVal + (i*arr[i])

maxVal = currVal

for j in range(1, n):

currVal = currVal + arrSum-n*arr[n-j]

if currVal > maxVal:

maxVal = currVal

return maxVal

if __name__ == '__main__':

arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print ("Max sum is: ", maxSum(arr))


Hexagons Turtle

import turtle

from random import randint

x = 20

y = 20

turtle.speed(100)

turtle.colormode(255)

def move(l, a):

                turtle.right(a)

                turtle.forward(l)

def hex():

        turtle.pendown()

        turtle.color( randint(0,255),randint(0,255),randint(0,255) )

        turtle.begin_fill()

        for i in range(6):

                move(x,-60)

        turtle.end_fill()

        turtle.penup()

turtle.penup()

for z in range (y):

        if z == 0:

                hex()

                move(x,-60)

                move(x,-60)

                move(x,-60)

                move(0,180)

        for i in range (6):

                move(0,60)

                for j in range (z+1):

                        hex()

                        move(x,-60)

                        move(x,60)

                move(-x,0)

        move(-x,60)

        move(x,-120)

        move(0,60)

turtle.exitonclick()

Dijkstra’s shortest path algorithm

import sys

class Graph():

def __init__(self, vertices):

self.V = vertices

self.graph = [[0 for column in range(vertices)]

for row in range(vertices)]

def printSolution(self, dist):

print("Vertex \tDistance from Source")

for node in range(self.V):

print(node, "\t", dist[node])

def minDistance(self, dist, sptSet):

min = sys.maxsize

for u in range(self.V):

if dist[u] < min and sptSet[u] == False:

min = dist[u]

min_index = u

return min_index

def dijkstra(self, src):

dist = [sys.maxsize] * self.V

dist[src] = 0

sptSet = [False] * self.V

for cout in range(self.V):

x = self.minDistance(dist, sptSet)

sptSet[x] = True

for y in range(self.V):

if self.graph[x][y] > 0 and sptSet[y] == False and \

dist[y] > dist[x] + self.graph[x][y]:

dist[y] = dist[x] + self.graph[x][y]

self.printSolution(dist)

g = Graph(9)

g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],

[4, 0, 8, 0, 0, 0, 0, 11, 0],

[0, 8, 0, 7, 0, 4, 0, 0, 2],

[0, 0, 7, 0, 9, 14, 0, 0, 0],

[0, 0, 0, 9, 0, 10, 0, 0, 0],

[0, 0, 4, 14, 10, 0, 2, 0, 0],

[0, 0, 0, 0, 0, 2, 0, 1, 6],

[8, 11, 0, 0, 0, 0, 1, 0, 7],

[0, 0, 2, 0, 0, 0, 6, 7, 0]

];


g.dijkstra(0);


Range Queries for Frequencies of array elements

def findFrequency(arr, n, left, right, element):

count = 0

for i in range(left - 1, right):

if (arr[i] == element):

count += 1

return count

arr = [2, 8, 6, 9, 8, 6, 8, 2, 11]

n = len(arr)

print("Frequency of 2 from 1 to 6 = ",

findFrequency(arr, n, 1, 6, 2))

print("Frequency of 8 from 4 to 9 = ",

findFrequency(arr, n, 4, 9, 8))


Optimum location of point to minimize total distance

import math

class Optimum_distance:

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

class Line:

def __init__(self, a, b, c):

self.a = a

self.b = b

self.c = c

def dist(self, x, y, p):

return math.sqrt((x - p.x) ** 2 +

(y - p.y) ** 2)

def compute(self, p, n, l, x):

res = 0

y = -1 * (l.a*x + l.c) / l.b

for i in range(n):

res += self.dist(x, y, p[i])

return res

def find_Optimum_cost_untill(self, p, n, l):

low = -1e6

high = 1e6

eps = 1e-6 + 1

while((high - low) > eps):

mid1 = low + (high - low) / 3

mid2 = high - (high - low) / 3

dist1 = self.compute(p, n, l, mid1)

dist2 = self.compute(p, n, l, mid2)

if (dist1 < dist2):

high = mid2

else:

low = mid1

return self.compute(p, n, l, (low + high) / 2)

def find_Optimum_cost(self, p, l):

n = len(p)

p_arr = [None] * n

for i in range(n):

p_obj = self.Point(p[i][0], p[i][1])

p_arr[i] = p_obj

return self.find_Optimum_cost_untill(p_arr, n, l)

if __name__ == "__main__":

obj = Optimum_distance()

l = obj.Line(1, -1, -3)

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

[ -1, 2 ], [ 1, 2 ],

[ 3, 4 ] ]

print(obj.find_Optimum_cost(p, l))


Euler’s Totient function for all numbers smaller than or equal to n

def computeTotient(n):

phi=[]

for i in range(n + 2):

phi.append(0)

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

phi[i] = i 

for p in range(2,n+1):

if (phi[p] == p):

phi[p] = p-1

for i in range(2*p,n+1,p):

phi[i] = (phi[i]//p) * (p-1)

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

print("Totient of ", i ," is ",

phi[i])

n = 12

computeTotient(n)


N Queen Problem

global N

N = 4

def printSolution(board):

for i in range(N):

for j in range(N):

print (board[i][j], end = " ")

print()

def isSafe(board, row, col):

for i in range(col):

if board[row][i] == 1:

return False

for i, j in zip(range(row, -1, -1),

range(col, -1, -1)):

if board[i][j] == 1:

return False

for i, j in zip(range(row, N, 1),

range(col, -1, -1)):

if board[i][j] == 1:

return False

return True

def solveNQUtil(board, col):

if col >= N:

return True

for i in range(N):

if isSafe(board, i, col):

board[i][col] = 1

if solveNQUtil(board, col + 1) == True:

return True

board[i][col] = 0

return False

def solveNQ():

board = [ [0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0] ]

if solveNQUtil(board, 0) == False:

print ("Solution does not exist")

return False

printSolution(board)

return True

solveNQ()


Interpolation Search

def interpolationSearch(arr, lo, hi, x):

if (lo <= hi and x >= arr[lo] and x <= arr[hi]):

pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) *

(x - arr[lo]))

if arr[pos] == x:

return pos

if arr[pos] < x:

return interpolationSearch(arr, pos + 1,

hi, x)

if arr[pos] > x:

return interpolationSearch(arr, lo,

pos - 1, x)

return -1

arr = [10, 12, 13, 16, 18, 19, 20,

21, 22, 23, 24, 33, 35, 42, 47]

n = len(arr)

x = 18

index = interpolationSearch(arr, 0, n - 1, x)

if index != -1:

print("Element found at index", index)

else:

print("Element not found")


program to add two numbers in base 14

def getNumeralValue(num) :

if( num >= '0' and num <= '9') :

return ord(num) - ord('0')

if( num >= 'A' and num <= 'D') :

return ord(num ) - ord('A') + 10

def getNumeral(val):

if( val >= 0 and val <= 9):

return chr(val + ord('0'))

if( val >= 10 and val <= 14) :

return chr(val + ord('A') - 10)

def sumBase14(num1, num2):

l1 = len(num1)

l2 = len(num2)

carry = 0

if(l1 != l2) :

print("Function doesn't support numbers of different"

" lengths. If you want to add such numbers then"

" prefix smaller number with required no. of zeroes")

res = [0]*(l1 + 1)

for i in range(l1 - 1, -1, -1):

nml1 = getNumeralValue(num1[i])

nml2 = getNumeralValue(num2[i])

res_nml = carry + nml1 + nml2;

if(res_nml >= 14) :

carry = 1

res_nml -= 14

else:

carry = 0

res[i+1] = getNumeral(res_nml)

if(carry == 0):

return (res + 1)

res[0] = '1'

return res

if __name__ == "__main__":

num1 = "DC2"

num2 = "0A3"

print("Result is ",end="")

res = sumBase14(num1, num2)

for i in range(len(res)):

print(res[i],end="")


Stooge Sort

def stoogesort(arr, l, h):

if l >= h:

return

if arr[l]>arr[h]:

t = arr[l]

arr[l] = arr[h]

arr[h] = t

if h-l + 1 > 2:

t = (int)((h-l + 1)/3)

stoogesort(arr, l, (h-t))

stoogesort(arr, l + t, (h))

stoogesort(arr, l, (h-t))

arr = [2, 4, 5, 3, 1]

n = len(arr)

stoogesort(arr, 0, n-1)

for i in range(0, n):

print(arr[i], end = ' ')


checking the given number is Lucky or Not

import math

def isLucky(n):

ar = [0] * 10

while (n > 0):

digit = math.floor(n % 10)

if (ar[digit]):

return 0

ar[digit] = 1

n = n / 10

return 1

arr = [1291, 897, 4566, 1232, 80, 700]

n = len(arr)

for i in range(0, n):

k = arr[i]

if(isLucky(k)):

print(k, " is Lucky ")

else:

print(k, " is not Lucky ")


Google Drive Logo Using Turtle

import turtle as t

t.hideturtle()

t.Screen().bgcolor("Black")

t.pencolor("white")

t.pensize(0)

t.begin_fill()

t.fillcolor('#4688F4')

t.forward(170)

t.left(60)

t.forward(50)

t.left(120)

t.forward(220)

t.left(120)

t.forward(50)

t.end_fill()

t.begin_fill()

t.fillcolor('#1FA463')

t.left(120)

t.forward(200)

t.left(120)

t.forward(50)

t.left(60)

t.forward(150)

t.left(60)

t.forward(50)

t.end_fill()

t.penup()

t.left(120)

t.forward(200)

t.left(120)

t.forward(50)

t.pendown()

t.begin_fill()

t.fillcolor('#FFD048')

t.left(125)

t.forward(160)

t.left(55)

t.forward(53)

t.left(126)

t.forward(163)

t.end_fill()

t.done()


Check whether a string starts and ends with the same character or not (using Regular Expression)

import re

regex = r'^[a-z]$|^([a-z]).*\1$'

def check(string):

if(re.search(regex, string)):

print("Valid")

else:

print("Invalid")

if __name__ == '__main__' :


sample1 = "abba"

sample2 = "a"

sample3 = "abcd"


check(sample1)

check(sample2)

check(sample3)


Javascript logo using turtle

import turtle

t=turtle.Turtle()

t.penup()

t.goto(-20,-70)

t.color("#F0DB4F","#F0DB4F")

t.begin_fill()

t.pendown()

t.left(165)

t.forward(100)

t.right(70)

t.forward(220)

t.setheading(0)

t.forward(229)

t.penup()

t.goto(-20,-70)

t.setheading(0)

t.pendown()

t.left(15)

t.forward(100)

t.left(70)

t.forward(229)

t.end_fill()

t.penup()

t.goto(-35,-20)

t.setheading(90)

t.color("white","white")

t.pendown()

t.begin_fill()

t.forward(150)

t.left(90)

t.forward(20)

t.left(90)

t.forward(130)

t.setheading(90)

t.left(75)

t.forward(40)

t.left(110)

t.forward(20)


t.penup()

t.goto(-35,-20)

t.setheading(90)

t.left(75)

t.pendown()

t.forward(60)

t.end_fill()

t.penup()

t.color("yellow","yellow")

t.goto(-20,-55)

t.setheading(90)

t.pendown()

t.begin_fill()

t.forward(215)

t.right(90)

t.forward(100)

t.right(95)

t.forward(195)

t.left(90)

t.end_fill()

t.penup()

t.color("white","white")

t.pensize(2)

t.goto(-10,-20)

t.begin_fill()

t.setheading(0)

t.left(15)

t.pendown()

t.forward(65)

t.left(70)

t.forward(70)

t.left(90)

t.left(15)

t.forward(50)

t.right(100)

t.forward(50)

t.right(90)

t.forward(50)

t.left(85)

t.forward(20)

t.left(95)

t.forward(70)

t.left(90)

t.forward(90)

t.left(100)

t.forward(50)

t.right(105)

t.forward(37)

t.right(75)

t.forward(50)

t.left(85)

t.forward(20)

t.end_fill()

t.hideturtle()

turtle.done()


Replace multiple words

test_str = 'Python for engineers,The complete solution for python programs'

print("The original string is : " + str(test_str))

word_list = ["for", 'The', 'solution']

repl_wrd = 'hai'

res = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])

print("String after multiple replace : " + str(res))


Program for Counting Sort

def countSort(arr):

output = [0 for i in range(256)]

count = [0 for i in range(256)]

ans = ["" for _ in arr]

for i in arr:

count[ord(i)] += 1

for i in range(256):

count[i] += count[i-1]

for i in range(len(arr)):

output[count[ord(arr[i])]-1] = arr[i]

count[ord(arr[i])] -= 1

for i in range(len(arr)):

ans[i] = output[i]

return ans

arr = "Pythonforengineers"

ans = countSort(arr)

print ("Sorted character array is %s" %("".join(ans)))


Program for Radix Sort

def countingSort(arr, exp1):

n = len(arr)

output = [0] * (n)

count = [0] * (10)

for i in range(0, n):

index = (arr[i]/exp1)

count[int((index)%10)] += 1

for i in range(1,10):

count[i] += count[i-1]

i = n-1

while i>=0:

index = (arr[i]/exp1)

output[ count[ int((index)%10) ] - 1] = arr[i]

count[int((index)%10)] -= 1

i -= 1

i = 0

for i in range(0,len(arr)):

arr[i] = output[i]

def radixSort(arr):

max1 = max(arr)

exp = 1

while max1/exp > 0:

countingSort(arr,exp)

exp *= 10

arr = [ 170, 45, 75, 90, 802, 24, 2, 66]

radixSort(arr)

for i in range(len(arr)):

print(arr[i],end=" ")


Maximum profit by buying and selling a share at most k times

def maxProfit(prices, n, k):

profit = [[0 for i in range(k + 1)]

for j in range(n)]

for i in range(1, n):

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

max_so_far = 0

for l in range(i):

max_so_far = max(max_so_far, prices[i] -

prices[l] + profit[l][j - 1])

profit[i][j] = max(profit[i - 1][j], max_so_far)

return profit[n - 1][k]

k = 2

prices = [10, 22, 5, 75, 65, 80]

n = len(prices)

print("Maximum profit is:",

maxProfit(prices, n, k))


Balloon Shooter Game

import pygame

import sys

import random

from math import *

pygame.init()

width = 700

height = 600

display = pygame.display.set_mode((width, height))

pygame.display.set_caption("CopyAssignment - Balloon Shooter Game")

clock = pygame.time.Clock()

margin = 100

lowerBound = 100

score = 0

white = (230, 230, 230)

lightBlue = (4, 27, 96)

red = (231, 76, 60)

lightGreen = (25, 111, 61)

darkGray = (40, 55, 71)

darkBlue = (64, 178, 239)

green = (35, 155, 86)

yellow = (244, 208, 63)

blue = (46, 134, 193)

purple = (155, 89, 182)

orange = (243, 156, 18)

font = pygame.font.SysFont("Arial", 25)

class Balloon:

    def __init__(self, speed):

        self.a = random.randint(30, 40)

        self.b = self.a + random.randint(0, 10)

        self.x = random.randrange(margin, width - self.a - margin)

        self.y = height - lowerBound

        self.angle = 90

        self.speed = -speed

        self.proPool= [-1, -1, -1, 0, 0, 0, 0, 1, 1, 1]

        self.length = random.randint(50, 100)

        self.color = random.choice([red, green, purple, orange, yellow, blue])

    def move(self):

        direct = random.choice(self.proPool)

        if direct == -1:

            self.angle += -10

        elif direct == 0:

            self.angle += 0

        else:

            self.angle += 10

        self.y += self.speed*sin(radians(self.angle))

        self.x += self.speed*cos(radians(self.angle))

        if (self.x + self.a > width) or (self.x < 0):

            if self.y > height/5:

                self.x -= self.speed*cos(radians(self.angle)) 

            else:

                self.reset()

        if self.y + self.b < 0 or self.y > height + 30:

            self.reset()         

    def show(self):

        pygame.draw.line(display, darkBlue, (self.x + self.a/2, self.y + self.b), (self.x + self.a/2, self.y + self.b + self.length))

        pygame.draw.ellipse(display, self.color, (self.x, self.y, self.a, self.b))

        pygame.draw.ellipse(display, self.color, (self.x + self.a/2 - 5, self.y + self.b - 3, 10, 10))   

    def burst(self):

        global score

        pos = pygame.mouse.get_pos()

        if isonBalloon(self.x, self.y, self.a, self.b, pos):

            score += 1

            self.reset()                

    def reset(self):

        self.a = random.randint(30, 40)

        self.b = self.a + random.randint(0, 10)

        self.x = random.randrange(margin, width - self.a - margin)

        self.y = height - lowerBound 

        self.angle = 90

        self.speed -= 0.002

        self.proPool = [-1, -1, -1, 0, 0, 0, 0, 1, 1, 1]

        self.length = random.randint(50, 100)

        self.color = random.choice([red, green, purple, orange, yellow, blue])   

balloons = []

noBalloon = 10

for i in range(noBalloon):

    obj = Balloon(random.choice([1, 1, 2, 2, 2, 2, 3, 3, 3, 4]))

    balloons.append(obj)

def isonBalloon(x, y, a, b, pos):

    if (x < pos[0] < x + a) and (y < pos[1] < y + b):

        return True

    else:

        return False   

def pointer():

    pos = pygame.mouse.get_pos()

    r = 25

    l = 20

    color = lightGreen

    for i in range(noBalloon):

        if isonBalloon(balloons[i].x, balloons[i].y, balloons[i].a, balloons[i].b, pos):

            color = red

    pygame.draw.ellipse(display, color, (pos[0] - r/2, pos[1] - r/2, r, r), 4)

    pygame.draw.line(display, color, (pos[0], pos[1] - l/2), (pos[0], pos[1] - l), 4)

    pygame.draw.line(display, color, (pos[0] + l/2, pos[1]), (pos[0] + l, pos[1]), 4)

    pygame.draw.line(display, color, (pos[0], pos[1] + l/2), (pos[0], pos[1] + l), 4)

    pygame.draw.line(display, color, (pos[0] - l/2, pos[1]), (pos[0] - l, pos[1]), 4)

def lowerPlatform():

    pygame.draw.rect(display, darkGray, (0, height - lowerBound, width, lowerBound))

def showScore():

    scoreText = font.render("Balloons Bursted : " + str(score), True, white)

    display.blit(scoreText, (150, height - lowerBound + 50))

def close():

    pygame.quit()

    sys.exit()    

def game():

    global score

    loop = True

    while loop:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                close()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_q:

                    close()

                if event.key == pygame.K_r:

                    score = 0

                    game()

            if event.type == pygame.MOUSEBUTTONDOWN:

                for i in range(noBalloon):

                    balloons[i].burst()

        display.fill(lightBlue)        

        for i in range(noBalloon):

            balloons[i].show()

        pointer()        

        for i in range(noBalloon):

            balloons[i].move()        

        lowerPlatform()

        showScore()

        pygame.display.update()

        clock.tick(60)

game()


Google Drive Logo Using Python Turtle

import turtle as t

t.hideturtle()

t.Screen().bgcolor("Black")

t.pencolor("white")

t.pensize(0)

t.begin_fill()

t.fillcolor('#4688F4')

t.forward(170)

t.left(60)

t.forward(50)

t.left(120)

t.forward(220)

t.left(120)

t.forward(50)

t.end_fill()

t.begin_fill()

t.fillcolor('#1FA463')

t.left(120)

t.forward(200)

t.left(120)

t.forward(50)

t.left(60)

t.forward(150)

t.left(60)

t.forward(50)

t.end_fill()

t.penup()

t.left(120)

t.forward(200)

t.left(120)

t.forward(50)

t.pendown()

t.begin_fill()

t.fillcolor('#FFD048')

t.left(125)

t.forward(160)

t.left(55)

t.forward(53)

t.left(126)

t.forward(163)

t.end_fill()

t.done()


Program to generate CAPTCHA and verify user

import random

def checkCaptcha(captcha, user_captcha):

if captcha == user_captcha:

return True

return False

def generateCaptcha(n):

chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

captcha = ""

while (n):

captcha += chrs[random.randint(1, 1000) % 62]

n -= 1

return captcha

captcha = generateCaptcha(9)

print(captcha)

print("Enter above CAPTCHA:")

usr_captcha = input()

if (checkCaptcha(captcha, usr_captcha)):

print("CAPTCHA Matched")

else:

print("CAPTCHA Not Matched")


Draw Spider web using Python Turtle

import turtle as t

t.speed(2)

for i in range(6):

   t.forward(150)

   t.backward(150)

   t.right(60)

side = 50

t.fillcolor("Orange")

t.begin_fill()

for i in range(15):

   t.penup()

   t.goto(0, 0)

   t.pendown()

   t.setheading(0)

   t.forward(side)

   t.right(120)

   for j in range(6):

      t.forward(side-2)

      t.right(60)

   side = side - 10 

t.end_fill()

turtle.done()


Program for Extended Euclidean algorithms

def gcdExtended(a, b):

if a == 0 :

return b,0,1

gcd,x1,y1 = gcdExtended(b%a, a)

x = y1 - (b//a) * x1

y = x1

return gcd,x,y

a, b = 35,15

g, x, y = gcdExtended(a, b)

print("gcd(", a , "," , b, ") = ", g)


Spotify logo using python turtle

import turtle as t

t.Screen().bgcolor("Black")

t.speed(15)

t.begin_fill()

t.fillcolor('#1DB954')

t.pencolor("#1DB954")

t.pensize(0)

t.circle(100)

t.end_fill()

t.penup()

t.goto(40,50)

t.pendown()

t.left(150)

t.forward(0)

t.pensize(15)

t.pencolor('black')

t.circle(80,60)

t.penup()

t.goto(50,85)

t.pendown()

t.pensize(17)

t.right(60)

t.forward(0)

t.circle(100,60)

t.penup()

t.goto(60,120)

t.pendown()

t.pensize(20)

t.right(60)

t.forward(0)

t.circle(120,60)

t.penup()

t.goto(130, 55)

t.pendown()

t.color("#1DB954")

t.write("Spotify", font=("Arial", 60, "bold"))

t.done()

FB logo using turtle

from turtle import *

speed(10)

color("#0270d6")

Screen().bgcolor('black')

penup()

goto(0, 150)

pendown()

begin_fill()

forward(150)

circle(-50, 90)

forward(300)

circle(-50, 90)

forward(300)

circle(-50, 90)

forward(300)

circle(-50, 90)

forward(150)

end_fill()

color("white")

penup()

goto(140, 80)

pendown()

begin_fill()

right(180)

forward(50)

circle(80, 90)

forward(50)

right(90)

forward(80)

left(90)

forward(40)

left(90)

forward(80)

right(90)

forward(160)

left(90)

forward(55)

left(90)

forward(160)

right(90)

forward(70)

left(80)

forward(45)

left(100)

forward(80)

right(90)

forward(40)

circle(-40, 90)

forward(40)

left(90)

forward(45)

end_fill()

hideturtle()

done()


Check if the characters in a string form a Palindrome in O(1) extra space

def firstPos(str, start, end):

firstChar = -1

for i in range(start, end + 1):

if (str[i] >= 'a' and str[i] <= 'z') :

firstChar = i

break

return firstChar

def lastPos(str, start, end):

lastChar = -1

for i in range(start, end - 1, -1) :

if (str[i] >= 'a' and str[i] <= 'z') :

lastChar = i

break

return lastChar

def isPalindrome(str):

firstChar = 0

lastChar = len(str) - 1

ch = True

for i in range(len(str)) :

firstChar = firstPos(str, firstChar, lastChar);

lastChar = lastPos(str, lastChar, firstChar);

if (lastChar < 0 or firstChar < 0):

break

if (str[firstChar] == str[lastChar]):

firstChar += 1

lastChar -= 1

continue

ch = False

break

return (ch)

if __name__ == "__main__":


str = "m a 343 la y a l am"

if (isPalindrome(str)):

print("YES")

else:

print("NO")

 

program to print all Prime numbers in an Interval

def prime(x, y):

prime_list = []

for i in range(x, y):

if i == 0 or i == 1:

continue

else:

for j in range(2, int(i/2)+1):

if i % j == 0:

break

else:

prime_list.append(i)

return prime_list

starting_range = 2

ending_range = 7

lst = prime(starting_range, ending_range)

if len(lst) == 0:

print("There are no prime numbers in this range")

else:

print("The prime numbers in this range are: ", lst)


Program for compound interest

def compound_interest(principle, rate, time):

Amount = principle * (pow((1 + rate / 100), time))

CI = Amount - principle

print("Compound interest is", CI)

compound_interest(10000, 10.25, 5)


Tkinter-Text Widget

from tkinter import *

root = Tk()

root.geometry("300x300")

root.title(" Q&A ")

def Take_input():

INPUT = inputtxt.get("1.0", "end-1c")

print(INPUT)

if(INPUT == "120"):

Output.insert(END, 'Correct')

else:

Output.insert(END, "Wrong answer")

l = Label(text = "What is 24 * 5 ? ")

inputtxt = Text(root, height = 10,

width = 25,

bg = "light yellow")

Output = Text(root, height = 5,

width = 25,

bg = "light cyan")

Display = Button(root, height = 2,

width = 20,

text ="Show",

command = lambda:Take_input())

l.pack()

inputtxt.pack()

Display.pack()

Output.pack()

mainloop()


Pattern Printing

def Pattern(line):

pat=""

for i in range(0,line):

for j in range(0,line):

if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or

i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2)

and j > line-5 and j < line-1) or (j == line-2 and

i != 0 and i != line-1 and i >=((line-1)/2))):

pat=pat+"#"

else:

pat=pat+" "

pat=pat+"\n"

return pat

line = 7

print(Pattern(line))


Program for Brick Sort

def oddEvenSort(arr, n):

    isSorted = 0

    while isSorted == 0:

        isSorted = 1

        temp = 0

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

            if arr[i] > arr[i+1]:

                arr[i], arr[i+1] = arr[i+1], arr[i]

                isSorted = 0

                  

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

            if arr[i] > arr[i+1]:

                arr[i], arr[i+1] = arr[i+1], arr[i]

                isSorted = 0

    return

arr = [34, 2, 10, -9]

n = len(arr)

oddEvenSort(arr, n);

for i in range(0, n):

    print(arr[i], end =" ")

      


Program for Find sum of even factors of a number

import math

def sumofFactors(n) :

if (n % 2 != 0) :

return 0

res = 1

for i in range(2, (int)(math.sqrt(n)) + 1) :

count = 0

curr_sum = 1

curr_term = 1

while (n % i == 0) :

count= count + 1

n = n // i

if (i == 2 and count == 1) :

curr_sum = 0

curr_term = curr_term * i

curr_sum = curr_sum + curr_term

res = res * curr_sum

if (n >= 2) :

res = res * (1 + n)

return res

n = 18

print(sumofFactors(n))


Program for Legendre\’s Conjecture

import math

def isprime( n ):

i = 2

for i in range (2, int((math.sqrt(n)+1))):

if n%i == 0:

return False

return True

def LegendreConjecture( n ):

print ( "Primes in the range ", n*n

, " and ", (n+1)*(n+1)

, " are:" )

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

if(isprime(i)):

print (i)

n = 50

LegendreConjecture(n)


Design with turtle

import turtle

turtle.speed(0)

turtle.bgcolor("black")

for i in range(15):

for colours in ("red", "magenta", "yellow", "orange", "blue", "green", "purple"):

turtle.color(colours)

turtle.pensize(3)

turtle.left(4)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)


Counter to find the size of largest subset of anagram words

from collections import Counter

def maxAnagramSize(input):

input = input.split(" ")

for i in range(0,len(input)):

input[i]=''.join(sorted(input[i]))

freqDict = Counter(input)

print (max(freqDict.values()))

if __name__ == "__main__":

input = 'ant magenta magnate tan gnamate'

maxAnagramSize(input)


program to count Even and Odd numbers in a List Using Python Lambda Expressions

list1 = [10, 21, 4, 45, 66, 93, 11]

odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))

even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)


Break a list into chunks of size N

my_list = ['python', 'for', 'engineers', 'like',

'complete','solution', 'for', 'python',

'related','queries']

def divide_chunks(l, n):

for i in range(0, len(l), n):

yield l[i:i + n]

n = 5

x = list(divide_chunks(my_list, n))

print (x)


Matrix creation of n*n Using next() + itertools.count()

import itertools

N = 4

print("The dimension : " + str(N))

temp = itertools.count(1)

res = [[next(temp) for i in range(N)] for i in range(N)]

print("The created matrix of N * N: " + str(res))