Python list index out of range testing all possible permutations

Question:

so the following code is meant to test every possible combination of characters untill it finds the one you typed, however at one point it says list index out of range, how do I fix this?

password = input()
chars = "abcdefghijklmnopqrstuvwxyz1234567890"
guess = ""
chars = list(chars)
chararray = []
for l in password:
    chararray.append(0)
while guess != password:
    guess = ""
    for element in chararray:
        guess = guess + chars[element]
    chararray[len(chararray) - 1] += 1
    i = 0
    while i < len(chararray) - 1:
        if i + 1 > len(chars):
            chars[i + 1] = 0
            chars[i] += 1
        i += 1
    print(guess)

the index out of range part is in the part that says
guess = guess + chars[element]

Asked By: ProfMonkey07

||

Answers:

I fixed it

chars = "abcdefghijklmnopqrstuvwxyz1234567890"
guess = ""
chars = list(chars)
chararray = []
for l in password:
    chararray.append(0)
while guess != password:
    guess = ""
    for element in chararray:
        print(element)
        guess = guess + chars[element]
    chararray[len(chararray) - 1] += 1
    i = 0
    while i < len(chararray) - 1:
        if chararray[i + 1] >= len(chars) - 1:
            chararray[i + 1] = 0
            chararray[i] += 1
        i += 1
    print(guess)```
Answered By: ProfMonkey07

You are only incrementing the last element of chararray every loop, access elements of chars[], which is fixed to 36 elements. For a test input of hello, your program will work like this:

loop 1:
chararray = [0,0,0,0,0]
loop 2:
chararray = [0,0,0,0,1]
loop 3:
chararray = [0,0,0,0,2]

If your program guesses incorrectly 36 times, it will increment the last element of chars 36 times as well, so on the 37th try it will be chararray = [0, 0, ..., 36], and since the inner loop runs for all elements of chararray, it will eventually try to execute guess = guess + chars[36], which will fail because chars only has 36 elements.

Answered By: alielbashir