How to generate all character set combinations without repeating?

I have the following list:

['a', 'b', 'c']

I am exploring a way to generate all possible strings containing these characters, with the following restrictions:

  • The icon may not appear multiple times ( aab, aba, abcaetc. is invalid)
  • a character can be excluded (for abexample, even if it cdoes not exist; aalso valid, even if bit is cnot present)

I can use

[''.join(p) for p in permutations('abc')]

to generate all lines containing a, band c. However, I must also do

[''.join(p) for p in permutations('ab')]
[''.join(p) for p in permutations('ac')]
[''.join(p) for p in permutations('bc')]

, , , , . Python, :

def generate(vals=['a', 'b', 'c']):
  # The initial list of allowed characters also has to be part of the 
  # final list since these also represent valid values
  res = vals
  # Generate all possible strings and store in res

  return res

, POST -, ( val) ( , ), . , , , val.

( "a", "ab", "ac", "abc", "b", "ba", 'bc' ..), , .

+4
3

, , , .

from itertools import permutations as p

def gen(lst):
    y = [[a for a in p(lst,y)] for y in range(1,len(lst)+1)]

    this = []
    for i in y:
        while len(i)>0:
            this.append(i.pop())
    return [''.join(x) for x in this]

print(gen(['a','b','c']))
+1

:

import itertools

def generate(vals="abc"):
    return ("".join(x) for x in itertools.chain.from_iterable(itertools.permutations(vals,i+1) for i in range(0,len(vals))))

print(list(generate("abc"))) # force iteration to print result

:

['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']

: , poweret ( ?), , (abc cba - 2 ) str.join .

+2

You can use recursion with a generator expression:

def permutation(s, current = []):
   if len(current) == len(s):
      yield current
   else:
      yield current
      for i in s:
        if current.count(i) == 0:
            for h in permutation(s, current + [i]):
               yield h

print(map(''.join, list(permutation(['a', 'b', 'c']))[1:]))

Conclusion:

['a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac', 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']
+1
source

Source: https://habr.com/ru/post/1694301/


All Articles