Blog Pages

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

def __init__(self):

def push(self, data):

ptr1 = Node(data)

temp = temp.next

temp.next = ptr1

else:

ptr1.next = ptr1

def printList(self):

while(True):

print ("%d" %(temp.data),end=' ')

temp = temp.next

break

return

fast_ptr = fast_ptr.next.next

slow_ptr = slow_ptr.next

fast_ptr = fast_ptr.next

fast_ptr.next = slow_ptr.next

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

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

Pune, Maharashtra

Mumbai, Maharashtra

Kolkata, West Bengal

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