0

i am trying to make an if statement but i realized that i need to test the string with the words in every possible arrangement. so how might I go about this.

here is my code

string = ("red blue black")

if string == "red blue black":
    print("cool")
jacky d
  • 5
  • 3
  • Possible duplicate of [How to generate all permutations of a list in Python](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – mkrieger1 Jan 16 '17 at 11:33

1 Answers1

0

If I understand your goal correctly, you want to create an if statement that creates all arrangements of your string variable, then test if your "string" is in any of those arrangements.

All arrangements of a list would be the "permutations", so you can use permutation of itertools module:

import itertools

string = ("red blue black")

all_arrangements = list(itertools.permutations(string.split()))

if string in [' '.join(i) for i in all_arrangements]:
    print "cool"

Since the arrangements are generated based on your string, you can expect your if statement will be satisfied, and "cool" will always be printed, unless you further change the logic of the if statement.

To better explain what's going on in the code above, you could replace the above if statement block with the following code, and confirm which arrangement of your string matches:

print "checking for ", string

for arrangement in all_arrangements:
    if string == ' '.join(arrangement):
        print arrangement , "cool"
    else:
        print arrangement

output:

checking for  red blue black
('red', 'blue', 'black') cool
('red', 'black', 'blue')
('blue', 'red', 'black')
('blue', 'black', 'red')
('black', 'red', 'blue')
('black', 'blue', 'red')

Hope this helps.