patternpythonMinor
Recursive functions for sorting
Viewed 0 times
functionsrecursiveforsorting
Problem
I made a few recursive functions for learning purposes which do a variety of tasks. Here is my current and functioning code:
Is there a way to write these recursive functions in a cleaner/concise way? Any help would be great.
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) ’ which indicates the relationship between the
first and second parameter.'''
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.
Solution
I recommend you be more consistent in not combining
as you do e.g. in
In
That way it is more clear to me that
Your comments should at least use triple double quotes (PEP8) and you should try to conform to PEP 257 (docstring conventions).
if followed by a statement sequence ending in return with an else (I left out the comments):def separate(p,l):
if len(l) == 0:
return ([],[])
(true_list, false_list) = separate(p,l[1:])
if p(l[0]):
return ([l[0]] + true_list, false_list)
return (true_list, [l[0]] + false_list)as you do e.g. in
compare().In
compare() I would nest the conditions (arbitrarily based on a):def compare(a,b):
if a == '':
if b == '':
return '='
return ''
if a[0] > b[0]:
return '>'
if a[0] < b[0]:
return '<'
return compare(a[1:],b[1:])That way it is more clear to me that
compare() never ends without a return value.Your comments should at least use triple double quotes (PEP8) and you should try to conform to PEP 257 (docstring conventions).
Code Snippets
def separate(p,l):
if len(l) == 0:
return ([],[])
(true_list, false_list) = separate(p,l[1:])
if p(l[0]):
return ([l[0]] + true_list, false_list)
return (true_list, [l[0]] + false_list)def compare(a,b):
if a == '':
if b == '':
return '='
return '<'
if a != '':
if b == '':
return '>'
if a[0] > b[0]:
return '>'
if a[0] < b[0]:
return '<'
return compare(a[1:],b[1:])Context
StackExchange Code Review Q#79921, answer score: 3
Revisions (0)
No revisions yet.