[Tutor] Complicating a simple expression (Python 3)

Alan Gauld alan.gauld at btinternet.com
Sun Aug 16 23:14:37 CEST 2015


On 16/08/15 21:28, Joseph Gulizia wrote:

> Assume that the grader defines two variables A and B for you. Write a
> program which prints out the value
> min(A, B)

So far a trivial exercise.

> However, there is a catch: your program is not allowed to use the min
> function. Instead, use max in a clever way to simulate min.

Now its just a stupid exercise. I rally hate when teachers
do this. It shows great lack of imagination and actively
teaches bad habits... sigh!

> Hint, Method 1
> What is max(-A, -B)?

> Hint, Method 2
> What is min(A, B)+max(A, B)?

Note that these are two separate methods.
You don't need both of them. In fact you
don't really need either of them! Writing
the min functionality directly is not
exactly difficult!

> My last code that worked somewhat
> -----------------------------------
> Original = max(A, B)
> Opposite = max(-A, -B)
> Grader =max(-A,- B)+max(A, B)
>
> print (Grader)

OK, Can you explain how you thought that might work?

> Before running your code: We defined A equal to 62 and B equal to 36.
>
> 26

Which is what doing the math suggests:

max (-62, -36) is -36
and max(62,36) is 62
so 62 + (-36) is 26

> Expected this correct output:
>
> 36

Which is the correct min of 36 and 62

> Result of grading: Your output is not correct.
>
>
> Spreadsheet examples:
> A    B        Max(A, B)    Min(A, B)    Min(A, B)+Max(A, B)    Max(A,
> B)+Max(A, B)    Min(A, B)+Min(A, B)
> 10    5        10        5        15            20            10
> 5    10        10        5        15            20            10
> 9    12        12        9        21            24            18
> 12    9        12        9        21            24            18
> 22    37        37        22        59            74            44
> 37    22        37        22        59            74            44
> 45    68        68        45        113            136            90
> 68    45        68        45        113            136            90
>
>
> Max(-A,- B)        Max(-A,- B)+Max(A, B)        Max(-A,- B)-Max(A, B)
> -5            5                -15
> -5            5                -15
> -9            3                -21
> -9            3                -21
> -22            15                -59
> -22            15                -59

This probably lost a little in (email) translation, but looks like
overkill to me. Choose one of the two methods above, since
that's what they ask you to do.

But it's just as easy to implement min() directly:

if A < B: min = A
else: min = B

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list