Problem Solving with Selection
Problem Set
The following problem sets are intended for practice. Attempt these on your own.
Largest of Three
Problem
Problem Description
Given three real numbers \(n_1\), \(n_2\), and \(n_3\), we want to find the largest of the three. Note that the largest one may not be unique, but we simply want the largest one. See the sample below.
- \(n_1 = 0.1\)
- \(n_2 = 0.3\)
- \(n_3 = 0.2\)
Largest is \(0.3\)
- \(n_1 = -0.1\)
- \(n_2 = -0.2\)
- \(n_3 = -0.3\)
Largest is \(-0.1\)
- \(n_1 = 0\)
- \(n_2 = 0\)
- \(n_3 = 0\)
Largest is \(0\)
Task
Write Python code to compute and print the largest of the three number.
Assumptions
n1
,n2
, andn3
are floating point numbers.n1
,n2
, andn3
are already initialized.
Hints
Hint #1
What is the condition to know if \(n_1\) is the largest number? Can you figure out the other conditions?
Note that we need to use >=
because there is a possibility there are two numbers that are equal.
Hint #2
What constructs do you need to use? What about for the subsequenc check?
We need at least one if-statement.
For the other, we need to use elif
because there is a possibility there are two numbers that are equal.
Possible Solution
There is an alternative solution by assuming that n1
is the largest.
Then we challenge that by checking if n2
is the current largest.
Finally, we challenge that by checking if n3
is the current largest.
The advantage of this technique is that it can be extended easily to more numbers without changing the condition too much.
Can you write the code based on this idea?
Waist-to-Hip Ratio
Problem
Problem Description
Waist-to-hip ratio (WHR) is an alternative to body mass index (BMI) indicator to measure if a given person is of normal weight, overweight, or obese. The computation requires two values:
- Waist measurement in cm.
- Hip measurement in cm.
First we compute the ratio of waist to hip and determine the weight indicator using the table below. Note that the indicator depends on whether the patient is male or female.
Male | Female | Indicator |
---|---|---|
< 0.9 | < 0.8 | Normal |
0.9 - 1.00 | 0.8 - 0.85 | Overweight |
> 1.00 | > 0.85 | Obese |
Task
Write Python code to compute and print weight indicator given three variables is_male
, waist
, and hip
.
Assumptions
is_male
is a boolean.waist
andhip
are positive floating point numbers (i.e.,waist > 0
andhip > 0
).waist
andhip
are given in cm.
Hints
Hint #1
Can you compute the waist-to-hip ratio?
Hint #2
Let us use nested if-statements.
Consider checking is_male
first.
What should be the inner condition?