使用函数可以通过y排除多少次x

发布于 2025-02-01 03:50:12 字数 288 浏览 2 评论 0原文

因此,基本上,我必须构建一种算法,该算法告诉我X可以被Y排除多少次。如果它不可分割,则应返回print -1。

这是我到目前为止的:

def divisible(x, y):
 n = int(x/y)
 if (n != 0 and x%y == 0):
   print(x, "its divisible by",y,n,"times")
 else:
    print(-1)

divisible(5, 2)

练习要求使用柜台做到这一点。我该怎么做?

谢谢

So, basically I have to built an algorithm that tells me how many times X is divisible by Y. If its not divisible, it should return print -1.

Here's what i've got so far:

def divisible(x, y):
 n = int(x/y)
 if (n != 0 and x%y == 0):
   print(x, "its divisible by",y,n,"times")
 else:
    print(-1)

divisible(5, 2)

The exercise its asking to use a counter to do this. How can I make It?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

铃予 2025-02-08 03:50:12

整数部门和Modulo功能应该使您到达那里 -

divisible = lambda x, y: x // y if x % y == 0 else -1
divisible(13, 3)
# -1
divisible(12, 3)
# 4

Integer division and the modulo function should get you there -

divisible = lambda x, y: x // y if x % y == 0 else -1
divisible(13, 3)
# -1
divisible(12, 3)
# 4
像你 2025-02-08 03:50:12
def divisible (x, y):
    # Initialize times to keep track of how many times x is
    # divisible by y:
    times = 0
    # Enter an infinite loop:
    while True:
        # If the remainder of x divided by y is 0
        # (= if x is divisible by y):
        if ( x % y == 0 ):
            # Increment times by 1 and actually divide x by y:
            times += 1
            x = x / y
        # If x is *not* divisible by y, break out of the infinite loop:
        else:
            break
    # If the original x was not divisible by y at all, return -1
    # (otherwise, keep times unchanged):
    if times == 0:
        times = -1
    return times
    
print(divisible(2, 2))
# 1

print(divisible(3, 2))
# -1

print(divisible(8, 2))
# 3

print(divisible(10000, 2))
# 4
def divisible (x, y):
    # Initialize times to keep track of how many times x is
    # divisible by y:
    times = 0
    # Enter an infinite loop:
    while True:
        # If the remainder of x divided by y is 0
        # (= if x is divisible by y):
        if ( x % y == 0 ):
            # Increment times by 1 and actually divide x by y:
            times += 1
            x = x / y
        # If x is *not* divisible by y, break out of the infinite loop:
        else:
            break
    # If the original x was not divisible by y at all, return -1
    # (otherwise, keep times unchanged):
    if times == 0:
        times = -1
    return times
    
print(divisible(2, 2))
# 1

print(divisible(3, 2))
# -1

print(divisible(8, 2))
# 3

print(divisible(10000, 2))
# 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文