Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def roll(d_str):
- import random
- # the following line can be broken into several lines:
- # num, size = map(int, d_str.split('d'))[:2]
- # suppose `d_str` has the value "4d20". After the following line,
- # `roll_fragments` will have the value ["4", "20"]. That is,
- # `roll_fragments` is a list of strings.
- roll_fragments = d_str.split('d')
- # We'd like to try to prevent bad input to this function from crashing the
- # program. Assume the function is called with errant input of
- # d_str="4d20d10". We can Choose to use only the first two values from the
- # `split` function in the previous line by using Python's list slicing
- # syntax. The following line, translated to English would read: "set the
- # variable `num_size` equal to the first two elements of the
- # `roll_fragments` list":
- num_size = roll_fragments[:2]
- # We ultimately need to determine the integer (int) representation of both
- # of these variables. We can do that with the following:
- num, size = map(int, num_size)
- # In English, the previous line reads: set `num` and `size` to the first
- # and second values (respectively) returned by calling the built-in
- # function `int` for each element in the list `num_size`. Recall that the
- # list num_size will have at most two elements in it.
- # To reiterate, the lines:
- # roll_fragments = d_str.split('d')
- # num_size = roll_fragments[:2]
- # num, size = map(int, num_size)
- # are together equivalent to the single line:
- # num, size = map(int, d_str.split('d'))[:2]
- # For more information about list slicing see:
- # http://stackoverflow.com/a/509295/60366
- # For more information about the `map` and `int` Python built-in functions
- # see:
- # http://docs.python.org/2/library/functions.html#map
- # http://docs.python.org/2/library/functions.html#int
- face_values = range(1, size+1)
- rolls = [str(random.choice(face_values)) for i in xrange(num)]
- print(' '.join(rolls))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement