【问题标题】:local variable referenced before assignment in recursion递归赋值前引用的局部变量
【发布时间】:2020-11-28 13:29:49
【问题描述】:

我的程序不工作。

本来就是

  • 你有一个数组和一个代码
  • 如果代码为 0,则必须将数字相加
  • 如果是其他值,则必须将它们相乘
  • 我希望它使用递归,但是当你得到少于 5 个数字时,我不会使用更多递归,我只想正常进行

这是我遇到的问题

    the_rest = sum_or_product(code, array[1:])
UnboundLocalError: local variable 'sum_or_product' referenced before assignment

这是程序

def sum_or_product(code, array):

    if code == 0:
        do = 'SUM'
    else:
        do = 'PRODUCT'

    # THIS IS WITH THE RECURSION

    if len(array) >= 5:
        this_one = array[0]
        the_rest = sum_or_product(code, array[1:])
        if do == 'SUM':
            return this_one + the_rest
        if do == 'PRODUCT':
            return this_one * the_rest

    # THIS IS WITHOUT THE RECURSION

    if do == 'SUM':
        start = 0

    if do == 'PRODUCT':
        start = 1

    sofar = start

    for i in array:
        if do == 'SUM':
            total = sofar + i
            sofar = total
        if do == 'PRODUCT':
            product = sofar * i
            sofar = product
    sum_or_product = sofar

    return sum_or_product


print(sum_or_product(1, [1,2,3,4,5,6,7,8,9,10]))

它应该将所有数字从 1 乘到 10。但它只会给出错误。

【问题讨论】:

  • sum_or_product 是一个函数,而不是一个变量。为什么要给函数赋值?
  • 你只想在数组中为 i rmultiply 代码吗?
  • 如果代码是 0 我想添加。但如果不是 0,我想乘以。

标签: python recursion unbound


【解决方案1】:

为了从函数中返回一个值,你只需

return <value>

而不是将值分配给函数。

所以为了修复你的代码,你只需要替换

    sum_or_product = sofar

    return sum_or_product

与

    return sofar

作为旁注,不要使用诸如“0 是 SUM,1 是 PRODUCT”之类的晦涩约定,而是使用常量,例如:

OP_SUM=0
OP_PRODUCT=1

def sum_or_product(operation, array):

...

    if operation == OP_SUM:
        ...
    elif operation == OP_PRODUCT:
        ...

...

print(sum_or_product(OP_SUM, [2, 3]))

【讨论】:

    【解决方案2】:
        def sum_or_product(code, array):
        
            return (([code * num for num in array if code != 0 and num <= 5]), ([code + num for num in array if num > 5]))
     print(sum_or_product(2, [1,2,3,4,5,6,7,8,9,10]))
    

    输出

    ([2, 4, 6, 8, 10], [8, 9, 10, 11, 12])
    

    【讨论】:

    • 这是你需要的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2011-11-06
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多