gpt4 book ai didi

python - 判断a是否是b的幂

转载 作者:太空狗 更新时间:2023-10-29 22:27:57 25 4
gpt4 key购买 nike

我目前正在使用 singpath.com 在我的 python 上练习,但我遇到了一个问题:

一个数a是b的幂,如果它能被b整除并且a/b是b的幂。编写一个名为 is_power 的函数,它接受参数 a 和 b,如果 a 是 b 的幂,则返回 True。

def is_power(a,b):
c = a/b
if (((a%b) == 0) and ((c%b) == 0)):
return True
else:
return False

以上是我的解决方案,但系统提示我概括我的解决方案。谁能告诉我我的解决方案有什么问题?

最佳答案

您的原始代码不起作用的原因如下:您只需检查 (c%b) == 0)又名 (a/b) is divisible by b ,比 a/b is a power of b 弱得多定义的一部分。

当你想解决这样的问题时,你应该总是从琐碎的案例开始。在这种情况下,有两种情况:is_power(x,x)is_power(1,x) - 两者的答案都是 True ,因为 x**1==xx**0==1 .

一旦你涵盖了这些案例,你只需要写下定义的其余部分。为 (a is divisible by b) and (a/b is a power of b) 编写代码并将它们放在一起。

最终的函数如下所示:

def is_power(a,b):
if <trivial case 1> or <trivial case 2>:
return True
# its a recursive definition so you have to use `is_power` here
return <a is divisible by b> and <a/b is a power of b>

剩下的唯一问题是如何回答<a/b is a power of b> .最简单的方法是使用函数 is_power本身 - 这称为递归。

关于python - 判断a是否是b的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4738908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com