2

我正在编写一个需要找到最近的交换机的电缆映射脚本。因此,如果配线架位于机架 08AB 中,并且机架 08AC 和 08AD 中有开关,我需要它来选择最近的(08AC)。问题是机架编号顺序。前两位数字将始终相同 (08),并且字母递增。但是他们先增加 AZ,然后再增加 AA-AZ。因此,如果面板在机架 08Z 中,则 08AA 比 08X 更接近。

我通过将字母转换为数字并查看哪个最接近,但它看起来很笨重,我想知道是否有更好的方法:

###CLOSEST SWITCH IS IN 08AA
full_panel_location = '08Z'
full_switches_location = ['08X', '08AA']
switches_checksum = []


###REMOVE DIGITS AND CONVERT LETTERS TO CHECKSUM
panel_letters = ''.join([i for i in full_panel_location if not i.isdigit()])
panel_checksum = int(reduce(lambda x,y:x+y, map(ord, panel_letters)))
if panel_checksum > 100:
    panel_checksum -= 39

for switch in full_switches_location:
    switch_letters = ''.join([i for i in switch if not i.isdigit()])
    switch_checksum = int(reduce(lambda x,y:x+y, map(ord, switch_letters)))
    if switch_checksum > 100:
        switch_checksum -= 39
    switches_checksum.append(switch_checksum)

###FIND CLOSEST CHECKSUM/INDEX/SWITCH
closest_switch_checksum = min(switches_checksum, key=lambda x: abs(x - panel_checksum))
closest_switch_index = switches_checksum.index(closest_switch_checksum)

closest_switch = full_switches_location[closest_switch_index]


这提供了最接近的开关是 08AA,这正是我想要的。我的问题是,有没有更好的方法来做到这一点?

4

1 回答 1

1

这基本上是一个 base 26 转换问题。以相反的顺序遍历位置的每个字母,并将其序数差加上字母A乘以 26 的字母偏移的幂以获得校验和,您可以使用它计算到参考位置的距离作为min函数的键:

def checksum(x):
    s = 0
    for i, c in enumerate(reversed(x)):
        s += (ord(c) - ord('A') + 1) * 26 ** i
    return s

full_panel_location = '08Z'
full_switches_location = ['08X', '08AA']
panel_checksum = checksum(full_panel_location[2:])
print(min(full_switches_location, key=lambda i: abs(checksum(i[2:]) - panel_checksum)))

这输出:

08AA
于 2019-04-05T13:03:56.390 回答