문제

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