Python 解密函数未产生预期输出

问题描述 投票:0回答:1

我正在Python中实现密码解密函数,但我无法获得预期的输出。该函数应该根据字符的索引对字符应用交替旋转值,并通过用

0
s 包围它们来处理元音。

这是我的代码:

def decrypt_password(password: str) -> str:
    rot7, rot9 = 7, 9  # Rotation values
    vowels = 'AEIOUaeiou'  # Vowels to check
    decrypted = []  # List to hold decrypted characters

    for index, char in enumerate(password):
        if char in vowels:
            rotation_key = rot9 if index % 2 == 1 else rot7  # Use 9 for odd indices
            decrypted.append('0')  # Add '0' before the vowel
        else:
            rotation_key = rot7 if index % 2 == 0 else rot9  # Use 7 for even indices

        if 33 <= ord(char) <= 126:  # Check if character is within the allowed ASCII range
            decrypted_char = chr((ord(char) - rotation_key - 33) % 94 + 33)  # Wrap around
            decrypted.append(decrypted_char)  # Add decrypted character to the list
        else:
            decrypted.append(char)  # Append unchanged if out of range

        if char in vowels:
            decrypted.append('0')  # Add '0' after the vowel

    return ''.join(decrypted)  # Join the list into a string and return
print(decrypt_password("bAnanASplit")) 

Expected Output:
"i0J0u0j0u0J0Zys0r0{".
Actual Output:
"0b0'C'0n0'c'0n0'C'Spl'k't".

调试工作:

我尝试添加打印语句来跟踪字符转换,但我仍然得到不正确的结果。

环境:3.12。 任何有关可能出现问题的帮助将不胜感激!

python string algorithm encryption
1个回答
0
投票

您的问题缺少详细信息,但我想正确的代码应该是这样的:

def decrypt_password(password: str) -> str:
    rot7, rot9 = 7, 9  # Rotation values
    decrypted = []  # List to hold decrypted characters
    for index, char in enumerate(password):
        rotation_key = rot9 if index % 2 == 1 else rot7  # Use 9 for odd indices
        if 33 <= ord(char) <= 126:  # Check if character is within the allowed ASCII range
            decrypted_char = chr(ord(char) + rotation_key)  # Wrap around
            decrypted.append(decrypted_char)  # Add decrypted character to the list
        else:
            decrypted.append(char)  # Append unchanged if out of range

    return '0'.join(decrypted)  # Join the list into a string and return


print(decrypt_password('bAnanASplit'))

输出:

i0J0u0j0u0J0Z0y0s0r0{

输出与预期相同。

我的编辑:

  1. 你应该加上
    rotation_key
    而不是减号,所以它来了
    decrypted_char = chr(ord(char) + rotation_key)
  2. 它与元音无关,所以我删除了所有关于元音的代码。
  3. 我们应该为每个解密的密码插入 0,所以我们有
    '0'.join(decrypted)

如果您有任何疑问,请随时在这里发表评论。

© www.soinside.com 2019 - 2024. All rights reserved.