0

I am trying to find the sum of to values from a text file that is equal to 2020 with python. The text file contains multiple numbers each written in one line like this:

text file with numbers

What is the easiest and fastest way to do this in python?

My code reads in the file correctly but does not access the inner for loop?

data = []
try:
    file = open('/Users/korbinianschleifer/desktop/input.txt', 'r+')
    data = file.readlines()
    file.close()
except x:
    print('file could not be loaded')

print(len(data))

for i in range(len(data)):
    for j in range(i+1,len(data)):
        if data[i]+data[j] == 2020: 
            print('solution found')
1

1 Answer 1

2

Your data list is a list of strings, which means + will concatenate them ("1" + "1" is "11"), which is not the behavior you want. Parse your data to an int:

# use with to avoid having to close the file manually
with open('/Users/korbinianschleifer/desktop/input.txt', 'r+') as file:
    data = file.readlines()

# parse it to an int
data = [int(x) for x in data]

for i in range(len(data)):
    for j in range(i + 1, len(data)):
        if data[i] + data[j] == 2020:
            print("solution found", data[i], data[j])

As a side note, the faster way to do this is to maintain a set of values:

# use with to avoid having to close the file manually
with open('/Users/korbinianschleifer/desktop/input.txt', 'r+') as file:
    data = file.readlines()

# parse it to an int
data = [int(x) for x in data]

seen = set()
for v in data:
    if 2020 - v in seen:
        print("solution found", v, 2020 - v)
    seen.add(v)
Sign up to request clarification or add additional context in comments.

Comments

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.