Skip to content

Instantly share code, notes, and snippets.

@mailpraveens
mailpraveens / FindMergePointLinkedLists.py
Created March 20, 2014 15:20
Find the merge point of two linked list
def findDivergePointForOfTwoLinkedLists(list1, list2):
# Assuming the list class has a method length to give the length of the list
lengthList1 = list1.length()
lengthList2 = list2.length()
differnce = lengthList2 - lengthList1
if(lengthList2>=lengthList1):
while(differnce!=0):
list2 = list2.next
differnce -= 1
@mailpraveens
mailpraveens / checkForAnagrams.py
Created March 20, 2014 12:02
Function to check for anagrams
#method to check for anagrams within a set
from operator import itemgetter
def checkForAnagrams(input):
temp = dict()
#Sort the input values individually
for k,v in input.items():
temp[k]=''.join(sorted(v))
#Now sort the entire list based on the value of the key
temp2 = sorted(temp.items(),key = itemgetter(1))
@mailpraveens
mailpraveens / heapify.py
Created March 20, 2014 12:03
Heapify method which can be used in heap sort
#max heap construction
def heapify(items,idx):
left = leftChild(idx)
right = rightChild(idx)
largest = -1
if(left < len(items) and items[left] > items[idx]):
largest = left
else:
largest = idx
@mailpraveens
mailpraveens / printCounterClockwiseBinaryTree.py
Created March 20, 2014 12:07
Print a binary tree counter clock wise
'''
1
2 3
4 5 6 7
should print 1,2,4,5,6,7,3,1
'''
@mailpraveens
mailpraveens / findLCA.py
Created March 20, 2014 14:13
Find the Lowest Common Ancestor of Binary Search Tree
def findLCA(node,value1,value2):
if(node == None):
return None
#move to right if values are greater
if(node.value < value1 and node.value < value2):
return findLCA(node.right,value1, value2)
#move to left if values are smaller
if(node.value > value1 and node.value > value2):
return findLCA(node.left,value1, value2)
# Whereever it diverges, return the node as its the LCA
@mailpraveens
mailpraveens / verifySquaringTheorem.py
Created February 26, 2014 07:25
Test to verify the theorem for squaring numbers greater than 25 found on Quora. For fun.
#http://www.quora.com/Whats-a-math-trick-that-is-not-very-well-known/answers/4234574
import sys
def verifySquaringTheorem(n):
for i in range(25,n):
nSquaredSupposed = (( i - 25 ) * 100) + pow(i-50,2)
actualSquare = pow(i,2);
if nSquaredSupposed == actualSquare:
print ("Pass for n = " + str(i) + " with value " + str(nSquaredSupposed))
else:
print("Fail for n = " + str(i) + "with value " + str(nSquaredSupposed) + "and actualSquare value = " + str(actualSquare))