-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path4.3.1.7Lab.py
83 lines (68 loc) · 2.1 KB
/
4.3.1.7Lab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'''
Estimated time
15-20 minutes
Level of difficulty
Medium
Prerequisites
LAB 4.3.1.6
Objectives
Familiarize the student with:
projecting and writing parameterized functions;
utilizing the return statement;
utilizing the student's own functions.
Scenario
Your task is to write and test a function which takes two arguments (a year and a month) and returns the number of days for the given month/year pair (while only February is sensitive to the year value, your function should be universal).
The initial part of the function is ready. Now, convince the function to return None if its arguments don't make sense.
Of course, you can (and should) use the previously written and tested function (LAB 4.3.1.6). It may be very helpful. We encourage you to use a list filled with the months' lengths. You can create it inside the function - this trick will significantly shorten the code.
We've prepared a testing code. Expand it to include more test cases.
def is_year_leap(year):
#
# Your code from LAB 4.3.1.6.
#
def days_in_month(year, month):
#
# Write your new code here.
#
test_years = [1900, 2000, 2016, 1987]
test_months = [2, 2, 1, 11]
test_results = [28, 29, 31, 30]
for i in range(len(test_years)):
yr = test_years[i]
mo = test_months[i]
print(yr, mo, "->", end="")
result = days_in_month(yr, mo)
if result == test_results[i]:
print("OK")
else:
print("Failed")
'''
# solution
def is_year_leap(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
def days_in_month(year, month):
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month < 1 or month > 12:
return None
elif month == 2 and is_year_leap(year):
return 29
else:
return months[month-1]
test_years = [1900, 2000, 2016, 1987]
test_months = [2, 2, 1, 11]
test_results = [28, 29, 31, 30]
for i in range(len(test_years)):
yr = test_years[i]
mo = test_months[i]
print(yr, mo, "->", end="")
result = days_in_month(yr, mo)
if result == test_results[i]:
print("OK")
else:
print("Failed")