Decisions inside decisions
Put a choice inside another choice, one question at a time. About 9 minutes.
A question, then a follow-up
A doctor asks first: do you have a fever? If you don't, that is the end of it. If you do, she asks a second question: for how many days? The second question only makes sense after the first answer.
Code does this by putting an if inside another if. The inner lines only get a turn when the outer condition is true. You can nest as deep as you like, but each level is more to keep in your head.
Sorting triangles
Here's a good example. Three sticks can only form a triangle if any two of them are together longer than the third. That's the outer question. If it fails, the answer is "impossible".
If it passes, you ask the inner questions: are all three the same length (equilateral)? Are exactly two the same (isosceles)? Otherwise they are all different (scalene).
if a + b > c and a + c > b and b + c > a:
if a == b and b == c:
kind = "equilateral"
elif a == b or b == c or a == c:
kind = "isosceles"
else:
kind = "scalene"
else:
kind = "impossible"- possible
- yes
The outer question: can these sticks make a triangle at all? 5 plus 5 is 10, which is more than 8. The other two pairs pass too.
Sticks of length 2, 3 and 6. What kind of triangle do they make?
- AImpossible
- BScalene
- CIsosceles
Show the answer
Impossible. 2 plus 3 is only 5, which is less than 6, so the two short sticks can't reach each other.
Triangle kind
You get three stick lengths. If they can't form a triangle (some two sticks together are not longer than the third), return "impossible". Otherwise return "equilateral" if all three are equal, "isosceles" if exactly two are equal, and "scalene" if all are different.
a = 5, b = 5, c = 8 → "isosceles"
1 ≤ a, b, c ≤ 1,000