4

I come from a musical background, so I was interested in implementing music set theory into a Python script.

Basically the variables of musical notes are assigned to numbers (C = 0, C sharp = 1 etc.). However music set theory only works up to the number 11, since B = 11 and the next C would be = 0 again.

I've assigned some variables already, they look like this.

# pitch classes
Bs = C = 0
Cs = Db = 1
D = 2
Ds = Eb = 3
E = Fb = 4
F = Es = 5
Fs = Gb = 6
G = 7
Gs = Ab = 8
A = 9
As = Bb = 10
B = Cb = 11

# intervals
m2 = 1 
mj2 = 2 
m3 = 3 
mj3 = 4
P4 = 5 
T = 6
P5 = 7
m6 = 8
mj6 = 9
m7 = 10
mj7 = 11

I want to be able to add notes and intervals together, for instance B plus a perfect 5. This would normally be 11 + 7 = 18, but I want it to equal 6 (since 6 = F sharp, and B and F sharp are a perfect 5th apart).

I think I need something like this, but I have no idea how to implement it.

if answer >= 12:
    answer - 12

Does anyone have any ideas? Is there a better way of going about doing this?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62

3 Answers3

5

There's a modulo operator, % which does exactly this (see also here):

print((11 + 7) % 12)

or more generally:

def add_wrap_overflow(x,y):
    return (x+y) % 12
DomTomCat
  • 8,189
  • 1
  • 49
  • 64
  • Haha this seems so obvious now, thanks so much. Anyway I can write something up so I don't have to type 'print((x + z) %12)' for every operation? –  Jun 04 '16 at 08:56
  • I don't quite understand. You can define a function, e.g. `module_add(x,y)` which does this for you, but you'd have to call this function every time - see updated answer – DomTomCat Jun 04 '16 at 09:01
  • Okay I'll probably a little out of my depth, I don't quite understand either. Your first answer is exactly what I was looking for, thanks! –  Jun 04 '16 at 09:15
0

Your solution is almost correct; however, answer - 12 is just an expression, i.e. it evaluates to the value answer - 12 without having any additional effect.

You need to make a statement that assigns that value to some variable (in this case, the same one):

answer = answer - 12.

Python offers a short way of writing this (though you should avoid it as it might be confusing to beginners):

answer -= 12.

However in your case, the modulo operator may be more useful:

answer = answer % 12 or answer %= 12

In short, the modulo operator subtracts or adds 12 until answer is in range(0, 12) (one of the numbers from 0 to 11).

mic_e
  • 5,594
  • 4
  • 34
  • 49
0

I would correct your code as

if (answer >= 12):
    answer = answer - 12
prab4th
  • 231
  • 1
  • 2
  • 11