My code:
lst = [int(i) for i in input().split()]
a = max(lst)
b = min(lst)
lst[lst.index(a)], lst[lst.index(b)] = lst[lst.index(b)], lst[lst.index(a)]
print(' '.join([str(i) for i in lst]))
The working answer:
a = [int(s) for s in input().split()]
index_of_min = 0
index_of_max = 0
for i in range(1, len(a)):
if a[i] > a[index_of_max]:
index_of_max = i
if a[i] < a[index_of_min]:
index_of_min = i
a[index_of_min], a[index_of_max] = a[index_of_max], a[index_of_min]
print(' '.join([str(i) for i in a]))
I see that there are answers posted to solve this challenge. I want to know why my version does not work.
Working test case: '1 2 3 4 5 6 7 8 9 10'
Failing test case: '10 9 8 7 6 5 4 3 2 1'
2
The assignations in lst[lst.index(a)], lst[lst.index(b)]
are done from left to right. So your code is equivalent to
lst = [int(i) for i in '10 9 8 7 6 5 4 3 2 1'.split()]
a = max(lst)
b = min(lst)
min_value, max_value = lst[lst.index(b)], lst[lst.index(a)]
lst[lst.index(a)] = min_value
print(lst)
# [1, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(lst[lst.index(b)])
# 1
lst[lst.index(b)] = max_value # Here lst.index(b) == 1 !!
Because lst.index(foo)
gives you the first occurrence of foo
, and you decided to start by swapping max for min, “it works” when the minimum value is in the left side:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
max <- min
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
first occurrence of min <- max
[10, 2, 3, 4, 5, 6, 7, 8, 9, 1]
1