Homework 2, Question 3 (Median)

Hello everyone,

I wasn't going to post anything regarding this question -although it was graded as an incorrect answer- as i haven't used any of the predefined procedures. But i saw allot of posts answering the same questions and they did not use any of the predefined procedures (bigger & biggest) and there answers were somehow correct while mine wasn't!, although i have tested the code repeatedly and it was working correctly.
This is my code if anyone finds anything wrong with it please let me know.

def median(a,b,c):

    if a < b and c > b or c < b and a > b:
        med = b

    if c < a and b > a or b < a and c > a:
        med = a

    if b < c and a > c or a < c and b > c:
        med = c

    return med

print median(67,98,45)

Mind you there weren't any instructions that we must use the 'bigger' or 'biggest' procedures.

asked 08 Mar '12, 17:21

AlKhozaee%2C%20Bandar's gravatar image

AlKhozaee, B...
131
accept rate: 0%

edited 08 Mar '12, 18:00

Anton%20Golov's gravatar image

Anton Golov ♦
13.3k2174174


3 Answers:

Did you test it on repeated values such as (2,1,1)? It gets to return med without having assigned a value to med.

link

answered 08 Mar '12, 17:24

fnenu-1's gravatar image

fnenu-1 ♦♦
18.5k1981231

Your code does not consider the case where any of the numbers are identical. Ex: (1, 1, 2).

link

answered 08 Mar '12, 17:22

David%20Harris's gravatar image

David Harris
8.1k2155111

How on earth didn't i think of that?
I can't believe that it slipped my mind!

Thanks for the quick reply.

(08 Mar '12, 17:28) AlKhozaee, B... AlKhozaee%2C%20Bandar's gravatar image

same happened to me

code worked "perfect" - but I forgot to test the case when 2 numbers a re equal.

did that now (after it all was graded) and yes, my code gives out the wrong answer for that case.

sigh

my code was sooo simple :P

def median(a,b,c):

    if a<c:
        if b<a:
            return a
        else:
            if a<b:
                return b
    else:
        return c

but on print (7,5,7) it gave me 7 -- :(

link

answered 08 Mar '12, 17:28

michaela-1's gravatar image

michaela-1
6361719

edited 08 Mar '12, 18:01

Anton%20Golov's gravatar image

Anton Golov ♦
13.3k2174174

if c is the smalest your program don't work

(08 Mar '12, 17:55) drimoh drimoh's gravatar image

to be precise it will work, but c might not be the correct output, for example median(3, 2, 1) would output 1

(08 Mar '12, 18:02) Gytis Zilinskas Gytis%20Zilinskas's gravatar image
Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×15,274
×1,718
×76
×43

Asked: 08 Mar '12, 17:21

Seen: 152 times

Last updated: 08 Mar '12, 18:02