Skip to the workspace
Pebellslearn by building
Recursion, Searching & Sorting  ›  Capstone Project

Capstone — Smart Shuffle

35 minFlatten, sort and search together to build a shuffle that never repeats an artist back to back

dsa / Capstone — Smart Shuffle

Explore each scene at your own pace.

01 · Flatten the road-trip folder (recursion)

Flatten the road-trip folder (recursion)

Capstone — Smart Shuffle

Definition
Smart Shuffle combines recursion to flatten nested playlists, sorting to order artists, and binary search insertion to keep a sorted queue, so the same artist never plays twice in a row whenever that is possible.
In plain words
It is a DJ who unpacks every folder, always plays from the artist with the most songs left, and never repeats an artist back to back unless there is no choice. Three earlier tools do the work behind that rule.

In short: this capstone chains everything in the section: recursion to flatten nested playlists, sorting to put each artist's tracks and the artist queue in order, and binary search (bisect.insort) to keep that queue sorted as it changes. The payoff is Tunebox's Smart Shuffle: the same artist never plays twice in a row when that's possible, and when it isn't, it says exactly where the repeat has to happen.

A sorted queue of name-cards "Kai 3 / Lu 1 / Mo 1" with the front card flipped face-down (just played), an arrow skipping to the second card, and the flipped card re-inserted one slot back after a play

Flatten the road-trip folder (recursion)

A playlist is a list of tracks — {"title": ..., "artist": ...} — and nested sub-playlists, to any depth. Flattening is the nested-playlist walk from the first lesson, with track dicts as the leaves:

python
Scene 1 of 7
Project context and further resources
You're building a piece ofTunebox — search & charts
This piece — smart_shuffle(): Orders a library so the same artist never plays twice in a row.
Scenario A listener's road-trip folder is half Kai. Plain shuffle keeps playing Kai back to back; Smart Shuffle flattens the folder and spreads each artist out — and when that's impossible, it only doubles up at the very end.
smart_shuffle.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
smart_shuffle(playlist) → listEvery title in a play order where no artist plays twice in a row, unless nobody else is left.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.