Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffling a word

Tags:

python

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

like image 608
babikar Avatar asked Jul 06 '10 01:07

babikar


2 Answers

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)))
like image 102
icktoofay Avatar answered Oct 20 '22 02:10

icktoofay


Take a look at the Fisher-Yates shuffle. It's extremely space and time-efficient, and easy to implement.

like image 7
derekerdmann Avatar answered Oct 20 '22 00:10

derekerdmann