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