how to shuffle a word's letters randomly in python? for example, we have the word "cat". change that randomly to, act, tac or tca and ex.. to be exact,The scrambling process must be implemented manually. Built-in functions or string methods that “automate” this process are prohibited from use. thanks
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)))
return "".join(random.sample(word, len(word)))
Used like:
word = "Pocketknife"
print "".join(random.sample(word, len(word)))
>>> teenockpkfi
Take a look at the Fisher-Yates shuffle. It's extremely space and time-efficient, and easy to implement.
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
word = "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(word)
This won't create all possible permutations with equal probability, but still might be alright for what you want
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
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.
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]