开发者

shuffling a word

开发者 https://www.devze.com 2023-01-06 14:15 出处:网络
How do I shuffle a word\'s letters randomly in python? For example, the word \"cat\" might be changed i开发者_如何学编程nto \'act\', \'tac\' or \'tca\'.

How do I shuffle a word's letters randomly in python?

For example, the word "cat" might be changed i开发者_如何学编程nto '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.


return "".join(random.sample(word, len(word)))

Used like:

import random
word = "Pocketknife"
print("".join(random.sample(word, len(word))))

>>> teenockpkfi


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.


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


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


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消