知恵袋のカードの確率の問題をPythonで解いてみました。前回の問題の類題です。(^_^;
赤青黄緑黒のカードが4枚ずつ計20枚ある。各色のカードには1から4までの数字が1つずつ書かれている。3枚同時に引いたとき
次の確率を求めよ
(1)赤色のカードが1枚だけ含まれている確率
(2)3枚のカードの数字がすべて異なる確率
(3)3枚のカードの色も数字もすべて異なる確率
(4)2枚のカードだけ数字が等しい確率
拙ブログのTrump1.pyを雛形にしました。(^_^;
カードに、0〜19の通し番号を与えると、4で割った商で色、4で割った余りからそれに1を加えてランク(番号)を得ることができます。
sColor: ('R','B','Y','G','K') = n: (0,1,2,3,4) = (赤,青,黄,緑,黒) sRank : ('1','2','3','4') = n: (0,1,2,3) = (1,2,3,4) 0 1 2 3 1 2 3 4: Rank 0 R 0 1 2 3 1 B 4 5 6 7 2 Y 8 9 10 11 3 G 12 13 14 15 4 K 16 17 18 19 Color
黒を1文字で表すのに、青で'B'が使われているので、'K'にしました。(^_^;
2枚のカードだけ数字が等しい条件は、len(set([p%N,q%N,r%N]))==2としました。
ちなみに、(4)は、知恵袋の回答と結果が異なりますが、「2枚のカードだけ色が等しい確率」を求められているようです。(^_^;
● ColorCard2.py
# coding: UTF-8 # ColorCard2.py import itertools from time import time from fractions import Fraction COLOR = 'RBYGK' RANK = '1234' N = len(RANK) # sColor: 'R','B','Y','G','K' def countColor(sColor, lCards): li = [x//N for x in lCards] return li.count(COLOR.index(sColor)) def toStrCards(lCards): result = '' for c in lCards: result += ','+COLOR[c//N]+RANK[c%N] return '(' + result[1:] + ')' def main(): tm=time() # Timer Start Cards = range(20) count = [0]*4 total = 0 for c in itertools.combinations(Cards,3): p,q,r = c total+=1 if countColor('R',c)==1: count[0]+=1 if len(set([p%N,q%N,r%N]))==3: count[1]+=1 if len(set([p//N,q//N,r//N]))==3: count[2]+=1 if len(set([p%N,q%N,r%N]))==2: count[3]+=1 # カードを表示 ## print(toStrCards(c)) for i in range(4): print("(%d) %d/%d = %s"%(i+1,count[i],total,Fraction(count[i],total))) print("Runtime : %.3f [sec]"%(time()-tm)) # Timer Stop & Disp if __name__ == '__main__': main()
●実行結果
(1) 480/1140 = 8/19 (2) 500/1140 = 25/57 (3) 240/1140 = 4/19 (4) 600/1140 = 10/19 Runtime : 0.010 [sec]
※参考URL
●知恵袋のカードの確率の問題をPythonで解いてみた。
●Python組み込みクラス(set 集合型)を使った論理式 - 今日のPython