Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Python 3.3.0 sort() method not working?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 JacobChristopher   Members   -  Reputation: 115

Like
1Likes
Like

Posted 07 November 2012 - 10:17 PM

Hey guys I'm new here and I'm practically brand new to programming. I knew how to do a (very small) handful of things in actionscript like 7-8 years ago but I'm just now finally getting back into programming. After browsing theses forums and others I decided that Python was the best for me to start with. Since this was the most helpful forum in that decision, I ended up signing yesterday. And today I finally have a problem that I could use some help with.

I'm following the inventwithpython.com book and got stuck on chapter 11:
http://inventwithpyt.../chapter11.html

A bit past halfway in the "The sort() list method" section it says to try typing the following into the shell:

>>> spam = [5, 'bat', 3, 1, 4, 'cat', 2, 'ape']
>>> spam.sort()
>>> spam
[1, 2, 3, 4, 5, 'ape', 'bat', 'cat']


I fully understand what the sort() method does, but it is giving me this error:

Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
spam.sort()
TypeError: unorderable types: str() < int()


This happens right after I enter spam.sort()


I've tried Googling this and using the search function on forums but I can't find anything.
Any help would be greatly appreciated! Thanks!


EDIT: Now that I'm running the Bagels game I can see that the sort() method isn't working in that either. But it's not giving me any errors when running or playing the game.

Edited by JacobChristopher, 07 November 2012 - 10:30 PM.


Sponsor:

#2 Martins Mozeiko   Crossbones+   -  Reputation: 1422

Like
2Likes
Like

Posted 07 November 2012 - 10:47 PM

That is happening because Python 3.x changed sort behavior. Now it can not sort elements with different types.
It kinda makes sense because what does it mean - to compare integer with string? Which is greater 1 or "1"? Try this yourself in Python - write print 1 < "1". Do you expect to see False ?

#3 JacobChristopher   Members   -  Reputation: 115

Like
0Likes
Like

Posted 07 November 2012 - 10:57 PM

Thanks for the quick reply. So is there a workaround I should learn or should I just skip this and continue on learning? Being completely new to this, I have no idea how important or not important sort() is/was.

#4 Bacterius   Crossbones+   -  Reputation: 9098

Like
1Likes
Like

Posted 08 November 2012 - 12:44 AM

I suppose you could sort the list in two steps, i.e. split it into two, one with integers and the other with the strings, sort these two separately, and concatenate them back with the integers first. That said, I don't see why an integer should compare lower than a string, it's a completely arbitrary decision and it's good that Python no longer assumes this behavior.

The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#5 Martins Mozeiko   Crossbones+   -  Reputation: 1422

Like
0Likes
Like

Posted 08 November 2012 - 12:49 AM

For Python 2.x built-in types it is described here: http://docs.python.org/2/library/stdtypes.html#comparisons

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

So basically values are ordered first by their type names - "int" < "string".

Edited by Martins Mozeiko, 08 November 2012 - 12:54 AM.


#6 GMuser   Members   -  Reputation: 211

Like
0Likes
Like

Posted 08 November 2012 - 03:58 AM

Python 3 has a cool new feature where you can supply a key to the 'sort' member and 'sorted' function. For example, to sort your example as a string you can do:
spam.sort(key=str)

Where the key expects a function that takes one argument and returns a value. A more advanced usage I ran into the other day was to sort a list of dictionaries, I wanted to sort by a key in the dictionary. Example:

[source lang="python"]a=[{'name':'Joe','cash':96},{'name':'Bob','cash':77},{'name':'Jane','cash':3},{'name':'Jill','cash':103}]a.sort(key=lambda x: x['cash'],reverse=True)print(a)[/source]

Since you are learning python I'll explain just a bit more.

Dictionary: Things between {} are a dictionary (key-value pair data structure). Value in a dictionary can be referenced easily with a['key name'] like in line 2.

Named arguments: on line 2 of my code, I use the named arguments 'key' and 'reverse'. reverse simply means I want to sort in reverse order (when True).

