我有一份名为countries.txt的名单,列出所有国家的名字、面积( km2)、人口(例如。“阿富汗”,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(加拿大)加拿大,面积: 9976140.0,人口: 35295770 printCountry(“临冬城”)很抱歉,没能找到临冬城的国家名单。
但是它打印了我很抱歉,找不到加拿大在国家名单上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)发布于 2015-11-16 20:17:36
您必须在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)发布于 2015-11-16 20:17:47
最后一行
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)https://stackoverflow.com/questions/33743749
复制相似问题