Racing Animation

from turtle import * 

from random import randint

speed(0)

penup()

goto(-140, 140)

for step in range(15):

write(step, align ='center')

right(90)

for num in range(8):

penup()

forward(10)

pendown()

forward(10)

penup()

backward(160)

left(90)

forward(20)

player_1 = Turtle()

player_1.color('red')

player_1.shape('turtle')

player_1.penup()

player_1.goto(-160, 100)

player_1.pendown()

for turn in range(10):

player_1.right(36)

player_2 = Turtle()

player_2.color('blue')

player_2.shape('turtle')

player_2.penup()

player_2.goto(-160, 70)

player_2.pendown()

for turn in range(72):

player_2.left(5)

player_3 = Turtle()

player_3.shape('turtle')

player_3.color('green')

player_3.penup()

player_3.goto(-160, 40)

player_3.pendown()

for turn in range(60):

player_3.right(6)

player_4 = Turtle()

player_4.shape('turtle')

player_4.color('orange')

player_4.penup()

player_4.goto(-160, 10)

player_4.pendown()

for turn in range(30):

player_4.left(12)

for turn in range(100):

player_1.forward(randint(1, 5))

player_2.forward(randint(1, 5))

player_3.forward(randint(1, 5))

player_4.forward(randint(1, 5))


BGR color palette

import cv2

import numpy as np

def emptyFunction():

pass

def main():

image = np.zeros((512, 512, 3), np.uint8)

windowName ="Open CV Color Palette"

cv2.namedWindow(windowName)

cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction)

cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction)

cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction)

while(True):

cv2.imshow(windowName, image)

if cv2.waitKey(1) == 27:

break

blue = cv2.getTrackbarPos('Blue', windowName)

green = cv2.getTrackbarPos('Green', windowName)

red = cv2.getTrackbarPos('Red', windowName)

image[:] = [blue, green, red]

print(blue, green, red)

cv2.destroyAllWindows()

if __name__=="__main__":

main()


Countdown Timer

import time

from tkinter import *

from tkinter import messagebox

root = Tk()

root.geometry("300x250")

root.title("Time Counter")

hour=StringVar()

minute=StringVar()

second=StringVar()

hour.set("00")

minute.set("00")

second.set("00")

hourEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=hour)

hourEntry.place(x=80,y=20)


minuteEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=minute)

minuteEntry.place(x=130,y=20)


secondEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=second)

secondEntry.place(x=180,y=20)

def submit():

try:

temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get())

except:

print("Please input the right value")

while temp >-1:

mins,secs = divmod(temp,60)

hours=0

if mins >60:

hours, mins = divmod(mins, 60)

hour.set("{0:2d}".format(hours))

minute.set("{0:2d}".format(mins))

second.set("{0:2d}".format(secs))

root.update()

time.sleep(1)

if (temp == 0):

messagebox.showinfo("Time Countdown", "Time's up ")

temp -= 1

btn = Button(root, text='Set Time Countdown', bd='5',

command= submit)

btn.place(x = 70,y = 120)

root.mainloop()


Pedestrian Detector for images

import cv2

import imutils

# detector

hog = cv2.HOGDescriptor()

hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# Reading the Image

image = cv2.imread('img_path')

# Resizing the Image

image = imutils.resize(image,

width=min(400, image.shape[1]))

# Detecting all the regions in the

# Image that has a pedestrians inside it

(regions, _) = hog.detectMultiScale(image,

winStride=(4, 4),

padding=(4, 4),

scale=1.05)

# Drawing the regions in the Image

for (x, y, w, h) in regions:

cv2.rectangle(image, (x, y),

(x + w, y + h),

(0, 0, 255), 2)

# Showing the output Image

cv2.imshow("Image", image)

cv2.waitKey(0)

cv2.destroyAllWindows()


Multiple color live camera

import cv2

import numpy as np

# capturing first camera 

cap = cv2.VideoCapture(0)

while True:

ret, frame = cap.read()

# Capturing grayscale

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

cv2.imshow('frame', frame)

cv2.imshow('gray', gray)

# Program will terminate when 'q' key is pressed

if cv2.waitKey(1) & 0xFF == ord('q'):

break

# Releasing resources

cap.release()

cv2.destroyAllWindows()


weight converter

from tkinter import *

window = Tk()

def from_kg():

gram = float(e2_value.get())*1000

pound = float(e2_value.get())*2.20462

ounce = float(e2_value.get())*35.274

t1.delete("1.0", END)

t1.insert(END,gram)

t2.delete("1.0", END)

t2.insert(END,pound)

t3.delete("1.0", END)

t3.insert(END,ounce)

e1 = Label(window, text = "Enter the weight in Kg")

e2_value = StringVar()

