我正在尝试构建一个随机单词生成器,它可以随机选择辅音和元音结构(例如,“cvvc”可以是“mean”)。它不起作用。我在调试器中运行它时的问题是while循环末尾的最后两行。在
import random
vowelsList = ['a','e','i','o','u']
constonentsList = ['b','c','d','f','g','h','j','k','l','p','q','r','s','t','u','v','w','x','y','z','th','ch','sh','st','ck']
n = random.randint(1,2)
word = ''
struct = ''
length = 0
x = True
len_con = len(constonentsList)
len_vow = len(vowelsList)
length = 0
while x:
if n == 1:
word += constonentsList[random.randint(0,len_con - 1)]
struct += 'c'
length += 1
elif n == 2:
word += vowelsList[random.randint(0,len_vow - 1)]
struct += 'v'
length += 1
n = random.randint(0,2)
if (length >= 3 & n == 0): #If the word is more than 3 letters and n == 0, don't continue
x = False
print(word)
print(struct)
print(length)
你的代码实际上正在工作,尽管只是这样。长度反映了您生成的辅音和元音的数量,但是生成的单词可以更长,因为您包含两个字母的辅音,如}。不过,还有一些改进需要改进。在
th
和{&
运算符没有执行您认为的操作。它是一个binary bitwise operator;它用整数设置二进制标志:您希望使用^{} operator 来执行布尔逻辑和测试:
^{pr2}$对于布尔值,使用
&
恰好是因为布尔类型重载了运算符以返回布尔值。在通过使用^{} function ,并将终止测试移动到
while
循环条件,可以大大简化程序。length
变量是多余的;您可以在这里使用len(struct)
:相关问题 更多 >
编程相关推荐