0
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
4
Contributors
5
Replies
31
Views
4 Years
Discussion Span
Last Post by jeremywduncan
Featured Replies
  • 1

    "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'], … Read More

0

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()?

1

"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)
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.