'Is there a way to eliminate multiple computations of same lambda expression occurring multiple times in a Python expression?
I was attempting to exemplify python lambda expressions with the well-known formula for triangle's area. Given the three sides a, b, and c and the semi perimeter s as (a+b+c)/2, the area is square root of (s * (s-a) * (s-b) * (s-c)). So, I wrote the python code:
s = lambda a, b, c : (a + b + c)/2 #Line 1
area_tri = lambda a, b, c : (s(a,b,c) * (s(a,b,c)-a) * (s(a,b,c)-b) * \
(s(a,b,c)*c)) ** 0.5
area_tri(1, 2, 3)
The statement computing area_tri has to compute s(a, b, c) four times. So, I thought if I could write something like:
semi = s
after Line 1 and replace every occurrence of s(a,b,c) with semi in the area_tri computation statement. But, it would produce an error that a, b and c are unknown symbols. Is there an error-free alternative?
Solution 1:[1]
After python3.8, you can use walrus operator:=:
area_tri = lambda a, b, c: ((semi := s(a, b, c)) * (semi - a) * (semi - b) * (semi - c)) ** 0.5
For earlier versions, the best way is to define a function:
def area_tri(a, b, c):
semi = s(a, b, c)
return (semi * (semi - a) * (semi - b) * (semi - c)) ** 0.5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mechanic Pig |
