加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何编写一个函数来计算python中2点之间的中点?

发布时间:2020-12-20 13:00:51 所属栏目: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 p2is computed and returned 使用以下规范编写函数中点 解决方法 你使用什么图形模块? (pypi包含几十
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

使用以下规范编写函数中点

解决方法

你使用什么图形模块? (pypi包含几十个,没有一个名为’graphics’)Point的界面是什么样的?

如果Point已命名属性(如p.x,p.y等),您可以执行类似的操作

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

如果Point可以作为列表访问(如p [0],p [1]等),您可以改为

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

如果Point有点加法和标量除法或乘法重载,你可以这样做

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

(虽然严格来说,添加两个点应该没有意义,从另一个点减去一个点应该给你一个Vector – 因此

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读