获取与单词不同的单词的随机排列
Get a random permutation of a word that is different from the word
我想获得单词字母的随机排列,如果可能,否则就是单词本身。
如何才能有效地做到这一点?
这是我目前拥有的
from itertools import permutations
import random
word = 'some_word'
permutations = [''.join(permutation) for permutation in permutations(word)]
random.shuffle(permutations)
scrambled_word = word
for permutation in permutations:
if permutation != word:
scrambled_word = permutation
break
基本上,我只是得到单词所有排列的第一个排列。我将对很多单词执行此操作,但我发现此方法效率低下。一般情况下,应该没有必要获取给定单词的所有排列。
我想我可以以某种方式拥有一个可迭代的随机排列,我可以从中检索第一个排列。如何在 Python 中完成此操作? itertools
的函数 permutations
是可迭代的,但元素的顺序不是随机的。我需要一个 随机 排列,这样它看起来就不像原来的单词了。
根据 random.shuffle
文档的建议,您可以使用 random.sample
:
scrambled_word = ''.join(random.sample(word, k=len(word)))
这不会阻止您偶尔取回原始单词,因为这是一个有效的排列。如果您不允许使用原件,您将无法获得真正随机的样本。如果需要,您可以过滤掉原件;如果你不喜欢你得到的单词,请再试一次(确保你检测到所有字母都相同的情况):
def scramble(word):
while True:
scrambled_word = ''.join(random.sample(word, k=len(word)))
if scrambled_word != word or all(c == word[0] for c in word):
return scrambled_word
只是添加到@rici 的回答中。此代码将检查单词是否仅由一个字母组成。
代码:
word = "aaa"
while True:
scrambled_word = ''.join(random.sample(word, k=len(word)))
if word.count(word[0]) == len(word) or scrambled_word != word:
break
print(scrambled_word)
我想获得单词字母的随机排列,如果可能,否则就是单词本身。
如何才能有效地做到这一点?
这是我目前拥有的
from itertools import permutations
import random
word = 'some_word'
permutations = [''.join(permutation) for permutation in permutations(word)]
random.shuffle(permutations)
scrambled_word = word
for permutation in permutations:
if permutation != word:
scrambled_word = permutation
break
基本上,我只是得到单词所有排列的第一个排列。我将对很多单词执行此操作,但我发现此方法效率低下。一般情况下,应该没有必要获取给定单词的所有排列。
我想我可以以某种方式拥有一个可迭代的随机排列,我可以从中检索第一个排列。如何在 Python 中完成此操作? itertools
的函数 permutations
是可迭代的,但元素的顺序不是随机的。我需要一个 随机 排列,这样它看起来就不像原来的单词了。
根据 random.shuffle
文档的建议,您可以使用 random.sample
:
scrambled_word = ''.join(random.sample(word, k=len(word)))
这不会阻止您偶尔取回原始单词,因为这是一个有效的排列。如果您不允许使用原件,您将无法获得真正随机的样本。如果需要,您可以过滤掉原件;如果你不喜欢你得到的单词,请再试一次(确保你检测到所有字母都相同的情况):
def scramble(word):
while True:
scrambled_word = ''.join(random.sample(word, k=len(word)))
if scrambled_word != word or all(c == word[0] for c in word):
return scrambled_word
只是添加到@rici 的回答中。此代码将检查单词是否仅由一个字母组成。
代码:
word = "aaa"
while True:
scrambled_word = ''.join(random.sample(word, k=len(word)))
if word.count(word[0]) == len(word) or scrambled_word != word:
break
print(scrambled_word)