def years_to_double(money, rate): '''Return how many years it takes for an investment to double at a given interest rate.''' years = 0 increased_value = money # Each year until the investment has doubled, add # interest for the year. while increased_value < (money * 2): years += 1 increased_value += rate * increased_value return years def num_dogs(L): ''' Given a pet list L, return the number of dogs in the list. ''' n = 0 for l in L: if l[1] == 'dog': n += 1 return n def ages(L): '''Given a pet list L, return the sum of the ages of the animals in the list.''' n = 0 for l in L: n += l[2] return n def nested_lengths(L): ''' Given a nested list L, returns a list of the lengths of the sublists. More formally: for each element e in L, the returned list contains a corresponding element, c, that represents the number of elements in e.''' lens = [] for l in L: lens.append(len(l)) return lens if __name__ == "__main__": # How many years will it take to turn 10 dollars into 20 dollars # if 10% interest is added every year? interest = 0.1 investment = 10 years = years_to_double(investment, interest) print "At an interest rate of " + str(interest), print "your money will double in " + str(years) + " years." pets = [["Shoji", "cat", 18], ["Hanako", "dog", 15], \ ["Sir Toby", "cat", 10], ["Sachiko", "cat", 7],\ ["Sasha", "dog", 3], ["Lopez", "dog", 13]] # Your testing should include more cases, to make sure you # are correct print num_dogs(pets), "sb", 3 print num_dogs([]), "sb", 0 print ages(pets), "sb", 66 print nested_lengths(pets), "sb", [3,3,3,3,3,3] print nested_lengths([[0,2],['a'],[2,3,5,4,5]]), "sb", [2,1,5]