patternpythonMinor
Music note class
Viewed 0 times
musicnoteclass
Problem
A class for notes calculation.
Test:
#!/usr/bin/env python3
from string import ascii_uppercase
class Notes:
notes = ascii_uppercase[:7]
notes_number = range(7)
notes_dict = dict(zip(notes, notes_number))
numbers_dict = dict(zip(notes_number, notes))
def __init__(self, _note):
if not _note in Notes.notes:
raise Exception("Not a valid note")
self.note = _note
self.note_number = Notes.notes_dict[self.note]
def add(self, n):
if not n in range(8):
raise Exception("Not a valid number")
old_number = Notes.notes_dict[self.note]
new_number = (old_number + n) % 7
return Notes.numbers_dict[new_number]
def minus(self, n):
if not n in range(8):
raise Exception("Not a valid number")
old_number = Notes.notes_dict[self.note]
new_number = (old_number - n) % 7
return Notes.numbers_dict[new_number]Test:
x = Notes("G")
x.add(7)Solution
__init__assignsself.note_number, but the other functions don't use it, instead they look up the number from thedict. Choose one approach and eliminate the other.
- Checking the range of
nand raising the exception inaddandminusis not necessary, because the computation has a valid result for all numbers.
addandminusare almost the same. One function that allows a negative argument would suffice. If you want to keepminusimplement it simply asreturn self.add(-n)
Context
StackExchange Code Review Q#71863, answer score: 6
Revisions (0)
No revisions yet.