gpt4 book ai didi

python - 求和 : Is recursion necessary, 以及递归算法是什么样的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:17 25 4
gpt4 key购买 nike

<分区>

def numPens(n):
"""
n is a non-negative integer

Returns True if some non-negative integer combination of 5, 8 and 24 equals n
Otherwise returns False.
"""
if n < 5:
return False
N = n
while N >= 0:
if N % 24 == 0 or N % 8 == 0 or N % 5 == 0: # if N / 24 is equal to 0 then we can buy N pens
return True
if N < 5:
return False # if N < 5 we cannot buy any pens

if N > 24: # if N is greater than 24 , take away 24 and continue loop
N -= 24
elif N > 8: # if N is greater than 8, take away 8 and continue loop
N -= 8
else:
N -= 5 # else take away 5 and continue loop

我不得不为测试创建这个函数,我只是想知道问题是否可以递归排序或者什么是最有效的解决方案,我是编程新手,所以任何帮助都会很好,谢谢。

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