随机字发生器终止条件故障

2024-10-01 07:42:03 发布

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

我正在尝试构建一个随机单词生成器,它可以随机选择辅音和元音结构(例如,“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)

Tags: lenifrandom单词conlengthstructword
1条回答
网友
1楼 · 发布于 2024-10-01 07:42:03

你的代码实际上正在工作,尽管只是这样。长度反映了您生成的辅音和元音的数量,但是生成的单词可以更长,因为您包含两个字母的辅音,如th和{}。不过,还有一些改进需要改进。在

&运算符没有执行您认为的操作。它是一个binary bitwise operator;它用整数设置二进制标志:

>>> 1 & 1
1
>>> 2 & 1
3

您希望使用^{} operator来执行布尔逻辑和测试:

^{pr2}$

对于布尔值,使用&恰好是因为布尔类型重载了运算符以返回布尔值。在

通过使用^{} function,并将终止测试移动到while循环条件,可以大大简化程序。length变量是多余的;您可以在这里使用len(struct)

import random
import string

vowels = 'aeiou'
consonants = [c for c in string.ascii_lowercase if c not in vowels]
consonants += ['th','ch','sh','st','ck']

n = random.randint(1, 2)
word = ''
struct = ''

while len(struct) < 3 or n:  # minimum length 3
    if n == 1:
        word += random.choice(consonants)
        struct += 'c'
    elif n == 2:
        word += random.choice(vowels)
        struct += 'v'
    n = random.randint(0, 2)

print(word)
print(struct)
print(len(struct))

相关问题 更多 >