您好我是python的新手,
我试图找到不同点的距离。 例如:
每扇门之间的距离约为2.5英尺。因此门1和门2之间的距离是2.5英尺。我将如何在门词典中寻找两个不同的距离。或者我应该使用别的东西。
d = {"door 1" : 2.5,"door 2" :2.5 , "door 3" : 2.5, "door 4": 2.5}
x = raw_input()
y = raw_input()
tol = 0
if x not in list and y not in list:
print 'not a door'
else:
if x in list and y in list:
tol = (list[x]) + (list[y])
print tol
答案 0 :(得分:0)
用一个功能做到这一点。这是一个样本:
# FUNTION
def calDoorDistance(doorX, doorY):
# Distance between doors
distance = 2.5
# Splits the input string by spaces
# gets the last portion of it
# and converts it to integers
door_01_value = int(doorX.split(' ')[-1])
door_02_value = int(doorY.split(' ')[-1])
# Calculates the amount of doors in between
# and multiplies it by the distance.
# abs makes sure that the result is always positive
return abs(door_01_value - door_02_value) * distance
x = raw_input() # Converts the input value into an integer
y = raw_input() # Converts the input value into an integer
print calDoorDistance(x, y)
答案 1 :(得分:0)
您可以尝试以下方法。这假设您的所有门都是间隔2.5并且是直线的:
valid_doors = {"door 1" : 1.0, "door 2" : 2.0, "door 3" : 3.0, "door 4": 4.0}
x = raw_input("Enter first door: ")
y = raw_input("Enter second door: ")
if x in valid_doors and y in valid_doors:
print abs(valid_doors[x] - valid_doors[y]) * 2.5
else:
print 'not a door'
这会给你以下类型的输出:
Enter first door: door 1
Enter second door: door 2
2.5
Enter first door: door 4
Enter second door: door 2
5.0
或者,稍微多一些Pythonic,您可以了解如下处理异常处理:
valid_doors = {"door 1" : 1.0, "door 2" : 2.0, "door 3" : 3.0, "door 4": 4.0}
x = raw_input("Enter first door: ")
y = raw_input("Enter second door: ")
try:
print abs(valid_doors[x] - valid_doors[y]) * 2.5
except KeyError:
print 'not a door'