Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

python - Return the right string according to the condition

I try to solve the following problem

Write function bmi that calculates body mass index (bmi = weight / height ^ 2).

Return values based on the calculated bmi value:

if bmi <= 18.5 return "Underweight"

if bmi <= 25.0 return "Normal"

if bmi <= 30.0 return "Overweight"

if bmi > 30 return "Obese"

My code:

def bmi(weight, height):
    b = weight / height ** 2
    return ['Underweight', 'Normal', 'Overweight' , 'Obese'][(b <= 18.5) + (b <= 25) + (b <=30)]

I get a wrong answer anyone know where is the mistake ?

question from:https://stackoverflow.com/questions/65850205/return-the-right-string-according-to-the-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Think about the actual output of the following statement:

(b <= 18.5) + (b <= 25) + (b <=30)

if b is 18, then all 3 will be true, so the output will be 3 - "Obese". If b is 24, then the second and third condition will be true, so the output will be 2 - "Overweight". If b is 29, then only the third condition will be true, so the output will be 1 - "Normal". If b is 31, then none of them will be true, so the output will be 0 - "Underweight".

A solution would be to reverse your array:

['Obese', 'Overweight', 'Normal', 'Underweight'][(b <= 18.5) + (b <= 25) + (b <=30)]

Or, you can reverse your conditions, so that the original order would work:

['Underweight', 'Normal', 'Overweight' , 'Obese'][(18.5 <= b) + (25 <= b) + (30 <= b)]

In this case, if b is 18, then (18.5 <= b) is False, (25 <= b) is False, and (30 <= b) is False, so the output is 0, "Underweight". If b is 24, then (18.5 <= b) is True, (25 <= b) is False, and (30 <= b) is False, so the output is 1, "Normal". If b is 29, then (18.5 <= b) is True, (25 <= b) is True, and (30 <= b) is False, so the output is 2, "Overweight". Lastly, if b is 31, then (18.5 <= b) is True, (25 <= b) is True, and (30 <= b) is True, so the output is 3, "Obese".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...