python - 尽管有 "if statement",但重复项最终出现在列表中

标签 python python-3.x

好的,我正在研究一个代码,它可以给出您输入的乱序字母的所有可能组合。在这里:

import random, math

words = []
original = raw_input("What do you need scrambled? ")

def word_scramble(scrambled):

    original_length = len(scrambled)
    loops = math.factorial(original_length)

    while loops > 0:
        new_word = []

        used_numbers = []

        while len(new_word) < original_length:

            number = random.randint(0, original_length - 1)

            while number in used_numbers:
                number = random.randint(0, original_length - 1)

            while number not in used_numbers:
                used_numbers.append(number)
                new_word.append(scrambled[number])

        if new_word not in words:
            words.append(("".join(str(x) for x in new_word)))
            loops -= 1

word_scramble(original)

print ("\n".join(str(x) for x in words))

问题是,它仍然会给出重复项,即使它不应该这样做。例如,我可以输入“imlk”,有时会得到两次“milk”,但仍然只给我 24 个排列,这意味着一些排列被排除在外。的:

if new_word not in words:
    words.append(("".join(str(x) for x in new_word)))
    loops -= 1

应该防止重复出现在列表中。所以我不太确定问题出在哪里。很抱歉,问题的主要标题是如此模糊/奇怪。我真的不确定如何更好地表达它。

最佳答案

itertools.permutations 怎么样?

import itertools
original = raw_input("What do you need scrambled? ")
result = [''.join(s) for s in itertools.permutations(original)]

关于python - 尽管有 "if statement",但重复项最终出现在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209750/

相关文章:

python - Django Tastypie v0.11.1,POST请求,无法使用obj_create保存数据

python - 调用类并不运行方法

python - 将 matplotlib 文件保存到目录

python - Python 主要版本升级后自动将包重新安装到虚拟环境中

python-3.x - Pandas 的 str.strip 性能

python-3.x - 在 Docker 镜像中安全地存储哈希

python - xbmc/kodi python 使用 BeautifulSoup 抓取数据

python 类命名空间和 init 函数

python - 在python中将字符串写入文件

python - 有没有办法在 python 中将 SQL 表用作类或对象?