## BMI Calculator

### August 30, 2013

A person’s body mass index is a simple calculation based on height and weight that classifies the person as underweight, overweight, or normal. The formulas, for imperial and metric units, are:

BMI (imperial) = weight in pounds / (height in inches)

^{2}* 703

BMI (metric) = weight in kilograms / (height in meters)

^{2}

The usual categories are:

BMI <= 18.5: underweight

18.5 < BMI < 25: normal

25 <= BMI < 30: overweight

30 <= BMI < 40: obese

40 <= BMI: morbidly obese

For example, the BMI of a person who is 5′ 4″ and 125 pounds is 21.5 (normal) and the BMI of a person who is 190 centimeters and 95 kilograms is 26.3 (overweight).

Your task is to write a program that calculates the BMI and category given a person’s height and weight. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

My version in Python. I cheated a little with the categories. According to specs underweight is when bmi <= 18.5. Here it is if bmi < 18.5.

CATEGORIES = zip([18.5, 25, 30, 40, 1000], ["underweight", "normal",

"overweight", "obese", "morbidly obese"])

WEIGHT_CONV = dict(zip(["kg", "lbs", "ounce"], [1, 0.45359237, 0.0283495231]))

LENGTH_CONV = dict(zip(["m", "cm", "inch", "ft"], [1, 0.01, 0.0254, 0.3048]))

def val_metric(value, conv):

"""convert to metric units (kg, m)

allowed: 5 ft 8 inch or 100 lbs 3 ounce

"""

elements = value.split()

total = 0

while elements:

total += float(elements.pop(0)) * conv[elements.pop(0)]

return total

def bmi(weight, length):

w = val_metric(weight, WEIGHT_CONV)

l = val_metric(length, LENGTH_CONV)

bmi = w / l ** 2

for c, txt in CATEGORIES:

if bmi < c:

cat = txt

break

return bmi, cat

print "bmi=", bmi("160 lbs", "5 ft 7 inch")

Hopefully this time with better formatting:

Kawa has built-in support for Quantities (numbers with units), so here’s a solution using them instead of case-lambda:

The

`bmi-class`

function is the same as above.`(bmi 95kg 190cm) =>`

26.31578947368421

(bmi 125lb (+ 5ft 4in)) =>

21.4559633220829