Two-Die Wager Expected Value
Easy · Statistics & Math · Data Scientist · Onsite
Problem Statement
A tabletop wager pits a challenger against a dealer, each throwing a single unbiased cube numbered 1 through 6 independently:
- Whenever the challenger's face value exceeds the dealer's (
challenger > dealer), the challenger collectsndollars (+n). - Whenever the dealer's face value exceeds or equals the challenger's (
challenger <= dealer, so identical faces favor the dealer), the challenger forfeitsmdollars (-m).
Given non-negative integer stakes n and m, implement dice_game_analysis(n, m) returning a dictionary with two entries:
"expected_value": afloatequal to the exact single-round mean net dollar payoff."should_play": aboolindicating whether a risk-neutral challenger accepts the wager (Truewhenever the mean net payoff is non-negative, including exact break-even0.0, andFalsewhen negative).
Examples
Example 1
Input: n = 12, m = 6
Output: {'expected_value': 1.5, 'should_play': True}
Out of 36 equally probable die pairs, 15 give challenger > dealer (+12 each, totaling +180) and 21 give challenger <= dealer (-6 each, totaling -126). Dividing 180 - 126 = 54 by 36 yields 1.5, which is positive, so "should_play" is True.
Example 2
Input: n = 6, m = 6
Output: {'expected_value': -1.0, 'should_play': False}
Equal payouts favor the dealer because all 6 matching rolls count as challenger losses: (15 * 6 - 21 * 6) / 36 = -36 / 36 = -1.0, so "should_play" is False.
Example 3
Input: n = 21, m = 15
Output: {'expected_value': 0.0, 'should_play': True}
Here 15 * 21 = 315 balances 21 * 15 = 315 exactly, producing mean payoff 0.0. Because non-negative expectation (>= 0) meets the risk-neutral acceptance rule, "should_play" is True.
Constraints
0 <= n, m <= 10^9- Avoid intermediate floating-point rounding drift when testing exact break-even stakes (
5 * n == 7 * m).
Step-by-step walkthrough
Restate the rules and what risk-neutral means
In each round, the challenger and the dealer each throw one unbiased, independent six-sided die:
- If
player_roll > house_roll(strictly higher), you gain+ndollars. - If
player_roll <= house_roll(the dealer rolls higher or both dice tie), you lose-mdollars.
We need to return
{"expected_value": EV, "should_play": bool}and also show how to cross-check the formula via simulation.The expected value (EV) of one round is the long-run average dollar gain (or loss) per round across infinitely many independent rounds. A risk-neutral participant cares only about this long-run average, not about round-to-round swings:
- If
EV > 0, you gain money on average, so accept (True). - If
EV < 0, you lose money on average, so decline (False). - If
EV == 0, playing and walking away have the exact same average return (0.0). As shown in Example 3 (n = 21, m = 15), exact break-even counts as acceptable (should_play = True), so the decision rule isEV >= 0.
- If
Map out all 36 dice pairs in a 6x6 grid
Because both dice are unbiased and independent, every ordered pair
(player_roll, house_roll)from(1, 1)to(6, 6)has the exact same probability:1 / 36. Laying out all6 * 6 = 36pairs in a grid makes the counts unmistakable (W= strict win,T= tie,L= lower roll):Dealer roll 1 2 3 4 5 6 Player 1 [ T L L L L L ] -> 0 W, 1 T, 5 L roll 2 [ W T L L L L ] -> 1 W, 1 T, 4 L 3 [ W W T L L L ] -> 2 W, 1 T, 3 L 4 [ W W W T L L ] -> 3 W, 1 T, 2 L 5 [ W W W W T L ] -> 4 W, 1 T, 1 L 6 [ W W W W W T ] -> 5 W, 1 T, 0 L Strict wins (below diagonal): 0 + 1 + 2 + 3 + 4 + 5 = 15 pairs Ties (on main diagonal): 6 pairs Strict losses (above diagonal): 15 pairsBecause ties belong to the dealer, your losing outcomes combine the 15 lower rolls and the 6 ties into
15 + 6 = 21pairs:P(win) = 15 / 36 = 5 / 12 (about 41.7%) P(lose) = 21 / 36 = 7 / 12 (about 58.3%)With only 36 pairs, we can also let a short loop count
win_pairsandloss_pairsdirectly so there is zero chance of an arithmetic slip:from typing import Tuple def count_outcomes() -> Tuple[int, int]: """Count (win_pairs, loss_pairs) across all 36 equally likely (player, house) rolls.""" win_pairs = 0 loss_pairs = 0 # Two fair 6-sided dice produce 6 * 6 = 36 equally likely ordered pairs (1..6, 1..6). for player_roll in range(1, 7): for house_roll in range(1, 7): # You win only on a strictly higher roll; ties go to the house as losses. if player_roll > house_roll: win_pairs += 1 else: loss_pairs += 1 return win_pairs, loss_pairsBuild the expected value formula step by step
Expected value multiplies each possible dollar outcome by its probability and adds them together. Here there are two outcomes:
+nwith probability15 / 36, and-mwith probability21 / 36:EV = (+n) * (15 / 36) + (-m) * (21 / 36) = (15 * n - 21 * m) / 36 = (5 * n - 7 * m) / 12 (dividing numerator and denominator by 3)Let's check Example 2 (
n = 6, m = 6):EV = (5 * 6 - 7 * 6) / 12 = (30 - 42) / 12 = -12 / 12 = -1.0 dollarsEven though the dice look symmetric at first glance, staking
6against6loses$1.00per round on average because all 6 ties go to the dealer.Derive the condition on n and m to play
A risk-neutral player accepts whenever
EV >= 0. Starting from our formula and multiplying both sides by positive12(which preserves the>=direction):(5 * n - 7 * m) / 12 >= 0 5 * n - 7 * m >= 0 5 * n >= 7 * mWhen
m > 0, we can also write this asn / m >= 7 / 5 = 1.4: a win must pay at least 1.4 times (40% more than) what a loss costs just to overcome the tie disadvantage.Example | n | m | 5*n vs 7*m | EV = (15*n - 21*m)/36 | should_play --------+-----+-----+--------------+-----------------------+------------ 1 | 12 | 6 | 60 > 42 | 1.5 | True 2 | 6 | 6 | 30 < 42 | -1.0 | False 3 | 21 | 15 | 105 == 105 | 0.0 | TrueIn code, always test
15 * n - 21 * m >= 0(or5 * n >= 7 * m) rather thann / m >= 1.4, becausem = 0is a valid input where dividing bymwould crash withZeroDivisionError.Write the exact analysis function without float drift
A subtle floating-point trap happens if you write
(5 / 12) * n - (7 / 12) * m. Because5 / 12and7 / 12are repeating binary fractions, Python rounds each fraction slightly before multiplying; at the exact break-even stakesn = 147, m = 105,(5 / 12) * 147 - (7 / 12) * 105evaluates to-7.105e-15instead of0.0, causing>= 0to wrongly returnFalse!Computing the integer numerator
net_payoff_sum = win_pairs * n - loss_pairs * mfirst uses exact Python integer arithmetic, so every break-even game givesnet_payoff_sum == 0and0 / 36 == 0.0with zero rounding drift.from typing import Dict def dice_game_analysis(n: int, m: int) -> Dict[str, object]: # win_pairs = 15 (strictly higher), loss_pairs = 21 (15 lower + 6 ties) win_pairs, loss_pairs = count_outcomes() total_pairs = win_pairs + loss_pairs # Compute the exact integer numerator first so break-even stakes (5n == 7m) never suffer float drift. net_payoff_sum = win_pairs * n - loss_pairs * m expected_value = net_payoff_sum / total_pairs # Risk-neutral rule: accept whenever EV >= 0 (including exact break-even EV == 0 as True). should_play = net_payoff_sum >= 0 return {"expected_value": expected_value, "should_play": should_play}Cross-check with a Monte Carlo simulation
A Monte Carlo simulation estimates the theoretical EV empirically by rolling two virtual dice for
Rindependent rounds (sayR = 100,000) using a seeded random number generator, adding+non strict wins and-motherwise, and dividing total net winnings byR. By the law of large numbers (as the number of independent trials grows, the sample average converges toward the true expected value), this sample average approaches(5n - 7m) / 12.import random def simulate_ev(n: int, m: int, rounds: int = 100_000, seed: int = 0) -> float: """Monte Carlo check: average the net payoff across many seeded random rounds.""" rng = random.Random(seed) total_payoff = 0 for _ in range(rounds): player_roll = rng.randint(1, 6) house_roll = rng.randint(1, 6) if player_roll > house_roll: total_payoff += n else: total_payoff -= m return total_payoff / roundsHow close should the simulated average be before we call it verified? One round wins
+nwith probabilityp = 5/12and loses-mwith probability1 - p = 7/12, so its spread per round has standard deviation(n + m) * sqrt(p * (1 - p)). AcrossRindependent rounds, the standard error (the typical random wiggle in the sample mean) shrinks bysqrt(R):standard_error = (n + m) * sqrt((5/12) * (7/12)) / sqrt(R) For n = 12, m = 6, R = 100,000: 18 * sqrt(35 / 144) / sqrt(100,000) ≈ 0.028Checking that
abs(simulated_ev - formula_ev) < 3 * standard_error(about±0.084here) confirms our formula without mistaking normal random noise for a bug.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import random def count_outcomes() -> Tuple[int, int]: """Count (win_pairs, loss_pairs) across all 36 equally likely (player, house) rolls.""" win_pairs = 0 loss_pairs = 0 # Two fair 6-sided dice produce 6 * 6 = 36 equally likely ordered pairs (1..6, 1..6). for player_roll in range(1, 7): for house_roll in range(1, 7): # You win only on a strictly higher roll; ties go to the house as losses. if player_roll > house_roll: win_pairs += 1 else: loss_pairs += 1 return win_pairs, loss_pairs def dice_game_analysis(n: int, m: int) -> Dict[str, object]: # win_pairs = 15 (strictly higher), loss_pairs = 21 (15 lower + 6 ties) win_pairs, loss_pairs = count_outcomes() total_pairs = win_pairs + loss_pairs # Compute the exact integer numerator first so break-even stakes (5n == 7m) never suffer float drift. net_payoff_sum = win_pairs * n - loss_pairs * m expected_value = net_payoff_sum / total_pairs # Risk-neutral rule: accept whenever EV >= 0 (including exact break-even EV == 0 as True). should_play = net_payoff_sum >= 0 return {"expected_value": expected_value, "should_play": should_play} def simulate_ev(n: int, m: int, rounds: int = 100_000, seed: int = 0) -> float: """Monte Carlo check: average the net payoff across many seeded random rounds.""" rng = random.Random(seed) total_payoff = 0 for _ in range(rounds): player_roll = rng.randint(1, 6) house_roll = rng.randint(1, 6) if player_roll > house_roll: total_payoff += n else: total_payoff -= m return total_payoff / rounds✅ Submit now — all tests should pass.
Intuition & how it works
Picture a carnival dice booth with one quiet rule: "ties go to the dealer." When challenger and dealer each roll an unbiased six-sided die, there are 6 * 6 = 36 equally likely outcome pairs. Six of those pairs are ties (1,1) through (6,6), leaving 30 non-ties that split evenly by symmetry—15 where the challenger's roll is higher and 15 where the dealer's roll is higher. Because the dealer claims all 6 ties on top of the 15 higher rolls, the challenger wins only 15 / 36 (5 / 12) of the time and loses 21 / 36 (7 / 12) of the time. We evaluate the wager using expected value (EV) (the long-run average dollar gain or loss per round) for a risk-neutral player (someone who judges a bet solely by its average payoff, regardless of ups and downs).
The most common mistake is treating "higher die wins" like a 50–50 coin flip and accepting equal payouts (n = m), which actually loses m / 6 dollars per round. On the coding side, writing the formula as (5 / 12) * n - (7 / 12) * m introduces tiny binary floating-point rounding errors (for instance, -7.1e-15 at the exact break-even stakes n = 147, m = 105), which flips EV >= 0 from True to False. Similarly, checking the ratio n / m >= 1.4 crashes with ZeroDivisionError whenever m = 0. Computing the exact integer numerator 15 * n - 21 * m before a single division by 36 avoids both traps completely.
Walk through the three statement examples:
1. n = 12, m = 6 (Example 1): Across 36 equally likely outcomes, 15 wins bring in 15 * 12 = +180 dollars and 21 losses cost 21 * 6 = -126 dollars. Net sum is +54, so EV = 54 / 36 = 1.5 and should_play is True.
2. n = 6, m = 6 (Example 2): 15 wins bring in +90 dollars while 21 losses cost -126 dollars. Net sum is -36, so EV = -36 / 36 = -1.0 and should_play is False.
3. n = 21, m = 15 (Example 3): 15 wins bring in +315 dollars and 21 losses cost -315 dollars. Net sum is 0, so EV = 0.0 and should_play is True.
Complexity
- Time:
O(1)fordice_game_analysis.count_outcomesalways loops over the exact same6 * 6 = 36pairs regardless of how largenandmare, followed by a handful of arithmetic operations. For the Monte Carlo simulation (estimating an expected value by averaging many randomized computer trials),simulate_evruns inO(R)time because it simulatesRrounds in a single loop doingO(1)work per round. - Space:
O(1)for bothdice_game_analysisandsimulate_ev. Only a few integer counters and the two-key output dictionary are stored in memory at any point, even whenRis in the hundreds of thousands.
Edge cases
- Exact break-even stakes (
5 * n == 7 * m, such as(21, 15)or(147, 105)):net_payoff_sumis0,expected_valueis0.0, andshould_playisTrue(matching Example 3). - Equal stakes (
n == m > 0, such as(6, 6)in Example 2):EV = (15n - 21n) / 36 = -n / 6 < 0, so equal payouts always favor the dealer. - Zero loss stake (
m == 0, n >= 0): losing or tying costs nothing, sonet_payoff_sum = 15 * n >= 0andshould_playisTruewithout ever dividing bym. - Zero win stake (
n == 0, m > 0): you can never gain money (EV = -21 * m / 36 < 0), soshould_playisFalse. - Very large integer stakes (
n = 700_000_007, m = 500_000_005): Python integers have arbitrary precision, so15 * n - 21 * mevaluates to0with zero overflow or catastrophic cancellation.
Common mistakes
- Treating ties as a "push" (0 dollars exchanged): if ties paid
0,P(lose)would be15 / 36instead of21 / 36andEVwould be15 * (n - m) / 36. Under this game's rules, ties forfeitmdollars. - Assuming
P(win) = 1/2: forgetting the 6 diagonal ties overestimates the win probability (18 / 36vs15 / 36). - Pre-dividing probabilities before multiplying:
(15 / 36) * n - (21 / 36) * mrounds repeating binary floats before subtraction and can produce tiny negative numbers like-7.1e-15when the true EV is0. Keep one division at the end:(15 * n - 21 * m) / 36. - Using strict
EV > 0instead ofEV >= 0: Exact break-even inputs like(21, 15)in Example 3 satisfy risk-neutral acceptance and expectshould_play = True. - Expecting a Monte Carlo simulation to hit the formula to 6 decimal places: by the law of large numbers (sample averages converge toward the true mean as trial count
Rgrows), the standard error (typical random error of the sample mean) shrinks at rate1 / sqrt(R). AtR = 100,000for(12, 6), random noise is around±0.028, so verify within2to3standard errors rather than testing exact float equality.
Follow-up questions
- How would the expected payoff and decision threshold change if tied rolls returned zero dollars instead of counting as losses? Six of the 36 outcomes would yield
0dollars, leaving 15 wins (+n) and 15 losses (-m). The expected value would becomeEV = (15 * n - 15 * m) / 36 = 5 * (n - m) / 12, and a risk-neutral challenger would accept whenevern >= m. That shows the dealer's entire statistical edge in the original wager comes from claiming ties. - Why might a risk-averse bettor reject a break-even wager, and how could they size bets when the edge is positive? A risk-averse player (someone who dislikes uncertainty and requires a positive profit cushion to compensate for potential losses) also cares about variance (the average squared distance of outcomes from the mean, here
(5/12) * (7/12) * (n + m)^2, which equals315at(21, 15)). AtEV = 0, taking on variance for zero expected reward makes a risk-averse player strictly worse off, so they requireEV > 0by a margin depending on their bankroll. WhenEV > 0and bets can be sized as a fraction of bankroll, the Kelly criterion (a formula that maximizes long-run logarithmic bankroll growth while avoiding ruin) risks fractionp - (1 - p) * (m / n)per round—for example,5/12 - (7/12) * (6/12) = 1/8at(12, 6), and0at break-even. - When winning pays 10 dollars and losing costs 5 dollars, about how many rounds are needed for a 95% probability of net profit? One round has mean
EV = (150 - 105) / 36 = 1.25dollars and standard deviationsqrt((5/12) * (7/12) * 15^2) = sqrt(54.6875) ≈ 7.40dollars. Using the normal approximation (approximating the sum of many independent rounds with a bell curve), total profit afterRrounds has mean1.25 * Rand standard deviation7.40 * sqrt(R), which stays above0with 95% probability when(1.25 * R) / (7.40 * sqrt(R)) >= 1.645, givingR >= (1.645 * 7.40 / 1.25)^2 ≈ 95rounds (and by exact binomial probabilities,P(profit > 0)stays permanently above 95% for everyR >= 100).
Follow-up questions
- How would the expected payoff and decision threshold change if tied rolls returned zero dollars instead of counting as losses?
- Why might a risk-averse bettor reject a break-even wager, and how could they size bets when the edge is positive?
- When winning pays 10 dollars and losing costs 5 dollars, about how many rounds are needed for a 95% probability of net profit?
Similar questions
- Three-Head Probabilities Across Fair Coin Tosses
- Confounding Bias in Ride-Hailing and Delivery Data
- P-Values, Confounded Regression, and Regularization
- Hypothesis Testing and p-Value Pitfalls in Fraud Experiments
- Expected Value of a Dice Wager
- Real-Time Payment Risk Scoring and Fraud Mitigations
More PayPal interview questions
- Evaluating Online Payments and Cold-Start Fraud Controls Hard
- Merchant Chargeback Filtering Using WHERE and HAVING Medium
- Four-Stop Building Elevator Dispatch Policy Medium Pro
- Comparing Python Lists and Tuples Hard Pro
- Risk Experience and Strategy-Focused Role Alignment Medium Pro
- Unsupervised Fraud Detection and Label-Scarce Evaluation Hard Pro
- Hypothesis Testing and p-Value Pitfalls in Fraud Experiments Hard Pro
- Curbing Airport Pickup Cancellations Under Queue Interference Easy Pro
- Expected Value of a Dice Wager Easy Pro
- Merchant Transaction Summaries via Conditional Aggregation Medium Pro