Y
Y
YraganTron2014-01-11 01:13:40
Python
YraganTron, 2014-01-11 01:13:40

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

Can't find an error. Perhaps the idea itself is wrong, but there are no other ideas for implementation.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
AlexP11223, 2014-01-11
@YraganTron

You reset s and b at each iteration of the loop.
And the names should be more understandable to give.

K
Konstantin Dovnar, 2014-01-11
@SolidlSnake

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:
        #...

upd. Error, you need to find the index, then you can use the enumerate function:
for i, x in enumerate(z):
    if x > s:
        #...

Now, at each step, i will have an index, and x will have the value itself.

A
Andrey Belov, 2014-01-11
@Andrey_Belov

It's better to use enumerate :

for i, v in enumerate(z):
    if v > max_v:
        max_v = v
        max_i = i

Option without loop:
max_i = z.index(max(z))

R
Rsa97, 2014-01-11
@Rsa97

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

A
Artem, 2014-01-11
@weend

def maximal(in_list):
    n = 0
    for i in in_list:
        if i > n: n = i
    print in_list.index(n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question