Skip to content

Commit 3b70109

Browse files
committed
finding new date after subtracting certain months in given date
1 parent c83388e commit 3b70109

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
3+
"""
4+
implement function 'subtract_months' to subtract 'n' number of months from a given year and month.
5+
6+
Inputs: Is a list of tuples [(year1, month1, months_to_subtract1), (year2, month2, months_to_subtract2), ...]
7+
where, year is a 4 digit integer
8+
month is an interger value between 1 to 12, 1=January, 2=February, ... 12=December) and
9+
months_to_subtract is an integer
10+
11+
Output: Is a list of tuples [(result_year1, result_month1), (result_year2, result_month2), ...]
12+
year (4 digit integer) month (interger value between 1 to 12, 1=January, 2=February, ... 12=December)
13+
14+
For example: subtract 3 months from May 2020. This should result in an output Feb 2020
15+
In this example inputs: year=2020 month=5
16+
output: year=2020 month=2
17+
18+
Code evaluation criteria:
19+
1. Correctness for all possible cases
20+
2. Code should be clean and readable
21+
3. optimal with respect to time and space complexity (e.g. avoid unnecessary extra variables and loops)
22+
23+
"""
24+
25+
def subtract_months(input_list):
26+
output_list = []
27+
28+
#TODO: implement your code here
29+
30+
for input_data in input_list:
31+
32+
assert len(input_data) == 3
33+
34+
year = input_data[0]
35+
month = input_data[1]
36+
months_to_subtract = input_data[2]
37+
38+
if months_to_subtract > 12:
39+
left_month = months_to_subtract - month
40+
41+
if left_month >= 12:
42+
43+
minus_year = left_month // 12
44+
output_year = year - minus_year - 1
45+
months_to_be_subtracted = left_month - (12 * minus_year)
46+
output_list.append((output_year, 12 - months_to_be_subtracted))
47+
48+
else:
49+
output_list.append((year-1, 12 - left_month))
50+
51+
else:
52+
if months_to_subtract < month:
53+
output_month = month - months_to_subtract
54+
output_list.append((year, output_month))
55+
56+
else:
57+
output_year = year - 1
58+
output_month = 12 - (months_to_subtract - month)
59+
output_list.append((output_year, output_month))
60+
61+
return output_list
62+
63+
64+
65+
# subtract_months([(2020, 5, 3), (2020, 6, 7), (2020, 5, 30), (2020, 5, 15), (2020, 5, 8)])

0 commit comments

Comments
 (0)