
import sys, random
import numpy as np
import matplotlib.pyplot as plt

def gamble(p1, g1_amt, g2_amt):
    g1_seq = [g1_amt]
    g2_seq = [g2_amt]    
    cur_g1 = g1_amt
    cur_g2 = g2_amt
    steps  = 0
    while cur_g1 > 0 and cur_g2 > 0 :
        if random.uniform(0,1) < p1 :  #   g1 wins, g2 loses!
            cur_g1 += 1
            cur_g2 -= 1    
        else:                          #   g2 wins, g1 loses! 
            cur_g1 -= 1
            cur_g2 += 1
        g1_seq.append(cur_g1)          #  Add to g1 and g2 sequence lists
        g2_seq.append(cur_g2)  
        steps += 1 
    return g1_seq, g2_seq, steps
#
#   Enter data from keyboard:
#        p, g1, g2, num_sim
#             
p  = float(input('Enter probability of gambler1 winning:  '))
if p<= 0.0 or p>=1 :
    print 'Probability entered =', p, ' prob must be between 0 and 1'
    sys.exit(0)
g1 = int(raw_input('Enter bankroll for gambler1: '))
g2 = int(raw_input('Enter bankroll for gambler2: '))
if g1<=0 or g2<=0:
    print 'Bankrolls entered were g1=', g1, 'and g2= ', g2,' Both must be > 0'
    sys.exit(0)
#  New : enter number of simulations to run
num_sim = int(input('Enter number of simulations to run: '))
#
#   Set up variables to accumulate number of steps to ruin 
#        and number of wins by g1
ruin_steps = np.zeros(num_sim)
g1_wins = 0
#
#   Execute main loop 'num_sim'  times
#
#############################################################
#
#   YOUR CODE GOES HERE  
#     Hints:  
#         1) Use for loop to execute num_sim simulations 
#         2) Accumulate result of each simulation   
#         3) g1 wins if end of g2_walk = 0 ( g2_walk[-1] == 0) 
#
#############################################################
 #   Print out key statistics and plot histogram of number of steps to ruin 
#
print 'Statistics for gamblers ruin with %d simulations:' % num_sim
print '   Prob g1 = %f , g1 bankroll = %d ,  g2 bankroll = %d' % (p,g1,g2) 
print '   Gambler1 wins  %f  \% of time' % round (100.0*(g1_wins/float(num_sim))), 
print '   Average number of steps to ruin is: %f ' %  int(np.mean(ruin_steps))
print '   Largest number of steps to ruin is: %f ' %  int(np.max(ruin_steps)) 
#  Print histogram of results
plt.hist(ruin_steps, bins=50, color='blue')      
plt.title(' Gambler\'s ruin: p='+ str(p)+ ', g1 = \$'+ str(g1)+ ', g2 = \$'+ str(g2))
plt.grid(True)  
plt.show()


