MATLAB One of the most frustrating aspects of using the Greg
MATLAB
One of the most frustrating aspects of using the Gregorian calendar is that it is difficult to communicate/compute elapsed time. For example, if I tell you that something is experiencing its 2-month anniversary, you don\'t know the exact number of days that have elapsed unless I tell you which 2 months - February 3rd to April 3rd is 59 days (in a non-leap year), while April 3rd to June 3rd is 61 days. For this problem, you need to write a program that will accept two days of the same year (in month-day form) and output the elapsed time between the two days (not including the last day!). To keep it simple, the program should first ask the user for the month of the first day, then the date of the first day, then the month of the second day, and lastly the date of the second day (so four total prompts). For example, if you wanted to know the elapsed number of days between September 4th and November 18th, you would enter 9 into the first prompt, 4 into the second prompt, 11 into the third prompt, and 18 into the fourth prompt. Assume that it is not a leap year!Solution
I wrote this in python. As the idea given in the problem, in order to count the number of days, we need to know which month has how many days. For that, maintaining a dictionary, then looping till month-1( because, we have the days of the current month) and adding days to it would give me the total number of days till that date. Doing this for both dates and keeping them in total1 and total2. Finally, finding the difference between total2 and total1 will be our result.
days_dict = {
1 : 31,
2 : 28,
3 : 31,
4 : 30,
5 : 31,
6 : 30,
7 : 31,
8 : 31,
9 : 30,
10 : 31,
11 : 30,
12: 31
}
month1 = int(raw_input(\"Enter month1:\"))
day1 = int(raw_input(\"Enter day1:\"))
month2 = int(raw_input(\"Enter month2:\"))
day2 = int(raw_input(\"Enter day2:\"))
# calculating the number of days since month1
total1 = 0
for i in range(1, month1):
try:
total1 += days_dict[i]
except KeyError:
raise KeyError(\"Something Went Wrong!!!\")
total1 += day1
total2 = 0
for i in range(1, month2):
try:
total2 += days_dict[i]
except KeyError:
raise KeyError(\"Something Went Wrong!!!\")
total2 += day2
print(\"Total number of days between given two dates is %d\" % (total2-total1))
Here\'s the output from my terminal
lokesh1729@lokesh1729-Inspiron-N5050:/tmp$ python calendar.py
Enter month1:2
Enter day1:3
Enter month2:4
Enter day2:5
Total number of days between given two dates is 61
lokesh1729@lokesh1729-Inspiron-N5050:/tmp$ python calendar.py
Enter month1:9
Enter day1:4
Enter month2:11
Enter day2:18
Total number of days between given two dates is 75
lokesh1729@lokesh1729-Inspiron-N5050:/tmp$ vim calendar.py
lokesh1729@lokesh1729-Inspiron-N5050:/tmp$ python calendar.py
Enter month1:1
Enter day1:4
Enter month2:2
Enter day2:6
Total number of days between given two dates is 33

