我发现问题的重点在于elif
:
import random as rnd
vowels="aeiou"
consonants="bcdfghlmnpqrstvz"
alphabet=vowels+consonants
vocabulary={}
index=0
word=""
positions=[]
while index<5:
random_lenght=rnd.randint(2,5)
while len(word)<random_lenght:
random_letter=rnd.randint(0,len(alphabet)-1)
if len(word)==0:
word+=alphabet[random_letter]
elif random_letter != positions[-1] and len(word)>0:
if word[-1] not in vowels:
word+=alphabet[random_letter]
if word[-1] not in consonants:
word+=alphabet[random_letter]
elif random_letter == positions[-1]:
break
if random_letter not in positions:
positions.append(random_letter)
if word not in vocabulary:
vocabulary[index]=word
index+=1
word=""
结果并不像我想的那样满足我:
{0: 'in', 1: 'th', 2: 'cuu', 3: 'th', 4: 'vd'}
任何帮助都将不胜感激。
答案 0 :(得分:0)
你想要的应该是这样的(基于你的实现):
import random as rnd
vowels="aeiou"
consonants="bcdfghlmnpqrstvz"
alphabet=vowels+consonants
vocabulary={}
index=0
word=""
positions=[]
while index<5:
random_lenght=rnd.randint(2,5)
while len(word)<random_lenght:
random_letter=rnd.randint(0,len(alphabet)-1)
if len(word) == 0:
word+=alphabet[random_letter]
elif random_letter != positions[-1] and len(word)>0:
if word[-1] not in vowels and alphabet[random_letter] not in consonants:
word+=alphabet[random_letter]
elif word[-1] not in consonants and alphabet[random_letter] not in vowels:
word+=alphabet[random_letter]
if random_letter not in positions:
positions.append(random_letter)
if word not in vocabulary:
vocabulary[index]=word
index+=1
word=""
另一个版本:
import string
import random
isVowel = lambda letter: letter in "aeiou"
def generateWord(lengthMin, lengthMax):
word = ""
wordLength = random.randint(lengthMin, lengthMax)
while len(word) != wordLength:
letter = string.ascii_lowercase[random.randint(0,25)]
if len(word) == 0 or isVowel(word[-1]) != isVowel(letter):
word = word + letter
return word
for i in range(0, 5):
print(generateWord(2, 5))