Sunday, February 2, 2014

Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents

#!/usr/bin/python

def find_ways(money,denom):
    next_denom=0
    while denom>0:
        if denom==25:
            next_denom=10
            break
        elif denom==10:
            next_denom=5
            break
        elif denom==5:
            next_denom=1
            break
        elif denom==1:
            return 1       
    ways=0
    i=0
    while i*denom<=money:
        ways +=find_ways(money-i*denom,next_denom)
        i=i+1
    return ways

result=find_ways(100,25)
print result

Wednesday, January 29, 2014

Recursive and Iterative approach for fibonacci in python

#!/usr/bin/python

### Recursive approach for fibonacci series
def fibo_recur(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fibo_recur(n-1) + fibo_recur(n-2)

### Iterative approach for fibonacci series
def fibo_iter(n):
    a=1
    b=1
    if n==0:
        return 0
    while n>=3:
        c=a+b
        a=b
        b=c
        n=n-1
    return b

recur_result=fibo_recur(3)
print recur_result

iter_result=fibo_iter(3)
print iter_result

My Profile

My photo
can be reached at 09916017317