【发布时间】:2019-03-31 00:10:04
【问题描述】:
我在 Grokking Algorithm 书 SelectionSort 中的 for loop in range() 中苦苦挣扎
def findthesmallest(arr):
# suppose that the left list is sorted
min = arr[0]
min_index = 0
for i in range(len(arr)):
if arr[i] < min:
min = arr[i]
min_index = i
return min_index
def selectionsort(arr):
new_arr = []
# For each i+= 1, n-=1
for i in range (len(arr)):
min_index = findthesmallest(arr)
# Add item to new_arr and update the arr
new_arr.append(arr.pop(min_index))
return new_arr
print (selectionsort([5, 3, 4, 8, 10]))
- 所以在第二个selectionsort() for_loop中,每次我们完成迭代,len(arr) - 1
- 当 i 增加每次迭代时,range(len(arr)) 会减少。
- 当我尝试检查每个迭代的每个 (i, len(arr)) 时,我得到: (0,5), (1, 4), (2, 3), (3, 2), (4, 1)
- i = 4 in range(1) 怎么可能?
提前致谢!
【问题讨论】:
标签: python-3.x for-loop syntax