Page - 128 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 128 -
Text of the Page - 128 -
128 5 SomeMorePythonEssentials
Filename:total_volume_boxes.py.
Exercise5.6:AreaofaPolygon
One of the most important mathematical problems through all times has been to
find the area of a polygon, especially because real estate areas often had the shape
of polygons, and it was necessary to pay tax for the area. We have a polygon as
depictedbelow.
The vertices (“corners”) of the polygon have coordinates (x1,y1), (x2,y2), . . .,
(xn,yn),numberedeitherinaclockwiseorcounterclockwisefashion.TheareaAof
thepolygoncanamazinglybecomputedbyjustknowingtheboundarycoordinates:
A= 1
2 ∣
∣(x1y2+x2y3+···+xn−1yn+xny1)−(y1x2+y2x3+···+yn−1xn+ynx1) ∣
∣ .
Writeafunctionpolyarea(x, y) that takestwocoordinatearrayswiththevertices
asargumentsandreturns thearea.
Test the function on a triangle, a quadrilateral, and a pentagon where you can
calculate the areabyalternativemethodsforcomparison.
Hint SincePythonlistsandarrayshave0as theirfirst index, it iswise torewrite the
mathematical formula in termsof vertexcoordinatesnumberedasx0,x1,.. .,xn−1
andy0,y1,.. .,yn−1.
Filename:polyarea.py.
Exercise5.7:CountOccurrencesofa String in aString
In the analysis of genesone encountersmanyproblemsettings involvingsearching
for certain combinations of letters in a long string. For example, we may have a
string like
gene = ’AGTCAATGGAATAGGCCAAGCGAATATTTGGGCTACCA’
We maytraverse this string, letterby letter, by the for loopfor letter in gene.
The length of the string is given by len(gene), so an alternative traversal over
an indexi isfor i in range(len(gene)).Letter numberi is reached through
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik