continue
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
continue
Riffing off of Nin17's answer but fulfilling the assignment's requirement to make it recursive yields:
You can make it a tad faster by eliminating the type conversions if
num1
andnum2
are guaranteed to be integers. With type hinting (added in python 3.5), the code becomes:Short and sweet. Recursion may be less efficient than looping, but it often delivers concise code.
The question is confusing, but this implements something similar to your example and provides the desired result for
fraction_count(32, 3)