如何在代码中转换速度?

时间:2015-12-10 12:58:51

标签: python python-3.x converter

我的任务是创建一个程序来检测外来超速的车牌号码。为此,必须创建道路的一部分,经过的时间等。代码的问题不在于速度有多么不现实,而是我最近从老师那里发现速度应该是英里/小时,而不是米每秒

import re

# DATA
distance = 0.06 # Distance between the Camera A and B; 0.06 = 600 metres
speed_limit = 20 # (meters per second)

number_plates = ["DV61 GGB",      #UK
                 "D31 EG 2A",     #F
                 "5314 10A02",    #F
                 "24TEG 5063",    #F
                 "TR09 TRE",      #UK
                 "524 WAL 75",    #F
                 "TR44 VCZ",      #UK
                 "FR52 SWD",      #UK
                 "100 GBS 12",    #F
                 "HG55 BPO"       #UK
                 ]

enter = [7.12,7.17,7.22,7.12,7.23,7.41,7.18,7.25,7.11,7.38]
leave = [7.56,7.39,7.49,7.56,7.45,7.57,7.22,7.31,7.59,7.47]

# Find the non-UK plates
pattern = "(?![A-Z]{2}\d{2}\s+[A-Z]{3}$)"
foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))

# Calculations for speed
elapsed = [(l - e)/100 for l, e in zip(leave, enter)]
speed = [distance/t for t in converted_elapsed]

# Dictionary for foreign speeders + 2 conditions
foreign_speeders = {plate: speed 
                    for plate, speed in zip(number_plates, speed)
                    if (plate in foreign_numbers) and (speed > speed_limit)}

print("10 cars have passed Camera A, then Camera B\nSpeed limit is 20 meters per second.\n")

# Write foreign speeders to file
for plate, speed in foreign_speeders.items():

    speeders_data = open("speeders.txt","w") # Opens file with name of "speeders.txt"
    speeders_data.write(
        "{0:>13s} is foreign and is speeding at{1:5.1f} mps, and has an excess speed of {2:3.1f} mps.".format(plate, speed, speed-speed_limit))
    speeders_data = open("speeders.txt","r")
    print(speeders_data.read())
    speeders_data.close()

我想知道,重写所有速度变量会更简单,例如speed_limitelapsed&转换后的表格中speed的公式,或者在代码中间转换速度?

无论哪种解决方案更合适,我该怎么做?

2 个答案:

答案 0 :(得分:1)

首先,你肯定需要一个可以转换单位的功能,例如: mps_to_mph正如@mirosval建议的那样。

但是,我建议你应该在某些时候让这个单位变得更加明显。 最简单的解决方案是使用变量名称:speed_mps = 78.7speed_mph = mps_to_mph(speed_mps),否则当您再次阅读时,您将无法理解您的代码(好吧,您可能永远不会阅读 this 代码,但至少你的老师会......并且你写的每个代码都应该很容易理解而不需要额外的解释。)

在一个更复杂的应用程序中,有许多这样的计算,你可能想要一个能记住单位并知道如何转换值的类,这样你就可以做到这样的事情:

speed = Speed(78.8, 'm/s')
if speed > Speed(60, 'mph'):
    # something

答案 1 :(得分:0)

您可以编写如下函数:

def mps_to_mph(mps):
    return 2.23694 * mps

然后在你的for循环中使用它:

speed = map(mps_to_mph, speed)
speed_limit = mps_to_mph(speed_limit)

您可以将计算和阈值保留为每秒米数,并仅转换为显示。