2016-07-28 59 views
-1

我看问题的角度停留在第一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

根据你的问题的标题,你的输出是正确的。这些'单词'都不包含出现在单词前的单词。 – usr2564301

+0

也许你想改变'如果单词不在词汇中:'用'如果单词不在词汇表中。():' –

+0

“cuu”包含比我想要的多一个。 'vd'包含两个辅音。每一对两个字母只需要一个元音和一个辅音。 –

回答

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

看起来像你在第一个控件中使用辅音,在第二个控件中使用元音。在我的最新版本中,我用相反的方式。但我不明白为什么我有不同的结果 –

+0

我用“如果单词[-1]不在元音和字母表[random_letter]不在元音:” 您使用 “如果单词[-1]不在元音和字母[random_letter]不是在辅音:“ 现在我明白了 –

+0

很高兴帮助:) – Sygmei

相关问题