我的代码:
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]))
答案:
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]))
我看到已经发布了解决此挑战的答案。我想知道为什么我的版本不起作用。
工作测试用例:'1 2 3 4 5 6 7 8 9 10'
失败的测试用例:'10 9 8 7 6 5 4 3 2 1'
lst[lst.index(a)], lst[lst.index(b)]
中的分配是按顺序完成的。所以你的代码相当于
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)])
lst[lst.index(b)] = max_value # Here lst.index(b) == 1 !!