python 二分法查找

这个也是之前写的程序,现在把它贴上来

#!/usr/bin/python
import os
os.system('clear')
def binsearch(seq,x,low,high):
	mid=(low+high)//2
	if x==seq[mid]:
		print 'i find it'
	elif low>=high:
		print "i can't find it"
	elif x>seq[mid]:
		binsearch(seq,x,mid+1,high)
	else:
		binsearch(seq,x,low,mid-1)
	


def input2():
	seq=[None]
	count=0
	print 'Enter an array!'
	while 1:
		try:
			temp=input()
			seq.append(None)
			seq[count]=temp
		except SyntaxError:
			print "Over!"
			seq.sort()
			del seq[0]
			return (seq,count)
			break
		except NameError:
			print 'Please,Enter a number not a letter.'
			continue
		count+=1

seq,count=input2()
while 1:
	try :
		x=input("Enter a number which you want to look up(q to quit): ")
	except (ValueError,NameError):
		print "GoodBye"
		break
	binsearch(seq,x,0,count-1)

 

posted @ 2013-09-11 22:01  花瓣奶牛  阅读(356)  评论(0编辑  收藏  举报