0

I was doing a codewars challenge and ran into an interesting lambda function that I don't really understand.

sum_corners=lambda n:n*n+2*(n>1)

I don't understand what's going on with multiplying by the conditional here (n>1)

The code wars challenge was to create a function that adds the corners of a triangle given the number of rows for the triangle.

example:

n = 3
-->1
-->2, 3
-->4, 5, 6 
1 + 4 + 6 = 11

I did write a working function that solves the problem, but the above code obviously is more efficient.

My Function:

def sum_corners(n): 
    if n == 0 or n == 1:
        return n
    else:
        lst = [x + 1 for x in range(n)]
        matrix = []
        last = 0
        for i in lst:
            matrix.append([last + x + 1 for x in range(i)])
            last = matrix[i-1][-1]
            print(matrix[i-1])
        return matrix[0][0] + matrix[-1][0] + matrix[-1][-1]

Just trying to understand how this particular lambda function is working.

Thanks!

  • 4
    The fact that this specific expression is in a lambda isn't terribly relevant, and you can consider the use of a lambda separately from multiplying by a boolean - this is discussed [here](https://stackoverflow.com/q/13332162/1424875). – nanofarad Aug 17 '22 at 20:23
  • 1
    True and False are equivalent to 1 and 0. This makes multiplication equivalent to `and`. – Barmar Aug 17 '22 at 20:24
  • in that case means sums 2 only if n is greater than one – Ulises Bussi Aug 17 '22 at 20:24

0 Answers0