I was wondering if there is a way to find min & max of a list without using min/max functions in Python. So i wrote a small code for the same using recursion. My logic is very naive: I make two stacks (min_stack and max_stack) which keep track of minimum and maximum during each recursive call. I have two questions:
- Could somebody help me estimate the complexity of my code?
- Is there a better way to do this? Will sorting the list using mergesort/quicksort and picking up first and last element give a better performance?
Thank you
Here is my attempt in Python:
minimum = []
maximum = []
# Defining Stack Class
class Stack:
def __init__(self) :
self.items = []
def push(self, item) :
self.items.append(item)
def pop(self) :
return self.items.pop()
def access(self, index):
return self.items[index]
def isEmpty(self) :
return (self.items == [])
def length(self):
return len(self.items)
def minmax(input_list):
# make two stacks, one for min and one for max
min_stack = Stack()
max_stack = Stack()
# comparing the first two elements of the list and putting them in appropriate stack
if input_list[0]<input_list[1]:
min_stack.push(input_list[0])
max_stack.push(input_list[1])
else:
max_stack.push(input_list[0])
min_stack.push(input_list[1])
# Pushing remaining elements of the list into appropriate stacks.
for i in range(2, len(input_list)):
if input_list[i] < min_stack.access(-1):
min_stack.push(input_list[i])
else:
max_stack.push(input_list[i])
# to find minimum
minlist = []
while min_stack.length() > 0:
minlist.append(min_stack.pop())
# to find maximum
maxlist = []
while max_stack.length() > 0:
maxlist.append(max_stack.pop())
if len(minlist) > 1:
minmax(minlist)
else:
minimum.append(minlist)
if len(maxlist) > 1:
minmax(maxlist)
else:
maximum.append(maxlist)
def main():
input_list = [2, 0, 2, 7, 5, -1, -2]
print 'Input List is: ', input_list
minmax(input_list)
print 'Global Minimum is: ', minimum[0]
print 'Global Maximum is: ', maximum[len(maximum)-1]
if __name__ == "__main__":
main()