python - 在 python 中移动 n 个字母

标签 python algorithm

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

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/

相关文章:

python - 如何在 Python 单元测试中模拟一个类?

python - 添加到数据库时时间值略有偏差

arrays - 按时间戳对对象排序,然后对依赖项进行分组

c - 五子棋:限时搜索

algorithm - 数组中数字的均匀分布

algorithm - 如何确定(子集的笛卡尔积并集)是否等于(完整集的笛卡尔积)

python matplotlib : retrieving colors used in contour plot

python - 提高我的 pyspark 数据过滤程序的性能

全新安装后出现 Python-pip 错误

algorithm - 铁路轨道的排列(堆栈实现)