【问题标题】:Binary Searching二分查找
【发布时间】:2015-11-16 20:10:17
【问题描述】:

我有一个名为 countries.txt 的列表,其中列出了所有国家的名称、面积(以 km2 为单位)、人口(例如 ["Afghanistan",647500.0,25500100])。 p>

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

【问题讨论】:

  • 我认为print 应该在while 循环之外。

标签: python binary-search


【解决方案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)

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 你不需要 if 语句,因为如果找到它,该函数将返回。
    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 2021-03-07
    • 2012-12-24
    • 2015-07-25
    • 1970-01-01
    • 2018-03-27
    • 2018-01-08
    相关资源
    最近更新 更多