algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

new-21-game.py (699B)


      1 import random
      2 
      3 def simulate(n,k,maxPts):
      4     count = 0
      5     while count < k:
      6         count += random.randrange(1,maxPts + 1)
      7     if count > n:
      8         return False
      9     return True
     10 
     11 class Solution:
     12     def new21Game(self, n: int, k: int, maxPts: int) -> float:
     13         
     14         # while less than k she draws
     15         # stops when she has k or more points
     16         # return probability that alice has n or fewer points
     17         
     18         avg = 0.00
     19         count = 0
     20 
     21         for _ in range(200000):
     22             eval = 0
     23 
     24             if simulate(n,k,maxPts):
     25                 eval = 1
     26             
     27             avg = avg + ((eval - avg) / (count + 1))
     28             
     29             count += 1
     30 
     31         return avg