hkus10 - 1 year ago 79
Python Question

# How to write a function which calculate the midpoint between 2 points in python?

``````def midpoint(p1, p2):
"""
PRE: p1 and p2 are Point objects (from the graphics module)
POST: a new Point equidistant from and co-linear with p1 and p2
is computed and returned
``````

Write a function midpoint with the following specification

What graphics module are you using? (pypi contains several dozen, none named 'graphics') What does the interface of a Point look like?

If Point has named attributes (like p.x, p.y, etc) you could do something like

``````def midpoint(p1, p2):
return Point((p1.x+p2.x)/2, (p1.y+p2.y)/2)
``````

If Point can be accessed as a list (like p[0], p[1], etc) you could instead do

``````def midpoint(p1, p2):
return Point((p1[0]+p2[0])/2, (p1[1]+p2[1])/2)
``````

If Point has Point addition and scalar division or multiplication overloaded, you could do

``````def midpoint(p1, p2):
return (p1+p2)/2     # or *0.5
``````

(although strictly speaking adding two Points should be meaningless, and subtracting one point from another should give you a Vector - thus

``````def midpoint(p1, p2):
return p1 + (p2-p1)/2     # or *0.5
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download