Let's write a function that compares two lists to see whether they are the same. In the code below, we examine the items at corresponding positions of the two lists. That is, we compare item L1[0] to item L2[0], and L1[1] to L2[1], and so on.
def lists_equal(L1, L2):
""" (list of int, list of int) -> bool
Return True iff L1 and L2 have the same contents in the same locations.
>>> lists_equal([1, 2, 3, 4], [1, 2, 3, 4])
True
>>> lists_equal([8, 3, 4], [8, 3, 4, 10, 2])
False
>>> lists_equal([5, 6, 7], [7, 6, 5])
False
"""
# Check whether the two lists have the same length first,
# to avoid index out of range errors later.
if len(L1) != len(L2):
return False
for i in range(len(L1)):
if L1[i] != L2[i]:
return False
return True
We store patient data in two lists of the same length. For example:
sex_data = ["m", "f", "f", "m", "m", "f"]
ward_data = [ 1, 3, 2, 2, 1, 2]
duration_data = [ 10, 5, 7, 2, 3, 4]
Write a function that computes the average length of stay in the hospital for a given sex, in a given ward. The function signature is:
def avg_stay(sex, ward, sex_data, ward_data, duration_data):
""" (str, int, list of int, list of str, list of int) -> float
Return the average duration of stay for patients of sex sex in ward ward,
given parallel list of sexes sex_data, list of wards ward_data, and
list of duration of stay duration_data.
>>> sex_data = ["m", "f", "f", "m", "m", "f"]
>>> ward_data = [ 1, 3, 2, 2, 1, 2]
>>> duration_data = [ 10, 5, 7, 2, 3, 4]
>>> avg_stay("f", 2, sex_data, ward_data, duration_data)
5.5
"""
Write a function that returns True iff string s1 starts with string s2. For example,
starts_with("abc", "ab") should return True
starts_with("ad", "ab") should return False
def starts_with(s1, s2):
""" (str, str) -> bool
Return True iff the string s1 starts with the string s2.
>>> starts_with("abc", "ab")
True
>>> starts_with("ad", "ab")
False
"""