这是我剧本的先决条件
"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()
我有个有趣的小主意。它基本上是通过查看是否所有括号对都可以转换为单独的列表来工作的:
这(我相信)每次都应该奏效,包括你举的例子:
最简单的方法就是使用木桩。下面的代码将为您提供答案:
在这段代码中,每个开始符号都被简单地推到堆栈上,等待匹配的结束符号稍后出现在序列中。当结束符号出现时,我们必须检查它是否与堆栈顶部的开始符号的类型正确匹配。如果两个符号不匹配,则字符串不平衡。如果处理了整个字符串,而堆栈上没有留下任何内容,则该字符串已正确平衡。你知道吗
相关问题 更多 >
编程相关推荐