【问题标题】:random chars for word game python文字游戏python的随机字符
【发布时间】:2013-03-20 17:07:06
【问题描述】:
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

这个函数是我做的一个文字游戏的一部分,它包含在一些帮助函数中以帮助开始,我的问题是它返回的字母不是很随机,有很多重复的字母,例如: a a c c b e e g j j m m m o o r t v y x,我只是想知道是否有可能获得更随机的字符集?

【问题讨论】:

  • 你有没有调用过random.seed()?必须调用种子才能初始化随机数生成器。
  • 不,您不必调用random.seed,当前系统时间用于在模块首次导入时初始化生成器。
  • 你能用散文(不是代码)解释你想要什么吗?
  • 这看起来像他想要的:“返回一个包含 n 个小写字母的随机手。至少 n/3 [of] 个手应该是元音。”

标签: python random chars


【解决方案1】:

下面是您的算法的更简洁的表示:

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

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

【讨论】:

  • 谢谢,这似乎提供了更好的选择,如果我希望字母出现不超过两次,我该如何实现?
  • 谢谢,我真的只是想根据手牌的处理方式找到一种让游戏更容易或更难的方法。我相信有更好的方法,但我刚刚开始编程,所以这是迄今为止我所能达到的技术水平,我会将你的第一个答案标记为最好的,因为它解决了我原来的问题,再次感谢您的输入
【解决方案2】:

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

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

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

如果 n > len(alphabet),无论如何你都会得到重复。

【讨论】:

    【解决方案3】:

    在这个版本中,从统计上讲,元音的数量应该是辅音的三倍,但不能保证确切的数量。

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

    【讨论】:

    • 回复:“元音是辅音的三倍”。为什么元音比辅音多三倍?您的字符串中有 15 个元音和 21 个辅音。
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多