二进制搜索

时间:2015-11-16 20:10:18

标签: python binary-search

我有一个名为countries.txt的列表,按名称,面积(以km2为单位),人口列出所有国家/地区(例如 ["阿富汗",647500.0,25500100] )。

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("加拿大&#34)    加拿大,面积:9976140.0,人口:35295770

     

printCountry("冬&#34)   对不起,在国家名单中找不到Winterfell。

但它打印出来我抱歉,在国家列表中找不到加拿大4次然后打印加拿大信息。

发生了什么事?

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)

2 个答案:

答案 0 :(得分:1)

您必须在while循环后移动不成功的消息并检查是否开始&gt;结束(这意味着没有找到该国家):

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 :(得分:1)

最后一行

print "I'm sorry, could not find %s in the country list" %(country)

应该在while循环之外。还要确保循环完成而不在文件中找到密钥,然后只有您确定列表中不存在国家/地区名称。

# If condition taken from Michel's answer.
if start > end:
    print "I'm sorry, could not find %s in the country list" %(country)