def is_sorted(t):
    if t == sorted(t):
        return True
    else:
        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

Recommended Answers

All 5 Replies

... 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.