Musical Anagrams
Practice problem · arrays and hashing

Musical Anagrams

C–E–G, E–G–C and G–C–E are the same three notes in a different order, the way "eat", "tea" and "ate" are the same three letters. Group a list of chords so that every chord built from the same notes lands together, then listen to the groups your code makes.

The problem

group_chords(chords) -> list of groups
chords list of chords, each a list of MIDI numbers pitch_class(note) given to you: every C is 0, every E is 4 same notes same note names, any order or octave return every chord in exactly one group

You don't need to know any music theory. MIDI numbers count piano keys, so 60 is middle C and 72 is the C one octave up. The starter code includes pitch_class(note), which turns every C into 0, every C♯ into 1, and so on up to B at 11, so notes an octave apart look the same. It stays available even if you delete it.

The order of the groups, and of the chords inside a group, does not matter. A doubled note counts twice, the way a repeated letter does in an anagram, so C4–E4–G4–C5 is not grouped with C4–E4–G4.

Hear the chords

Each column is one chord. The letter and color under a chord show its group. Play by group plays each group's chords back to back, with a pause between groups, so you hear "same chord, different voicing."

Your code

Python 3, runs in your browser
Ctrl or Cmd + Enter also runs

Test results

Not run yetPress Run tests. Three examples are shown below and the rest stay hidden until you run.
Solutions: three approaches, slow to fast

Each solution uses the pitch_class helper from the starter code, which is just note % 12. n is the number of chords and k the number of notes in a chord. The word version of this problem is Group Anagrams, where the count key has 26 slots, one per letter. Here it has 12, one per pitch class, which musicians call a pitch-class vector.