# Untitled

By: a guest on Jun 28th, 2013  |  syntax: Python  |  size: 2.04 KB  |  views: 77  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. def roll(d_str):
2.     import random
3.
4.     # the following line can be broken into several lines:
5.     #    num, size = map(int, d_str.split('d'))[:2]
6.
7.     # suppose `d_str` has the value "4d20". After the following line,
8.     # `roll_fragments` will have the value ["4", "20"]. That is,
9.     # `roll_fragments` is a list of strings.
10.     roll_fragments = d_str.split('d')
11.
12.     # We'd like to try to prevent bad input to this function from crashing the
13.     # program. Assume the function is called with errant input of
14.     # d_str="4d20d10". We can Choose to use only the first two values from the
15.     # `split` function in the previous line by using Python's list slicing
16.     # syntax. The following line, translated to English would read: "set the
17.     # variable `num_size` equal to the first two elements of the
18.     # `roll_fragments` list":
19.     num_size = roll_fragments[:2]
20.
21.     # We ultimately need to determine the integer (int) representation of both
22.     # of these variables. We can do that with the following:
23.     num, size = map(int, num_size)
24.     # In English, the previous line reads: set `num` and `size` to the first
25.     # and second values (respectively) returned by calling the built-in
26.     # function `int` for each element in the list `num_size`. Recall that the
27.     # list num_size will have at most two elements in it.
28.
29.     # To reiterate, the lines:
30.
31.     #   roll_fragments = d_str.split('d')
32.     #   num_size = roll_fragments[:2]
33.     #   num, size = map(int, num_size)
34.
35.     # are together equivalent to the single line:
36.
37.     #   num, size = map(int, d_str.split('d'))[:2]
38.