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?
input.txtlook like?forward 6\n up 4\n forward 8\n, made the edit to the question mentioning the same. Thanksre.findall('^f',a)finds nothing, so the index 0 is out of range. Do you really need to useregexhere? Is your file onlyforwardandupfollowed by a number?