I need help making a program that takes a string using args and randomizes it into every possibility. The program's results would then be saved into a text file provided by the user when executing the program.
Asked
Active
Viewed 708 times
-1
-
3Unless your string is very short, there are going to be too many possibilities for it to be practical to list them all. – DSM Jan 27 '14 at 16:53
-
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) – user1251007 Jun 25 '14 at 13:42
1 Answers
2
If you need all of the possible permutations in a random order, then I would suggest building then shuffling a list:
from itertools import permutations
from random import shuffle
def shuffled_permutations(s):
perms = list(permutations(s)) # create all permutations
shuffle(perms) # shuffle the list randomly
return ["".join(p) for p in perms] # rebuild strings and return
Applying this function:
>>> shuffled_permutations("ABC")
['BCA', 'CBA', 'BAC', 'ABC', 'ACB', 'CAB']
If you don't really need the permutations in a random order (i.e. you just want to know what they all are), it is much more efficient to use permutations directly, e.g.
for p in permutations(s):
Note that, for a string len(s) == n, the length of all permutations is n! (e.g. for n == 5, (5 * 4 * 3 * 2 * 1) == 120); this gets long pretty fast (there are 3,628,800 permutations of my user name, for example).
jonrsharpe
- 107,083
- 22
- 201
- 376
-
To make it more effiecient, turn this function into a generator and drop the shuffle method – smac89 Jan 27 '14 at 16:54
-
Then you can just call `permutations` directly! But if the OP doesn't need the `shuffle` that's the way to go. – jonrsharpe Jan 27 '14 at 16:57