Menu
CoddyTech

Algorithms and Comprehensions

Lesson 20 of 48 in Coddy's Python for C++ Developers course.

A Python comprehension combines element selection and transformation into a new list. sorted(iterable, key=...) creates a new sorted list; list.sort changes an existing list and returns None. Both Python sorts are stable. A Python key function computes one sort key per element, unlike a C++ comparator that compares pairs repeatedly. C++ stable_sort preserves equal-key order; std::sort does not promise it.

C++17 excerpt: inside main

Standard-library headers are supplied in the runnable companion program.

std::vector<std::string> words{"pear", "fig", "plum"};
words.erase(std::remove_if(words.begin(), words.end(), [](const auto& w) { return w.size() < 4; }), words.end());
std::stable_sort(words.begin(), words.end(), [](const auto& a, const auto& b) { return a.size() < b.size(); });
for (const auto& w : words) std::cout << w << '\n';

Python

words = ["pear", "fig", "plum"]
result = sorted([w for w in words if len(w) >= 4], key=len)
print(result)

Porting trap

Python key=len takes one argument and produces a length. A comparator-shaped lambda with two arguments is not a valid key function.

Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.

challenge icon

Challenge

Beginner

Read a line of lowercase words, then a nonnegative minimum length. Keep words whose length is at least the minimum, including duplicates. Sort them by increasing length, preserving original order for equal lengths. Print one word per line, or none if no words qualify. The supplied scaffold parses both input lines.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C++ Developers

Practice on your own: Online Python compiler