ネットで見つけた判断推理のカードの問題をPythonで解いてみました。(^_^;
A~Dの4人に、1~13までの数字が1つずつ書かれた13枚のカードを配った。配ったカードについて、ア~オのことがわかっているとき、最も妥当なのはどれか。
・ア Aには4枚配られ、すべて奇数である。
・イ Bには4枚配られ、13のカードを持っている。
・ウ Bの持っているカードの数字の合計は38である。
・エ Cには3枚配られ、1のカードを持っている。
・オ Cの持っているカードの数字の合計は21である。
1.Aは7のカードを持っている。
2.Aは9のカードを持っている。
3.Bは6のカードを持っている。
4.Bは9のカードを持っている。
5.Dは6のカードを持っている。
aは、1~13までの奇数の組合せ、bは、aが選んだものを取り除いた残りの組合せ、cは、更にbが選んだものを取り除いた残りの組合せで回してみました。それから、dは、更にcが選んだものを取り除いた残りをとりました。(^_^;
● Cards2.py
# coding: UTF-8 # Cards2.py import itertools from time import time # 確実にいえる選択肢を1つ得る def getAns(choices): fmt = '%s' if choices.count(True)==1 else 'Error! {%s}' lst = ['12345'[i] for i in range(len(choices)) if choices[i]] return fmt%','.join(lst) def main(): tm = time() # Timer Start choices = [True]*5 Nums = range(1,14) Odds = range(1,14,2) for a in itertools.combinations(Odds,4): # 条件ア bs = set(Nums)-set(a) # aが選んだものを取り除いた残り for b in itertools.combinations(bs,4): # 条件イ if not 13 in b: continue # 条件イ if not sum(b)==38: continue # 条件ウ cs = set(bs)-set(b) # 更にbが選んだものを取り除いた残り for c in itertools.combinations(cs,3): # 条件エ if not 1 in c: continue # 条件エ if not sum(c)==21: continue # 条件オ pass # チェックを潜り抜けたものだけを表示 d = tuple(set(cs)-set(c)) # 更にcが選んだものを取り除いた残り print(a,b,c,d) pass # 選択肢のチェック choices[0] &= (7 in a) choices[1] &= (9 in a) choices[2] &= (6 in b) choices[3] &= (9 in b) choices[4] &= (6 in d) print(u"∴%s"%getAns(choices)) print("Runtime : %.3f [sec]"%(time()-tm)) # Timer Stop & Disp if __name__ == '__main__': main()
●実行結果
(3, 5, 7, 9) (4, 10, 11, 13) (1, 8, 12) (2, 6) (3, 5, 7, 11) (6, 9, 10, 13) (1, 8, 12) (2, 4) ∴1 Runtime : 0.000 [sec]
※参考URL
●判断推理のカードの問題をJavaで解いてみた。 - rscのブログ
●判断推理のカードの問題をPythonで解いてみた。 - rscのブログ
●Googleの入社試験の覆面算をPythonで解いてみた。 - rscのブログ
畑中敦子×津田秀樹の「判断推理」勝者の解き方 敗者の落とし穴NEO【第2版】
- 作者: 畑中敦子,津田秀樹
- 出版社/メーカー: 洋泉社
- 発売日: 2017/10/24
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る