1.11M Members

Think Python - Exercise 10.6 - is_sorted.py

def is_sorted(t):
    if t == sorted(t):
        return True
        return False

print is_sorted([1,2,2]) # True
print is_sorted(['b','a']) # False
print is_sorted([3, 1, 5, 2, 4]) # False
print is_sorted(['d', 'a', 'c', 'b']) # False
print is_sorted(['a', 'b', 'b', 'd', 'e', 'e', 'f', 'g']) # True

... and your problem is?


I know the Think Python book says to try to avoid naming a function like this one if you are using a another function or variable with the same name. Since sorted() is already a built-in function, is it even logical to create a function that calls sorted() or could I have just done print sorted([3, 1, 5, 2, 1])? Is there a better way to program this without using sorted()?


"Better" is in the eye of the beholder. The first rule is that the program does what it is supposed to.

def in_order(t):
    for ctr in range(1, len(t)):
        if t[ctr-1] > t[ctr]:
            return False
    return True

for t in ([1,2,2], ['b','a'], [3, 1, 5, 2, 4],
          ['d', 'a', 'c', 'b'], ['a', 'b', 'b', 'd', 'e', 'e', 'f', 'g']):
    print t, in_order(t)

The built-in Python functions sorted() and sort() are highly optimized and a good choice to use.


Thank you for the help.

Question Answered as of 1 Year Ago by woooee, vegaseat and Ene Uran
This question has already been solved: Start a new discussion instead
Start New Discussion
Tags Related to this Article