0
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?

6
  • 1
    What does input.txt look like? Commented Dec 2, 2021 at 20:20
  • It's a text file containing a few thousand lines, of text with a pattern similar to the code box under testcases. Ie forward 6\n up 4\n forward 8\n, made the edit to the question mentioning the same. Thanks Commented Dec 2, 2021 at 20:24
  • Ok, can you add a few lines to your question, and make sure they include lines that cause your problem. Commented Dec 2, 2021 at 20:25
  • Updated it now, my bad Commented Dec 2, 2021 at 20:26
  • 1
    The issue is that your re.findall('^f',a) finds nothing, so the index 0 is out of range. Do you really need to use regex here? Is your file only forward and up followed by a number? Commented Dec 2, 2021 at 20:33

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Replace the string splicing index with -1 and you will always access the last value of a string. This removes the need to know the length of the string to start the slice at the correct index. The strength of regex lies in in being able to define a pattern of unknown characters and pull whatever matches that pattern. If you know you are looking for a string 'forward' then using the in keyword is more readable and reduces code complexity. You can access all the elements in a list with in as well, accessing elements in a list by the index can cause errors and reduce readability.
I accept the solution, it worked. Thanks. But is there a way i can move forward with the over-engineered regex method.
@CrunchyLentils I didn't suggest [-1] because that would break for values greater than 9, but of course if the value is in the range [0, 9] that would be easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.