Please tell the error in code below, as seems as perfectly fine as it's alternative.
Please tell why the below code is considered incorrect?
Code:
def is_leap(year): The alternative provided is : Code:
def is_leap(year): Also, ran the stated (earlier) code, and gives correct results. |
Please provide why the first code is incorrect?
|
First all, this is python.
Both of those work. Code:
python Code:
>>> def is_leap(year): |
The Python code for determining a leap year is "calendar.isleap(year)"
Anything else is redundant code. If this is homework, then a correct answer should start by pointing out the built-in function, then solving it anyway, along with with a full set of test cases showing how the function handles all edge cases correctly. The "alternative provided" is stupidly over-verbose but also looks like it is a correction of different code - so maybe the teacher sent you an updated version of someone else's attempt. Have you tried asking the teacher? |
Quote:
|
Quote:
Code:
def isleap(year): |
I would suggest that if you are doing a course then it is expecting specific answers.
Whilst your version may work and still be correct, it would appear the source material required the answer provided |
I actually prefer your version, as long as it can be proved to be correct using an appropriate set of test cases. I have doubts about the second with regard to the "% 400" case, since "% 100" is tested first, and it would also "pass" the "400 case." Very importantly, yours does not do that.
However, I would have written the final bit as: "else return false." I would not bother to have a "leap" variable – just "return true/false" – because you never subsequently test that variable. The resulting code is clear: the most-restrictive case first, each one directly "returns" true or false, and the final "else" exists to very-clearly show the catch-all case. But, such a function then needs to be rigorously tested against a set of appropriately-chosen dates which test both the expected results and the "edge cases." |
All times are GMT -5. The time now is 04:26 AM. |