函数rot(rot,s),将整数rot和字符串s作为输入,并返回s的一个副本,该副本将s反转,然后移动

2024-10-03 23:28:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试为只包含大写字母、下划线和句点的字符串实现一个类似于Caesar密码的编码方案。使用字母顺序进行旋转: biao jijklmnopqrstufwxyz\。在

迄今为止,Mycode:

def rrot(rot, s):
    'returns reverse rotation by rot of s'
    res = ''
    for c in s:
        x = ord(c)
        res += chr(x + rot)
        copy = res[::-1]
    return copy

输出示例如下:

^{pr2}$

但是当运行时,它会在整个字母表中运行,包括符号{[/etc)。我可以正确地移动字母的数量,但是会得到不需要的符号。我的错误输出:

^{3}$

但这是正确的:

>>> rrot(1, 'ABCD')
'EDCB'

如何让它只遵循字符“ABCDEFGHIJKLMNOPQRSTUVWXYZ”的字母顺序?在


Tags: 字符串密码顺序字母符号res大写字母copy
1条回答
网友
1楼 · 发布于 2024-10-03 23:28:30

您的代码可以简单地修复:

def rrot(rot, s):
    'returns reverse rotation by rot of s'
    res = ''
    for c in s:
        x = ord(c)
        res += chr(x + rot)
        copy = res[::-1]
    return copy

您可以通过替换以下内容来修复它以使用其他字符顺序:

^{pr2}$

说:

    x = alphabet.index(c)
    res += alphabet[(x + rot) % len(alphabet)]

考虑:

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_.'

def rrot(rot, s):
    'returns reverse rotation by rot of s'
    res = ''
    for c in s:
        x = alphabet.index(c)
        res += alphabet[(x + rot) % len(alphabet)]
        copy = res[::-1]
    return copy

用那些不好的例子:

>>> rrot(3, 'YO_THERE.')
'1HUHKWbR\\'
>>> rrot(1, 'SNQZDRQDUDQ')
'REVERSE[ROT'

这些例子的结果如下:

>>> rrot(3, 'YO_THERE.')
'CHUHKWBR.'
>>> rrot(1, 'SNQZDRQDUDQ')
'REVERSE_ROT'

另一种方法是建立一个翻译表,如:

trans = dict(zip(alphabet, alphabet[rot:] + alphabet[:rot]))

一旦超出循环,然后使用:

    res += trans[c]

像这样:

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_.'

def rrot(rot, s):
    'returns reverse rotation by rot of s'
    trans = dict(zip(alphabet, alphabet[rot:] + alphabet[:rot]))
    res = ''
    for c in s:
        res += trans[c]
        copy = res[::-1]
    return copy

结果是一样的:

>>> rrot(3, 'YO_THERE.')
'CHUHKWBR.'
>>> rrot(1, 'SNQZDRQDUDQ')
'REVERSE_ROT'

相关问题 更多 >