Answer the question
In order to leave comments, you need to log in
How to find the position of the maximum element in a list?
def max2(z):
for x in range(len(z)):
s = 0
b = 0
if z[x] > s:
s = z[x]
b = x
print b
Answer the question
In order to leave comments, you need to log in
You reset s and b at each iteration of the loop.
And the names should be more understandable to give.
Also note that you use for in the style of languages like C, you only get the index through the loop, although here you can get by with a simpler one:
for x in z:
if x > s:
#...
for i, x in enumerate(z):
if x > s:
#...
It's better to use enumerate :
for i, v in enumerate(z):
if v > max_v:
max_v = v
max_i = i
max_i = z.index(max(z))
An error in the algorithm - s and b must be initialized before the start of the loop.
An error in logic - the maximum element can be less than 0. It would be better s = -maxint-1 if we are talking about integers
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question