using an answer given in this Q&A (credits to here!) , you could do
a = [12,7,5,3,8,5,2,3,42]
# assuming no duplicates in a and len(a) > 1:
if a[0] > a[1]: # make sure that m1 != m2 and s1 != s2
m1, m2 = a[0], a[1]
s1, s2 = a[0], a[1]
else:
m1, m2 = a[1], a[0]
s1, s2 = a[1], a[0]
for i in a:
# maximum and second maximum
if i > m1:
m1, m2 = i, m1
elif i > m2:
m2 = i
# minimum and second minimum
if i < s1:
s1, s2 = i, s1
elif i < s2:
s2 = i
print(m1, m2, s1, s2)
# 42 12 2 3
comparing to the code in question
- initialize correctly so that the logic works. setting everything to
a[0]
could work e.g. for the maxima if a[0]
is not the maximum - or for the minima if a[0]
is not the minimum. Not both.
- modify the logic so that values are updated simultaneously, not sequentially. Otherwise, the conditionals won't work as I commented.
Note: I assume the whole point of this exercise is to do it all with conditionals. Otherwise, you could simplify to
a = list(set([1,7,5,3,8,5,2,3,1])) # remove duplicates with set
m1, s1 = max(a), min(a)
_, _ = a.remove(m1), a.remove(s1)
m2, s2 = max(a), min(a)
print(m1, m2, s1, s2)
# 8 7 1 2
or even simpler:
a_srt = sorted(list(set(a)))
m1, m2, s1, s2 = a_srt[-1], a_srt[-2], a_srt[0], a_srt[1]
...and I bet there's even more possibilities.