How to find leap year leap year useing python - for-loop

hello my name is chetan I am trying the python code of leap year and nonleap year
can you give me a code for this program
I want to try how to check leap year and nonleap year using python but my code was incorrect.

y=int(input("enter your year : "))
if (y % 400 == 0) or (y % 4 == 0 and y % 100 != 0) :
print("It is a leap year")
else :
print("It is not a leap year")

Related

3 condition python while loop regarding checking if two dates are the same

I'm currently working on this problem of counting how many days between two dates including leap years.
However it keeps skipping the loop from the beginning, even though the two months and days aren't the same?
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
day_count = 0
while (year2 != year1) and (month2 != month1) and (day2! = day 1):
# print "in loop" // tester
if (day2 != 0):
day2 = day2 - 1
day_count = day_count + 1
else:
if(month2 != 0):
month2 = month2 - 1
if month2 == (9 or 4 or 6 or 11):
day2 = 30
if month2 == 2:
day2 = 28
if (month2 == 2) and (year2 % 4):
day2 = 29
else:
day2 == 31
else:
year2 = year2 - 1
month2 = 12
#print day_count //tester
return day_count
# Test routine
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
Here's one way.
>>> from datetime import datetime
>>> diff = datetime(2012, 2, 28)-datetime(2012, 1, 1)
>>> diff.days
58

Ruby Determine Season (Fall, Winter, Spring or Summer)

I am working on a script that is supposed to determine the "season" of the year based on date ranges:
For Example:
January 1 - April 1: Winter
April 2 - June 30: Spring
July 1 - September 31: Summer
October 1 - December 31: Fall
I am not sure how the best way (or the best ruby way) to go about doing this. Anyone else run across how to do this?
31 September?
As leifg suggested, here it is in code:
require 'Date'
class Date
def season
# Not sure if there's a neater expression. yday is out due to leap years
day_hash = month * 100 + mday
case day_hash
when 101..401 then :winter
when 402..630 then :spring
when 701..930 then :summer
when 1001..1231 then :fall
end
end
end
Once defined, call it e.g. like this:
d = Date.today
d.season
You could try with ranges and Date objects:
http://www.tutorialspoint.com/ruby/ruby_ranges.htm
without ranges.
require 'date'
def season
year_day = Date.today.yday().to_i
year = Date.today.year.to_i
is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
if is_leap_year and year_day > 60
# if is leap year and date > 28 february
year_day = year_day - 1
end
if year_day >= 355 or year_day < 81
result = :winter
elsif year_day >= 81 and year_day < 173
result = :spring
elsif year_day >= 173 and year_day < 266
result = :summer
elsif year_day >= 266 and year_day < 355
result = :autumn
end
return result
end
Neil Slater's answer's approach is great but for me those dates aren't quite correct. They show fall ending on December 31st which isn't the case in any scenario I can think of.
Using the northern meteorological seasons:
Spring runs from March 1 to May 31;
Summer runs from June 1 to August 31;
Fall (autumn) runs from September 1 to November 30; and
Winter runs from December 1 to February 28 (February 29 in a leap year).
The code would need to be updated to:
require "date"
class Date
def season
day_hash = month * 100 + mday
case day_hash
when 101..300 then :winter
when 301..531 then :spring
when 601..831 then :summer
when 901..1130 then :fall
when 1201..1231 then :winter
end
end
end

Leap year in FreePascal

Input - Year
Output - Leap year or not
I have tried
Program LeapYear;
var
Year:Integer
begin
writeln('Insert year');
readln(Year)
if Year MOD 4 = 0 and Year MOD 100 = 0 and not Year MOD 400 = 0 then
begin
writeln(Year,'is leap year')
end
else
begin
writeln(Year,'is not leap year')
end
end.
But this is not working
Your algorithm is wrong. It should be:
if (year mod 400 = 0) or ((year mod 4 = 0) and not (year mod 100 = 0))
The IsLeapYear function is already defined in the datih.inc file, so you don't need write your own version, only you must add the sysutils unit.
Hope it helps:
if((a MOD 4) = 0) and ((a MOD 100) = 0) and ((a MOD 400) = 0) then y:=true
else y:=false;
Program LeapYear;
Uses crt;
var
Year:Integer;
begin
clrscr;
writeln('Insert year');
readln(Year);
if (Year MOD 4 = 0)then
writeln(Year,'is leap year');
If (Year Mod 4 >=1 ) Then
writeln(Year,'is not leap year')
end.

Calculating number of days between two dates that are in a leap year

