使用python执行二进制搜索

时间:2015-11-13 04:57:50

标签: python format

我正在编写一个函数,该函数将表示国家/地区名称的字符串作为参数。此功能首先从前一个问题调用您的方法答案以获取国家/地区列表,然后通过列表进行二进制搜索并打印国家/地区的信息(如果找到)。

这是获取国家/地区列表的第一部分的代码:

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.

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个

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)