【发布时间】:2016-09-15 09:22:01
【问题描述】:
有一道数学题:
- 选择一个正整数 n 作为开始。
- 如果 n 是偶数,则将其除以 2。
- 如果 n 是奇数,则乘以 3,然后加 1。
- 继续此过程,直到 n 为 1。
我想写一个递归函数,它以n为参数,然后返回一个元组,其中包含进程中的n的轨道序列,以及序列的长度。但是失败了。
我的代码有什么问题?如何完成任务?
def hailstone(n):
"""the implementation of recursive one,
return a tuple that includes the hailstone sequence
starting at n, and the length of sequence.
>>> a = hailstone(1)
([1, 4, 2, 1], 4)
"""
if n % 2 == 0:
n = n//2
else:
n = n*3 + 1
if n == 1:
return [n]
else:
"""
for some magic code here,
it will return a tuple that includes the list track of n,
and the length of sequence,
like ([1, 4, 2, 1], 4)
"""
return ([n for some_magic in hailstone(n)], lenght_of_seq)
【问题讨论】:
-
对“失败”有任何进展吗?
-
我不知道如何在递归调用中使用列表跟踪不断变化的 n?@jonrsharpe
-
请将问题edit给minimal reproducible example解释实际问题,然后。
-
你没有在两次返回中返回相同的对象!!另外,你试过
len([n for some_magic in hailstone(n)])吗?它给出了数组的 len。这不是 C,这是一种进化的语言。所以你可以在返回值上使用len来获取长度。 -
仅供参考,这是Collatz conjecture
标签: python algorithm recursion