I have a text file that contains lines of numbers. My program is trying to extract the lines of code and put them in a list, with each list being composed of the numbers that make up that line in the file, and then put all of these lists into one list (lets call this Triangle) and have a function applied to them, but the Python interpreter says that Triangle[x] is an integer type when I am trying to work with it, but when I ask it type(Triangle[x]), it says that it is a list. My code is below:
def compare(a,b):
"""Returns the larger of a and b"""
if a > b:
return a
else:
return b
doc = open('C:/Users/Joseph/My Documents/Programming fun/Python/Project Euler/18triangle.txt')
Triangle = []
for line in doc:
Triangle.append( map( int, line.split() ) )
doc.close()
Triangle.reverse()
for i in xrange(len(Triangle) - 1):
for j in xrange(len(Triangle[i]) - 1): # Here it says that 'type int has no len'
TEMP = compare(Triangle[i][j],Triangle[i][j + 1])
Triangle[i+1] = TEMP
Thank you in advance for any advice you can offer.
This looks suspicious:
TEMP = compare(Triangle[i][j],Triangle[i][j + 1])
Triangle[i+1] = TEMP
Triangle starts out with lists of integers as members, but as you go through you're assigning elements to be integers. In fact, this happens for each element other than Triangle[0], so this will always happen as soon as i gets to 1.
By the way, this is a somewhat nicer way to read the document:
with open('C:/Users/Joseph/My Documents/Programming fun/Python/Project Euler/18triangle.txt') as doc:
Triangle = [map(int, line.split()) for line in doc]
And your compare function is a subset of the standard max function; you could just use that instead (as pointed out by @BrendenBrown in the comments).
Also, Triangle should be triangle according to standard Python style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With