Home > Software engineering >  Python regex findall list index out of range
Python regex findall list index out of range

Time:12-04

import re
with open("day2.txt", "r") as file: 
    line=file.read().split("\n")
    forward=0
    pos=0
    for i in range(0,len(line)-1):
        a=line[i]
        print(a)
        if (re.findall('^f',a)[0]) == 'f':
             forward=forward int(((re.findall('\d',a)[0])))
        if (re.findall('^u',a)[0]) == 'u':
             pos=pos-int(((re.findall('\d',a)[0])))
        if (re.findall('^d',a)[0]) == 'd':
             pos=pos int(((re.findall('\d',a)[0])))
print(forward*pos)
            

Here a or line[i] is a string. Test cases in the input.txt file is this but a few thousand lines of these

forward 6
up 4
forward 8
down 6
forward 9

Ideally the output should be the sum of 6 8 I get an error when i run it as a script i get list index out of range, but no errors when i run it via the shell line by line

The exact error message is :

Traceback (most recent call last):
  File "day2.py", line 10, in <module>
    if (re.findall('^u',a)[0]) == 'u':
IndexError: list index out of range

Where am i going wrong?

CodePudding user response:

It would be possible to do with regex, but in my opinion that would be very over-engineered. Since your file is made of a small number of known strings followed by a number, you can simply isolate the numbers based on the strings.

This should work:

forward = 0
pos = 0
with open("input.txt", 'r') as file:
    elements = file.read().split("\n")

for e in elements:
    if "forward" in e:
        forward  = int(e[7:])
    elif "up" in e:
        pos -= int(e[2:])
    elif "down" in e:
        pos  = int(e[4:])

print(forward*pos)
  • Related