def selection_sort(a):
for i in range(0, len(a) - 1):
minIndex = i
for j in range(i + 1, len(a)):
if a[j] < a[minIndex]:
minIndex = j
if minIndex != i:
a[i], a[minIndex] = a[minIndex], a[i]
def selection_sort_runs():
run_time_list = []
n = 1
while [having trouble thinking of loop condition here]
start_time = time.time()
rand = [random.randint(0, 100) for x in range(1, 10001*n)]
selection_sort(rand)
end_time = time.time()
run_time = end_time - start_time
run_time_list.append(run_time)
if run_time < 60:
n += 1
我想继续循环直到run_time大于60,但我想不出一个条件允许我这样做,并且将n加1,因为run_time是循环内包含的乘积,有什么想法吗?
答案 0 :(得分:2)
您可能有两个选择,就是使用break
语句
while True:
start_time = time.time()
rand = [random.randint(0, 100) for x in range(1, 10001*n)]
selection_sort(rand)
end_time = time.time()
run_time = end_time - start_time
run_time_list.append(run_time)
if run_time < 60:
n += 1
else:
break
或者您可以重构代码,以便在循环外初始化run_time
变量。
run_time = -1
while run_time < 60:
start_time = time.time()
rand = [random.randint(0, 100) for x in range(1, 10001*n)]
selection_sort(rand)
end_time = time.time()
run_time = end_time - start_time
run_time_list.append(run_time)
if run_time < 60:
n += 1