【问题标题】:(cipher program) Index out of range error(密码程序)索引超出范围错误
【发布时间】:2022-01-04 17:58:16
【问题描述】:

我正在根据 NDev 的 YT 视频制作一个密码程序,出现的错误是索引超出范围,我是 python 新手,这是我的代码:

charToBin = {
  "a":1,
  "b":10,
  "c":11,
  "d":100,
  "e":101,
  "f":110,
  "g":111,
  "h":1000
}
binToWrd = {
  1:"Intel",
  10:"Info",
  11:"Indipendent",
  101:"Imposibble",
  100:"Info-stolen",
  110:"Indian-Ogres",
  111:"Initially",
  1000:"Infant-Orphan-Ogre-Ogle"
}

endTxt = " "
cipher = " "

def txtToBin():
  global endTxt
  txt = input(":")
  txtArray = txt.split(" ")
  for x in range(len(txt)):
    endTxt += str(charToBin[txtArray[x]])+" "
  print(endTxt)

def binToCip():
  global cipher
  codeTxtArr = endTxt.split(" ")
  for x1 in codeTxtArr:
    for x2 in binToWrd:
      cipher += x1.replace(str(x2), binToWrd[x2])
  print(cipher)

txtToBin()
binToCip()

我在输入中输入 b a d 时返回的错误:

Traceback (most recent call last):
  File "main.py", line 41, in <module>
    txtToBin()
  File "main.py", line 30, in txtToBin
    endTxt += str(charToBin[txtArray[x]])+" "
IndexError: list index out of range

【问题讨论】:

  • 假设您输入了“b a d”。它的长度为 5。您将其拆分为长度为 3 的 txtArray,但您的 for 循环使用 len(txt),所以它仍然是 5。您不需要任何拆分的东西。我会在下面告诉你。
  • 好的,我会检查的

标签: python arrays encryption indexing


【解决方案1】:

好的,我在这里更改了几处。

首先,全局变量是邪恶的。您的功能不需要它们。你的函数应该有一个输入和一个输出。输入作为参数输入,输出作为返回输出。

其次,在这样的实用函数中,不要进行 I/O。让调用者弄清楚如何获取和呈现数据,然后让函数完成工作。这意味着不要在函数中执行print。相反,返回值并让调用者执行print。这样,您可以在其他地方重用此功能。简单、可重复使用的功能是提高生产力的关键。

第三,任何时候你写for x in range(len(y)):,几乎总是有更好的写法,通常是for x in y:。 Python 非常乐意将每个元素一个一个地交付给您。您不必进行索引。

我不确定为什么您将编码作为整数值在这里,因为您需要将它们转换为字符串以进行打印。您不妨将编码值设为字符串:"1", "10", "11" 等。您确实明白这些不是二进制数,对吧?那是一、十、十一、一百等?

您的两个函数都可以使用列表推导式转换为单行代码。我会在之后展示。

charToBin = {
  "a":1,
  "b":10,
  "c":11,
  "d":100,
  "e":101,
  "f":110,
  "g":111,
  "h":1000
}
binToWrd = {
  1:"Intel",
  10:"Info",
  11:"Indipendent",
  101:"Imposibble",
  100:"Info-stolen",
  110:"Indian-Ogres",
  111:"Initially",
  1000:"Infant-Orphan-Ogre-Ogle"
}

def txtToBin(txt):
    endTxt = []
    for c in txt.split():
        endTxt.append( str(charToBin[c]) )
    return ' '.join(endTxt)

def binToCip(code):
    cipher = []
    for x1 in code.split():
        cipher.append( binToWrd[int(x1)])
    return ' '.join(cipher)

endTxt = txtToBin(input(":"))
print(endTxt)
cipher = binToCip(endTxt)
print(cipher)

或者:

def txtToBin(txt):
    return ' '.join( str(charToBin[c]) for c in txt.split() )

def binToClip(code):
    return ' '.join( binToWord[int(c)] for c in code.split() )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多