You should probably do a kind of insertion sort:
def sort_tuple(t):
result = () # start with an empty result
for val in t:
result = insert_tup(val, result) # insert each value into its place
return result
This is not terribly efficient, but it is very easy to do with the functions you've been given to work with.
While the code above is very straight forward, in this case it is only working by a fluke, as the search
function behaves badly (returning None
) when passed an empty tuple. Fortunately tup[:None]
is a legal slice. In the specific situation it comes up in, it's even correct!
A better implementation of search
would return an integer always. Here's a quick stab at it:
def search(x, seq):
for i, v in enumerate(seq):
if x < v:
return i
return len(seq)
Or better still, use the bisect
module to do the searching in O(log n)
time rather than O(n)
.