マルチンゲールベッティングシミュレーター2.0
これは、マルチンゲール賭博シミュレーターを作成する際の2番目のショットです。元のコードは、私が最初から始めたばかりのような重いリファクタリングを必要としていました。
スクリプトは、損失が発生するまで一定額を賭けるというマルチンゲールの賭け戦略をシミュレートします。損失が発生すると、損失を補うために賭けが2倍になります。これは、勝利が発生するまで続き、勝利後、賭けは元の賭けの値にリセットされます。ブラックジャックを模倣するオッズを設定しました(49%の確率で勝利)。簡単にするために、ラウンドで勝ち負けた金額は賭けと同じです。指定されたラウンド数が経過したとき、次の賭けのサイズが現在利用可能な資金よりも大きいとき、利用可能な資金が0に達したとき、または目標利益が達成されたときに、シミュレーションは終了します。
私はPythonとコーディング全般にまったく慣れていないので、フィードバックをいただければ幸いです。
import random
def main(rounds=10, bet=25, goal_profit=1000, each=False, end_script_prt=True):
"""Runs a simulation of the Martingale betting strategy over a specified number of rounds.
each = True will print a summary of each round's results. end_script_prt = True will
print a summary of the game's results"""
original_bet = bet
current_bet = bet
starting_funds = 5000
current_profit = 0
current_funds = starting_funds
round_n = 0
wins = 0
losses = 0
while current_profit < goal_profit\
and round_n < rounds\
and current_funds > 0\
and current_funds > current_bet:
round_n += 1
rng_v = rng()
current_funds += change_current_funds(current_bet, rng_v)
current_profit = current_profits(current_funds, starting_funds)
if winloss_generator(rng_v) == 'win':
wins += 1
elif winloss_generator(rng_v) == 'loss':
losses += 1
if each:
print('ROUND:', round_n, 'of', rounds)
print('BET:', current_bet)
print('OUTCOME:', winloss_generator(rng_v).capitalize())
print('WINS/LOSSES:', wins, 'Wins', losses, 'losses')
print('CURRENT FUNDS:', current_funds)
print('CURRENT PROFIT:', current_profit)
print()
current_bet = change_bet(original_bet, current_bet, rng_v)
print()
if end_script_prt:
end_script(round_n, wins, losses, starting_funds, current_funds, goal_profit, current_profit)
return change_iterated_winloss(current_profit, goal_profit)
def rng():
"""Returns random number"""
return random.random()
def winloss_generator(rng_v):
"""Returns win/loss condition"""
if rng_v <= .49:
return 'win'
if rng_v > .49:
return 'loss'
def change_current_funds(current_bet, rng_v):
"""Returns change in funds resulting from round outcome"""
if winloss_generator(rng_v) == 'win':
return current_bet
if winloss_generator(rng_v) == 'loss':
return current_bet * -1
def change_bet(original_bet, current_bet, rng_v):
"""Returns updated bet value
If outcome is a win, bet is reset to original value. If outcome is a loss bet is doubled"""
if winloss_generator(rng_v) == 'win':
return original_bet
if winloss_generator(rng_v) == 'loss':
return current_bet * 2
def current_profits(current_funds, starting_funds):
"""Returns current profit"""
return current_funds - starting_funds
def end_script(round_n, wins, losses, starting_funds, current_funds, goal_profit, current_profit):
"""Prints final outcome of the game and summary of the results"""
print('*************************')
if current_profit >= goal_profit:
print('YOU WIN!')
else:
print('YOU LOSE')
print('TOTAL ROUNDS:', round_n)
print('WIN/LOSS RECORD:', wins, 'Wins', losses, 'Losses')
print('STARTING FUNDS:', starting_funds)
print('ENDING FUNDS: ', current_funds)
print('GOAL PROFIT:', goal_profit)
print('ENDING PROFIT:', current_profit)
def change_iterated_winloss(current_profit, goal_profit):
"""Returns game's win/loss outcome as a string"""
if current_profit >= goal_profit:
w_l = 'w'
return w_l
else:
w_l = 'l'
return w_l
def iterated_winloss_count(iterations, each=False):
"""Returns a summary of the total win/loss record across game iterations. each = True will
print each game result individually"""
total_wins = 0
total_losses = 0
for x in range(iterations):
game_outcome = main(1000, 25, 5000, False, False)
if game_outcome == 'w':
total_wins += 1
if each:
print('WIN!')
if game_outcome == 'l':
total_losses += 1
if each:
print('LOSS')
print()
print('WINS/LOSSES OVER', iterations, 'ITERATIONS:', total_wins, 'Wins', total_losses, 'Losses')
# Single Game
if True:
main(1000, 25, 5000, True, True)
# Iterated Games
if False:
iterated_winloss_count(1000, False)
回答
異常な条件構造を持つ関数がいくつかあります。私は何かを誤解しているかもしれませんが、私はプレーヤーが勝つか負けるかのどちらかだと思います。その観点から、2番目の条件付きチェックには目的はありませんelse。単にを使用してください。
def winloss_generator(rng_v):
if rng_v <= .49: # win
return 'win'
if rng_v > .49: # else loss
return 'loss'
これは学習者の間で最も一般的な問題ではありませんが、計算を大幅に過大評価しているため、単純なことを理解するのが難しくなっています。乱数が生成され、勝敗が決まります(ただし、結果は覚えていません)。次に、その乱数は複数のステップを経て織り込まれ、それぞれがを呼び出しますwinloss_generator(RANDOM_NUM)。これにより、(再び)勝ち負けかどうかがわかります。代わりに、で直接main()、結果をすぐに決定します。
won = (random.random() <= .49)
その変数を覚えておけば、残りの計算はすべて1か所で簡単に理解できます。計算がかなり単純で、密接に関連していて、グループとして簡単に実行できる場合は、原則としてそれらをまとめてください。
current_funds += current_bet * (1 if won else -1)
current_profit = current_funds - starting_funds
wins += int(won)
losses += int(not won)
...
current_bet = original_bet if won else 2 * current_bet
アルゴリズムをオーバーファクタリングすることに加えて、副作用の観点からコードをアンダーファクタリングしました(ここでは印刷が副作用です)。一般的な考え方は、プログラムの薄い外層の副作用を囲い込むことです。コードの残りの部分は、純粋にデータを返す関数の領域で動作できます(少なくとも、それは希望です。現実には課題があります)。これが、コードをリファクタリングしてその分離を強制する1つの方法です。
from collections import namedtuple
# A simple data object to store all relevant details
# for one round of play.
Round = namedtuple('Round', 'round_n won funds profit wins losses bet')
# Entry point.
def main():
# Run the rounds and get data back. No printing yet.
rounds = list(martingale(200, 25, 5000))
# Analyze the results as much as we like.
for r in rounds:
...
# Report the results. Printing OK here.
for r in rounds:
print(...)
# The algorithmic code of the betting strategy.
# It sticks fairly close to your original code, absent side effects.
def martingale(rounds=10, bet=25, goal_profit=1000):
funds = 5000
orig_bet = bet
orig_funds = funds
profit = 0
round_n = 0
wins = 0
losses = 0
while profit < goal_profit and round_n < rounds and funds > bet:
round_n += 1
won = (random.random() <= .49)
funds += bet * (1 if won else -1)
profit = funds - orig_funds
wins += int(won)
losses += int(not won)
yield Round(round_n, won, funds, profit, wins, losses, bet)
bet = orig_bet if won else 2 * bet
あなたがそれでより多くのことをすることができるので、そのデザインはより良いです。入力パラメーターを定義するためのコマンドライン引数のサポートに加えて、さまざまなタイプの分析またはレポート用のさまざまなオプションを追加することを想像してみてください。のアルゴリズムコードを変更せずに、これらすべてを追加できますmartingale()。異なる賭け戦略を実装する別の関数を作成することも可能になりました。それも戻りrounds、で使用されているのと同じコードでそれらを分析できますmartingale()。最後に、あなたが望むかもしれないもう一つのことは、このような機能をテストできることです:自動化された方法で、またはデバッグセッションでアドホックに。関数を呼び出して、印刷されたテキストの山ではなくデータとしての回答を取得できれば、どちらも簡単です。後で使用するために印刷を保存します。最初にデータを正しく取得します。