带字符串输出的递归计数

问题描述 投票:1回答:3

我需要做一个打印为字符串的计数值-因此,如果用户输入5,它将从1开始计数-'1 2 3 4 5'而不是单独的行。这是我对基本递归函数的要求,该函数递归计数,但是它没有给我字符串输出。任何帮助将不胜感激

def countup(N, n=0):
    print(n)
    if n < N:
        countup(N, n + 1)
python string recursion
3个回答
0
投票

如果需要返回字符串,请考虑返回字符串。结果的第一部分将n转换为字符串:str(n)。尚未完成时,请在其余数字后面加上一个空格,后跟countup。像这样:

def countup(N, n=1):
    res = str(n)
    if n < N:
        res += ' ' + countup(N, n + 1)
    return res

print(countup(5))

不需要本地变量的另一个版本是:

def countup(N, n=1):
    if n < N:
        return str(n) + ' ' + countup(N, n + 1)
    else:
        return str(n)

0
投票

print(n, end = ' ')更改打印的结尾以避免换行。参见How to print without newline or space?

此外,假设调用了n=1,默认参数应为it would count up from 1以符合countup(5)

def countup(N, n=1):
    print(n, end = ' ')
    if n < N:
        countup(N, n + 1)

0
投票

为什么不只使用str.join?此处无需递归。

def countup(N, n=1):
    return ' '.join(map(str, range(n, N)))
© www.soinside.com 2019 - 2024. All rights reserved.