Advanced · Comprehensions · 187 of 264
Word lengths
Build a dictionary {word: length} with a dictionary comprehension (each word once, ignoring capitals). Print it longest first; equal lengths alphabetically.
Input: one line of words. Output: lines like python 6
Examples
Input
Python is a fun language
Output
language 8 python 6 fun 3 is 2 a 1
Input
a A b
Output
a 1 b 1
One more test checks other inputs when you press Check.
Stuck? The idea behind comprehensions
A comprehension builds a list in one line: [x * x for x in range(5)]. Add if to keep only some: [x for x in nums if x > 0].
The same works for sets {…} and dictionaries {key: value for …}.
nums = [int(x) for x in input().split()] print([x * x for x in nums if x % 2 == 0])
Watch for: Clear first, short second: when a comprehension needs two ifs and two fors, a loop reads better.