Pregunta

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()
¿Fue útil?

Solución

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.

Otros consejos

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))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top