I am trying to build a function that takes in a list and returns a tuple of (min, max).
For example,
[2,1,4,9,4.5]
would return
(1, 9)
I am trying to use only recursion and want to perform this task without using other things that would make this very easy (such as min(),max(),sort(),sorted(),loop..etc)
So far, I have been able to create function that find maximum
def findmax(alist):
if len(alist) <= 1:
return tuple(alist)
elif len(alist) == 2:
if alist[0] >= alist[1]:
return findmax([alist[0]])
elif alist[0] <= alist[1]:
return findmax([alist[1]])
elif len(alist) > 2:
if alist[0] >= alist[1]:
return findmax([alist[0]] + alist[2:])
elif alist[0] <= alist[1]:
return findmax(alist[1:])
which
findmax([2,1,4,9,4.5])
returns
(9,)
and a function that find minimum (which is not too different)
def findmin(alist):
if len(alist) <= 1:
return tuple(alist)
elif len(alist) == 2:
if alist[0] >= alist[1]:
return findmin([alist[1]])
elif alist[0] <= alist[1]:
return findmin([alist[0]])
elif len(alist) > 2:
if alist[0] >= alist[1]:
return findmin(alist[1:])
elif alist[0] <= alist[1]:
return findmin([alist[0]] + alist[2:])
which
findmin([2,1,4,9,4.5])
returns
(1,)
Is there a way to put this two separate functions into one using only recursion so that it would return a desired result of
(1, 9)
Any help would really be appreciated.