CareerCup Find out the winning probability given n, m and x

You are given n dices each with heads numbered from 1 to m. You are to throw the n dices and note down the sum of the numbers on each of the n dices. You'll be give a number x and its a win if the sum obtained is greater than x. The problem is the find out the winning probability given n, m and x. 

Note 1<=n<=100, 
1<=m<=10, 

m<=x<=n*m.

-------------------------------------------------------


Google loves such probability computations based on dynamic programming 

If P(n, x) is the probability that n die generate a sum greater than or equal to x, then P(n, x) follows this recursive definition:

P(n, x) = P(n-1, x) + (1/m) * sum { P(n-1, x-k), 1<=k<=m }

The first term computes the probability of generating a sum >=x using n-1 die, irrespective of the result of the nth dice. The second term computes the probability of generating a sum >=x-k using n-1 die and the probability of the nth dice generating a value k so that the total sum becomes >=x 

Base cases:

P(1, x) = { 0 if x > m, (m-x+1) / m, otherwise }

Sure, I can help you with that. Here's an implementation of the Dice class: ```python import random class Dice: def __init__(self, num_sides): self.num_sides = num_sides def roll(self): return random.randint(1, self.num_sides) ``` This class has a constructor that takes in the number of sides of the dice and a roll method that returns a random number between 1 and the number of sides. To create a simple game using this class, we can do the following: ```python num_players = int(input("Enter the number of players: ")) num_sides = int(input("Enter the number of sides on the dice: ")) winning_score = int(input("Enter the winning score: ")) players = [] for i in range(num_players): players.append({'id': i+1, 'score': 0, 'rolls': 0, 'dice': Dice(num_sides)}) winner = None while not winner: for player in players: roll = player['dice'].roll() player['score'] += roll player['rolls'] += 1 print(f"Player {player['id']} rolled a {roll}. Current score: {player['score']}") if player['score'] >= winning_score: winner = player break print(f"\nPlayer {winner['id']} won with a score of {winner['score']} after {winner['rolls']} rolls.") ``` This code prompts the user for the number of players, the number of sides on the dice, and the winning score. It then creates a list of player dictionaries, each containing an ID, score, number of rolls, and a Dice object. The game loop iterates through each player, rolls their dice, updates their score and number of rolls, and checks if they have reached the winning score. If a player has reached the winning score, the game loop ends and the winner is announced.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值