【问题标题】:Number to words decryption数词解密
【发布时间】:2020-05-24 06:38:05
【问题描述】:

给定以下代码:

list = [1, 0 ,3]

def decrypt(text, alphabet):
    decrypt_final = ""

    for j in alphabet:
        aindex = alphabet.index(j)
        for i in list:
            if aindex == i:
                decrypt_final = decrypt_final + str(j)

    print(decrypt_final)

decrypt("103", "abcde")

运行代码时,结果是"abd",这不是我想要的。我正在尝试根据"abcde" 的字母范围解密数字103,如果输入为"103",正确的结果应该是"bad"

我上面的代码试图做的是查看列表(列表中的数字来自另一个我没有包含以简化这一点的函数),如果列表编号与字母表的索引匹配,则输出字母表。不幸的是,输出顺序是错误的。

希望得到一些指导。

【问题讨论】:

  • 在你的函数中你不使用参数text
  • 你不想/不需要在这里循环alphabet。您想遍历text 中的每个字符,将其转换为数字,然后在alphabet 中索引该位置...

标签: python python-3.x string encryption


【解决方案1】:

我想以下应该可以工作

def decrypt(text, alphabet):
    decrypt_final = ""
    # convert text to list of indices
    str_to_int = [int(i) for i in text]
    for j in str_to_int:
        decrypt_final += alphabet[j]

    print(decrypt_final)

decrypt("103", "abcde")

您只需将文本 ("103") 转换为索引列表。

【讨论】:

  • 循环遍历text 以生成要循环遍历的列表似乎有点迂回。只需循环 text 并将当前字符转换为 int 即可。
  • @tripleee 是的,完全正确。我在一小时前发布了相同的答案,但不受欢迎,不知道为什么。
【解决方案2】:

你可以试试这个。

您可以通过索引提取所需的内容。您需要做的就是将字符串103 转换为整数。可以通过int(str_num) 将字符串数字转换为整数。现在一旦这些是整数,它们就是您要提取的字母字符串的索引。上面所有的步骤都可以浓缩成下面的代码。

'delimiter'.join(iterable) 用分隔符连接可迭代对象中的所有元素。

def decrypt(txt,alphabets):
      cipher_text=[alphabets[int(i)] for i in txt]
      return ''.join(cipher_text)

decrypt('103','abcde')
#'bad'

【讨论】:

  • 这对于初学者来说可能过于简洁了;或者你应该解释代码。 ipython I/O 格式掩盖了实际代码。
  • @tripleee 同意,我现在添加了解释。也许我应该为初学者写一个富有表现力的版本。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
相关资源
最近更新 更多