226
CHAPTER 4
4.1
Write out the code for the earlier
sum
function.
Answer:
def sum(list):
if list == []:
return 0
return list[0] + sum(list[1:])
4.2
Write a recursive function to count the number of items in a list.
Answer:
def count(list):
if list == []:
return 0
return 1 + count(list[1:])
4.3
Find the maximum number in a list.
Answer:
def max(list):
if len(list) == 2:
return list[0] if list[0] > list[1] else list[1]
sub_max = max(list[1:])
Dostları ilə paylaş: