Minimum element in a tuple I'm solving exercise 2 from lecture 3 of Berkeley's CS 61A (2012):


  Write a function min_element that returns the minimum element in a tuple.

def min_element(tup):
    """ Returns the minimum element in tup.
    &gt;&gt;&gt; a = (1, 2, 3, 2, 1)
    &gt;&gt;&gt; min_element(a)
    1
    """



I know that Python has a built-in min function, but at this point in the course, the only operations on tuples that we have studied are indexing [1] [-1], slicing [1:], and concatenation +, so my solution needs to restrict itself accordingly.

My solution:

def min_element(tup):
    """ Returns the minimum element in tup.
    &gt;&gt;&gt; a = (1, 2, 3, 2, 1)
    &gt;&gt;&gt; min_element(a)
    1
    """
    def find_min(tup, min):
        if not tup:
           return min
        else:
           min = tup[0] if tup[0] &lt; min else min
           return min_element(tup[1:], min)
    if tup:
        return find_min(tup[1:], tup[0])


Can this solution be improved?
Berkeley CS61A alum here. Your solution looks fine. Having sat through many a lecture where the prof would go through problems like this, I can pretty much guarantee this is the solution that would have been given:

def min_element(tup):
    min = tup[0]
    for element in tup[1:]:
        if element &lt; min:
            min = element
    return min


So this solution might be considered by someone really pedantic to be a bit "better" than yours since it is less verbose and because, in general, recursion tends to be slower than iteration. Your solution works just fine though :)