【问题标题】:Python returning none instead of string output [duplicate]Python返回none而不是字符串输出[重复]
【发布时间】:2019-12-01 15:05:54
【问题描述】:

我在递归函数中编写了一些关于收缩字符串的代码。

当输入字符串结束时返回输出。

它在函数中显示正确的东西,但它返回 None,而不是 answer

def rec_encyption(input, i, cnt, output):
    if i + 1 == len(input):
        print(output)
        return output
    elif input[i] == input[i + 1]:
        rec_encyption(input, i + 1, cnt + 1, output)
    else:
        output = output + input[i] + str(cnt)
        rec_encyption(input, i + 1, 1, output)

def do_rec_encyption(input):
    n = rec_encyption(input + " ", 0, 1, "")
    print(n)
    return n

print(do_rec_encyption("aaabbcccccca"))

我在 VSCode 中运行这段代码,结果是这样的:

a3b2c6a1

这意味着rec_encyption返回None,而不是'输出'

我找不到解决此问题的原因和方法

【问题讨论】:

    标签: python


    【解决方案1】:

    在 else 中使用 return

    def rec_encyption(input, i, cnt, output):
        if i + 1 == len(input):
            print(output)
            return output
        elif input[i] == input[i + 1]:
            return rec_encyption(input, i + 1, cnt + 1, output)
        else:
            output = output + input[i] + str(cnt)
            return rec_encyption(input, i + 1, 1, output)
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2019-08-08
      相关资源
      最近更新 更多