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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler