首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >二进制搜索

二进制搜索
EN

Stack Overflow用户
提问于 2015-11-16 20:10:17
回答 2查看 89关注 0票数 0

我有一份名为countries.txt的名单,列出所有国家的名字、面积( km2)、人口(例如。“阿富汗”,647500.025500100)。

代码语言:javascript
复制
def readCountries(filename):
    result=[]
    lines=open(filename)

    for line in lines:
        result.append(line.strip('\n').split(',\t'))
    for sublist in result:
        sublist[1]=float(sublist[1])
        sublist[2]=int(sublist[2])

这个输入列表并打印出来。我想创建一个二进制搜索和搜索,通过列表和打印国家的信息,如果找到。有了这段代码,它应该这样做。

printCountry(加拿大)加拿大,面积: 9976140.0,人口: 35295770 printCountry(“临冬城”)很抱歉,没能找到临冬城的国家名单。

但是它打印了我很抱歉,找不到加拿大在国家名单上4次,然后打印加拿大的信息。

怎么一回事?

代码语言:javascript
复制
def printCountry(country):

    myList=readCountries('countries.txt')
    start = 0
    end = len(myList)-1
    while start<=end:
        mid =(start + end) / 2
        if myList[mid][0] == country:
            return '%s, Area: %.3f, Population: %i' %(country,myList[mid][1],myList[mid][2])
        elif myList[mid][0] > country:
            end = mid - 1
        else:
            start = mid + 1
        print "I'm sorry, could not find %s in the country list" %(country)
EN

回答 2

Stack Overflow用户

发布于 2015-11-16 20:17:36

您必须在while循环之后移动不成功的消息,并检查“启动”>“结束”(这意味着未找到国家):

代码语言:javascript
复制
myList = readCountries('countries.txt')
start = 0
end = len(myList) - 1
while start<=end:
    mid = (start + end) / 2
    if myList[mid][0] == country:
        return '%s, Area: %.3f, Population: %i' %(country,myList[mid][1],myList[mid][2])
    elif myList[mid][0] > country:
        end = mid - 1
    else:
        start = mid + 1
if start > end:
    print "I'm sorry, could not find %s in the country list" %(country)
票数 1
EN

Stack Overflow用户

发布于 2015-11-16 20:17:47

最后一行

代码语言:javascript
复制
print "I'm sorry, could not find %s in the country list" %(country)

应该在while循环之外。还要确保在没有找到文件中的键的情况下完成了循环,然后只有您将确保列表中不存在国家名称。

代码语言:javascript
复制
# If condition taken from Michel's answer.
if start > end:
    print "I'm sorry, could not find %s in the country list" %(country)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33743749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档