如果可能的话,在脚本的最后一部分需要帮助吗

2024-03-28 18:06:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我剧本的先决条件

"Generate a string with N opening brackets ("[") and N closing brackets     ("]"), in some
arbitrary order. You will need to use random numbers.
Determine whether the generated string is balanced; that is, whether it     consists entirely of
pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples:
 [] OK ][ NOT OK
[][] OK ][][ NOT OK
[[][]] OK []][[] NOT OK

““

我已经想到了这一点,并认为我已经做了,但我只是相信,它并没有完全越过底线,因为我得到了一个积极的结果“[][”

有人能帮我完成这部分“成对的开合括号(按顺序)”吗

#!/usr/bin/python


import string
import random


def brackets():
count = 0


sample = [random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))] 
sample2 =''.join([random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))])


count1 = sample2.count('[')
count2 = sample2.count(']')


for x in sample2: 
    if x == "[":
        count +=1 
    if x == "]":
        count -=1

if count != 0 or count < 0 :
    print "The generated sample is %s " % (sample2,)
    print "There are %d [ in the generated string" % (count1,)
    print "There are %d ] in the generated string" % (count2,)
    print "This string is Not ok"


if count == 0 :
    print "The generated sample is %s " % (sample2,)
    print "There are %d [ in the generated string" % (count1,)
    print "There are %d ] in the generated string" % (count2,)
    print "This string is ok"



print brackets()

Tags: oftheinstringifiscountok
2条回答

我有个有趣的小主意。它基本上是通过查看是否所有括号对都可以转换为单独的列表来工作的:

from ast import literal_eval

def valid(s):
    if any(c not in '[]' for c in s): return False
    try:
        literal_eval(s.replace('[]', '[],'))
        return True
    except SyntaxError:
        return False

这(我相信)每次都应该奏效,包括你举的例子:

>>> valid('[]')
True
>>> valid('][')
False
>>> valid('[][]')
True
>>> valid('][][')
False
>>> valid('[[][]]')
True
>>> valid('[]][[]')
False

最简单的方法就是使用木桩。下面的代码将为您提供答案:

from pythonds.basic.stack import Stack

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)


print(parChecker('{{([][])}()}'))
print(parChecker('[{()]'))

在这段代码中,每个开始符号都被简单地推到堆栈上,等待匹配的结束符号稍后出现在序列中。当结束符号出现时,我们必须检查它是否与堆栈顶部的开始符号的类型正确匹配。如果两个符号不匹配,则字符串不平衡。如果处理了整个字符串,而堆栈上没有留下任何内容,则该字符串已正确平衡。你知道吗

相关问题 更多 >