I am working with a some small functions to test recursion. I am fairly new to Python and am wondering if there is a cleaner way to get the job done.
def count(t,p):
''' recursive function when passed a binary tree (it doesn’t matter if it is a
binary search tree) and a predicate as arguments; it returns a count of all the
values in the tree for which the predicate returns True. '''
if t == None or t.value == None:
return 0
elif p(t.value):
return 1 + count(t.right, p) + count(t.left, p)
else:
return count(t.right, p) + count(t.left, p)
def equal(ll1,ll2):
''' recursive function when passed two linked lists; it returns whether or not
the linked lists contain exactly the same values in the same order. '''
if ll1 == None and ll2 == None:
return True
if (ll1 != None and ll2 == None) or\
(ll2 != None and ll1 == None):
return False
elif ll1.value == ll2.value:
return equal(ll1.next, ll2.next)
else:
return False
def min_max(ll):
''' a recursive when passed a linked list; it returns a 2-tuple containing the
minimum value followed by the maximum value. If the linked list is empty, return
(None, None) '''
if ll == None:
return None, None
maybe_min, maybe_max = min_max(ll.next)
if maybe_min == None or ll.value < maybe_min:
least = ll.value
if maybe_min != None and ll.value > maybe_min:
least = maybe_min
if maybe_max == None or ll.value >= maybe_max:
most = ll.value
if maybe_max != None and ll.value < maybe_max:
most = maybe_max
return least, most