How do I shuffle a word's letters randomly in python?
For example, the word "cat" might be changed into 'act', 'tac' or 'tca'.
I would like to do this without using built-in functions
asked Jul 6, 2010 at 1:14
3
import random
word = "cat"
shuffled = list[word]
random.shuffle[shuffled]
shuffled = ''.join[shuffled]
print[shuffled]
...or done in a different way, inspired by Dominic's answer...
import random
shuffled = ''.join[random.sample[word, len[word]]]
answered Jul 6, 2010 at 1:17
icktoofayicktoofay
123k20 gold badges242 silver badges229 bronze badges
6
Take a look at the Fisher-Yates shuffle. It's extremely space and time-efficient, and easy to implement.
answered Jul 6, 2010 at 1:31
derekerdmannderekerdmann
17.2k10 gold badges73 silver badges108 bronze badges
return "".join[random.sample[word, len[word]]]
Used like:
import random
word = "Pocketknife"
print["".join[random.sample[word, len[word]]]]
>>> teenockpkfi
answered Jul 6, 2010 at 1:20
Dominic Bou-SamraDominic Bou-Samra
14.2k26 gold badges97 silver badges153 bronze badges
2
This cookbook recipe has a simple implementation of Fisher-Yates shuffling in Python. Of course, since you have a string argument and must return a string, you'll need a first statement [say the argument name is s
] like ary = list[s]
, and in the return
statement you'll use ''.join
to put the array of characters ary
back into a single string.
answered Jul 6, 2010 at 2:22
Alex MartelliAlex Martelli
822k163 gold badges1202 silver badges1378 bronze badges
To be very slightly more low level, this just swaps the current letter with a random letter which comes after it.
from random import randint
hi = "helloworld"
def shuffle[word]:
wordlen = len[word]
word = list[word]
for i in range[0, wordlen - 1]:
pos = randint[i + 1, wordlen - 1]
word[i], word[pos] = word[pos], word[i]
word = "".join[word]
return word
print[shuffle[hi]]
This won't create all possible permutations with equal probability, but still might be alright for what you want
answered Jul 6, 2010 at 1:38
Jamie WongJamie Wong
17.8k7 gold badges60 silver badges82 bronze badges
1
Here is a way that doesn't use random.shuffle
. Hopefully random.choice
is ok. You should add any restrictions to the question
>>> from random import choice
>>> from itertools import permutations
>>> "".join[choice[list[permutations["cat"]]]]
'atc'
This method is not as efficient as random.shuffle, so will be slow for long words
answered Jul 6, 2010 at 1:48
John La RooyJohn La Rooy
285k50 gold badges357 silver badges498 bronze badges
2
from random import random
def shuffle[x]:
for i in reversed[xrange[1, len[x]]]:
j = int[random[] * [i+1]]
x[i], x[j] = x[j], x[i]
answered Jul 6, 2010 at 11:46
John La RooyJohn La Rooy
285k50 gold badges357 silver badges498 bronze badges
4