GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Math/calculate_area_of_polygon.py at master · BiKodes/coding-problems Expand file tree/ Copy pathcalculate_area_of_polygon.pyMore file actions 41 lines (30 loc) · 1.05 KB / Copy pathcalculate_area_of_polygon.pyFile metadata and controls41 lines (30 loc) · 1.05 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 ''' Calculate Area of Polygon Given ordered coordinates of a polygon with n vertices. Find area of the polygon. Here ordered mean that the coordinates are given either in clockwise manner or anticlockwise from first vertex to last. Input: [(0, 0), (3, 0), (3, 2), (0, 2)] Output: 6.0 Output explanation: The polygon is a 3x2 rectangle parallel with the X axis. The area is 6 (3*2). ========================================= Use Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula). abs( 1/2 ((X1Y2 + X2Y3 + ... + Xn-1Yn + XnY1) - (X2Y1 + X3Y2 + ... + XnYn-1 + X1Yn)) ) Time Complexity: O(N) Space Complexity: O(1) ''' ############ # Solution # ############ def calculate_area_of_polygon(polygon): n = len(polygon) prev = polygon[-1] area = 0 for curr in polygon: area += (prev[0] + curr[0]) * (prev[1] - curr[1]) prev = curr return abs(area / 2) # return absolute value ########### # Testing # ########### # Test 1 # Correct result => 6.0 print(calculate_area_of_polygon([(0, 0), (3, 0), (3, 2), (0, 2)])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |