"""
括号匹配
首先设置两个列表分别存放的是各种括号的开括号和闭括号,然后遍历给定的字符串,分如下几种情况:
1.字符串 首字符 出现在闭括号列表中,直接结束,输出错误
2.字符串长度不为偶数,直接结束,输出错误
3.对原始字符串列表化去重,如果去重后的列表长度不为偶数直接结束,输出错误
4.遍历字符串,将属于开括号集合的括号加入到列表中,当遇上一个闭括号的时候计算该闭括号在闭括号列表中的索引与
当前列表最后一个开括号在开括号列表中的索引是否一致,一致则继续,否则直接结束,输出错误
"""
def match ( lists) :
tmp_list = [ ]
open_bracket_list = [ '(' , '[' , '{' , '<' , '《' ]
close_bracket_list = [ ')' , ']' , '}' , '>' , '》' ]
set_list = list ( set ( lists) )
length = len ( lists)
if length % 2 != 0 :
return False
elif lists[ 0 ] in close_bracket_list:
return False
elif len ( set_list) % 2 != 0 :
return False
else :
for i in range ( length) :
if lists[ i] in open_bracket_list:
tmp_list. append( lists[ i] )
elif lists[ i] in close_bracket_list:
if close_bracket_list. index( lists[ i] ) == open_bracket_list. index( tmp_list[ - 1 ] ) :
tmp_list. pop( )
else :
return False
break
return True
if __name__ == '__main__' :
one_str_list = [ '({})' , '({[<《》>]})' , '[(]){}' , '{{{{{{' , '([{}])' , '}{[()]' ]
for one_str in one_str_list:
if match( one_str) :
print ( one_str, '正确' )
else :
print ( one_str, '错误' )
"""
二分查找
"""
def chop ( lists, data) :
length = len ( lists)
first = 0
last = length - 1
while first <= last:
mid = ( last + first) // 2
if lists[ mid] > data:
last = mid - 1
elif lists[ mid] < data:
first = mid + 1
else :
return True
return False
def chop2 ( lists, data) :
length = len ( lists)
if length< 1 :
return False
mid = length // 2
if lists[ mid] > data:
return chop2( lists[ 0 : mid] , data)
elif lists[ mid] < data:
return chop2( lists[ mid+ 1 : ] , data)
else :
return True