My assignment is to find out how many times it takes for num1 to be divided by num2 before its a whole number, using recursion. My current code is
def fraction_count(num1, num2):
times = int(0)
result = num1/num2
num1 = int(result)
if result%2 == 0:
return times
if (num1/num2)%2 != 0:
return times 1
print(fraction_count(32,3))
Expected is:
fraction_count(32, 3) → 2 # 32 → 10.667 → 3.333 → 1; 1 is whole → 2
So I have the output of 1 right now because its just running through once. What am I missing here?
CodePudding user response:
Riffing off of Nin17's answer but fulfilling the assignment's requirement to make it recursive yields:
def fraction_count(num1, num2):
num1 = int(num1)
num2 = int(num2)
if num1 % num2 == 0:
return 0
return 1 fraction_count(num1 // num2, num2)
You can make it a tad faster by eliminating the type conversions if num1
and num2
are guaranteed to be integers. With type hinting (added in python 3.5), the code becomes:
def fraction_count(num1: int, num2: int) -> int:
if num1 % num2 == 0:
return 0
return 1 fraction_count(num1 // num2, num2)
Short and sweet. Recursion may be less efficient than looping, but it often delivers concise code.
CodePudding user response:
The question is confusing, but this implements something similar to your example and provides the desired result for fraction_count(32, 3)
def fraction_count(num1, num2):
num1 = int(num1)
num2 = int(num2)
count = 0
while num1 % num2:
num1 //= num2
count = 1
return count