Lambda: Lambda functions (in simple to understand terms) are nameless functions that implicitly return a value. Keep in mind, key was expecting a function 'pointer', so you can see that when you use lambda it returns a function pointer. I read that using lambda in this situation has a performance hit compared to using an equivalent function, but that's just something to note rather than overly concern yourself with.

#7 tufflax   Members   -  Reputation: 498

Like
0Likes
Like

Posted 08 November 2012 - 08:16 AM

Python 3 has a cool new feature where you can supply a key to the 'sort' member and 'sorted' function. For example, to sort your example as a string you can do:
spam.sort(key=str)

Not new. Posted Image My python 2.7 has it at least.

Edited by tufflax, 08 November 2012 - 08:19 AM.


#8 swiftcoder   Senior Moderators   -  Reputation: 10242

Like
2Likes
Like

Posted 08 November 2012 - 11:44 AM

So is there a workaround I should learn or should I just skip this and continue on learning?

What you should do, is install the correct version of Python for your tutorial (or find a tutorial that is meant for Python 3.x).

There are enough differences between Python 2.x and 3.x to make your learning process a nightmare if you persist with the current tutorial/Python mismatch.

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#9 JacobChristopher   Members   -  Reputation: 115

Like
0Likes
Like

Posted 08 November 2012 - 08:15 PM

Python 3 has a cool new feature where you can supply a key to the 'sort' member and 'sorted' function. For example, to sort your example as a string you can do:
spam.sort(key=str)

Where the key expects a function that takes one argument and returns a value. A more advanced usage I ran into the other day was to sort a list of dictionaries, I wanted to sort by a key in the dictionary. Example:

[source lang="python"]a=[{'name':'Joe','cash':96},{'name':'Bob','cash':77},{'name':'Jane','cash':3},{'name':'Jill','cash':103}]a.sort(key=lambda x: x['cash'],reverse=True)print(a)[/source]

Since you are learning python I'll explain just a bit more.

Dictionary: Things between {} are a dictionary (key-value pair data structure). Value in a dictionary can be referenced easily with a['key name'] like in line 2.

Named arguments: on line 2 of my code, I use the named arguments 'key' and 'reverse'. reverse simply means I want to sort in reverse order (when True).

Lambda: Lambda functions (in simple to understand terms) are nameless functions that implicitly return a value. Keep in mind, key was expecting a function 'pointer', so you can see that when you use lambda it returns a function pointer. I read that using lambda in this situation has a performance hit compared to using an equivalent function, but that's just something to note rather than overly concern yourself with.


Thanks for this! I don't 100% understand this yet, but I've written it down in my notes. It'll click eventually. That's what I'm starting to realize is happening. I'll understand half of what I'm learning right away, and the other half I'm like "ummmmmmm, I kinda get it but not all the way..." and then all of a sudden when a very similar function is being defined I get an "a-ha!" moment. Then I go back to what I was having trouble with and it's no sweat. As lame as it sounds, this is very exciting to me haha.


So is there a workaround I should learn or should I just skip this and continue on learning?

What you should do, is install the correct version of Python for your tutorial (or find a tutorial that is meant for Python 3.x).

There are enough differences between Python 2.x and 3.x to make your learning process a nightmare if you persist with the current tutorial/Python mismatch.


The inventwithpython.com book says to download Python 3.1. I didn't think that there would be too much of a difference between that and 3.3, but looks like I was wrong! The only 3.1 version they have for download is 3.1.5 so I'll give that a try. Thanks!

Edited by JacobChristopher, 08 November 2012 - 08:16 PM.


#10 swiftcoder   Senior Moderators   -  Reputation: 10242

Like
0Likes
Like

Posted 09 November 2012 - 09:48 AM

The inventwithpython.com book says to download Python 3.1. I didn't think that there would be too much of a difference between that and 3.3, but looks like I was wrong! The only 3.1 version they have for download is 3.1.5 so I'll give that a try. Thanks!

Actually you are correct on that. I hadn't looked at the book previously, and while it does (strongly) direct you to download Python 3.x, it looks like they haven't actually finished updating the book for 3.x.

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#11 Animate2D   Members   -  Reputation: 182

Like
0Likes
Like

Posted 14 November 2012 - 07:17 PM

May I ask why you are mixing types in a list?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS