Jacob W. Dallas
Jacob W. Dallas

Reputation: 381

Generate Sequence of Characters with a Certain Amount of Each Character

So I'm currently generating a sequence of characters as a string using:

def nth(lists, num):
    res = []
    for a in lists:
        res.insert(0, a[num % len(a)])
        num //= len(a)
    return res

def generate_page(chars, length, iteration):
    result = nth([chars] * length, iteration)
    return "".join(result)

length = 15
seed = 16
number = generate_page('0123456789ABC', length, seed)

But what I can't wrap my head around is how would I generate a sequence of characters if I know how much of each character I want.

For example, let's say I want to generate a sequence that had 1 "A", 3 "B"'s, and 1 "C" how could I get to any arrangement of "ABBBC"?

I'm thinking I would just concatenate a list of the amounts I know I want and then scramble them up like:

A = 1
B = 3
C = 1
listOfCharacters = ["A"]*A + ["B"]*B + ["C"]*C
>>> ['A', 'B', 'B', 'B', 'C']
random.seed(1)
listOfCharacters = random.shuffle(listOfCharacters)
>>> None
listOfCharacters = ''.join(listOfCharacters)
>>> TypeError

But am obviously getting a TypeError at the moment, and am not even sure if this is the best route to retrieve all of the permutations without repeats with a seed.

Upvotes: 2

Views: 579

Answers (3)

Joseph Wood
Joseph Wood

Reputation: 7597

A better approach in order to avoid duplicates is to use the right tool as pointed out by @BillBell here : permutations with unique values. Essentially, we are dealing with Multisets, and using sympy we can get the desired outcome:

from sympy.utilities.iterables import multiset_permutations

for item in multiset_permutations(listOfCharacters):
    print(''.join(item))

ABBBC
ABBCB
ABCBB
ACBBB
BABBC
BABCB
BACBB
BBABC
BBACB
BBBAC
BBBCA
BBCAB
BBCBA
BCABB
BCBAB
BCBBA
CABBB
CBABB
CBBAB
CBBBA

Upvotes: 0

Jacob W. Dallas
Jacob W. Dallas

Reputation: 381

UPDATE: So here is what I ended up doing:

A = 1
B = 3
C = 1
listOfCharacters = ["A"]*A + ["B"]*B + ["C"]*C
>>> ['A', 'B', 'B', 'B', 'C']
random.seed(1)
random.shuffle(listOfCharacters)
listOfCharacters = ''.join(listOfCharacters)
>>>'BBCAB'

And then I just iterated over the shuffle with a for loop.

Upvotes: 0

Eb946207
Eb946207

Reputation: 778

Just do this:

import itertools
match = 'ABBBC' #string of letter combinations to match.
permutations = itertools.permutations(match) #get all
all_combos = list({''.join(per) for per in permutations}) #use sets to remove duplicates

The values of all_combos is a list of all possible combinations.

Upvotes: 1

Related Questions