繁体   English   中英

编写一个包含迭代和递归 function 的程序来打印前 100 个元素

[英]Write a program which contains iterative and recursive function to print the first 100 elements

鉴于这个问题

在此处输入图像描述

我想这个问题是怎么说的。 那就是像下面的例子一样打印:

Eg.
n Iterative Recursive
1 1          1
2 3          3
3 6          6
4 10        10
.  .        . 
.  .        .

我能够使用显式公式为我的问题打印 n 和递归。

print("    n       Recursive")
def recursive(n):
    result = ((4 * n) - 1) - 14
    print("%5d" % n, end="")
    print("%12d" % result)
    if n == 100:
        return 0
    else:
        recursive(n + 1)
recursive(1)

我不知道什么是迭代或如何打印出来。 根据上面的例子,递归是否相同?

迭代意味着一个一个地遍历每个元素。 我想一个简单的 for 循环应该可以完成这项工作:

def iterative():
    for n in range(100):
        result = ((4 * n) - 1) - 14
        print("%5d" % n, end="")
        print("%12d" % result)
    return 0

iterative()

“好”迭代 function 应该看起来像这样才能打印正确的值:

def iterative():
    # np being the previous value
    np = 14

    # starts from 2 since the first case is already assumed to known (14)
    # go up to the 100th number
    for n in range(2, 101):
        result = np - 4
        print("%5d" % n, end="")
        print("%12d" % result)
        np = result
    return 0

iterative()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM