尽管"if statement",重复项最终仍在列表中

Ben*_*ker 2 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))
Run Code Online (Sandbox Code Playgroud)

问题是,它仍然提供重复,即使它不应该.例如,我可以输入"imlk"并且有时会获得两次"牛奶",同时仍然只给出24个排列,这意味着排除了一些排列.的:

if new_word not in words:
    words.append(("".join(str(x) for x in new_word)))
    loops -= 1
Run Code Online (Sandbox Code Playgroud)

应该防止副本出现在列表中.所以我不确定问题是什么.对不起,问题的主题是如此模糊/怪异.我不太确定如何更好地说出来.

Jac*_*din 6

怎么样itertools.permutations

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