Python,生成随机括号串 [英] Python, Generating random string of brackets

查看:42
本文介绍了Python,生成随机括号串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我希望生成方括号的随机长度和模式,[] ][ [] ][ [] [[ ]] []

I am looking to generate random lengths and patterns of square brackets for example, [] ][ [] ][ [] [[ ]] []

到目前为止,我已经设法让我的程序随机生成括号,但是随机生成括号的次数,所以目前我的程序给了我这样的结果,

I have so far managed to get my program to generate brackets randomly, but randomly in terms of how many times it generates them, so currently my program is giving me results such as,

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

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

[][][]

[][][][][]

所以括号内没有随机性,只有括号显示数量的随机性.

So there is no randomness within the brackets, only randomness in the number of brackets displayed.

我想知道如何使括号的顺序随机 ASWELL 作为显示的括号数量.

I want to know how I can make the order of the brackets random ASWELL as the amount of brackets on show.

到目前为止,这是我的代码,

Here is my code so far,

import random
import string

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

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

newValue = randomGen(99)

for i in range(newValue):
    newList = char1
    newList2 = char2
    finalist.append(newList + newList2)

for everChar in finalist:
    print everChar,

谢谢.

推荐答案

您可以使用 random.sample 来选择放置位置的索引,例如左括号.然后在其他地方放置右括号:

You could use random.sample to select the index for where to place, say, left brackets. Then place right-brackets everywhere else:

In [119]: import random

In [122]: N = 10

In [125]: idx = set(random.sample(range(N), N//2))

In [126]: idx
Out[126]: {0, 1, 4, 5, 7}

In [127]: ''.join(['[' if i in idx else ']' for i in range(N)])
Out[127]: '[[]][[][]]'

根据您的示例,我假设您需要相同数量的左右括号.如果没有,请使用 jonrsharpe 的解决方案.

Given your examples, I assumed you want an equal number of left and right brackets. If not, use jonrsharpe's solution.

这篇关于Python,生成随机括号串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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