我有这段代码
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.
我不知道如何做这部分,感谢任何帮助。
答案 0 :(得分:-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))