Min and Max of a List (without using min/max function)
Solution 1:
Using sorted()
would, of course, be reliable, quick to write, and high performance for moderate-sized lists because it is built-in. For large lists, an O(n) algorithm would be faster e.g.:
def minmax1 (x):
# this function fails if the list length is 0
minimum = maximum = x[0]
for i in x[1:]:
if i < minimum:
minimum = i
else:
if i > maximum: maximum = i
return (minimum,maximum)
print(minmax1([9,8,7,6,5,4,3,2,1,11,12,13,14,15,16,17,18,19]))
print(minmax1([1]))
print(minmax1([2, 0, 2, 7, 5, -1, -2]))
... for which the output is:
(1, 19)
(1, 1)
(-2, 7)
I was interested to check the performance of the two alternatives. On my PC running Windows XP and Python 3.2.3, I found that the sorting approach is faster than the minmax1()
function defined above for lists of fewer than 500 elements but, for longer lists, the O(n) minmax1()
is faster. My timing test code was as follows:
def minmax_sort(x):
x = sorted(x)
return (x[0],x[-1])
import timeit
aa = list(range(0,100))
a = aa
while (1):
stime = min(timeit.repeat('minmax_sort(a)', "from __main__ import minmax_sort,a",number=1000))
mtime = min(timeit.repeat('minmax1(a)', "from __main__ import minmax,a",number=1000))
if (stime > mtime):
break
else:
a = a + aa
print(len(a))
Solution 2:
Finding Min and Max of a list using only recursion.
I had this similar assignment last week and I divided the code into three parts.
Step 1: Finding the minimum value in list
def RecursiveMin(L):
if len(L)==2:
if L[0]<L[1]:
return L[0]
else:
return L[1]
else:
X= RecursiveMin(L[1:])
if L[0]<X:
return L[0]
else:
return X
Step 2: Sorting the list using into ascending order (smallest to largest)
def Sort(x):
L=sorted(x)
if x==L:
return x
else:
i=0
for i in range (len(x)):
if x[i] > x[i+1] :
break
unsortedPart = x[i:]
R = RecursiveMin(unsortedPart)
I = unsortedPart.index(R)
for j in range (len(x)):
if x[j] > R :
del x[(I+i)]
x.insert(j,R)
break
return Sort(x)
(I have previously answered a sorting a list question and provided the same code. So please don't flag me for plagiarism since it's my own code Likn: Finding minimum element in a list (recursively) - Python ).
**Step 3: Make a new function with an argument whether the user wants Min value or Max*
def minMax(lst,user):
if user == min:
return Sort(lst)
elif user == max:
s = Sort(lst)
return s[::-1]
The last step is not recursive but if you compile all the three steps into one function it will be "1 recursive function". P.S if your question was only about finding the Min and Max in a list you can skip Step 2 and make a few changes to to Step 1 and Step 3