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 791 times
-2
-
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
2 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
- 115,751
- 26
- 228
- 437
-
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
0
Call this function:
def permutations(word):
if len(word) == 1:
return [word]
perms = permutations(word[1:])
char = word[0]
result = []
for perm in perms:
for i in range(len(perm) + 1):
result.append(perm[:i] + char + perm[i:])
return result

ChrisGPT was on strike
- 127,765
- 105
- 273
- 257
-
1Welcome to Stack Overflow. Code is a lot more helpful when it is accompanied by an explanation. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your answer and explain how it answers the specific question being asked. See [answer]. – ChrisGPT was on strike Jul 10 '22 at 19:16