Given two dates, what is the best method to calculate the number of days between those two dates that fall in a leap year.
For example if d1 = 12/1/2007 and d2 = 1/31/2008 then the total number of days between d1 and d2 would be 62 and the number of days that fall in a leap year would be 31.
Another example is if d1 = 12/1/2007 and d2 = 6/30/2012 then the total number of days between d1 and d2 would be 1674 and the number of days that fall in a leap year would be 548.
I already have function to calculate if a specific year is a leap year and and a function to calculate the number of days between two dates.
If anyone has such a algorithm in Delphi (Pascal) or C/C++/C# that would be greatly appreciated. Any suggestions and assistance would be great.
The solution is in python, and it shouldn't be hard to convert to any other language.
def isLeapYear(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
return True
else:
return False
else:
return True
else:
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
cumDays = [0,31,59,90,120,151,181,212,243,273,304,334] #cumulative Days by month
leapcumDays = [0,31,60,91,121,152,182,213,244,274,305,335] # Cumulative Days by month for leap year
totdays = 0
if year1 == year2:
if isLeapYear(year1):
return (leapcumDays[month2-1] + day2) - (leapcumDays[month1-1] + day1)
else:
return (cumDays[month2-1] + day2) - (cumDays[month1-1] + day1)
if isLeapYear(year1):
totdays = totdays + 366 - (leapcumDays[month1-1] + day1)
else:
totdays = totdays + 365 - (cumDays[month1-1] + day1)
year = year1 + 1
while year < year2:
if isLeapYear(year):
totdays = totdays + 366
else:
totdays = totdays + 365
year = year + 1
if isLeapYear(year2):
totdays = totdays + (leapcumDays[month2-1] + day2)
else:
totdays = totdays + (cumDays[month2-1] + day2)
return totdays
Here's my pseudo code version using your functions for - is_leap_year, days_between. As a commenter noted, these are tricky functions to write correctly.
int leap_year_days_between(Date d1, Date d2) {
if (d1.year == d2.year) {
if (is_leap_year(d1.year) { return days_between(d1,d2); }
else { return 0; }
}
else {
Date last_day_in_year(12, 31, d1.year);
int count=0;
Date tmp = d1;
while (tmp.year < d2.year) {
if ( is_leap_year(tmp.year) ) {
count += days_between(tmp,last_day_in_year);
}
tmp = (1, 1, tmp.year+1);
}
if ( is_leap_year(d2.year) ) {
count += days_between(tmp, d2);
}
}
}
A naive approach would be:
Check your start year. If it's a leap year, count the number of days from your current day to December 31 (inclusive). If not, until your starting year equals your ending year, increment the year by 1. Then, check the year. If it is a leap year, start counting days, if not increment the year. Once the current year and ending year are the same, then check to see if the current (== ending) year is a leap year. If it is, count days in months from January to the ending month, otherwise break the algorithm. Once your current month is your ending month, count your days.

Algorithm to determine if a given date/time is between two date/time pairs

I have an array of dates in a one week range stored in an unusual way.
The Dates are stored in this numeric format: 12150
From left to right:
1st digit represents day: 1 = sunday, 2 = monday, 3 = tuesday, ...., 7 = saturday
next two digits represent hour in a 24 hour system: 00 = midnight, 23 = 11pm
next two digits represent minutes: 00-59
Given an input date and a start date and end date I need to know if the input date is between the start and end date.
I have an algorithm right now that I think works 100% of the time, but I am not sure.
In any case, I think there is probably a better and simpler way to do this and I was wondering if anybody knew what that algorithm was.
If not it would be cool if someone could double check my work and verify that it does actually work for 100% of valid cases.
What I have right now is:
if (startDate < inputDate &&
endDate > inputDate) {
inRange = yes;
}
else if (endDate < startDate) {
if((inputDate + 72359) > startDate &&
(inputDate + 72359) < endDate) {
inRange = yes;
}
else if((inputDate + 72359) > startDate &&
(inputDate + 72359) < (endDate + 72359)) {
inRange = yes;
}
}
How about
const int MAX = 72460; // Or anything more than the highest legal value
inRange = (MAX + inputDate - startDate) % MAX <
(MAX + endDate - startDate) % MAX;
This assumes of course that all the dates are well formed (according to your specs).
This addresses the case where the start is "after" the end. (e.g. Friday is in range if start is Wednesday and end is Monday)
It may take a second to see (which probably isn't good, because readability is usually the most important) but I think it does work.
Here's the basic trick:
Legend:
0: Minimum time
M: Maximum time
S: Start time
1,2,3: Input Time test points
E: End Time
The S E => Not in range
2 In range
3 > E => Not in range
The S > E case
0 M
Original -1--E----2---S--3--
Add Max -------------------1--E----2---S--3--
Subtract StartDate ------1--E----2---S--3--
% Max S--3--1--E----2----
1 In range
2 > E => Not in range
3 In range
If you really want to go nuts (and be even more difficult to decipher)
const int MAX = 0x20000;
const int MASK = 0x1FFFF;
int maxMinusStart = MAX - startDate;
inRange = (maxMinusStart + inputDate) & MASK <
(maxMinusStart + endDate) & MASK;
which ought to be slightly faster (trading modulus for a bitwise and) which we can do since the value of MAX doesn't really matter (as long as it exceeds the maximum well-formed value) and we're free to choose one that makes our computations easy.
(And of course you can replace the < with a <= if that's what you really need)
There is some logic error with dates in that format. Since the month and year information is missing, you cannot know what calendar day is missing. e.g. 50755 might be Thursday March 12 2009, but it might just as well be exactly a week ago, or 18 weeks ahead. That for you could never be 100% sure if any date in that format is between any other 2 dates.
Here the condition of the inner if can never be true, since endDate < startDate:
if (endDate < startDate) {
if((inputDate + 72359) > startDate &&
(inputDate + 72359) < endDate) {
// never reached
inRange = yes;
}
The following if also can't be optimal, since the first part is always true and the second part is just identical to inputDate < endDate:
if((inputDate + 72359) > startDate &&
(inputDate + 72359) < (endDate + 72359))
I think you want something like this:
if (startDate < endDate)
inRange = (startDate < inputDate) && (inputDate < endDate);
else
inRange = (startDate < inputDate) || (inputDate < endDate);
you should use >= and <= if you really want it in range
say i pick this date 10000 or 72359, how you would handle this? it is in range or not?
also i didn't know value for startDate and endDate since you didn't initialize it, correct me if i were wrong, variable that didn't initialized will start with 0 or null or ''
so i assume the startDate = 10000 and endDate 72359
btw why you pick this kind of array (as int or string value?) why first value was day? not date example:
010000 -> date 1st of the month 00:00
312359 -> date 31th of the month 23:59
but it's up to you :D
so sorry if i were wrong i took algorithm class only on university and it was 5 years ago :D
A better approach might be to normalize your data converting all the day of the week values to be relative to the start date. Something like this:
const int dayScale = 10000; // scale factor for the day of the week
int NormalizeDate(int date, int startDay)
{
int day = (date / dayScale) - 1; // this would be a lot easier if Sunday was 0
int sday = startDay - 1;
if (day < sday)
day = (day + 7 - sday) % 7;
return ((day+1) * dayScale) + (date % dayScale);
}
int startDay = startDate / dayScale; // isolate the day of the week
int normalizedStartDate = NormalizeDate(startDate, startDay);
int normalizedEndDate = NormalizeDate(endDate, startDay);
int normalizedInputDate = NormalizeDate(inputDate, startDay);
inRange = normalizedInputDate >= normalizedStartDate &&
normalizedInputDate <= normalizedEndDate;
I am pretty sure this will work as written. In any case, the concept is cleaner that multiple comparisons.
The simplest solution i found is this:
said x your generic time and S, E the start and end time respectively (with 0 < S,E < T):
f(x) = [(x-S) * (x-E) * (E-S) < 0]
This function returns TRUE if x is in between the start and end time, and FALSE otherwise.
It will also take care of start time bigger than end time (i.e. you start working at 20:00 and finish at 04:00, 23:13 will return TRUE)
i must say, considering the multiplications, it could not be the most efficient in terms of speed, but it is definitely the most compact (and pretty IMHO)
EDIT:
i found a much more elegant and efficient solution:
f(x) = (x<S) XOR (x<E) XOR (E<S)
you can substitute XOR with the "different" operator ( != )
I explain it:
The first formula comes from the considering the relation inequality study:
if S < E:
...............S.....E..........
(x-S)----------+++++++++++++++++
(x-E)----------------+++++++++++
(E-S)+++++++++++++++++++++++++++
total++++++++++------+++++++++++
so, the total is negative if x is in between S and E
if S > E:
...............E.....S..........
(x-S)----------------+++++++++++
(x-E)----------+++++++++++++++++
(E-S)---------------------------
total----------++++++-----------
so, the total is negative if x is bigger than S or smaller than E
To reach the final equation, you decompose the first formula in 3 terms:
(x-S)<0 => x<S
(x-E)<0 => x<E
(E-S)<0 => E<S
the product of these terms is negative only if they are all negative (true, true, true) or only one is negative and the other are positive (true, false, false, but the order does not matter)
Therefore the problem can be solved via
f(x) = (x<S) != (x<E) != (E<S)
These solution can be applied to any similar problem with periodic system, such as checking if the angle x is inside the arc formed by the two angles S and E.
Just make sure that all the variable are between 0 and the period of your system (2PI for arcs in a circle, 24h for hours, 24*60*60 for the seconds count of a day.....and so on)

Resources