如何使用嵌套的for循环重写while循环?

时间:2019-04-16 05:01:23

标签: python

我在算法中使用了while循环,但是问题的一个参数是我使用嵌套的for循环,但我不确定该怎么做。

这是while循环:

i = len(lst)
while i > 0:
    big = lst.index(max(lst[0:i]))
    lst[big], lst[i-1] = lst[i-1], lst[big]
    i = i - 1
    return lst

这是它正在回答的问题:

输入:[5,1,7,3]

首先,找到最大的数字,即7
交换它和当前在列表末尾的数字3。现在我们有了:[5,1,3,7]
现在,找到最大的数字,不包括7,即5
交换它和倒数第二个数字3。现在我们有了:[3,1,5,7]
现在,找到第三大数字(前两个数字除外),即3
交换它和倒数第二个数字1

输出:[1, 3, 5, 7]

3 个答案:

答案 0 :(得分:2)

您在算法中看到的是一个selection sort。这是您要求的第二个解决方案(嵌套<?php require 'IP2Location.php'; $myip = '8.8.8.8'; $db = new \IP2Location\Database('./database/IP-COUNTRY-SAMPLE.BIN', \IP2Location\Database::FILE_IO); $records = $db->lookup($myip, \IP2Location\Database::ALL); echo '<pre>'; echo 'IP Address : ' . $records['ipAddress'] . "\n"; echo 'Country Code : ' . $records['countryCode'] . "\n"; echo 'Country Name : ' . $records['countryName'] . "\n"; echo 'Region Name : ' . $records['regionName'] . "\n"; echo 'City Name : ' . $records['cityName'] . "\n"; echo 'Latitude : ' . $records['latitude'] . "\n"; echo 'Longitude : ' . $records['longitude'] . "\n"; echo '</pre>'; ?> 循环):

for

快速测试:

def insertion_sort(arr):
    l = len(arr)
    for i in range(l-1, -1, -1):
        m = -10000 # it should be lower than min(arr)
        idx = -1
        for key, val in enumerate(arr[:i+1]):
            if m < val:
                m = val
                idx = key
        if idx != -1:
            arr[i], arr[idx] = arr[idx], arr[i]
    return arr

答案 1 :(得分:0)

这看起来像一个(相当慢的)排序算法-即冒泡排序。从列表lst的末尾开始进行迭代。然后,它在前n-1个元素中搜索最大值,然后将它们与末尾交换。但是,如果最大值已经在末尾,它将失败,因为它将自动将max(n-1)n值交换。您需要为此添加一张支票。

因此,从第一眼看,我不确定i是否已定义,但让我们假设它似乎是在列表lst的长度上定义的。因此,让我们从外部循环开始-有一个while循环,它看起来像是从i倒数到0。这与增加for循环相反,因此我们可以创建一个保留范围:

rev_range = range(0,len(lst))
rev_range.reverse() 
for j in rev_range:
    # perform the sort

我们现在有了用于倒计时while循环的外循环。排序本身会向前迭代,直到找到最大值。这是一个正向循环。

# sorting
max_val_so_far_index=lst[j]
# lst[:j-1] gets the first j-1 elements of the list
for k in lst[:j-1]:
    if lst[k] > lst[max_val_so_far_index]:
        max_val_so_far_index = k
# now we have the index of the maximum value
# swap
temp = lst[j]
lst[j] = lst[max_val_so_far_index]
lst[max_val_so_far_index]=temp

我们将两个组件放在一起得到:

rev_range = range(0,len(lst))
rev_range.reverse() 
for j in rev_range:
    # perform the sort
    # sorting
    #print j
    max_val_so_far_index=j

    # get the first j items
    for k in range(j):
        if lst[k] > lst[max_val_so_far_index]:
            max_val_so_far_index = k
    # now we have the index of the maximum value
    # swap
    temp = lst[j]
    lst[j] = lst[max_val_so_far_index]
    lst[max_val_so_far_index]=temp

最后lst被排序。

答案 2 :(得分:-1)

问题中的算法只是bubble sort的另一种形式。原始算法使用两个嵌套的for循环。您可以找到很好的解释here