I made a few recursive functions for learning purposes which do a variety of tasks. Here is my current and functioning code:
def separate(p,l): ''' recursive function when is passed a predicate and a list returns a 2-tuple whose 0 index is a list of all the values in the argument list for which the predicate returns True,and whose 1 index is a list of all the values in the argument list for which the predicate returns False.''' if len(l) == 0: return ([],[]) else: (true_list, false_list) = separate(p,l[1:]) if p(l[0]): return ([l[0]] + true_list, false_list) else: return (true_list, [l[0]] + false_list) def is_sorted(s): ''' recursive function when passed a list returns a bool telling whether or not the values in the list are in non-descending order: lowest to highest allowing repetitions. ''' if len(s) <= 1: return True elif s[0] < s[1]: return is_sorted(s[1:]) else: return False def sort(l): ''' recursive function when passed a list; it returns a new list (not mutating the passed one) with every value in the original list, but ordered in non- descending order. ''' if len(l) == 0: return [] else: (before, after) = separate(lambda i: i < l[0], l[1:]) return sort(before) + [l[0]] + sort(after) def compare(a,b): ''' a recursive function when is passed two str arguments; it returns one of three str values: '<’, '=’, or '>’ which indicates the relationship between the first and second parameter.''' if a == '' and b == '': return '=' if a == '' and b != '': return '<' if a != '' and b == '': return '>' if a[0] > b[0]: return '>' if a[0] < b[0]: return '<' else: return compare(a[1:],b[1:])
Is there a way to write these recursive functions in a cleaner/concise way? Any help would be great.
code_metric()
. It is neither recursive, nor does it reuse your other functions. (I believe you have missed the point of the exercise as well.)\$\endgroup\$