[Tutor] Beginner's question
Peter O'Doherty
mail at peterodoherty.net
Thu Nov 22 15:56:09 CET 2012
On 11/22/2012 03:17 PM, Walter Prins wrote:
> Hi Peter,
>
>
> On 22 November 2012 12:55, Peter O'Doherty <mail at peterodoherty.net
> <mailto:mail at peterodoherty.net>> wrote:
>
> Hi list,
> Firstly, apologies for the low-level nature of this question -
> it's really quite basic but I don't seem to be able to solve it.
>
> 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
>
> if x > y and x > z and x%2 != 0:
> print 'x is largest and odd'
> elif y > x and y > z and y%2 != 0:
> print 'y is largest and odd'
> elif z > x and z > y and z%2 != 0:
> print 'z is largest and odd'
> else:
> print 'no odd'
>
>
> The key logical mistake you make is that by your current logic the
> *smallest* number can never be the largest odd number, which is
> obviously false as in your example.
>
> Break the problem down (divide and conquer). Suppose I gave you only
> 2 numbers, and you had to say which of the 2 numbers were the largest
> odd, what would be the possible outcomes and what would the the
> solution be? (Hint, both can be odd, only x can be odd, only y can be
> odd, or neither can be odd.) Once you have that answer, then repeat
> the exact same solution for the first 2 numbers and apply to the
> answer from x&y and and the remaining z. The result from that is
> tells you the largest odd number from all 3. (Aside, your question
> states to print the largest odd number, which I interpret to mean the
> value, not the name of the variable holding the value. )
>
> Walter
Thanks Walter.
This code appears to work although it's very cumbersome. Is there a
better way to do it?
x, y, z = 6, 23, 16
if x%2 != 0 and y%2 !=0:
if x > y:
ans = x
else:
ans = y
elif x%2 !=0 and y%2 == 0:
ans = x
else:
ans = y
if ans%2 != 0 and z%2 !=0:
if ans > z:
ans = ans
else:
ans = z
elif ans%2 !=0 and z%2 == 0:
ans = ans
else:
ans = z
print str(ans) + ' is largest odd'
Regards,
Peter
--
//=============================
-> Peter O'Doherty
-> http://www.peterodoherty.net
-> mail at peterodoherty.net
-> https://joindiaspora.com/people/70716
//=============================
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121122/98a0b1fd/attachment-0001.html>
More information about the Tutor
mailing list