Python中输入的Anagram生成器故障

2024-06-02 05:55:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着编写一个简单的生成器,它由一个输入组成一个anagram列表。但在我重写代码后,它只给我2个输出。这是密码

import random
item=input("Name? ")
a=''
b=''
oo=0
while oo<=(len(item)*len(item)):
    a=''.join([str(y) for y in random.sample(item, len(item))]) #this line was found on this site
    b=''.join([str(w) for w in random.sample(item, len(item))]) #because in no way i had success in doing it by myself
    j=[]
    j.append(a) #During the loop it should add the anagrams generated
    j.append(b) #everytime the loop repeats itself
    oo=oo+1
j=list(set(j)) #To cancel duplicates
h=len(j)
f=0
while f<=(h-1):
    print(j[f])

但它给出的输出只是一个永远重复的字谜。在


Tags: thesampleinloopforlenitrandom
2条回答

循环构造有几个问题,包括每次都重新初始化结果。尝试一种更简单的方法,即事物已经是它们想要的类型,而不是不断地转换。不是所有你想做的事情都需要一个循环:

import random

item = input("Name? ")

length = len(item)

anagrams = set()

for repetitions in range(length**2):
    anagrams.add(''.join(random.sample(item, length)))

print("\n".join(anagrams))

然而,这些字谜并不是详尽无遗的(随机性意味着会漏掉一些),它们也不是真正的字谜,因为没有字典来帮助生成实际的单词,只是随机字母。在

据我所见,你在结尾处没有增加f。 做得更像:

for item in j:
   print( item )

另一件事是,在每个循环中重写j。你确定你想要那样吗?在

相关问题 更多 >