TIMEX
TIMEX

Reputation: 271684

Combining words in Python (permutations?)

Suppose I have 4 words, as a string. How do I join them all like this?

s = orange apple grapes pear

The result would be a String:

"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"

I am thinking:

list_words = s.split(' ')
for l in list_words:

And then use enumerate? Is that what you would use to do this function?

Upvotes: 5

Views: 3867

Answers (5)

John La Rooy
John La Rooy

Reputation: 304137

>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> '/'.join([''.join(y) for y in [ x for z in range(len(s)) for x in combinations(s,z)] if len(y)>1])
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear'

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304137

>>> s = "orange apple grapes pear".split()
>>> '/'.join(''.join(k) for k in [[s[j] for j in range(len(s)) if 1<<j&i] for i in range(1<<len(s))] if len(k)>1)
'orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear/orangeapplegrapespear'

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304137

>>> import itertools
>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> res=[]
>>> for i in range(2,len(s)+1):
...     res += [''.join(x) for x in combinations(s,i)]
... 
>>> '/'.join(res)
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear/orangeapplegrapespear'

Upvotes: 1

forefinger
forefinger

Reputation: 3857

s = 'orange apple grapes pear'

list_words = s.split()

num = len(list_words)
ans = []
for i in xrange(1,2**num-1):
  cur = []
  for j,word in enumerate(list_words):
    if i & (1 << j):
      cur.append(word)
  if len(cur) > 1: 
    ans.append(''.join(cur))
print '/'.join(ans)

This gives all subsets of the list of words except the empty one, single words, and all of them. For your example: orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838096

Maybe this is what you want?

s = "orange apple grapes pear"

from itertools import product
l = s.split()
r='/'.join(''.join(k*v for k,v in zip(l, x))
           for x in product(range(2), repeat=len(l))
           if sum(x) > 1)
print r

If run on 'a b c' (for clarity) the result is:

bc/ac/ab/abc

(Updated after comment from poster.)

Upvotes: 4

Related Questions