[Tutor] Having Unusual results

Peter Otten __peter__ at web.de
Sat May 2 10:36:19 CEST 2015


Jag Sherrington wrote:

> Hi Can anyone tell me where I am going wrong the end result doesn't add
> up? 

Leaving out the Python side for a moment let's look again at one part of 
your problem:

You need 20 buns.
There are 8 buns in a package.
How many packages do you need?

You could say 2.5 because 2.5 * 8 == 20. But when you go to the shop you are 
limited to buying complete packages. Two won't do, so you have to take three 
packages and cope with the 4 extra buns. 

How can this be calculated in Python? One way is integer division:

>>> 20 // 8
2

Integer division always gives you a number equal or one below the actual 
number of packages:

>>> 21 // 8
2
>>> 23 // 8
2
>>> 24 // 8
3

To find out if you need an extra package you can calculate the rest with

>>> buns = 20
>>> package_size = 8
>>> buns - (buns // package_size) * package_size
4

You need 4 more buns and thus an extra package. Spelt in Python:

>>> buns = 20
>>> package_size = 8
>>> whole_packages = buns // package_size
>>> missing_buns = buns - (buns // package_size) * package_size
>>> if missing_buns:
...     total_packages = whole_packages + 1
... else:
...     total_packages = whole_packages
... 
>>> total_packages
3

Can we simplify that? Python has an operator to calculate the rest or 
"modulo" directly:

>>> 20 % 8
4
>>> 21 % 8
5
>>> 22 % 8
6
>>> 23 % 8
7
>>> 24 % 8
0

There's also a way to calculate // and % in one step:

>>> divmod(20, 8)
(2, 4)

With that the calculation becomes

>>> buns = 20
>>> package_size = 8
>>> whole_packages, missing_buns = divmod(buns, package_size)
>>> total_packages = whole_packages
>>> if missing_buns: total_packages += 1
... 
>>> total_packages
3

You can also find out the leftover buns:

>>> unused_buns = (total_packages * package_size) % buns
>>> unused_buns
4

Enjoy your meal ;)



More information about the Tutor mailing list