Home > Back-end >  Skipping array items based in a list of intervals
Skipping array items based in a list of intervals

Time:01-11

So I'm trying to code a program for my girlfriend in python to automate the process of getting all musical notes in a given scale.

I want to make the list of notes:

notes =  ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

skip their indexes by this set of intervals:

intervals = [2, 1, 2, 2, 1, 2, 2]

Thank you in advance!

I tried to do it manually but I really want to automate all the process.

CodePudding user response:

You can use modular arithmetic for this Similar to what Edo Akse wrote -

notes =  ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3

for interval in intervals:
    print(notes[idx])
    idx  = interval
    idx %= len(notes)

result

D#
F
F#
G#
A#
B
C#

CodePudding user response:

use an index for the notes, start where you want, and add each interval to the index in a loop. Subtract length of the list if you're past the end to loop the notes list.

notes =  ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3


for interval in intervals:
    print(notes[idx])
    idx  = interval
    if idx > len(notes):
        idx -= len(notes)

output

D#
F
F#
G#
A#
B
C#
  • Related