Last active
July 9, 2016 15:27
-
-
Save reeddunkle/7a23dcb4d2062f90e0d2e611774abeca to your computer and use it in GitHub Desktop.
Roll a die with optional weighted side and specified weight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| def is_int(x): | |
| ''' | |
| Given a number, returns a boolean declaring if | |
| the number is an integer. | |
| ''' | |
| return x % 1 == 0 | |
| def roll_die(n_sides, n_weighted=None, weight=None): | |
| ''' | |
| Given number of sides to the die, the (optional) side that is weighted, | |
| and the weight of that side, returns the roll. | |
| ''' | |
| if n_weighted is None and weight is not None: | |
| raise ValueError('Must specify a side to weigh if providing a weight.') | |
| if n_weighted > n_sides: | |
| raise ValueError('The weighted side must be <= the number of sides on the die.') | |
| if n_sides < 1 or n_weighted < 1 and n_weighted is not None: | |
| raise ValueError('Die values must be greater than 0.') | |
| if not is_int(n_sides) or not is_int(n_weighted) or not is_int(weight): | |
| raise ValueError('All values must be integers.') | |
| if weight is None: | |
| weight = n_sides | |
| if weight == 1: | |
| numbers = [n_weighted] | |
| elif weight < 1: | |
| numbers = [n for n in range(1, n_sides+1) if n is not n_weighted] | |
| elif n_weighted == None: | |
| numbers = [n for n in range(1, n_sides+1)] | |
| else: | |
| dist = n_sides - 1 | |
| numbers = sum([[n] * (weight-1) + [n_weighted] for n in range(1, n_sides+1) if n is not n_weighted], []) | |
| # Debugging | |
| # print("With {} being rolled every 1/{} rolls, the numbers to choose from are \n{}\n".format(n_weighted, weight, numbers)) | |
| roll = random.choice(numbers) | |
| print(roll) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment