知恵袋で見つけた判断推理のトランプの問題をPythonで解いてみました。(^_^;
トランプの4種類のマークのカードがそれぞれ5枚ずつ計20枚あり、どの種類のカードにもキングとエースが含まれている。この20枚をA〜Dの4人に5枚ずつ配ったところ、次のことがわかった。
・Aの持ち札には、同じ種類のカードが4枚あり、エースが2枚あった。
・Bの持ち札には、ハートが3枚クラブが1枚あり、キングが3枚あった。
・Cの持ち札には、ハートが1枚、スペードが3枚あった。
・Dの持ち札には、すべての種類があり、キングとエースが1枚ずつあった。
これらのことから、確実にいえるものは次のうちどれか。
①Aはクラブのエースを持っている。
②Bはハートのエースを持っている。
③Cはスペードのエースを持っている。
④Dはダイヤを2枚持っている。
⑤Dはクラブを1枚しか持っていない。
ただし、選択肢①は、「クラブとエース」→「クラブのエース」に修正しました。(^_^;
トランプに、0〜19の通し番号を与えて、5で割った商でスート(絵柄マーク)、5で割った余りからランク(番号)を得ることにします。
sSuit: ('S','D','C','H') = n: (0,1,2,3) = (スペード,ダイア,クラブ,ハート) sRank: ('K','A','2','3','4') = n: (0,1,2,3,4) = (キング,エース,2,3,4) 0 1 2 3 4 K A 2 3 4 : Rank 0 S 0 1 2 3 4 1 D 5 6 7 8 9 2 C 10 11 12 13 14 3 H 15 16 17 18 19 Suit
● Trump1.py
# coding: UTF-8 # Trump1.py import itertools from time import time SUIT = 'SDCH' RANK = 'KA234' # sRank: 'K','A','2','3','4' def countRank(sRank, cards): n = RANK.index(sRank) count = 0 for c in cards: if c%5==n: count+=1 return count # sSuit: 'S','D','C','H' def countSuit(sSuit, cards): n = SUIT.index(sSuit) count = 0 for c in cards: if c//5==n: count+=1 return count def countSuits(cards): return [countSuit(SUIT[i],cards) for i in range(4)] # suitとrankから通し番号を得る def getN(sSuit,sRank): return SUIT.index(sSuit)*5+RANK.index(sRank) def toStrCards(cards): result = '' for c in cards: result += ','+SUIT[c//5]+RANK[c%5] return "(" + result[1:] + ")" def main(): tm=time() # Timer Start choices = [True]*5 Cards = range(20) for a in itertools.combinations(Cards,5): if not 4 in countSuits(a): continue # 条件A-1 if countRank('A',a)!=2: continue # 条件A-2 rA = [x for x in Cards if not x in a] # aを除いた残り for b in itertools.combinations(rA,5): if countSuit('H',b)!=3: continue # 条件B-1 if countSuit('C',b)!=1: continue # 条件B-2 if countRank('K',b)!=3: continue # 条件B-3 rB = [x for x in rA if not x in b] # a,bを除いた残り for c in itertools.combinations(rB,5): if countSuit('H',c)!=1: continue # 条件C-1 if countSuit('S',c)!=3: continue # 条件C-2 d = tuple([x for x in rB if not x in c]) # a,b,cを除いた残り if 0 in countSuits(d): continue # 条件D-1 if countRank('K',d)!=1: continue # 条件D-2 if countRank('A',d)!=1: continue # 条件D-3 # チェックを潜り抜けたものだけを表示 ## print(toStrCards(a),toStrCards(b),toStrCards(c),toStrCards(d)) # 選択肢のチェック choices[0] &= (getN('C','A') in a ) choices[1] &= (getN('H','A') in b ) choices[2] &= (getN('S','A') in c ) choices[3] &= (countSuit('D',d)==2) choices[4] &= (countSuit('C',d)==1) s = "" for c in choices: if c : s+=" %s"%(choices.index(c)+1) print(u"∴%s"%s) tm=time()-tm # Timer Stop print("Runtime : %.3f [sec]"%tm) if __name__ == '__main__': main()
●実行結果
∴ 1 Runtime : 0.561 [sec]
●知恵袋で見つけた判断推理のトランプの問題をPythonで解いてみた。(2) - rscのブログ
●知恵袋で見つけた判断推理のトランプの問題をPythonで解いてみた。(3) - rscのブログ
- 作者:鈴木 清士
- 発売日: 1999/11/01
- メディア: 単行本