Python trouble with groupby

While writing my code for 'anadrome' challenge, I wanted to use groupby from itertools module. My goal is to sort strings in two groups whether they have an even/odd number of characters. The result surprised me: there are multiple groups for each key... See my code to get what I mean. My question : what happens + how can I get it right? https://code.sololearn.com/cd75P2c5FgKh/?ref=app

12/6/2018 5:17:13 PM


12 Answers

New Answer


michal I think you're right. (it was not obvious first, I think you wrote nn instead of ll). Strange behaviour to group only neighbour's... Thank you 😊


Kishalaya Saha Oups,... Great ! That was in the doc. I had an eye on the doc, should have used both 😅 Thank you !


I think this fixes it but collections.Counter is better for this in my opinion collections.Counter('tooth') #Counter({'t': 2, 'o': 2, 'h': 1}) letters.sort(key=lambda x:len(x)%2)


Mert Yazıcı Ok, collection can help. A little less direct than in my dream but heh 😅 Thanks !


Thanks everybody, I could finally oneline it the way I wanted with your help 😊 https://code.sololearn.com/cRXco9kSV8rM/?ref=app


__import__('itertools').groupby you can use this to decrease 7 chars and a line


Oh, great ! Thank you Mert Yazıcı


From the docs, "It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function)." https://docs.python.org/3/library/itertools.html#itertools.groupby


Haha, you're welcome! 😊 I'd probably just use two list comprehensions or a for loop.


It seems that groupby takes only consecutive elements with same value of key function into one group. When you have for example 'oo', 'll', 'r', 'e', 'nn' oo and nn will be in one group, then the length's parity changes, so r and e are in another group, and nn goes into new group


Wow this thread ended up doing great