Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
TIMEX Avatar asked Feb 19 '10 21:02

TIMEX


People also ask

How do you write permutations in Python?

The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.

How do you code a combination in Python?

To calculate combinations in Python, use the itertools. combinations() method. The itertools. combinations() method takes an iterator as an argument and returns all the possible combinations of elements in the iterator.

How do you find the combination of a string in Python?

To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.


3 Answers

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

like image 53
Mark Byers Avatar answered Oct 16 '22 14:10

Mark Byers


>>> 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'
like image 33
John La Rooy Avatar answered Oct 16 '22 13:10

John La Rooy


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

like image 31
forefinger Avatar answered Oct 16 '22 14:10

forefinger