代码之家  ›  专栏  ›  技术社区  ›  Tim Anderson

使用数组时无法解决“列表索引超出范围”错误

  •  1
  • Tim Anderson  · 技术社区  · 6 年前

    我正在尝试编写一个“现金箱”式密码破解程序,它可以旋转拨号盘,每个拨号盘上都有每个字符,直到找到答案。我对Python(以及一般的编码)相当陌生,但在很多帮助下,我能够用数字和字母(大写和无头)完成这项工作

    现在我正在尝试构建它,以便只检查数字和无头字母,而不是大写字母。以下是我得到的:

    def method_2(num_pass_wheels):
        result = False
        still_searching = True
        print()
        print("Using method 2 and searching with " + str(num_pass_wheels) + " characters.")
        wheel = " abcdefghijklmnopqrstuvwxyz0123456789"
    # set all of the wheels to the first position
        pass_wheel_array = array('i', [1, 0, 0, 0, 0, 0, 0, 0, 0])
    
        while still_searching:
            ourguess_pass = ""
            for i in range(0, num_pass_wheels):  # once for each wheel
                if pass_wheel_array[i] > 0:
                    ourguess_pass = wheel[pass_wheel_array[i]] + 
        ourguess_pass
            print ("trying [" + ourguess_pass + "]")
            if (check_pass(which_password, ourguess_pass)):
                print ("Success! Password  " + str(which_password) + " is " + ourguess_pass)
                still_searching = False   # we can stop now - we found it!
                result = True
    
     # spin the rightmost wheel and if it changes, spin the next one over and so on
            carry = 1
            for i in range(0, num_pass_wheels):  # once for each wheel
                pass_wheel_array[i] = pass_wheel_array[i] + carry
                carry = 0
                if pass_wheel_array[i] > 62:
                    pass_wheel_array[i] = 1
                    carry = 1
                    if i == (num_pass_wheels - 1):
                        still_searching = False
    
        return result
    

    错误消息指向:

    line 341, in <module>
        foundit = method_2(8)
    
    line 188, in method_2
        ourguess_pass = wheel[pass_wheel_array[i]] + ourguess_pass
    

    并抛出错误:

    IndexError: string index out of range
    

    我知道这跟我把“轮子”上的大写字母去掉有关,但我不知道如何去修复它。有什么帮助吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   wwii    6 年前

    硬编码 此处的长度检查限制:

            if pass_wheel_array[i] > 62: <-----
                pass_wheel_array[i] = 1
                carry = 1
    

    wheel 您发布的版本中只有36项。而不是使用 62 使用 len(wheel) .

    但由于数组索引是基于零的,您可能希望将其更改为

    if pass_wheel_array[i] > len(wheel) - 1:
    #or
    if pass_wheel_array[i] == len(wheel):