Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Shaggar
Apr 26, 2006

gonadic io posted:

code:
> let names = ["john doe", "jane smith", "butt fucker"]
> sortWith (\name -> (getLast name, getFirst name)) names
["john doe","butt fucker","jane smith"]

so does string in python have a default sort key for that to work?

Adbot
ADBOT LOVES YOU

tef
May 30, 2004

-> some l-system crap ->

Shaggar posted:

so does string in python have a default sort key for that to work?

yes

gonadic io
Feb 16, 2011

>>=

Shaggar posted:

so does string in python have a default sort key for that to work?

i don't care, i hope to never program in python again

tef
May 30, 2004

-> some l-system crap ->
ps https://docs.python.org/3/library/functools.html#functools.cmp_to_key

gonadic io
Feb 16, 2011

>>=

gonadic io posted:

i don't care, i hope to never program in python again

although i wouldn't immediately kill myself, unlike with fortran or matlab

Brain Candy
May 18, 2006

please don't mention the m-word

leftist heap
Feb 28, 2013

Fun Shoe

lol that this exists.

Shaggar
Apr 26, 2006

why is that function defined like this:
Python code:
def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K
seems like its overloading a bunch of comparison operators? how is that different from just using compareTo?

how does it get a key from this?

triple sulk
Sep 17, 2014



Shaggar posted:

seems like its overloading a bunch of comparison operators? how is that different from just using compareTo?

how does it get a key from this?

Very carefully, Shaggar! Haha

Shaggar
Apr 26, 2006
also does that class K get created and destroyed every time the cmp_to_key function is invoked?

Bloody
Mar 3, 2013

Brain Candy posted:

please don't mention the m-word

It is triggering

seiken
Feb 7, 2005

hah ha ha
shaggar have you ever stopped to think about literally any new concept for even a couple of seconds before feigning bemusement and asking a volley of backfiring loaded questions that serve only to reveal how little you really understand about anything

Shaggar
Apr 26, 2006
sort keys were claimed to not use comparisons and that doesnt seem to be true based on the python documentation so I am asking for clarification.

I don't use python so I really don't know which is correct

raminasi
Jan 25, 2005

a last drink with no ice

Shaggar posted:

yes this uses compareto/compare which isn't part of python

no it doesn't, it uses the default comparer. the python version doesn't not use comparison, it just no longer allows you to specify a custom comparison.

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord

EVGA Longoria posted:

python ain't down with timtowdi? but how will i know how whimsical i was feeling the day i wrote it if i can't tell whether I dereferenced a hash with -> or {}????

it's a nice rule of thumb but it's not a great commandment to obey no matter what

extremes dude

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord

gonadic io posted:

although i wouldn't immediately kill myself, unlike with fortran or matlab

fortran is fine

sarehu
Apr 20, 2007

(call/cc call/cc)
cmp_to_key is using a design pattern.

Shaggar
Apr 26, 2006

GrumpyDoctor posted:

no it doesn't, it uses the default comparer. the python version doesn't not use comparison, it just no longer allows you to specify a custom comparison.

the default comparer in c# uses the default comparable for the objects being compared. also, like most comparison operations, orderby allows you to additionally specify a custom comparer.

either way the claimed reason for eliminating compare from python was that it was faster which is clearly not the case since its doing the same thing, only in a more limiting and confusing way.

it appears that the actual reason was because someone wanted everyone to use operator overloads for comparison which is about the worst thing I can think of.

Brain Candy
May 18, 2006

Shaggar posted:

seems like its overloading a bunch of comparison operators? how is that different from just using compareTo?

how does it get a key from this?

the key is the K it returns

