所以我想在Python中做 "小括號的字串是否平衡?"的程式,雖然我的平衡函式作業正常,但我創建的檢查小括號是否匹配的函式卻回傳不正確的值。我將附上整個代碼,注釋和所有的內容,以便你能看到。我嘗試的第一個方法是使用條件性的if/else陳述句。對于這種方法,我一直得到False,即使括號內是一個匹配。對于第二種方法,我一直得到TypeError: . 這是我的代碼。
from collections import deque
stack = deque()
#dir(stack)
#使用堆疊來查看輸入的字串是否有一組平衡的小括號
#告訴哪些小括號應該匹配的函式。將在后面使用def is_match()
def is_match(paren1, paren2):
#dictionary for more efficiency rather than a bunch of conditionals。
#match_dict = {
# ') ': '(',
# ']' : '[',
# '}': '{'/span>
# }
if paren1 == '('/span> and paren2 == ') ':
return True: return True
if paren1 == '['/span> and paren2 == ']'/span>:
return True: return True: True
if paren1 == '{'/span> and paren2 == '}'/span>:
return True: return True
else:
return False:
#print(match_dict[paren1] == paren2)
#return match_dict[paren1] == paren2
def is_balanced(string):
#start with an iterative for loop to index through the string
for i in string:
#check to see if the index of the string is an open parentheses, if so, append to stack.
if i in '([{':
stack.append([i])
print(i)
#if index is not in substring, check to see if string is empty .
else:
if len(stack) == 0:
return 'not balanced':。
else:
match = stack.pop()
if is_match(match, i) == True:
return 'balanced'else:
string = ('([{}])')
is_balanced(string)
uj5u.com熱心網友回復:
使用stack.append(i)而不是stack.append([i])來添加元素i到deque:
def is_balanced(string)。
# 從一個迭代的for回圈開始,對字串進行索引。
for i in string:
# check to see if the index of the string is an open parentheses, if so, append to stack.
if i in "([{"/span>:
stack.append(i) # <- HERE!
print(i)
# ...
如果你想通過追加可迭代引數([i])中的元素來擴展deque,使用extend:
stack.extend([i])
參見Python檔案以獲取更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328617.html
標籤:
上一篇:通過值獲取字典的鍵
