0

Coding Challenge :: Grouping Words

Group the words in "Zen of Python" by size and order them alfabetically. Exemple: Entry - "Group and sort this sentence for answering this challenge." Output - {3 : ['and', 'for'], 4 : ['sort', 'this', 'this'], 5 : ['Group'], 8 : ['sentence'], 9 : ['answering', 'challenge']} The output doesn't have to be exactly in this format, just group and sort the words in a recognizable way. Do it with "Zen of Python" For those who aren't using Python, here it is: The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

31st Jul 2017, 3:08 AM
Felipe
Felipe - avatar
2 Answers
+ 5
import re entry = 'Group and sort this sentence for answering this challenge.' wregx = r'[\w]+'; def group_and_sort(str): wdict = {} words = re.findall(wregx,entry) words.sort(key=lambda x: x.lower()) # case insensitive alpha sort words.sort(key=len) # length sort for w in words: k = len(w) if k not in wdict: wdict[k] = [] wdict[k].append(w) keys = list(wdict.keys()) keys.sort() # numerical sort (dict doesn't have order) for k in keys: print('{}: {}'.format(k,wdict[k])) group_and_sort(entry)
31st Jul 2017, 6:25 AM
visph
visph - avatar
1st Aug 2017, 6:04 PM
Garikai
Garikai - avatar