制作函数并从中调用两个不同的结果。我该怎么办

问题描述 投票:0回答:1

我正在尝试检查匹配方程式的平衡。下面的代码是我目前拥有的。

#Creating the math equation the use check_html on.
e = "10 - (3 + (2+1)*8)" 
 def check_html(html_string):   
d = Stack()
balanced = True
for symbol in html_string: 
if symbol == "(":
    d.push(symbol)
elif symbol == ")":
    if d.is_empty():
        balanced = False
    else:
        d.pop()

if not d.is_empty:
balanced = False
str1 = "10 - (3 + (2+1)*8)"
str2 = "10 - (3 + (2+1)*8))"
print ("is the first valid?", check_html(str1))
print ("is the second valid?", check_html(str2))
print("Is it balanced? ", balanced) 

此代码的输出是

is the first valid? None
is the second valid? None
Is it balanced?  True

应该说第一个是TRUE,第二个是FALSE。我现在在做什么错了。

python html function
1个回答
0
投票

您必须在行中使用html_string而不是e

for symbol in html_string:  # `html_string` instead` of `e`

就这些。


BTW:最好在函数内部创建并使用Stack()-因此,当您使用新字符串运行函数时,它将创建新的空堆栈。


EDIT:全功能

# --- functions ---

def check_html(html_string):
    d = Stack()

    balanced = True

    for symbol in html_string: 
        if symbol == "(":
            d.push(symbol)
        elif symbol == ")":
            if d.is_empty():
                balanced = False
            else:
               d.pop()

    if not d.is_empty(): # you forgot `()
        balanced = False

    print("Is it balanced? ", balanced)

# --- main ---

e = "10 - (3 + (2+1)*8))"
check_html(e)
check_html(e + ')')

如果要在check_html()中使用print(),则应使用return balanced代替of print()

# --- functions ---

def check_html(html_string):
    d = Stack()

    balanced = True

    for symbol in html_string: 
        if symbol == "(":
            d.push(symbol)
        elif symbol == ")":
            if d.is_empty():
                balanced = False
            else:
               d.pop()

    if not d.is_empty(): # you forgot `()
        balanced = False

    return balanced

# --- main ---

e = "10 - (3 + (2+1)*8))"
print("Is it balanced? ", check_html() )
print("Is it balanced? ", check_html(e+')') )
© www.soinside.com 2019 - 2024. All rights reserved.