4

I have 3 strings:

strand1 = "something"
strand2 = "something else"
strand3 = "something else again"

I want to run a few functions on each possible arrangement of those 3 strings, e.g.:

Case 1:

strand1 = "something else again"
strand2 = "something"
strand3 = "something else"

Case 2

strand1 = "something else"
strand2 = "something else again"
strand3 = "something"

etc ...

How would I do that elegantly in Python? I considered putting the strings in an array and using itertools but it seems to cut the strings at each iteration.

Another thing to consider is that the strings are stored in an object. For example I call strand1 by typing

strand1.aa

Thanks for any help, I hope that the question is clear.

Silas Parker
  • 8,017
  • 1
  • 28
  • 43
cachemoi
  • 343
  • 2
  • 13

2 Answers2

3

itertools is the right place to look. Have you tried itertools.permutations?

Check out the documentation for it.

Something on the ways of itertools.permutations(iterable) will give you a generator of permutations, then you could use a for loop to process each permutation.

from itertools import permutations

# Any iterable will do. I am using a tuple.
for permutation in permutations(('a', 'b', 'c')):  # Use your strings
    print(permutation)  # Change print() to whatever you need to do with the permutation

This sample produces

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
Bernardo Sulzbach
  • 1,293
  • 10
  • 26
  • 1
    Should've posted a sample code demonstrating the application of your answer .. just to be more complete.. – Iron Fist Apr 05 '16 at 16:47
  • @IronFist I agree. If I don't solve his problem explicitly there is no issue with it. There it is. I've passed the permutations as a tuple as we already have an example of the star operator. – Bernardo Sulzbach Apr 05 '16 at 16:59
3

You may use itertools.permutations. If function has multiple argument, you may pass them via splat operator.

import itertools

def f(a, b, c):
    print(a, b, c)

# o = get_my_object()
# seq = [o.a, o.b, o.c]
seq = ['s1', 's2', 's3']
for perm in itertools.permutations(seq):
    f(*perm)

Output:

s1 s2 s3
s1 s3 s2
s2 s1 s3
s2 s3 s1
s3 s1 s2
s3 s2 s1
Community
  • 1
  • 1
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93