##清書(最終)
Python3
1def coin_sums2(remainder, coin): 2 if coin < 0: 3 return 1 4 n = remainder // coins[coin] 5 total2 = 0 6 for i in range(n + 1): 7 total2 += coin_sums2(remainder - i * coins[coin], coin - 1) 8 return total2 9 10 11coins = [2, 5, 10, 20, 50, 100, 200] 12ans = coin_sums2(200, len(coins) - 1) 13print(ans)
##追記(18:40)
回答頂いた後ものをヒントに修正したらこれで動きました。
Python3
1def coin_sums2(remainder, coin,total2=0): 2 if coin < 0: 3 return total2 + 1 4 n = remainder // coins[coin] 5 for i in range(n + 1): 6 total2 += coin_sums2(remainder - i * coins[coin], coin - 1) 7 return total2 8 9coins = [2, 5, 10, 20,50, 100, 200] 10ans = coin_sums2(200, len(coins)-1) 11print(ans)
####参考課題
ProjectEuler Problem 31 : Coin sums
日本語訳
#現状
環境:Python3.7.0
coin_sums
関数の外で定義したtotal変数をインクリメントすると最後にprint(total)で正解が出力されています。
coin_sums2
少し修正し戻り値を受け取って出力させたい。
その為にtotal変数の代わりに初期値0の引数を渡して最終的な戻り値をans変数に代入してprint(ans)で出力させたい。
しかし結果はNoneでした。
#知りたいこと
引数の渡し方や戻り値の受け取り方のどこかで間違っているのだと思うのですが堂々巡りしていて時間だけが過ぎています。
正常に動くにはどうすれば良いかヒントなどご教示頂けると助かります。
#coin_sums
python3
1def coin_sums(remainder, coin): 2 global total 3 if coin < 0: 4 total += 1 5 return 6 n = remainder // coins[coin] 7 for i in range(n + 1): 8 coin_sums(remainder - i * coins[coin], coin - 1) 9 10coins = [2, 5, 10, 20,50, 100, 200] 11total = 0 12coin_sums(200, len(coins)-1) 13print(total) 14#73682
#coin_sums2
python3
1def coin_sums2(remainder, coin,t): 2 total2 = t 3 if coin < 0: 4 total2 += 1 5 return total2 6 n = remainder // coins[coin] 7 for i in range(n + 1): 8 coin_sums2(remainder - i * coins[coin], coin - 1,total2) 9 10coins = [2, 5, 10, 20,50, 100, 200] 11ans = coin_sums2(200, len(coins)-1,0) 12print(ans) 13#None
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/12 09:27
2018/10/12 09:29
2018/10/12 09:34
2018/10/12 09:43
2018/10/12 09:43
2018/10/12 09:50
2018/10/12 10:03 編集
2018/10/12 10:33