括號匹配、二分查詢
阿新 • • 發佈:2020-12-31
技術標籤:python
"""
括號匹配
首先設定兩個列表分別存放的是各種括號的開括號和閉括號,然後遍歷給定的字串,分如下幾種情況:
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