通过lis进行二进制搜索

2024-04-27 03:28:15 发布

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

我有这个密码

def readCountries(self):
    countryList = []
    with open('countries.txt', 'r') as countryText:
        for line in open('countries.txt', 'r'):
            countries = countryText.read()
            countryList.append(line.strip().split())
        return countryList

他的代码输出如下:

[["Afghanistan",647500.0,25500100],["Albania",28748.0,2821977],...,["Zimbabwe",390580.0,12973808]]

t经过[name, area, population]。我要做的是编写一个函数,从上面的代码中调用答案来获取国家列表,并进行二进制搜索,如果找到了国家信息,则打印它。示例:

printCountry("Canada")

  Canada, Area: 9976140.0,  Population: 35295770

 printCountry("Winterfell")

  I'm sorry, could not find Winterfell in the country list.

我不知道如何做这一部分,任何帮助是感激的。你知道吗


Tags: 代码intxt密码deflineopen国家
1条回答
网友
1楼 · 发布于 2024-04-27 03:28:15

希望这有助于:

def binary_search(clist, cname):
    low = 0
    high = len(clist)
    while low<=high: 
        mid = int((low+high)/2)
        print(mid, low, high)
        if clist[mid][0]== cname:
            return clist[mid]
        elif clist[mid][0] > cname:
            high = mid-1
        else:
            low = mid+1

def printCountry(self,country_name):
    country = binary_search(self.countryList, country_name)
    if country:
        print("{0}, Area:{1}, Population:{2}".format(country[0],    country[1], country[2]))
    else:
        print("I'm sorry, could not find {0} in the country list.".format(country_name))

相关问题 更多 >