[Tutor] Help with Guess the number script
Danny Yoo
dyoo at hashcollision.org
Fri Mar 7 10:05:42 CET 2014
Can you split the conditions so that they're not overlapping?
One of the things that you learn about programming is that if the
program is hard for humans to read, even if the program is computing
something useful, you may want to work to make it humanly
understandable, even if the human is having a bad day. :P
That is, if you're doing something like:
if A: ...
if B: ...
elif C: ...
elif D: ...
else: ...
if E: ...
elif F: ...
elif G: ...
else: H: ...
which is, roughly, the control flow within your program, then it
should not be too surprising that this is unexpectedly difficult to
understand. I don't understand it.
Can you try to rephrase what you're doing as a bunch of
_nonoverlapping_ alternatives?
That is, just look at the conditions your program has now.
#############################################
if guess < secret:
...
elif guess < (secret - 10) or guess > (secret - 10):
...
elif guess < (secret - 5) or guess > (secret - 5):
....
#############################################
I can't tell, from a glance, that these conditions aren't overlapping.
Wait. In fact, I'm pretty sure they are overlapping.
Concretely, if guess is 0 and secret is 11, then the first, second,
and third cases are all true.
This is a sign that the case analysis is fragile.
To get it right: draw it out graphically. It will help. You are
trying to break down the number line into sections.
---------------------------secret-------------------------
where you want some condition to capture warmness:
Case A:
-----------------(--------)secret(--------)----------------
You want another to capture not-so-warmness
Case B:
--------(-------)----------secret----------(-------)-------
one for the too-low case:
Case C:
-------)-------------------secret--------------------------
one for the too-high case:
Case D:
---------------------------secret-------------------(------
What's case have we forgotten? The winning one: the one where the
secret and the guess are the same! Call that Case E.
Ok, that should cover it all, right? Notice that these are _five_
distinct, non-overlapping cases, and it should be exhaustive. For any
guess and secret, exactly one of the cases above will apply. And
because the conditions don't overlap, it won't even matter what order
you check for A, B, C, D, or E.
You might be able to break this down into a different case analysis.
But try doing the non-overlapping approach. It should be clear that,
if you express it well, it won't break on you.
If you have more questions, please feel free to ask. Good luck!
More information about the Tutor
mailing list