如何将带空格的多个整数作为输入?

时间:2014-04-01 20:32:33

标签: python input integer

我必须采用由空格分隔的3个整数输入,例如。 3 4 5并从下一个中减去每个后续的一个。例如,4从4和4从5,然后添加结果。

有谁知道我会如何做到这一点,这里有一个问题我被问到你是否有兴趣:

Lineland是一个伟大的无限国家,沿着Ox轴。 Lineland有三个城市。城市A具有坐标xA,城市B具有坐标xB,城市C具有坐标xC。

旅行者Chloe住在A市。她想先按顺序前往B市,然后前往C市。但为了准备这次旅行,她现在需要提前离开的距离。

给定坐标xA,xB,xC,找到Chloe从城市A到城市B然后从城市B到城市C的距离。

输入 第一行包含三个以空格分隔的整数:xA,xB,xC(1≤xA,xB,xC≤100) - 城市A,B和C的坐标。

输出 打印一个整数 - 克洛伊从城市A到城市B然后从城市B到城市C必须经过的距离。

1 个答案:

答案 0 :(得分:1)

您的输入将以字符串形式显示,您可以使用str.split(sep)

拆分字符串
def distance(start,end):
    # I'll leave implementation of this to you
    # use the distance formula if you want to impress your teacher
    # but since Lineland lies entirely upon one axis, this shouldn't
    # be very hard for you :)

# if in_ is your input
xA, xB, xC = in_.split(" ")
# you could also do = map(int,in_.split(" ")) to avoid the int() calls below
# but frankly I think using the map function is a lesson better suited for
# later.
chloes_travel_time = distance(int(xA),int(xB)) + distance(int(xB),int(xC))

print(chloes_travel_time)