二进制搜索

2024-04-26 06:26:53 发布

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

我把这张单子叫做国家.txt该表列出了所有国家的名称、面积(平方公里)、人口(例如:阿富汗,647500.025500100)。你知道吗

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("Canada") Canada, Area: 9976140.0, Population: 35295770

printCountry("Winterfell") I'm sorry, could not find Winterfell in the country list.

但它打印我很抱歉,无法找到加拿大在国家名单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)

Tags: intxtdefresult国家filenamecountrystart
2条回答

您必须在while循环之后移动不成功的消息,并检查start>;end(这意味着找不到国家/地区):

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)

最后一行

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)

相关问题 更多 >