用python执行二进制搜索

2024-10-01 00:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它将表示国家名称的字符串作为参数。此函数首先调用前面问题的方法answer来获取国家列表,然后对列表进行二进制搜索,如果找到了国家信息,则打印国家信息。你知道吗

这是第一部分的代码,其中列出了国家:

def readCountries():
    open_file = open("countries.txt", 'r')
    new_list = []
    contents = open_file.readlines()
    for i in range(len(contents)):
        lsSplit = contents[i].split(",")
        new_list.append([lsSplit[0], float(lsSplit[1].strip()), int(lsSplit[2])])
    open_file.close()
    return new_list

这是我需要帮助的部分:

new_list = readCountries()  
def printCountry(name):
    lo, hi = 0, len(new_list) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        country = new_list[mid]
        test_name = country[0]
        if name > test_name:
            lo = mid + 1
        elif name < test_name:
            hi = mid - 1
        else:
            return country
    return countries[lo] if countries[lo][0] == name else None

我从第二部分得到的结果是:

>>> printCountry("Canada")
['Canada', 9976140.0, 35295770]

我怎样才能让它看起来像这样:

>>> printCountry("Canada")
Canada, Area: 9976140.0,    Population: 35295770
>>> printCountry("Winterfell")
I'm sorry, could not find Winterfell in the country list.

任何帮助都将不胜感激。你知道吗


Tags: namelonewcontentsopen国家hicountry
1条回答
网友
1楼 · 发布于 2024-10-01 00:20:29

试试这个

new_list = readCountries()  
def printCountry(name):
    lo, hi = 0, len(new_list) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        country = new_list[mid]
        test_name = country[0]
        if name > test_name:
            lo = mid + 1
        elif name < test_name:
            hi = mid - 1
        else:
            return country[0] + ", Area: " + str(country[1]) + ",    Population: " + str(country[2])
    return "Sorry Can not find " + str(name)

相关问题 更多 >