Page Ranges
Advanced · Stretch · from Python Lists: Create, Access, Modify, and Loop Through Lists
From the lesson: Python Lists: Create, Access, Modify, and Loop Through Lists
Think about your favorite music playlist. It has a bunch of songs stored in a specific order. You can add new songs, remove old ones, rearrange them, or skip to song number five.
Read the lessonA print dialog shows the pages you picked in a short form, joining runs of pages that follow each other. Write a function page_ranges(pages) that takes a list of page numbers and returns that text.
page_ranges([1, 2, 3, 5, 7, 8, 9]) # '1-3, 5, 7-9'
page_ranges([4, 10]) # '4, 10'The list can be in any order and can name a page more than once. A run of one page is written as the page alone. With no pages, return an empty string.
Return the answer instead of printing it: Check calls page_ranges() with its own lists, some of them hidden.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| page_ranges([1, 2, 3, 5, 7, 8, 9]) | '1-3, 5, 7-9' |
| page_ranges([4, 10]) | '4, 10' |
More List exercises
- Create a List and Print Its LengthBeginner
- Access the Last Item with Negative IndexingBeginner
- Shopping List: Add and Remove ItemsBeginner
- Fix the Bug: IndexErrorBeginner
- Sum All Numbers Using a LoopBeginner
- Find the Largest Number Without max()Intermediate
- Predict the Output: List AliasingIntermediate
- Reverse a List Without reverse() or [::-1]Intermediate
All Python exercises · 50 practice problems · Data Structures quiz