e2 = Entry(window, textvariable = e2_value)

e3 = Label(window, text = 'Gram')

e4 = Label(window, text = 'Pounds')

e5 = Label(window, text = 'Ounce')

t1 = Text(window, height = 1, width = 20)

t2 = Text(window, height = 1, width = 20)

t3 = Text(window, height = 1, width = 20)

b1 = Button(window, text = "Convert", command = from_kg)

e1.grid(row = 0, column = 0)

e2.grid(row = 0, column = 1)

e3.grid(row = 1, column = 0)

e4.grid(row = 1, column = 1)

e5.grid(row = 1, column = 2)

t1.grid(row = 2, column = 0)

t2.grid(row = 2, column = 1)

t3.grid(row = 2, column = 2)

b1.grid(row = 0, column = 2)

window.mainloop()


Counting Faces

import cv2

import numpy as np

import dlib

cap = cv2.VideoCapture(0)

# Detect the coordinates

detector = dlib.get_frontal_face_detector()

while True:

# Capture frame-by-frame

ret, frame = cap.read()

frame = cv2.flip(frame, 1)

# RGB to grayscale

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = detector(gray)

i = 0

for face in faces:

x, y = face.left(), face.top()

x1, y1 = face.right(), face.bottom()

cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)

i = i+1

cv2.putText(frame, 'face num'+str(i), (x-10, y-10),

cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

print(face, i)

cv2.imshow('frame', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):

break

cap.release()

cv2.destroyAllWindows()


Turtle moving circle

import turtle

def moving_object(move):

    move.fillcolor('Purple') 

    move.begin_fill() 

    move.circle(10)  

    move.end_fill()             

if __name__ == "__main__" :

    screen = turtle.Screen() 

    screen.setup(600,600)    

    # screen background color

    screen.bgcolor('white')   

    screen.tracer(0)           

    move = turtle.Turtle() 

    move.color('Purple')

    move.speed(0) 

    move.width(2)     

    move.hideturtle()          

    move.penup()               

    move.goto(-250, 0) 

    move.pendown()             

    while True :

        move.clear()  

        moving_object(move)   

        screen.update()    

        move.forward(0.5)      

creating a real time color detector

#Color Detection

import numpy as np

import cv2

# Capturing video through webcam

webcam = cv2.VideoCapture(0)

while(1):

_, imageFrame = webcam.read()

# Convert the imageFrame in

# BGR(RGB color space) to

# HSV(hue-saturation-value)

# color space

hsvFrame = cv2.cvtColor(imageFrame, cv2.COLOR_BGR2HSV)

red_lower = np.array([136, 87, 111], np.uint8)

red_upper = np.array([180, 255, 255], np.uint8)

red_mask = cv2.inRange(hsvFrame, red_lower, red_upper)

green_lower = np.array([25, 52, 72], np.uint8)

green_upper = np.array([102, 255, 255], np.uint8)

green_mask = cv2.inRange(hsvFrame, green_lower, green_upper)

blue_lower = np.array([94, 80, 2], np.uint8)

blue_upper = np.array([120, 255, 255], np.uint8)

blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper)

kernal = np.ones((5, 5), "uint8")

red_mask = cv2.dilate(red_mask, kernal)

res_red = cv2.bitwise_and(imageFrame, imageFrame,

mask = red_mask)

green_mask = cv2.dilate(green_mask, kernal)

res_green = cv2.bitwise_and(imageFrame, imageFrame,

mask = green_mask)

blue_mask = cv2.dilate(blue_mask, kernal)

res_blue = cv2.bitwise_and(imageFrame, imageFrame,

mask = blue_mask)

contours, hierarchy = cv2.findContours(red_mask,

cv2.RETR_TREE,

cv2.CHAIN_APPROX_SIMPLE)

for pic, contour in enumerate(contours):

area = cv2.contourArea(contour)

if(area > 300):

x, y, w, h = cv2.boundingRect(contour)

imageFrame = cv2.rectangle(imageFrame, (x, y),

(x + w, y + h),

(0, 0, 255), 2)

cv2.putText(imageFrame, "Red Colour", (x, y),

cv2.FONT_HERSHEY_SIMPLEX, 1.0,

(0, 0, 255))

contours, hierarchy = cv2.findContours(green_mask,

cv2.RETR_TREE,

cv2.CHAIN_APPROX_SIMPLE)

for pic, contour in enumerate(contours):

area = cv2.contourArea(contour)

if(area > 300):

x, y, w, h = cv2.boundingRect(contour)

imageFrame = cv2.rectangle(imageFrame, (x, y),

(x + w, y + h),

(0, 255, 0), 2)

cv2.putText(imageFrame, "Green Colour", (x, y),

cv2.FONT_HERSHEY_SIMPLEX,

1.0, (0, 255, 0))

