[Tutor] Beginner's question
Steven D'Aprano
steve at pearwood.info
Fri Nov 23 02:16:43 CET 2012
On 23/11/12 01:56, Peter O'Doherty wrote:
> This code appears to work although it's very cumbersome. Is
>there a better way to do it?
Of course it is cumbersome, that's because of the artificial
constraints set on the problem. I quote from your description
of the problem:
"using only the simple operators and keywords above,
no functions, lists or any other form of iteration."
This constraint makes the problem cumbersome. Imagine if we needed
to do the same thing for a thousand numbers, not just three!
The solution you give isn't quite right -- it works for the
example given, but not others. There are thirteen cases to consider:
1) none of the numbers are odd;
2) only x is odd;
3) only y is odd;
4) only z is odd;
5) only x is even, and y is largest;
6) only x is even, and z is largest;
7) only y is even, and x is largest;
8) only y is even, and z is largest;
9) only z is even, and x is largest;
10) only z is even, and y is largest;
11) all of the numbers are odd, and x is largest;
12) all of the numbers are odd, and y is largest;
13) all of the numbers are odd, and z is largest.
not including cases where two or more numbers are odd and equal since
that can be naturally handled.
Whatever solution you come up with, it needs to work correctly with
all thirteen cases. The code you gave fails on case #1, and possibly
others.
However, just because there are thirteen different cases to check,
doesn't mean your code needs thirteen different branches! Think of
the problem slightly differently:
Suppose you only had *one* number to check.
if x is odd:
set the biggest odd number yet seen to x
if we haven't seen a biggest odd number yet:
print "no biggest odd number seen"
otherwise:
print the biggest odd number seen
Easy, right? Now add a second number:
if x is odd:
set the biggest odd number yet seen to x
if y is odd:
if we haven't seen a biggest odd number yet:
set the biggest odd number yet seen to y
otherwise, we have seen a biggest odd number, so:
if y is larger than the biggest odd number yet seen:
set the biggest odd number yet seen to y
if we haven't seen a biggest odd number yet:
print "no biggest odd number seen"
otherwise:
print the biggest odd number seen
Can you extend that to a third number, z?
Can you convert that pseudo-code into Python code?
Hint:
Python doesn't make it easy to check whether a variable exists.
The easy way is to set a placeholder value that cannot be mistaken
for a legitimate value, and then check whether the variable equals
the placeholder. "variable is None" or "variable is not None" are
the standard ways to do this.
Finally, here is how I would solve the problem for real:
try:
print max(filter(lambda n: n%2 != 0, (x, y, z)))
except ValueError:
print ('no largest odd number')
You are not expected to understand this! Especially not the
mysterious lambda.
--
Steven
More information about the Tutor
mailing list