python 二分法查找

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/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)