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!