[Tutor] enumeration in C++
Erik Price
erikprice@mac.com
Tue, 2 Apr 2002 22:31:28 -0500
On Tuesday, April 2, 2002, at 01:05 PM, Jeff Shannon wrote:
> As you can see, this lets us get the weeday corresponding to a specific
> number, or
> the number for a particular weekday name, and it lets us do a certain
> amount of
> arithmetic with weekdays (if we're careful). One caution with the
> arithmetic --
> we *do* want to be sure that the result of all of our arithmetic is
> within the
> range of the length of our list (0-6). We can use the modulus
> operator ( % ) to
> do this:
>
>>>> weekdays[ weekdays.index('friday') + 5 ]
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> IndexError: list index out of range
>>>> weekdays[ (weekdays.index('friday') + 5) % len(weekdays) ]
> 'wednesday'
>>>> weekdays.index('friday') + 5
> 10
>>>> (weekdays.index('friday') + 5) % len(weekdays)
> 3
>>>>
>
> Hope this makes some sense to you. :)
It made a lot of sense to me AND it showed me a good reason to use the
modulus operator. (I'm not saying good reasons don't exist, I just
haven't seen many of them yet.)
Now I know what enumerations are used for, and why they don't exist in
Python (and how to wing it if I really want to use them, though I would
probably use a tuple since it seems that enumerations don't change*).
Erik
* ... but then, when I tried the code, it says that tuples don't have
the attribute 'index' -- what gives? I thought that tuples and lists
were pretty much the same, except for immutableness on the part of
tuples.