0

So I'm fairly new to Python, and I'm having difficulty understanding why this code wont compile. The point is to go line by line through the file, find the difference between the highest and lowest int, and sum the difference for all lines. It seems to me like the int casting is causing an issue; without it Python seems to accept that the first index of each list is a string, but if I try and cast that string as an int then that index apparently doesn't exist.

sum_count = 0
with open('C:\\...\\input_day_two.txt') as file:
    for line in file:
        line_list = line.split()
        list_copy = line_list.copy()
        line_count = len(list_copy)
        smallest = int(list_copy[0])
        largest = int(list_copy[0])
        for index in range (line_count):
            if int(list_copy[index]) < smallest:
                smallest = int(list_copy[index])
            if int(list_copy[index]) > largest:
                largest = int(list_copy[index])
            difference = largest - smallest
            sum_count += difference
    print(sum_count)

I thought initially that there may be an issue with trying to access the list indices outside of the for loop, but Python will recognize and print out every index of the list outside of the loop. I have to imagine the error has something to do with int parsing, but I can't see why.

Edit: This is the error that's being thrown

Traceback (most recent call last):
File "C:/.../adventcode_daytwo.py", line 7, in <module>
smallest = int(list_copy[0])
IndexError: list index out of range
  • Off the bat, if something says the index is out of bounds, that means that index does not exist in the size of the container. If your index is `0`, that means that your container is empty (i.e. `myList = []`). – pstatix Jan 08 '18 at 19:23
  • Line 7: `smallest = int(list_copy[0])` But it isn't, that's the weird thing. I can tell the program to print out that specific index and it will get the correct value from the text file I'm reading from. Unless something about parsing the int of that index somehow invalidates the whole list of that index? – Charlie Monnone Jan 08 '18 at 19:24
  • Is Line 7 where the error is occurring? – pstatix Jan 08 '18 at 19:25
  • And what is the error? Is it index out of bounds or something else? Please provide more details, based on what you have I don't see any issue, it should work as you expect it to. – GSazheniuk Jan 08 '18 at 19:27
  • You could use print() before casting, and that will give you an idea what is the last value that you are trying to parse. If you have commas in the initial file, it would cause the issue. – GSazheniuk Jan 08 '18 at 19:29
  • Some issues in your code: 1) Instead list_copy = line_list.copy(), do list_copy=list(line_list), 2) line_count = len(list_copy) wont work it will show '1' at each line, just do another index on the top like n=0 .....and after 'print' n +=1. If you fix this there will probably be no error message. The logic seems to ok but did not put much thought on that. Use the buil in min() max() methods as shown by pstatix – cyclomen Jan 08 '18 at 20:16

2 Answers2

0

As I cannot fully tell yet what exactly your attempting to do, allow me to point out some already visible assumptions/enhancements:

sum_count = 0
with open('C:\\...\\input_day_two.txt', 'r') as f:
    for line in f:
        line_list = list(map(int, line.split()))
        smallest = min(line_list)
        largest = max(line_list)
        sum_count += (largest - smallest) # you could just do max() - min() here instead
        #sum_count += (max(line_list) - min(line_list))
    print(sum_count)

Walking through it:

line_list = list(map(int, line.split())): We create a list object by calling split() on the line in the file (since all lines will be of type str) and then we map() the int() function to each element returned by the split() call. Remember than when you call split(), a list object (i.e. an iterable) is returned. So what this produces for us is a list of elements of type int.

smallest = min(line_list): Uses the built-in min() function to get the smallest integer.

largest = max(line_list): Uses the built-in max() function to get the largest integer.

Now as I mentioned in the comments, you can reduce the number of lines and local variables by just doing the function calls in the summing line, but that is up to you.

If I were implementing something that was finding the summing difference between the largest and smallest values on each line in a file (assuming separating by a space) I would do the following:

sums = 0
with open('/path/to/file', 'r') as f:
    for line in f:
        nums = list(map(int, line.split()))
        sums += max(nums) - min(nums)
    print(sums)

You may be able to skip the nums line into some kind of generator or list comprehension using lambda (somebody correct me or please post the one-line) but I couldn't think of a way to do that.

pstatix
  • 3,611
  • 4
  • 18
  • 40
0

The error is in the file formatting; somehow there's an extra empty line after each valid line in the text file, despite that not visually appearing to be the case. There must be extra new line characters or something. Thank you all.

  • If the file is coming from platform different from what you are running python on, then there will be difference in Line Ending characters. I suggest you read following topic on Line Endings in Python: https://stackoverflow.com/questions/10785131/line-endings-in-python – GSazheniuk Jan 08 '18 at 19:44