External Exam Download Resources Web Applications Games Recycle Bin

Recursion

recursion.py

intRate = 0.05

def compound(amt, termsRemaining):
    if(termsRemaining == 0):
        return amt
    else:
        termsRemaining = termsRemaining - 1
        newamt = amt + (amt*intRate)
        return compound(newamt, termsRemaining)

print(compound(100,2))


  1. The following function takes 2 integer values, and increments the first up to be equal with the second (using recursion).
    def closegap(x,y):
        if x == y:
            print("values are now level")
            return x
        else:
            return closegap(x+1, y)
        
    print(str(closegap(11,22)))
    
    
    
    ...which prints values are now level and 22 which is the final value of x (level with y).
    Modify the closegap function to decrease y to the value of x.

  2. there are other implementations of recursion you can explore, such as G.C.D, factorial, fibonacci, etc. Implement these in Python as you see fit. Is recursion always the best strategy to use? (short answer - definitely not)