确定字符串的结构

2024-09-28 01:26:33 发布

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

我有一个显示方括号的程序,'['']'。它以随机顺序和随机次数(最多99次)显示它们。你知道吗

下面的代码是我当前的代码,每次运行模块时都会显示如下内容。你知道吗

输入:

[[[[]]]]
[][]][]][[][]
[]]]][[[[[[]]][][][[]

我的代码:

import random
import string

def randomGen(N):
    return random.randint(1,N)

char1 = '['
char2 = ']'
finalist = []
newList = []
newList2 = []

newValue = randomGen(99)
newValue2 = randomGen(99)

for i in range(newValue):
    newList.append('[')

for j in range(newValue2):
    newList2.append(']')

finalist = newList + newList2

for everChar in finalist:
    print everChar,

我现在想让程序告诉用户显示的括号是平衡的还是不平衡的。我的意思是它是否由完全嵌套的对组成。你知道吗

所以'[][][]'是平衡的,'[]]][[]'是不平衡的。你知道吗

当我的模块运行时,我希望它显示一些关于括号的'balanced''unbalanced'的文本。你知道吗

我已将此添加到我的代码中,我不确定为什么它不起作用,但我认为我的思路是正确的:

def balanced(input):
  opened = 0
  for c in input:
    if c == '[':
      openend += 1
    elif c == ']':
      opened -= 1

    if opened < 0:
        print 'Not Balanced'

    if opened > 0:
        print 'Not Balanced'

    if opened == 0:
        print 'Balanced'

        print opened
  return opened == 0

Tags: 模块代码inimport程序forifrandom
2条回答

对于按任意顺序由[]组成的一般输入:

def balanced(input):
  opened = 0
  for c in input:
    if c == '[':
      opened += 1
    elif c == ']':
      opened -= 1
    if opened < 0:
      return False
  return opened == 0

对于这段代码,您只需检查if newValue == newValue2。你知道吗

相关问题 更多 >

    热门问题