Reputation: 46
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.
Upvotes: 3
Views: 526
Reputation: 174622
for i in xrange(len(Triangle) - 1)
this is not very pythonic.
Since you want to compare two objects at once, first adjusting the list might be better. This snippet converts your list into a list of 2-tuples
>>> from itertools import izip_longest, islice
>>> x
[1, 2, 3, 4, 5]
>>> list(izip_longest(islice(x,0,None,2),islice(x,1,None,2)))
[(1, 2), (3, 4), (5, None)]
Once you have the list in that format, you can step through it like this:
for i,j in two_list:
# rest of your loop
Upvotes: 1
Reputation: 28846
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.
Upvotes: 4
Reputation: 1419
The problem is that TEMP gets an integer, and then you put that into Triangle, so now Triangle has an element that is an integer rather than a list. Maybe you want something like
Triangle[i+1] = [TEMP]
instead of
Triangle[i+1] = TEMP
Upvotes: 1