jmu-python-组合数据类型-1.计算坐标点欧氏距离

读取若干个点,每个点放入元组。并将所有点的点信息、点的类型、点与原点的距离打印出来。

函数接口定义:

 

readPoint() #从一行以,分隔的数中读取坐标,放入元组并返回 distance(point) #计算point与原点的距离并返回,要math库中的函数

裁判测试程序样例:

 

/* 请在这里填写答案 */ n = int(input()) for i in range(n): p = readPoint() print('Point = {}, type = {}, distance = {:.3f}'.format(p,type(p),distance(p)))

输入格式:

输入n,代表底下要输入n行点坐标。坐标全部为整数。
点坐标x,y,z以,分隔。坐标全部为整数。

注意:坐标以,分隔,相应位置可能无字符或者包含多个空格字符,读入时按照0进行处理。

输出格式:

见输出样例

输入样例:

5
1,1,1
,,
2,,1
3,1,3
5,,

输出样例:

Point = (1, 1, 1), type = <class 'tuple'>, distance = 1.732
Point = (0, 0, 0), type = <class 'tuple'>, distance = 0.000
Point = (2, 0, 1), type = <class 'tuple'>, distance = 2.236
Point = (3, 1, 3), type = <class 'tuple'>, distance = 4.359
Point = (5, 0, 0), type = <class 'tuple'>, distance = 5.000
import math

def readPoint():
    # 从用户输入中读取点的坐标,假设用户输入格式为 x,y,z
    coord = input().split(',')
    
    # 尝试将坐标转换为整数类型,如果转换失败(比如用户输入非数字字符),则将该位置的值设为0
    for i in range(3):
        try:
            coord[i] = int(coord[i])
        except:
            coord[i] = 0
    
    # 将转换后的坐标列表转换为元组
    coord = tuple(coord)
    
    return coord

def distance(point):
    # 计算给定点到原点的欧几里得距离
    s = math.sqrt(pow(point[0], 2) + pow(point[2], 2) + pow(point[1], 2))
    
    return s
  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值