Reputation: 36
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:
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')
Upvotes: 0
Views: 79
Reputation: 35482
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)
Upvotes: 2