Landon G
Landon G

Reputation: 839

How to use recursion to divide a number multiple times and keep track of the iterations?

I'm trying to make a function that will half the integer argument until it's under 1. I also want to keep track of how many iterations it took for it to do this. Here is what I have so far, but I am stuck on what to put in the recursive case:

def case(number):
    if number == 1:
       return 1
    else:
       return number * 0.50    # not sure how to do this part
case(20)

So for example, if I had 20 passed as an argument for "case", I want the recursive case/ function to do 20 * 0.50 (or 20/2)= 10, then take 10 * 0.50 = 5, then take 5 * 0.50 ect.. until the number is under 1.

In this example, it would have taken 6 iterations to get below 1 (0.625).

How do you get the recursive case to keep dividing or taking half of the number and for it to print the amount of iterations it took to the console?

Note: I'm aware that while loops would be a lot more suited for this situation, but the project I'm working, recursion will make it easier later.

Thank you for the help!

Upvotes: 1

Views: 958

Answers (4)

Cumar Yusuf
Cumar Yusuf

Reputation: 61

def case(number,count):
    if number < 1:
       return "Taken %s iteration to get below 1 (%s)" % (count,number)
    return case(number * 0.5, count+1)  

print case(20, 0)

Upvotes: 0

TheGreatGeek
TheGreatGeek

Reputation: 56

def case(number, t=0):
    if number < 1:
        return (number,t)
    else:
        return case(number/2, t+1)

This will return a tuple containing the number (e.g. 0.625) and the number of iterations (e.g. 6)

The parameter t represents the number of iterations.

When number is less than one, nothing else needs to be done, so we return the tuple (number, t). If number is greater than or equal to 1, will return the result of calling case with number/2 as the first parameter (number) and t+1 as the second parameter (t). This way t is incremented once for every level of recursion.

Upvotes: 1

Jacob Kaddoura
Jacob Kaddoura

Reputation: 175

def case(number):
   return recursiveFunc(number, 0, 0.5)
def recursiveFunc(number, count, multiplier):
    if(number <= 1):
       return count
    return recursiveFunc(number*multiplier, count+1, multiplier)

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

def case(number):
    if number <= 1: # base case (exit)
       return 1
    else:
       return 1+case(number * 0.50) # recursive case

Upvotes: 3

Related Questions