【问题标题】:Binary search through a list通过列表进行二分搜索
【发布时间】:2015-11-16 01:44:23
【问题描述】:

我有这个代码

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

他的代码像这样输出countries.txt

[["阿富汗",647500.0,25500100],["阿尔巴尼亚",28748.0,2821977],...,["津巴布韦",390580.0,12973808]]

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

printCountry("Canada")

  Canada, Area: 9976140.0,  Population: 35295770

 printCountry("Winterfell")

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

我不知道如何做这部分,感谢任何帮助。

【问题讨论】:

  • 如果你只是想找国家,又不想自己实现二分查找,python提供了一个二分查找的bisect库。
  • 您是否考虑过使用va 字典而不是列表?这似乎是您应该使用它们的典型场景。

标签: python binary-search


【解决方案1】:

希望这会有所帮助:

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))

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多