发布于 2025-01-21 23:37:43 字数 8 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

踏月而来 2025-01-28 23:37:43

continue

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.

岁吢 2025-01-28 23:37:43
def fraction_count(num1, num2):
    num1 = int(num1)
    num2 = int(num2)
    count = 0
    while num1 % num2:
        num1 //= num2
        count += 1
    return count

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文