[Tutor] Basic terminology
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Feb 15 23:26:52 CET 2005
> A remainder is what's left over after a division:
>
> 10/3 = 3 remainder 1
> 12/5 = 2 remainder 2
> 27/3 = 9 remainder 0
>
> and the modulus operator (which is % in python) gives you that remainder:
>
> 10%3 = 1
> 12%5 = 2
> 27%3 = 0
Hi Bernard,
Another familiar example of modulo is checking to see if a number is even
or odd:
###
def isEven(n):
"""Check to see if n is divisible by 2."""
return n % 2 == 0
###
The remainder of 'n' divided by 2, that is, "n modulo 2", is zero if 'n'
is even.
Another cute thing about modulo is that we can use it to evenly distribute
things. Let's make this more concrete, or at least a little sweeter.
Imagine that it's Halloween, and we want to evenly distribute some candy
out to some trick-or-treaters:
###
people = ['fred', 'wilma', 'barney', 'betty']
candy = ['almond joy', 'take 5', 'cadbury', 'twizzlers',
'reeses', 'york', 'jolly rancher', 'nestle crunch']
###
There are two ways we can pass candy to the folks: we can give each people
two candies each:
###
>>> for (i, c) in enumerate(candy):
... print people[i / (len(candy) / len(people))], "gets", c
...
fred gets almond joy
fred gets take 5
wilma gets cadbury
wilma gets twizzlers
barney gets reeses
barney gets york
betty gets jolly rancher
betty gets nestle crunch
###
That is, since there are eight pieces of candy, and only four people, we
can give each person two pieces of candy each. We use simple division:
(i / (len(candy) / len(people))
==> i / 2
to figure out, given the index number of the candy, which person can seize
the sugary treat. So the first two pieces belong to fred, the second two
pieces belong to wilma, and so on.
Or we can do something that looks more round-robin:
###
>>> for (i, c) in enumerate(candy):
... print people[i % len(people)], "gets", c
...
fred gets almond joy
wilma gets take 5
barney gets cadbury
betty gets twizzlers
fred gets reeses
wilma gets york
barney gets jolly rancher
betty gets nestle crunch
###
And here, we use the modulo operator to figure out which person each candy
belongs to. In this case, we see the calculation involves:
i % len(people)
So there's this intimate relationship between division and modulo that
corresponds to two main ways we pass things out to people.
Does this make sense?
More information about the Tutor
mailing list