bleurhgarator
bleurhgarator

Reputation: 13

Calculate the number of unique strings that can be made from a string

If I have a string (e.g. 'AABC'), how can I calculate the number of possible unique strings?

The answer is 12 in this case, but how can I caclulate this with an algorithm?

I could do it for 'ABC', but having the repeated character confuses me.

I'm trying to do it in Python

Edit: Also, I am not looking to generate all the possible strings, only to calculate the number.

Upvotes: 1

Views: 485

Answers (2)

linus
linus

Reputation: 336

You could walk through all the permutations and count the unique one using the itertools module

import itertools

string = "AABC"
count = len(set(itertools.permutations(string)))
print(count)

But since you just need the count, you can do that a bit more easily:

import math
import collections

string = "AABC"

chars = collections.Counter(string)
denominator = reduce(lambda x,y: x * math.factorial(y), chars.values(), 1)
count = math.factorial(len(string)) / denominator
print(count)

Upvotes: 2

heartofrevel
heartofrevel

Reputation: 181

You can do that with itertools module.

Open up your python interpreter.

import itertools
for unique in itertools.permutations("AABC"):
    print "".join(unique)

Just change "AABC" with whatever you want.

Upvotes: 0

Related Questions