2013-03-20 68 views
0
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,我只是想知道是否有可能得到一個更隨機的字符集?的文字遊戲蟒蛇隨機字符

+0

你有沒有打電話給random.seed()?必須調用種子才能初始化隨機數生成器。 – 2013-03-20 17:13:29

+1

不,您不必調用'random.seed',當模塊第一次導入時,使用當前系統時間來初始化發生器。 – Matthias 2013-03-20 17:18:04

+0

你能解釋一下你想散文(而不是代碼)嗎? – 2013-03-20 18:00:26

回答

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 

這是一個無限循環,直到找到一組字母,滿足您的條件。運行時間:不確定。

+0

謝謝,這似乎是給予更好的選擇,如果我想讓信件出現不超過兩次,我怎麼能實現這一點? – 2013-03-20 18:16:10

+0

謝謝,我真的只是想找到一種方法來讓遊戲變得更容易或更困難,這取決於雙手的處理方式。我相信有更好的方法,但我剛剛開始編程,所以這是儘可能技術性的,因爲我可以得到迄今爲止,我將標記您的第一個答案,因爲它解決了我的原始問題,再次感謝輸入 – 2013-03-20 18:41:40

1

「它返回的字母不是很隨機,有很多重複的字母」 - 嚴重嗎?

如果你想獲得N個字母不重複,使用這樣的:

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

如果n> LEN(字母),你會得到重複反正。

0

在這個版本中,你應該有比輔音多三倍的元音,但確切的數字是不能保證的。

import collections 
import random 

VOWELS = 'aeiou' 
CONSONANTS = 'bcdfghjklmnpqrstvwxyz' 

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

回覆: 「比輔音多三倍」。爲什麼你會比輔音多出三倍的元音?你的字符串中有15個元音和21個輔音。 – hughdbrown 2013-03-20 18:22:43