user14587018
user14587018

Reputation:

Number of combinations of n terms

Is there an algebraic formula to tell me the different combinations of n temrs?

If I have:

{0: ['Hello!']}

{1: ['Welcome']}

{2: ['to']}

All the combinations would be:

['Hello!',  'Welcome', 'to'],
['Hello!',  'to',      'Welcome'],
['Welcome', 'Hello!',  'to'],
['Welcome', 'to',      'Hello!'],
['to',      'Hello!',  'Welcome'],
['to',      'Welcome', 'Hello!'],

But what is the formula that describes this? Then I would use the formula to write my program and create all the possible triplets from the words I have available. I have looked at this link but havent figured out the anser:

https://www.mathsisfun.com/combinatorics/combinations-permutations.html

Upvotes: 1

Views: 90

Answers (2)

Ismail H Rana
Ismail H Rana

Reputation: 371

You need the permutations of n terms, itertools has a permutations method. You can use it as follows:

import itertools

lst = ['A', 'B', 'C', 'D']
z = itertools.permutations(lst, len(lst))

print(list(z))

If you want to learn more: https://docs.python.org/3/library/itertools.html#itertools.permutations

import itertools

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in itertools.product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

lst = ['A', 'B', 'C', 'D']
z = permutations(lst, len(last))

print(list(z))

Upvotes: 4

orlp
orlp

Reputation: 117681

What you're describing is the number of permutations of n objects. There are n! = 1 × 2 × ... × n (also known as n factorial) such permutations.

Upvotes: 4

Related Questions