递归任意序列

2024-04-20 12:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定义一个递归的几何函数,它将询问用户序列的第一个值和序列的乘数值。函数应该给出所需长度的序列作为参数,并生成该长度的任意几何序列的列表作为返回值。作为澄清示例,如果用户提供5作为起始值,3作为期望长度为6的乘法器,则任意几何序列的前6个元素将是[5、15、45、135、405、1215]

当我运行这段代码时,我得到了奇怪的随机序列。这是我目前的代码:

# This will define a recursive arbitrary Geometric sequence function
def recursive_geo_helper(length):
    start = int(input("Enter the first value of the sequence: "))
    multiplier = int(input("Enter the value that must be multiplied: "))
    return actual_recursive_geo(length, start, multiplier)


def actual_recursive_geo(length, start, multiplier):
    sequence = []

   # print(start)
    if length <= 1:

        exit()
       # return sequence

    else:
        sequence.append(start)

        start = start * multiplier
        length = length - 1



        return actual_recursive_geo(length, start, multiplier)

#recursive_geo_helper(5)

print(recursive_geo_helper(6))

Tags: the函数代码用户helperreturndef序列
2条回答

不幸的是,你的代码没有什么意义。这里有一些问题:内置的exit不应该在shell之外使用,你的函数不返回任何基本情况,即使返回了,也不会递归地附加到这个基本情况。你知道吗

解决所有这些问题,下面是递归解决方案的样子。你知道吗

def actual_recursive_geo(length, a, r):
    if length <= 0:
        return  [] # base case
    else:
        return [a] + actual_recursive_geo(length - 1, a * r, r) # prepend to your base case

虽然这有点低效,因为它做了很多不必要的列表连接。。你知道吗

发电机

我建议从零开始使用更适合的数据结构来表示无限序列:生成器。你知道吗

生成器可以懒洋洋地表示无限序列。此外,Python还提供了itertools标准库来操作它们。在这里,我们将返回一个生成器并用itertools.islice对其进行切片。你知道吗

import itertools

def geometric_input():
    """
    Prompt the user for an initial value and a ratio
    Return the corresponding geometric series
    """
    a = int(input("Enter the first value of the sequence: "))
    r = int(input("Enter the ratio: "))
    return geometric_sequence(a, r)


def geometric_sequence(a, r):
    """ Return a generator for the sequence x_i = a * r ^ i"""
    r_exp = 1
    while True:
        yield a * r_exp
        r_exp *= r


seq = geometric_input()

first_elements = list(itertools.islice(seq, 6))

print(*first_elements)

这是输出。你知道吗

Enter the first value of the sequence: 5
Enter the ratio: 3
5 15 45 135 405 1215

关于生成器的另一个好处是元素在生成时被消耗。这意味着如果您再次切片生成器,您将获得序列中的下一个元素

next_elements = list(itertools.islice(seq, 6))

print(*next_elements)
# prints: 3645, 10935, 32805, 98415, 295245, 885735

我相信你的问题是你在函数中声明了序列而没有正确返回它。你知道吗

另外,如果我们要使用递归,我们可以更进一步,通过将修改后的变量传递给递归调用来避免变量的变异。你知道吗

def geo(sequence, length, multiplier):
    if length <= 1:
        return sequence
    else:
        return sequence + geo([sequence[-1] * multiplier], length - 1, multiplier)

以下是REPL的输出:

>>> geo([5], 6, 3)
[5, 15, 45, 135, 405, 1215]

另外,我更喜欢JavaScript而不是Python,所以我先用JS做了它,然后移植了它。你知道吗

这是JavaScript中的等效函数:

相关问题 更多 >