Python trouble with groupby | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 11

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

6th Dec 2018, 5:17 PM
Cépagrave
Cépagrave - avatar
12 Answers
+ 10
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)
6th Dec 2018, 6:17 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 9
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 😊
6th Dec 2018, 10:15 PM
Cépagrave
Cépagrave - avatar
+ 9
Kishalaya Saha Oups,... Great ! That was in the doc. I had an eye on the doc, should have used both 😅 Thank you !
7th Dec 2018, 6:33 AM
Cépagrave
Cépagrave - avatar
+ 8
Mert Yazıcı Ok, collection can help. A little less direct than in my dream but heh 😅 Thanks !
6th Dec 2018, 10:19 PM
Cépagrave
Cépagrave - avatar
+ 8
Thanks everybody, I could finally oneline it the way I wanted with your help 😊 https://code.sololearn.com/cRXco9kSV8rM/?ref=app
7th Dec 2018, 8:36 PM
Cépagrave
Cépagrave - avatar
+ 8
__import__('itertools').groupby you can use this to decrease 7 chars and a line
7th Dec 2018, 8:41 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 6
Oh, great ! Thank you Mert Yazıcı
7th Dec 2018, 8:55 PM
Cépagrave
Cépagrave - avatar
+ 5
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
7th Dec 2018, 2:08 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
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
6th Dec 2018, 5:38 PM
michal
+ 4
Haha, you're welcome! 😊 I'd probably just use two list comprehensions or a for loop.
7th Dec 2018, 6:40 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
Wow this thread ended up doing great
7th Dec 2018, 11:32 PM
Genghis
Genghis - avatar
0
method code util
7th Dec 2018, 6:40 PM
Ḿổḩảḿḿẻď Ấḿiň
Ḿổḩảḿḿẻď Ấḿiň - avatar