Say you have a set of characters (ex. abcdef). I was wondering how I would go about generating all the possible srings I could make with these letters that are size X (ex. 7). I know this will result in a list that is number of characters in set C x in length but am not quite sure how to accomplish it. Any help would be greatly appreciated.

Dani AI

Generated

OP wants all length‑X strings from a given character set and clarified that characters may not repeat. Note: with no repetition the requested length r must be <= number of distinct characters (so asking for length 7 from "abcdef" is impossible without repeats).

suggested combinations; that applies when order does not matter. For strings order matters, so use permutations (arrangements without repetition). The count is P(n,r) = n! / (n-r)!, which is useful to check feasibility before generating anything.

Here is a simple Python generator for permutations (no repeats):

from itertools import permutations

chars = 'abcdef'
r = 3

if r > len(set(chars)):
    raise ValueError('r cannot be larger than number of unique characters')

for p in permutations(chars, r):
    s = ''.join(p)
    print(s)

If repeats are allowed (each position can reuse any character), use Cartesian product instead:

from itertools import product

for p in product(chars, repeat=r):
    print(''.join(p))

Practical notes and pitfalls:

  • Duplicate characters in the input produce duplicate output permutations; remove duplicates from the input first if distinct letters are intended, or filter outputs with a seen set (memory tradeoff).
  • Counts grow very quickly. Compute P(n,r) first (use math.factorial) to avoid attempting to generate billions of strings.
  • For large result sets, stream results to a file or process them on the fly instead of building a list in memory.

This clarifies the permutations vs combinations distinction and gives direct, memory‑friendly Python patterns to generate the required strings.

Recommended Answers

All 3 Replies

Can you repeat characters?

Each character can only be used once in the final string.

Then you want Combinations

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.