Home > Software engineering >  Python 3.x : I'm out of range
Python 3.x : I'm out of range

Time:01-03

I'm asking to have some help cause I believe I know why I'm out of range but I don't know out to solved it. Thanks you :D

#Import input.
from pathlib import Path
test = Path(r'C:\Users\Helphy\Desktop\Perso\GitHub\Advent_of_Code_2021\Day_3\Input.txt').read_text().split("\n")
#Defined some variable 
temp = []
finalnumtemp = []
finalnum = []
f_num = []
zero = 0
one = 0
for t in range(len(test)):
    for j in range(len(test)):
        temp = list(test[j])
        print(temp)
        finalnumtemp.append(temp[j])
        print(finalnumtemp)
     """for i in range(len(finalnumtemp)):
        if int(finalnumtemp[i]) == 0:
            zero  = 1
        else:
            one  = 1
    if zero > one:
        finalnum.append(0)
    else:
        finalnum.append(1)
    zero == 0
    one == 0
    finalnumtemp = []
print(finalnum)"""
    Input :
    00100
    11110
    10110
    10111
    10101
    01111
    00111
    11100
    10000
    11001
    00010
    01010
error: An exception has occurred: IndexError 
list index out of range
  File "C: \ Users \ Helphy \ Desktop \ Perso \ GitHub \ Advent_of_Code_2021 \ Day_3 \ Day_3.py", line 16, in <module>
    finalnumtemp.append (temp [j])

CodePudding user response:

What to solve? What did you intend for the program to achieve?

You have an error because...

  • j goes from 0 to len(test), that is, 12
  • test[j] as temp has only 5 elements.

To select among the digits in temp, the index should be something of 0, 1, 2, 3, 4 (first, second, third, ... from the left) or -1, -2, -3, -4, -5 (first, second, third, ... from the right).

To append the first of temp to finalnumtemp, fix

        finalnumtemp.append(temp[j])

to

        finalnumtemp.append(temp[0])

CodePudding user response:

Maybe you should look into list comprehension. I know it is maybe a bit daunting at first but I personally found it to make much more sense than nested for loops after I had gotten the hang of them. You could convert your strings of zeros and ones into lists of separate integers in a single line:

numbers = [[int(char) for char in line] for line in test]
[[0, 0, 1, 0, 0], [1, 1, 1, 1, 0], ... , [0, 0, 0, 1, 0], [0, 1, 0, 1, 0]]

And then fetch the first number (or any number really):

first_num = [num[0] for num in numbers]
[0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0]

And even perform operations on the lists if you wish:

sum_num = [sum(num) for num in numbers]
[1, 4, 3, 4, 3, 4, 3, 3, 1, 3, 1, 2]

Nested for loops can get real messy real quick. I know this isn't the actual answer to the question, but I thought it might be helpful regardless.

  • Related