皆さん、質問の回答・コメント有難うございました。
Rubyでは、メソッド表現で簡単にできるようですが、Pythonでは難しいようです。
そこで、拙ブログの論理問題のプログラムをPythonからRubyに翻訳して、「Imp(p,q)」を「p.Imp(q)」に書き直してみました。(^_^;
● Logic1.rb
# encoding: Shift_JIS # Logic1.rb # 論理包含「P⇒Q」の真理値を得る関数Imp def Imp(p,q) return (!p)||q end # Impのメソッド版 def true.Imp q q end def false.Imp q true end # 真理値表の1行を文字列で得る def getRowOfTruthTable(lst) result = '' for b in lst result += (b ? " T" : " F") end return result end def main() tm = Time.now # Timer Start tf = [true, false] puts '[b,g,s] 1 2 3 4 5' # b:野球; g:ゴルフ; s:サッカー choices = [true]*5 cnt = 0 tf.product(tf,tf).each do |b,g,s| next if !(( !b).Imp(g)) # 条件A next if !((s&&b).Imp(g)) # 条件B # チェックを潜り抜けたものだけを表示 cnt+=1 t = getRowOfTruthTable([b,g,s]) # 選択肢のチェック choices[0] &= (c1 = (!b).Imp(!s)) choices[1] &= (c2 = ( s).Imp( g)) choices[2] &= (c3 = (!s).Imp( b)) choices[3] &= (c4 = ( g).Imp(!b)) choices[4] &= (c5 = (!g).Imp( s)) puts '%s %s'%[t,getRowOfTruthTable([c1,c2,c3,c4,c5])] end s = '' choices = [false]*5 if cnt==0 for c in choices s+=' %s'%[choices.index(c)+1] if c end puts '∴%s'%s print "Runtime : %.3f [sec]\n"%(Time.now-tm) # Timer Stop & Disp end if $0 == __FILE__ main() end
●実行結果
[b,g,s] 1 2 3 4 5 T T T T T T F T T T F T T T F T T F F T T T T F F T T F T T T T F T F T T F T T ∴ 2 Runtime : 0.000 [sec]
※参考URL
●知恵袋の判断推理の論理問題をPythonで解いてみた。 - rscのブログ
●知恵袋の判断推理の論理問題をPythonで解いてみた。(2) - rscのブログ
●知恵袋の判断推理の論理問題をJavaで解いてみた。 - rscのブログ