views:

398

answers:

5

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?

+4  A: 

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.)

Mark Byers
How would this change if I only want the joined-words? In other words, I don't want "a", "b", or "c" alone. (Only the joined words). Thanks.
TIMEX
Updated answer for your new requirements.
Mark Byers
+1  A: 
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

forefinger
thanks forefinger
TIMEX
+1  A: 
>>> 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'
gnibbler
+1  A: 
>>> 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'
gnibbler
ONE LINE_-now that's fucking amazing.
TIMEX
+3  A: 
>>> 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'
gnibbler
Yeah +1: combinations is a good choice here.
Mark Byers