繁体   English   中英

文字游戏python的随机字符

[英]random chars for word game python

def dealHand(n):
    """
    Returns a random hand containing n lowercase letters.
    At least n/3 the letters in the hand should be VOWELS.

    Hands are represented as dictionaries. The keys are
    letters and the values are the number of times the
    particular letter is repeated in that hand.

    n: int >= 0
    returns: dictionary (string -> int)
    """

    hand={}
    numVowels = n / 3

    for i in range(numVowels):
        x = VOWELS[random.randrange(0, len(VOWELS))]
        hand[x] = hand.get(x, 0) + 1

    for i in range(numVowels, n):
        x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
        hand[x] = hand.get(x, 0) + 1

    return hand

这个函数是我必须制作的文字游戏的一部分,它被包含在一些帮助函数中以帮助入门,我的问题是它返回的字母不是很随机,有很多重复的字母如: aaccbeegjjmmmoortvyx ,I我只是想知道是否有可能得到一组更随机的字符?

“它返回的字母不是很随机,有很多重复的字母” - 说真的吗?

如果你想得到没有重复的n个字母,请使用以下内容:

from random import shuffle
alphabet = ['a', .., 'z']
shuffle(alphabet)
print(alphabet[:n])

如果n> len(字母表),无论如何你都会重复。

这是一个更紧凑的算法表示:

from __future__ import division
from collections import Counter
import random
import string

VOWELS = "aeiou"
CONSONANTS = "".join(set(string.lowercase) - set(VOWELS))

def dealHand(n):
    numVowels = n // 3
    lettersets = [VOWELS] * numVowels + [CONSONANTS] * (n - numVowels)
    return Counter(c
        for letterset in lettersets
        for c in random.choice(letterset)
    )

看似随机。


后来:“如果我希望信件出现不超过两次,我怎么能实现这一目标呢?”

好吧,你可以这样做,但我不推荐这个:

def dealHand2(n):
    while True:
        candidate = dealHand(n)
        if all(v <= 2 for v in candidate.values()):
            return candidate

这是一个无限循环,直到找到一组满足您条件的字母。 运行时间:不确定。

在这个版本中,你的元音数量应该是辅音的三倍,但确切的数字并不能保证。

import collections
import random

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

def dealHand(n):
 letters = 3 * VOWELS + CONSONANTS 
 collections.Counter(random.sample(letters, n))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM