1.shuffle deck of cards and draw cards
import itertools,random
deck=list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
random.shuffle(deck)
for i in range(5):
print deck[i][0],"of",deck[i][1]
2.lowest common ancestor:
class TreeNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
root=head=TreeNode(3)
head.left=TreeNode(5)
head.right=TreeNode(1)
head.left.left=TreeNode(6)
head.left.right=TreeNode(2)
head.right.left=TreeNode(0)
head.right.right=TreeNode(8)
head.left.right.left=TreeNode(7)
head.left.right.right=TreeNode(4)
def match(root,p1):
if root==None:
return False
if root.val==p1.val:
return True
return match(root.left,p1) or match(root.right,p1)
def lca(root,p1,p2):
if match(root.left,p1) and match(root.left,p2):
return lca(root.left,p1,p2)
if match(root.right,p1) and match(root.right,p2):
return lca(root.right,p1,p2)
return root.val
def main():
p1=TreeNode(1)
p2=TreeNode(0)
print lca(root,p1,p2)
if __name__=="__main__":
main()
3. find min in rotated sorted array
def minSearch(num):
low=0
high=len(num)-1
while low<high and num[low]>num[high]:
mid=low+(high-low)/2
if num[mid]<num[high]:
high=mid
else:
low=mid+1
return num[low]
def main():
num=[7,7,8,9,0,1,2,3,3]
print minSearch(num)
if __name__=="__main__":
main()