[Tutor] Beginner's question
Dave Angel
d at davea.name
Thu Nov 22 16:49:12 CET 2012
On 11/22/2012 10:14 AM, Joel Goldstick wrote:
>> > Peter O'Doherty wrote:
>>> > >
>>> < snip >
>>> > > I need to write a program that examines 3 variables x, y, z, and prints
>>> > > the largest odd number. I've tried all sorts of variations and this is
>>> > > the current version:
>>> > >
> x, y, z = 26, 15, 20
>
> largest = None
> if x %2:
> largest = x
> if y % 2:
> if y > largest:
> largest = y
> if z % 2:
> if z > largest:
> largest = z;
>
> if Largest:
> print "largest value is", largest
> else:
> print "no odd values"
>
This one first gets into trouble if x is even and y is odd, because if
tries to compare y with None, which is basically an undefined ordered
comparison (and illegal in Python3, I believe). The flag value needs to
be an int, or at least numeric.
How about:
x, y, z = 26, 15, 20
if x%2 == y%2 == z%2 == 0:
print "No odd values"
else:
if x%2==0: x = y
if x%2==0: x = y #now x is odd
if y%2==0: y = x
if z%2==0: z = x
#at this point, they're all odd and we just want the largest one
if x < y: x, y = y,x
if x < z: x = z
print "largest odd value is", x
With the caveat that x, y, and z may get modified on their way through.
I doubt if that really violates the problem statement, however.
I didn't test this with all 120 cases, just with the data supplied.
--
DaveA
More information about the Tutor
mailing list