我怎样才能创建一个不包含单词中包含的前一个字母的单词?

How can I create a word that does not contain the previous letter contained in the word?

我看到问题的重点停留在第一个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'}

如有任何帮助,我们将不胜感激。

你想要的应该是这样的(基于你的实现):

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))