I am working on a data structure list class in python. I would like to get the largest item in the list.
inlist = self.data
if inlist[0] > inlist[1]:
largest = inlist[0]
else:
largest = inlist[1]
for item in inlist[2]:
if item > largest:
largest = item
return largest
With the above getting stuck at largest gets returns
<bound method ListData.largest2 of <list.ListData instance at 0x2b35602c3440>>
while the data
[2, 5]
asked Feb 7, 2013 at 21:46
bobsr
4,0158 gold badges32 silver badges39 bronze badges
2 Answers 2
Trust the loop to get all the indicies rather than specifying them yourself.
if len(self.data) == 0:
return None
result = self.data[0]
for item in self.data:
if item > result:
result = item
return result
that for loop is going through all your data. Trying to coerce an index got you into trouble.
answered Feb 7, 2013 at 21:50
Mel Nicholson
3,22416 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
bobsr
it still returns <bound method ListData.largest3 of <list.ListData instance at 0x2adc79695ef0>> <bound method ListData.largest4 of <list.ListData instance at 0x2adc79695ef0>>
Mel Nicholson
Sounds like self.data isn't an array of numerics. What did you put in self.data?
bobsr
def data(self): return self.data
Mel Nicholson
doh! Change the word "largest" to "temp" wherever it occurs. I bet you defined and used largest as something else in a different part of your code.
Mel Nicholson
I suspect you have (another) problem in the code not included here. Likely culprits include bad indentation on your
def myFunction: lineYou can use the build in max() function.
mylist = [2, 5]
mymax = max(mylist)
answered Feb 7, 2013 at 21:53
Ben Mordecai
6952 gold badges8 silver badges19 bronze badges
1 Comment
bobsr
<bound method ListData.largest5 of <list.ListData instance at 0x2adc79695ef0>>
lang-py
inlist[2]max(self.data)?<blah hex-code for memory address>when you forget something silly, like forgetting the trailing parenthesis in a function that takes zero arguments.self.data, so clearly you're expecting that to be alistor other iterable. So... what is it a list or iterable of? For example, is your structure inself.datasomething like(len, capacity, [item0, item1, ...])? Ideally, give us the actual class definition (stripped down to just enough to run a test that shows the problem), either posted here or somewhere like pastebin.com.