Note that there are some explanatory texts on larger screens.

plurals
  1. POMin and Max of a List in Python (without using min/max function)
    primarykey
    data
    text
    <p>I was wondering if there is a way to find min &amp; 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: </p> <ol> <li>Could somebody help me estimate the complexity of my code?</li> <li>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?</li> </ol> <p>Thank you</p> <p>Here is my attempt in Python: </p> <pre><code>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]&lt;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] &lt; 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() &gt; 0: minlist.append(min_stack.pop()) # to find maximum maxlist = [] while max_stack.length() &gt; 0: maxlist.append(max_stack.pop()) if len(minlist) &gt; 1: minmax(minlist) else: minimum.append(minlist) if len(maxlist) &gt; 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() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload