使用Python中不同列表中的随机字母生成单词

时间:2017-03-24 01:08:03

标签: python random

我需要创建一个从三个不同列表/字符串中随机选择的单词列表,并遵循以下规则:

sem_t* proc_semaphore = sem_open(SEM_PROC, O_CREAT, "0777", 0);
if (proc_semaphore == SEM_FAILED) {
    perror("ERROR:");// e.g. "ERROR: Permission denied" or similar
    exit(1);
}

所有字母都应该从列表a = ["p","r","s","t","v"] b = ["a","e","i"] c = "ing" a中随机选择,新列表中的字词应格式为ba+b+a+c。这些单词也不应包含任何b+b+a+c。任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

根据我的其他解决方案的反馈,这是一种方法的变化:

from random import choice

d = {"a": ["p","r","s","t","v"], "b": ["a","e","i"], "c": "ing"}
pattern1, pattern2 = 'abac', 'bbac'

def create_word():

    pattern_to_use = choice([pattern1, pattern2])
    while True:
        word = "".join([choice(d[x]) if isinstance(d[x], list) else d[x] for x in pattern_to_use])
        if "te" not in word:
            return word

print(create_word())

可以根据需要更改模式字符串和字母选择数据,而无需修改create_word()功能。

答案 1 :(得分:0)

这种方法使用单一模式,因为两种模式几乎相同。它还故意避免递归。

from random import choice

a = ["p","r","s","t","v"]
b = ["a","e","i"]
c = "ing"

def random_word():
    while True:
        word = choice(choice((a, b))) + choice(b) + choice(a) + c
        if 'te' not in word:
            return word

样本用法:

for _ in range(5):
  print(random_word())

aesing
vering
eating
seting
eaping

如果你想要列表中的单词,这是一个例子:

words = [random_word() for _ in range(5)]

答案 2 :(得分:-1)

只是一个想法:

from random import choice
words = []
while True:
    ran_a, ran_b, ran_c = choice(a), choice(b), choice(c)
    word = ''.join([ran_a, ran_b, ran_c])
    if word.find('te') < 0 or word in words:
        continue
    words.append(word)
    # You can define the termination condition according to requirements