I don't understand why "head" is undefined in the following code, I'm trying to use a Accumulate pattern to get the some of a list of numbers.

def sum(items):
    if (items == None): #base case
        return 0
    else:
        return head(items) + sum(tail(items))
def main():
    items = (input("give me a list"))
    print ("the sum of the list is", sum(items))

main()
有帮助吗?

解决方案

Since head and tail are being called by passing arguments to them (items is the argument to both), you should declare them as functions:

def head(items):
    # ...
    return ...

def tail(items):
    # ...
    return ...

Note:

  • If this is a homework, then the problem statement should specify what are those functions supposed to do.

其他提示

def sum(items):
    if not items:
        return 0
    else:
        head = lambda x: x[0]
        tail = lambda x: x[1:]
        return head(items) + sum(tail(items))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top