Ricardo Campos
Ricardo Campos

Reputation: 53

Lambdas and sums Python

def summation(calc_termo, linf, prox, lsup):
    soma = 0
    while linf <= lsup:
        soma = soma + calc_termo(linf)
        linf = prox(linf)
    return soma
summation(lambda x: summation(lambda x: x, 1, lambda x: x + 1, x),1, lambda x: x + 1, 5)

I'm having trouble to understand how this code works. I got this as an exercise from my university and I'm having some trouble understanding the code.

It seems to be the sum of the numbers between 1 to 5, but can't understand what summation(lambda x: x, 1, lambda x: x + 1, x) does.

Upvotes: 1

Views: 130

Answers (2)

Dan
Dan

Reputation: 12675

The last line that you had trouble with could better be stated as:

summation(lambda x: summation(lambda y: y, 1, lambda z: z + 1, x),1, lambda w: w + 1, 5)

The lambdas don't all interfere with each other, if that's what you were confused about.

Upvotes: 0

Blender
Blender

Reputation: 298206

I'd start by taking those arguments apart:

lambda x: summation(lambda x: x, 1, lambda x: x + 1, x)

Substitute those variables back into the the original functions and simplify it:

def inner_function(x):
    soma = 0
    linf = 1

    while linf <= x:
        soma += linf + 1
        linf += 1

    return soma

Simplify that a little more:

def inner_function(x):
    soma = 0

    for linf in range(1, x + 1):
        soma += linf

    return soma

And a little more:

inner_function = lambda x: sum(range(1, x + 1))

And some more:

inner_function = lambda x: x * (x + 1) / 2

Now your original function becomes:

def summation(calc_termo, linf, prox, lsup):
    soma = 0

    while linf <= lsup:
        soma = soma + calc_termo(linf)
        linf = prox(linf)

    return soma

summation(inner_function, 1, lambda x: x + 1, 5)

Or:

def summation(linf, prox, lsup):
    soma = 0

    while linf <= lsup:
        soma = soma + linf * (linf + 1) / 2
        linf = prox(linf)

    return soma

summation(1, lambda x: x + 1, 5)

You can take it from there. I got:

summation = lambda: sum(n * (n + 1) / 2 for n in range(6))

Which is equal to:

sum(sum(range(n + 1)) for n in range(6))

Upvotes: 3

Related Questions