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?
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}.
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.
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.
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.)
>>> 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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With