Python, Generating random string of brackets

2019-07-03 23:18发布

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.

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,

Thanks.

4条回答
虎瘦雄心在
2楼-- · 2019-07-03 23:41

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]: '[[]][[][]]'

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

查看更多
Rolldiameter
3楼-- · 2019-07-03 23:56

You need to randomly choose from the two characters; you can do this all in one line:

 finallist = [random.choice('[]') for _ in range(random.randint(1, 99))]

You can also simplify the output:

print " ".join(finallist)

An example I just ran:

[ ] ] [ [ [ ] [ ] ] [
查看更多
甜甜的少女心
4楼-- · 2019-07-03 23:56
import random
import string

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

length_to_generate = randomGen(99)
finalist = []
for i in range(length_to_generate):
    if random.randint(0, 1):
        finalist.append("[")
    else:
        finalist.append("]") 

for everChar in finalist:
    print everChar,

You can also generate a string rather than a list:

length_to_generate = randomGen(99)
finalist = ""
for i in range(length_to_generate):
    if random.randint(0, 1):
        finalist += "]"
    else:
        finalist += "["

print finalist
查看更多
Rolldiameter
5楼-- · 2019-07-03 23:58

Well, if you just want to fix your code, you can simply do

finalist = list("".join(finalist))
random.shuffle(finalist)
for everChar in finalist:
    ...

If you want efficient and better ways, please have a look at the other answers.

查看更多
登录 后发表回答