contours, hierarchy = cv2.findContours(blue_mask,

cv2.RETR_TREE,

cv2.CHAIN_APPROX_SIMPLE)

for pic, contour in enumerate(contours):

area = cv2.contourArea(contour)

if(area > 300):

x, y, w, h = cv2.boundingRect(contour)

imageFrame = cv2.rectangle(imageFrame, (x, y),

(x + w, y + h),

(255, 0, 0), 2)

cv2.putText(imageFrame, "Blue Colour", (x, y),

cv2.FONT_HERSHEY_SIMPLEX,

1.0, (255, 0, 0))

# Program Termination

cv2.imshow("Multiple Color Detection in Real-TIme", imageFrame)

if cv2.waitKey(1) & 0xFF == ord('q'):

cap.release()

cv2.destroyAllWindows()

break


Screen recorder

# importing packages

import pyautogui

import cv2

import numpy as np

#resolution

resolution = (1920, 1080)

codec = cv2.VideoWriter_fourcc(*"XVID")

#Output file

filename = "Recordings.avi"

#frames rate

fps = 60.0

# Create a VideoWriter object

out = cv2.VideoWriter(filename, codec, fps, resolution)

# Creating an Empty window

cv2.namedWindow("Live", cv2.WINDOW_NORMAL)

# Resize this window

cv2.resizeWindow("Live", 480, 270)

while True:

# Take screenshot using PyAutoGUI

img = pyautogui.screenshot()

# Convert the screenshot to a numpy array

frame = np.array(img)

# Convert it from BGR(Blue, Green, Red) to

# RGB(Red, Green, Blue)

frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Write output file

out.write(frame)

#Display the recording screen

cv2.imshow('Live', frame)

# Stop recording when we press 'q'

if cv2.waitKey(1) == ord('q'):

break

# Release the Video writer

out.release()

# Destroy windows

cv2.destroyAllWindows()


ToDo App

from tkinter import *

from tkinter import messagebox

tasks_list = []

counter = 1

def inputError() :

if enterTaskField.get() == "" :

messagebox.showerror("Input Error")

return 0

return 1

def clear_NumberField() :

taskNumberField.delete(0.0, END)

def clear_taskField() :

enterTaskField.delete(0, END)

# Function for inserting the content

# from the task entry field to the text area

def insertTask():

global counter

value = inputError()

if value == 0 :

return

content = enterTaskField.get() + "\n"

# store task in the list

tasks_list.append(content)

TextArea.insert('end -1 chars', "[ " + str(counter) + " ] " + content)

counter += 1

clear_taskField()


# function for deleting the specified task

def delete() :

global counter

if len(tasks_list) == 0 :

messagebox.showerror("No task")

return

# get the task number, which is required to delete

number = taskNumberField.get(1.0, END)

if number == "\n" :

messagebox.showerror("input error")

return

else :

task_no = int(number)

# function calling for deleting the

# content of task number field

clear_NumberField()

# deleted specified task from the list

tasks_list.pop(task_no - 1)

# decremented

counter -= 1

TextArea.delete(1.0, END)

for i in range(len(tasks_list)) :

TextArea.insert('end -1 chars', "[ " + str(i + 1) + " ] " + tasks_list[i])

if __name__ == "__main__" :

gui = Tk()

gui.configure(background = "light blue")

gui.title("ToDo App")

gui.geometry("250x300")

enterTask = Label(gui, text = "Enter Your Task", bg = "light blue")

enterTaskField = Entry(gui)

Submit = Button(gui, text = "Submit", fg = "Black", bg = "light yellow", command = insertTask)

TextArea = Text(gui, height = 5, width = 25, font = "lucida 13")

taskNumber = Label(gui, text = "Delete Task Number", bg = "Red")

taskNumberField = Text(gui, height = 1, width = 2, font = "lucida 13")

delete = Button(gui, text = "Delete", fg = "Black", bg = "Red", command = delete)

Exit = Button(gui, text = "Exit", fg = "Black", bg = "Red", command = exit)

enterTask.grid(row = 0, column = 2)

enterTaskField.grid(row = 1, column = 2, ipadx = 50)

Submit.grid(row = 2, column = 2)

TextArea.grid(row = 3, column = 2, padx = 10, sticky = W)

taskNumber.grid(row = 4, column = 2, pady = 5)

taskNumberField.grid(row = 5, column = 2)

delete.grid(row = 6, column = 2, pady = 5)

Exit.grid(row = 7, column = 2)

gui.mainloop()


Creating a AudioBook

 Installing pyttsx3:

          pip install pyttsx3

Installing espeak:

          sudo apt install espeak


