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. >>> a = (1, 2, 3, 2, 1) >>> 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.
>>> a = (1, 2, 3, 2, 1)
>>> min_element(a)
1
"""
def find_min(tup, min):
if not tup:
return min
else:
min = tup[0] if tup[0] < min else min
return min_element(tup[1:], min)
if tup:
return find_min(tup[1:], tup[0])
Can this solution be improved?
min(tup)
allowed? \$\endgroup\$min
function? No. \$\endgroup\$non-negative integer
index less than its length, starting at 0 for the first element.". But python allowstup[:-1]
? \$\endgroup\$tup[:-1]
is shorthand fortup[:len(tup)-1]
. \$\endgroup\$min
function. We can't read your mind, so you need to tell us these things in the question! \$\endgroup\$