python - 键盘拼字神秘减法1
问题描述
此代码生成“路径”以拼出特定宽度的字母表中的单词。例如,宽度为 4,字母表是这样的
a b c d
e f g h
i j k l
m n o p
q r s t
u v w x
y z
并且拼写"dog"
生成的路径(从 开始a
)是
选择字符的R R R ! L D D D ! U U !
位置。!
宽度为 3 时,会生成下面的字母,并且拼写"dog"
有路径
D ! D D D R R ! L L U U !
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
我正在查看某人关于如何解决此问题的解决方案,但我无法弄清楚为什么会出现负 1 ord(previous_char) - 1
以及ord(word[idx]) - 1
. 这对我来说似乎有点神秘。我认为它必须以某种方式进入坐标系。减 1 在开始路径时有很大的不同,a
但我不确定为什么。
import math
def walk_keyboard(width, word):
res = []
for idx in range(len(word)):
# find the x and y coordinates of the previous character
# if there was no previous letter, use 'a'
previous_char = word[idx - 1] if idx > 0 else 'a'
previous_ord = ord(previous_char) - 1
previous_x = previous_ord % width
previous_y = math.floor(previous_ord / width)
# find the x and y coordinates of the current character
current_ord = ord(word[idx]) - 1
current_x = current_ord % width
current_y = math.floor(current_ord / width)
if current_y < previous_y:
res += ['U'] * int(previous_y - current_y)
if current_x < previous_x:
res += ['L'] * int(previous_x - current_x)
if current_y > previous_y:
res += ['D'] * int(current_y - previous_y)
if current_x > previous_x:
res += ['R'] * int(current_x - previous_x)
res.append('!')
return ' '.join(res)
print(walk_keyboard(4, 'dog'))
解决方案
我认为这- 1
是脚本工作的一个技巧。
在我看来,- 1
用于匹配第一列 (0) 的索引和% width
.
它适用于- 97
( ord('a') = 97
) 但不适用于宽度 5。基于 Unicode ( ord
) 的坐标对于这个问题有点奇怪,您应该有一个自定义函数来获取字母表中字母的索引。那么你就不会有这种黑客行为了。
就像是:
def get_index_in_alphabet(letter):
alphabet = 'abcdefhijklmnopqrstuvwxyz'
return alphabet.index(letter)
编辑:
此外,为了确保您的脚本真正工作,您可以进行单元测试。因为我不确定它目前是否适用于每个单词。
推荐阅读
- r - 将 R 中的人与 Loop 配对
- javascript - 如何在 JS 中使用来自两个不同 HTML 页面的变量
- html - 如何让 XSLT 发出尖括号?
- java - Java DCEVM - 为 Java 1.8.0.202 版本获取“无法获得 D:\Java8 的 dceverion”
- google-drive-api - 功能请求 - 新版本文件通知
- html - 我的输入应该是一个复选框,但呈现为一个文本输入框
- powershell - 如何在类方法中使用 Try-Catch-Finally 块?
- postgresql - 具有 PostgreSQL 本机(声明性)分区的 pg_partman
- python - 根据键获取嵌套 dic 中的特定 subdic
- python - 从 2 个数据帧计算一个特征