import pyttsx3
book=open(r"#add_path_of_txt_file")
book_text=book.readlines()
engine = pyttsx3.init()
for i in book_text:
engine.say(i)
engine.runAndWait()

Voice Recorder using python

 install portaudio using:

               pip install portAudio

install portaudio library:
    
               sudo apt-get install libportaudio2


import sounddevice
from scipy.io.wavfile import write 
fs=44100 #sample_rate
second=int(input("Enter the time duration in second: "))
print("Recording....\n")
record_voice=sounddevice.rec(int(second * fs),samplerate=fs,channels=2)
sounddevice.wait()
write("out.wav",fs,record_voice)
print("Finished....\nPlease check it...")

Compound Interest GUI Calculator using Tkinter

# importing classes and functions from the tkinter

from tkinter import *

# Function for clearing the

# contents of all entry boxes

def clear_all() :

# whole content of entry boxes is deleted

principle_field.delete(0, END)

rate_field.delete(0, END)

time_field.delete(0, END)

compound_field.delete(0, END)

# set focus on the principle_field entry box

principle_field.focus_set()

# Function to find compound interest

def calculate_ci():

# get a content from entry box

principle = int(principle_field.get())

rate = float(rate_field.get())

time = int(time_field.get())

# Calculates compound interest

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

# insert method inserting the

# value in the text entry box.

compound_field.insert(10, CI)

#code

if __name__ == "__main__" :

# Create a GUI window

root = Tk()

# Set the background colour of GUI window

root.configure(background = 'white')

# Set the configuration of GUI window

root.geometry("400x250")

# set the name of tkinter GUI window

root.title("Compound Interest Calculator")

# Create a Principle Amount : label

label1 = Label(root, text = "Principle Amount(Rs) : ",

fg = 'white', bg = 'black')

# Create a Rate : label

label2 = Label(root, text = "Rate(%) : ",

fg = 'white', bg = 'black')

# Create a Time : label

label3 = Label(root, text = "Time(years) : ",

fg = 'white', bg = 'black')


# Create a Compound Interest : label

label4 = Label(root, text = "Compound Interest : ",

fg = 'white', bg = 'black')

# grid method is used for placing

# the widgets at respective positions

# in table like structure .

# padx keyword argument used to set padding along x-axis .

# pady keyword argument used to set padding along y-axis .

label1.grid(row = 1, column = 0, padx = 10, pady = 10)

label2.grid(row = 2, column = 0, padx = 10, pady = 10)

label3.grid(row = 3, column = 0, padx = 10, pady = 10)

label4.grid(row = 5, column = 0, padx = 10, pady = 10)

# Create a entry box

# for filling or typing the information.

principle_field = Entry(root)

rate_field = Entry(root)

time_field = Entry(root)

compound_field = Entry(root)

# grid method is used for placing

# the widgets at respective positions

# in table like structure .

# padx keyword argument used to set padding along x-axis .

# pady keyword argument used to set padding along y-axis .

principle_field.grid(row = 1, column = 1, padx = 10, pady = 10)

rate_field.grid(row = 2, column = 1, padx = 10, pady = 10)

time_field.grid(row = 3, column = 1, padx = 10, pady = 10)

compound_field.grid(row = 5, column = 1, padx = 10, pady = 10)

# Create a Submit Button and attached

# to calculate_ci function

button1 = Button(root, text = "Submit", bg = "red",

fg = "black", command = calculate_ci)

# Create a Clear Button and attached

# to clear_all function

button2 = Button(root, text = "Clear", bg = "red",

fg = "black", command = clear_all)

button1.grid(row = 4, column = 1, pady = 10)

button2.grid(row = 6, column = 1, pady = 10)

# Start the GUI

root.mainloop()


Number guessing game (Basic Python Project)

import random

import math

# Taking Inputs

lower_input = int(input("Enter lower_input number:- "))

# Taking Inputs

upper_input = int(input("Enter upper_input number:- "))

# generating random number between

# the lower_input and upper_input

x = random.randint(lower_input, upper_input)

print("\n\tYou've only ",

round(math.log(upper_input - lower_input + 1, 2)),

" chances to guess the integer!\n")

# Initializing the number of guesses.

count = 0

# for calculation of minimum number of

# guesses depends upon range

while count < math.log(upper_input - lower_input + 1, 2):

count += 1

# taking guessing number as input

guess = int(input("Guess a number:- "))

# Condition testing

if x == guess:

print("Congratulations you did it in ",

count, " try")

# Once guessed, loop will break

break

elif x > guess:

print("You guessed too small!")

elif x < guess:

print("You Guessed too high!")

# If Guessing is more than required guesses,

# shows this output.

if count >= math.log(upper_input - lower_input + 1, 2):

print("\nThe number is %d" % x)

print("\tBetter Luck Next time!")


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