質問

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