I’m looking for some code improvement, or a pre-built version of what I’ve implemented myself as I think there might be, or should be, a cleaner way to achieve what I want.
I’m writing a piece of software to convert guitar tabs into classical notation, I need to convert the number on a tab to it’s corresponding note and it would be useful for building a list of each strings note from the starting string.
I have a list of notes, (a – g#) and a list of frets (0, 21).
Notes[fret] works fine for the first eleven notes but after that I obviously get an out of index error.
The code I have to get around this is here:
JavaScript
x
9
1
notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
2
note = 21
3
while note >= len(notes):
4
note -= 11
5
try:
6
print notes[note]
7
except:
8
continue
9
It works but it seems a little long, is there a better way to do this?
Advertisement
Answer
Use the %
operator to produce a modulus:
JavaScript
1
2
1
notes[note % len(notes)]
2
Demo:
JavaScript
1
5
1
>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
2
>>> note = 21
3
>>> notes[note % len(notes)]
4
'g#'
5
or in a loop:
JavaScript
1
5
1
>>> for note in range(22):
2
print notes[note % len(notes)],
3
4
a a# b c c# d e f f# g g# a a# b c c# d e f f# g g#
5