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
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)))
Take a look at the Fisher-Yates shuffle. It's extremely space and time-efficient, and easy to implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With