Invalid Python result

I have a little doubt. When I run the following code in python, I don't get the desired result. Can anyone explain why?

x,temp=[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],[]

for y in x[:-1]:temp.append(max(y,x[x.index(y)+1]))

print temp 

Output for the above code: -

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 62]

But it should be -:

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 23]

The only mistake I get is the last element 62, as it should be 23. Can someone explain the reason?

+4
source share
2 answers

As mentioned in the comment, your code does not do what you want, because the method .indexfinds the first matching element in the list. Therefore, when he tests the final 4, he does not test it against 23, he tests it against 62 after the first 4 c x.

Here is the best way.

x = [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]

temp = [max(u,v) for u,v in zip(x, x[1:])]
print(temp)

Output

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 23]

FWIW, .index, , , , .

+4

. -1, , , .

x[:-1] x[:], .

+1

Source: https://habr.com/ru/post/1659053/


All Articles