gpt4 book ai didi

python - 在 python 中移动 n 个字母

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:44 24 4
gpt4 key购买 nike

我正在尝试解决一个大胆的编程问题,如下所示:

Write a procedure, shift_n_letters which takes as its input a lowercase letter, a-z, and an integer n, and returns the letter n steps in the alphabet after it. Note that 'a' follows 'z', and that n can be positive, negative or zero.

代码:

def shift_n_letters(letter, n):
result = chr(ord(letter) + n)
if ord(result) > 122:
return chr(96+ ord(result) - 122)
return result


print shift_n_letters('s', 1)
#>>> t
print shift_n_letters('s', 2)
#>>> u
print shift_n_letters('s', 10)
#>>> c
print shift_n_letters('a', -1)
#>>> z

我得到 t, u , c 和 ` 作为结果。请有人帮助我哪里出错了。谢谢。

最佳答案

只需将n取字母长度的模数即可:

def shift_n_letters(letter, n):
n_ = n % 26
result = chr(ord(letter) + n_)
if ord(result) > 122:
result = chr(ord(result) - 26)
return result

它搞砸了,因为(我认为)它使用 unicode 系统中的字母顺序,显然 ` 出现在 a 之前。

更新

我想出了一个更简单的算法。

def shift_n_letters(letter, n):
return chr((ord(letter) - 97 + n % 26) % 26 + 97)

算法

  1. ord(letter) - 97 -- 通过减去 a 的 unicode 顺序,将 letter 置于 0-25 范围内
  2. + n % 26 -- 添加偏移,针对 za
  3. 之间的周期边界进行调整
  4. % 26 -- 取模 26 以防移位导致订单离开范围 0-25
  5. + 97 -- 添加a的unicode顺序(之前减去)
  6. chr(...) -- 返回我们刚刚计算的 unicode 顺序索引的字符

关于python - 在 python 中移动 n 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com