Shoelace formula for polygonal area: Difference between revisions
Content added Content deleted
(→=={{header|PowerBASIC}}==: added PowerBASIC code) |
(→{{header|Python}}: Added a variant in terms of reduce and cycle) |
||
Line 910: | Line 910: | ||
30.0 |
30.0 |
||
>>> </lang> |
>>> </lang> |
||
Or, defined in terms of '''reduce''' and '''cycle''': |
|||
{{Trans|Haskell}} |
|||
{{Works with|Python|3}} |
|||
<lang python>'''Shoelace formula for polygonal area''' |
|||
from itertools import (cycle, islice) |
|||
from functools import (reduce) |
|||
# shoelaceArea :: [(Float, Float)] -> Float |
|||
def shoelaceArea(xys): |
|||
'''Area of polygon with vertices |
|||
at (x, y) points in xys.''' |
|||
def go(a, tpl): |
|||
(x, y), (dx, dy) = tpl |
|||
l, r = a |
|||
return (l + x * dy, r + dx * y) |
|||
(nl, nr) = reduce( |
|||
go, |
|||
zip(xys, tail(cycle(xys))), |
|||
(0, 0) |
|||
) |
|||
return abs(nl - nr) / 2 |
|||
# TEST ------------------------------------------------- |
|||
# main :: IO() |
|||
def main(): |
|||
'''Test''' |
|||
print( |
|||
shoelaceArea( |
|||
[(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)] |
|||
) |
|||
) |
|||
# GENERIC ------------------------------------------------- |
|||
# tail :: [a] -> [a] |
|||
# tail :: Gen [a] -> [a] |
|||
def tail(xs): |
|||
'''The elements following the head of a |
|||
(non-empty) list or generator stream.''' |
|||
if isinstance(xs, list): |
|||
return xs[1:] |
|||
else: |
|||
list(islice(xs, 1)) # First item dropped. |
|||
return xs |
|||
if __name__ == '__main__': |
|||
main()</lang> |
|||
{{Out}} |
|||
<pre>30.0</pre> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |