顺序查找
# sequential search
def sequential(ls,value):
for i in range(len(ls)):
print('\033[036m',i,ls[i],'\033[0m') # show steps
if ls[i]==value:
return i
l=[0,11,22,33,44,55,66,77,88,99]
print(l)
for i in range(9):
v=int(input('look up number').strip())
print(sequential(l,v))
二分查找
# binary search
def binary(ls,value):
head,tail=0,len(ls)-1
mid=(head+tail)//2
while head<=tail:
if ls[mid]==value:
return mid
elif value<ls[mid]:
print('\033[036m',mid,ls[mid],'\033[0m') # show steps
tail=mid-1
mid=(head+tail)//2
elif ls[mid]<value:
print('\033[036m',mid,ls[mid],'\033[0m') # show steps
head=mid+1
mid=(head+tail)//2
l=[0,11,22,33,44,55,66,77,88,99]
print(l)
for i in range(9):
v=int(input('look up number').strip())
print(binary(l,v))
字符串查找1
# string find 1
def find1(sentence,word,start=0,end=None):
if not end:
end=len(sentence)-len(word)+1
if end>start and end<=len(sentence)-len(word)+1:
for i in range(start,end):
for j in range(len(word)):
print(i,j,sentence[i+j],word[j],sep='\t') # show steps
if sentence[i+j]!=word[j]:
break
else:
return i
s='To see a world in a grain of sand. And a heaven in wild flower.'
print('find1(s," a ",7)',find1(s,' a ',7))
print('find1(s," a ",7,17)',find1(s,' a ',7,17))
for i in range(9):
for i in range(len(s)):
print(i%10,end='')
print('\033[036m')
print(s,'\033[0m')
w=input('word: ')
n=input('start number: ')
e=input('end number: ')
if w and n.isdigit() and e.isdigit():
print('\033[031m',find1(s,w,int(n),int(e)),'\033[0m')