Python程序检查简单括号的匹配 [英] Python program to check matching of simple parentheses

查看:105
本文介绍了Python程序检查简单括号的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我遇到了一个检查给定字符串中的简单括号(,)是否均匀匹配的练习。



<我在这里看到了使用尚未遇到的stack命令的示例,因此我尝试了另一种方法。谁能告诉我我要去哪里哪里?

  def匹配(str):
ope = []
clo = []
对于范围(0,len(str))中的i:
l = str [i]
如果l ==(:
ope = ope + [(]
else:
,如果l ==):
clo = clo + [)]
else:
return( ope,clo)如果len(ope)== len(clo),则

返回True
否则:
return False

想法是将(和)堆积到两个单独的列表中,然后比较列表的长度。我还有另一个版本,我在列表ope和clo后面分别附加了(或)对应的i。



感谢您的时间!

解决方案

下面是一种更为优雅的方法。它清除for循环,并用简单的计数器变量替换列表。如果计数器降到零以下,它也会返回false,这样 matched()()将返回 False

  def匹配(str):
count = 0
for str in:
如果i ==(:
计数+ = 1
elif i ==):
计数-= 1
如果count < 0:
返回False
返回计数== 0


I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.

I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?

def matched(str):
    ope = []
    clo = []
    for i in range(0,len(str)):
        l = str[i]
        if l == "(":
            ope = ope + ["("]
        else:
            if l == ")":
                clo = clo  + [")"]
            else:
                return(ope, clo)
    if len(ope)==len(clo):
        return True
    else:
        return False

The idea is to pile up "(" and ")" into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant i which held either ( or ) respectively.

Thanks for your time!

解决方案

A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(") will return False.

def matched(str):
    count = 0
    for i in str:
        if i == "(":
            count += 1
        elif i == ")":
            count -= 1
        if count < 0:
            return False
    return count == 0

这篇关于Python程序检查简单括号的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