0

Hi I trying to create function with string argument and return ordered permutation dict. Example:

word = 'abc'; func(word) - > [a, b, c, ab, ac, bc, abc]

Sergey Arenzon
  • 325
  • 4
  • 17
  • 4
    This is called the [powerset](https://docs.python.org/3/library/itertools.html?highlight=powerset). Look under itertools recipies – Chris Charley Dec 22 '19 at 17:00
  • Why is bc before abc? – Luka Rahne Dec 22 '19 at 17:08
  • 1
    @ChrisCharley Nitpicking: powerset *without* the empty set. – Bakuriu Dec 22 '19 at 17:17
  • 1
    Does this answer your question? [How to get all subsets of a set? (powerset)](https://stackoverflow.com/questions/1482308/how-to-get-all-subsets-of-a-set-powerset). Or [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – wwii Dec 22 '19 at 17:21

3 Answers3

1

itertools.combinations returns in lexicographical order

Somthing like

def word(w):
   for i in range(len(w)):
      yield from itertools.combinations(w,i+1)

Edir:

This is wrong just like powerset, because it does not return all results in lexicographical order.

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
0

I think you are referring to a combination. Permutations are combinations where the different orders in the elements take importance. If combinations of 'ab' look like ['a', 'b', 'ab'], a permutation looks like ['a', 'b', 'ab', 'ba']

from itertools import combinations

word = 'abc'
my_list = []
for n in range(len(word)):
    my_list.extend([''.join(x) for x in combinations(word, n + 1)])

print(my_list)

Result:

['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
Lucas Vazquez
  • 1,456
  • 16
  • 20
0

def toString(List): return ''.join(List)

def permute(a, l, r): 
if l==r: 
    print toString(a) 
else: 
    for i in xrange(l,r+1): 
        a[l], a[i] = a[i], a[l] 
        permute(a, l+1, r) 
        a[l], a[i] = a[i], a[l]
string = "ABC"
    n = len(string) 
    a = list(string) 
    permute(a, 0, n-1) 
Uday Kiran
  • 229
  • 2
  • 13