1,105,310 Community Members

Think Python - Exercise 10.6 - is_sorted.py

Member Avatar
jeremywduncan
Newbie Poster
20 posts since Feb 2013
Reputation Points: -1 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

... and your problem is?

Member Avatar
jeremywduncan
Newbie Poster
20 posts since Feb 2013
Reputation Points: -1 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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()?

Member Avatar
woooee
Posting Maven
2,793 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
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)
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
0
 

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

Member Avatar
jeremywduncan
Newbie Poster
20 posts since Feb 2013
Reputation Points: -1 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank you for the help.

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