# Leap year

Rustom Mody rustompmody at gmail.com
Mon Sep 29 08:58:42 CEST 2014

```On Saturday, September 27, 2014 9:21:15 AM UTC+5:30, Seymore4Head wrote:
> Still practicing.  Since this is listed as a Pseudocode, I assume this
> is a good way to explain something.  That means I can also assume my
> logic is fading with age.
> http://en.wikipedia.org/wiki/Leap_year#Algorithm

> Me trying to look at the algorithm, it would lead me to try something
> like:
> if year % 4 !=0:
> 	return False
> elif year % 100 !=0:
> 	return True
> elif year % 400 !=0:
> 	return False

> ****   Since it is a practice problem I have the answer:
> def is_leap_year(year):
> return ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0))

> I didn't have any problem when I did this:

> if year % 400 == 0:
> 	print ("Not leap year")
> elif year % 100 == 0:
> 	print ("Leap year")
> elif year % 4 == 0:
> 	print ("Leap year")
> else:
> 	print ("Not leap year")

Python has an if-expression distinct from the if-statement.
However its confusing because its order is 'upside down'

So below I use C's if-expression a?b:c to state some 'laws' of programming and leave it as an exercise to pythonify them

a?T:F ≡ a       A
a?F:T ≡ not a   B

a?T:b ≡ a or b     C
a?b:F ≡ a and b    D

if p:              E
return x
else:
return y

≡

return (p ? x : y)

Likewise

if p              F
print x
else
print y

≡

print (p ? x : y)
----------------------------
Now putting:
a ≜ y%4==0
b ≜ y%100!=0
c ≜ y%400 == 0

the expression that is the (given) answer is
a and (b or c)

Lets use the above laws to open it up
"by C"
a and (b ? T: c)
"by D"
a?(b?T:c):F

year%4==0 ? (y%100!=0 ? T: y%400==0) :  F

--------------------------

if year % 400 == 0:
print ("Not leap year")
elif year % 100 == 0:
print ("Leap year")
elif year % 4 == 0:
print ("Leap year")
else:
print ("Not leap year")

And now 'de-print' it [A good idea though I wont suggest it to you again!]

print (!c ? F : (b? T : (a? T : F)))

Forget about the print since its irrelevant and concentrate on

(!c ? F : (b? T : (a? T : F)))
"by A"
= (!c ? F : (b? T : a))
"by B"
= (c ? (b? T : a) : F)
"by D"
= (c and (b?T:a)
"by C"
= c and (b or a)

Lets re-substitute a,b,c

= y%400==0 and (y%100 !=0 or y%4 == 0)

which interpreted says that ONLY years divisible by 400 are leap
and not even all those!!

```