Yo look it at this
Java code:
 
  Compartor<Butt> comparator = (x , y) -> x.someExpensiveOperation().compareTo(y.someExpensiveOperation();
if i do it with a comparator i do someExpensiveOperation twice for every comparison operation (n log n of them). i could use a map to memoize, but then you have a stateful comparator

or i could make another list
Java code:
  
   List<Key> keys = list.stream().map(Butt::someExpensiveOperation).collect(Collectors.toList());
   //sort keys, but shadow every operation on the original list
if I do it like keys, I only do someExpensiveOperation once per thing in the list

Shaggar
Apr 26, 2006
but the K isn't a value you could compare. its an object containing overloads that reference the same expensive comparison.

Shaggar
Apr 26, 2006
I guess maybe I don't understand why a compareTo which first compares lastname, and then compares firstname is more expensive than a sort that compares on the lastname key first and the firstname key second.

Brain Candy
May 18, 2006

uh, because it isn't. it's only better if you are doing an expensive thing

cmp_to_key is a way of back porting comparators to the new code. of course it isn't going to be better than doing it the old way since it's still doing it the old way with a goofy wrapper

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
it makes it more convenient to write a custom comparator in the common case where the custom comparator is just comparing one or more properties. it also enables a cute library hack where sort maps the whole list to its keys once and then sorts the two lists in parallel, which is a major optimization if projecting keys is expensive

but it's significantly less general, and the cute hack means that sort will frequently take waaaay more memory than it otherwise would, even if your keys are trivial to derive

MeruFM
Jul 27, 2010
please don't use or talk about backward compatability hacks
also the 2 are practically the same for 99.999% of use cases, please don't trigger

MononcQc
May 29, 2007

To see why it might be desirable, imagine you want to sort a list by the bcrypt12 of each item in the list.

If you use a comparing function that hashes each item, you're gonna have to calculate two hashes per comparison (unless you memoize, which costs memory obviously), and if you use the function you're gonna have precisely one hashing per element of the list.

It's somewhat comparable to sorting [(hash(x), x) for x in list] except you also have to make a pass to remove the first element of the tuple.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
yes, but who the gently caress wants to sort by the bcrypt of their data

that's not just a theoretical question, there's a real trade off here, and Python chose to prioritize the performance of a tiny corner case (super-expensive sort keys) over the performance of the common case (easily derived sort keys)

MononcQc
May 29, 2007

rjmccall posted:

yes, but who the gently caress wants to sort by the bcrypt of their data

that's not just a theoretical question, there's a real trade off here, and Python chose to prioritize the performance of a tiny corner case (super-expensive sort keys) over the performance of the common case (easily derived sort keys)

bcrypt is the absurd example. You could want to sort a bunch of items by the average values of whatever subcomponents they have and then it gets more expensive, or you may just want to sort them by a precomputed value. Both cases have their place as far as I can see.

pseudorandom name
May 6, 2007

If only there were some way to choose to sort using either a key function or a comparator function depending on your needs.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

MononcQc posted:

Both cases have their place as far as I can see.

great, so the way we make design decisions here in pythonland is we try really hard to imagine worst possible cases that would justify doing something expensive instead of trying to make a balanced decision about what's likely to happen and how reasonable programmers could work around this expected behavior

MononcQc
May 29, 2007

rjmccall posted:

great, so the way we make design decisions here in pythonland is we try really hard to imagine worst possible cases that would justify doing something expensive instead of trying to make a balanced decision about what's likely to happen and how reasonable programmers could work around this expected behavior
Python programmers are known to work in memory constrained environments and never complain about speed of their programs, so that change was totally unwarranted.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
thank goodness this put to rest all their complaints about performance, then

tef
May 30, 2004

-> some l-system crap ->

rjmccall posted:

yes, but who the gently caress wants to sort by the bcrypt of their data

that's not just a theoretical question, there's a real trade off here, and Python chose to prioritize the performance of a tiny corner case (super-expensive sort keys) over the performance of the common case (easily derived sort keys)

i use key more than i ever used cmp. most of the python types already have comparisons, and for user types, implementing <, >, >=, <= is usually enough.

i do a lot of sorting by property, but not as much as sorting in default order, and very rarely sorting with a custom ordering

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

tef posted:

i use key more than i ever used cmp. most of the python types already have comparisons, and for user types, implementing <, >, >=, <= is usually enough.

i do a lot of sorting by property, but not as much as sorting in default order, and very rarely sorting with a custom ordering

there are three separable questions here

should python make it convenient to sort by a projection? sure, that's an important case to make convenient

should python have made this promise about the projection only being called once? depends on how you answer the tradeoff

should python have removed the ability to conveniently sort by a custom comparator? because that seems completely unnecessary

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

how do you sort in reverse on one of the keys in that model?

Notorious b.s.d.
Jan 25, 2003

by Reene

tef posted:

i do a lot of sorting by property, but not as much as sorting in default order, and very rarely sorting with a custom ordering

i constantly find myself sorting by unusual orderings

i assume the reason you do not is that your favorite language requires you to implement a four method interface for each custom ordering you might desire

sapir whorf for compilers

VikingofRock
Aug 24, 2008




if I were concerned about performance why would I be using python?

tef
May 30, 2004

-> some l-system crap ->

Notorious b.s.d. posted:

i constantly find myself sorting by unusual orderings

i assume the reason you do not is that your favorite language requires you to implement a four method interface for each custom ordering you might desire

sapir whorf for compilers

it was dropped in python 3 a language i have not yet been paid to write in

tef
May 30, 2004

-> some l-system crap ->

Subjunctive posted:

how do you sort in reverse on one of the keys in that model?

.sort(reversed=True)

tef
May 30, 2004

-> some l-system crap ->
i am really curious what cmp stuff people are doing because i really don't ever write them since i stopped doing java

Adbot
ADBOT LOVES YOU

tef
May 30, 2004

-> some l-system crap ->

rjmccall posted:

there are three separable questions here
should python have removed the ability to conveniently sort by a custom comparator? because that seems completely unnecessary

as mentioned, you can still lift a cmp into a key, using a built in function, if you must. otoh if you only have one then you can just implement >= methods on the class and just use sort()

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply