python - 尝试在圆形数组中实现一个可以顺时针和逆时针方向移动的指针
问题描述
由于这个问题,我在编码面试中失败了。有人可以帮我解决这个问题吗?
这是我的代码(Python):
import string
alphabet = string.ascii_lowercase # String 'abcdefghijklmnopqrstuvwxyz'
current_position = 0 # Letter 'A', the first item in our alphabet list
distances = []
word = 'Croves'.lower()
for letter in word:
destination = alphabet.index(letter) # Index of the letter in the alphabet array where the pointer should move
distance_clockwise = abs(destination - current_position)
distance_counter = abs(len(alphabet) - destination + current_position)
distance = distance_counter if distance_clockwise > distance_counter else distance_clockwise
distances.append(distance) # No of movements from current position to destination
current_position = destination # Repositioning the pointer
print(letter, distance) # Debuging...
print(sum(distances))
根据我的测试用例,字符串 'Croves' 应该具有以下距离:
- 从 A(指针初始位置)到 C(第一个字母),2 个动作
- 从C到R,11个动作
- 从 R 到 O,3 个动作
- 从O到V,7个动作
- 从V到E,9个动作
- 从 E 到 S,12 个动作
- 总动作数应为 44
但我的代码输出是:
- 从 A(指针初始位置)到 C(第一个字母),2 个动作
- 从C到R,11个动作
- 从 R 到 O,3 个动作
- 从O到V,7个动作
- 从 V 到 E,17 个动作
- 从 E 到 S,12 个动作
- 动作总数为52
当指针需要穿过字母“A”时存在一个错误,我不知道如何解决它。
谢谢!
解决方案
您可以计算distance_counter
为26-distance_clockwise
,这可以解决问题。
我还提出了这个带有列表理解的解决方案:
import string
alphabet = string.ascii_lowercase # String 'abcdefghijklmnopqrstuvwxyz'
word = 'Croves'.lower()
distances = {l: min(abs(alphabet.index(l) - alphabet.index(c)), 26 - abs(alphabet.index(l) - alphabet.index(c))) for l, c in zip(word, 'a' + word[:-1])}
print(distances)
print(sum(distances.values()))
输出:
{'r': 11, 'v': 7, 'o': 3, 'c': 2, 's': 12, 'e': 9}
44
如果你想要相同的输出,你可以使用:
import string
import collections
alphabet = string.ascii_lowercase # String 'abcdefghijklmnopqrstuvwxyz'
word = 'Croves'.lower()
distances = collections.OrderedDict((l, (min(abs(alphabet.index(l) - alphabet.index(c)), 26 - abs(alphabet.index(l) - alphabet.index(c))))) for l, c in zip(word, 'a' + word[:-1]))
for k, v in distances.items():
print(k, v)
print(sum(distances.values()))
输出:
c 2
r 11
o 3
v 7
e 9
s 12
44
推荐阅读
- wsh - 如何停止失控的 wscript 命令?
- javascript - 调试器表明它不是函数
- webrtc - 为什么有 WebRTC 时我们需要 crossbar.io (WAMP)?
- powershell - 是否可以阻止 PowerShell 模块在低于 Windows 8 的系统上运行?
- python - 我可以将多个 keras 神经网络模型保存/加载到一个 .h5 文件中吗?
- sql - Oracle SQL Developer 中日期格式的正确语法是什么
- python - 如何从单元测试跟踪在 Python shell 中运行的脚本的代码覆盖率?
- filter - 如何过滤组中的最小不同值?
- ios - AudioKit/DSP:了解磁盘上与内存中未压缩音频大小之间的差异
- excel - Scala不读取Excel文件