前回の続きです。Pythonなら楽なので、matplotlibを使って、グラフを描いてみました。前回のプログラムに続けてもいいですが、結果のデータだけ取り出して続けました。(^_^;
それから、「油分け算」は、英語で「Three Jugs Problem」とも呼ばれているようなので、プログラム名をこれに由来するものに変更してみました。(^_^;
● ThreeJugsProb1.py
# coding: UTF-8 # ThreeJugsProb1.py # 油分け算 import matplotlib.pyplot as plt def main(): ans = [ [16, 0, 0],[ 7, 9, 0],[ 7, 2, 7],[14, 2, 0],[14, 0, 2],[ 5, 9, 2], [ 5, 4, 7],[12, 4, 0],[12, 0, 4],[ 3, 9, 4],[ 3, 6, 7],[10, 6, 0], [10, 0, 6],[ 1, 9, 6],[ 1, 8, 7],[ 8, 8, 0],[ 8, 1, 7],[15, 1, 0], [15, 0, 1],[ 6, 9, 1],[ 6, 3, 7],[13, 3, 0],[13, 0, 3],[ 4, 9, 3], [ 4, 5, 7],[11, 5, 0],[11, 0, 5],[ 2, 9, 5],[ 2, 7, 7],[ 9, 7, 0], [ 9, 0, 7],[16, 0, 0] ] g = ans.index([ 8, 8, 0]) # グラフの作成 # 前半2列目と3列目を取り出す x = [ans[n][1] for n in range(g+1)] y = [ans[n][2] for n in range(g+1)] plt.plot(x, y) plt.plot(x, y, 'ro') plt.title('Three Jugs Problem (1)') plt.xlabel('Amount in 9L-Jug B') plt.ylabel('Amount in 7L-Jug C') plt.vlines(range(10), 0, 7, color='r', linestyles="-") plt.hlines(range( 8), 0, 9, color='r', linestyles="-") plt.xticks(range(10)) plt.yticks(range( 8)) for n in range(len(x)): plt.text(x[n],y[n],'(%d)'%n, va='bottom') plt.xlim([-1,10]) plt.ylim([-1, 8]) plt.show() # 後半2列目と3列目を逆順に取り出す x = [ans[n][1] for n in reversed(range(g,len(ans)))] y = [ans[n][2] for n in reversed(range(g,len(ans)))] plt.plot(x, y) plt.plot(x, y, 'ro') plt.title('Three Jugs Problem (2)') plt.xlabel('Amount in 9L-Jug B') plt.ylabel('Amount in 7L-Jug C') plt.vlines(range(10), 0, 7, color='r', linestyles="-") plt.hlines(range( 8), 0, 9, color='r', linestyles="-") plt.xticks(range(10)) plt.yticks(range( 8)) for n in range(len(x)): plt.text(x[n],y[n],'(%d)'%n, va='bottom') plt.xlim([-1,10]) plt.ylim([-1, 8]) plt.show() if __name__ == '__main__': main()
※参考URL
http://mathworld.wolfram.com/ThreeJugProblem.html
●知恵袋の油分け算の問題をPythonで解いてみた。
●[Python] matplotlibによるグラフ描画 - TIPS - FC2
●Matplotlibでのグラフ描画まとめ | 健忘症の備忘録
●matplotlib入門 - りんごがでている
●1.4. Matplotlib: 作図 − Scipy lecture notes
●matplotlibで、グラフにテキストを入れる。 - ぱたヘネ