Euclidean Rhythm in vanilla py3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Euclidean Rhythm in vanilla py3 | |
def euclidean_rhythm(beats, pulses): | |
"""Computes Euclidean rhythm of beats/pulses | |
Examples: | |
euclidean_rhythm(8, 5) -> [1, 0, 1, 0, 1, 0, 1, 1] | |
euclidean_rhythm(7, 3) -> [1, 0, 0, 1, 0, 1, 0] | |
Args: | |
beats (int): Beats of the rhythm | |
pulses (int): Pulses to distribute. Should be <= beats | |
Returns: | |
list: 1s are pulses, zeros rests | |
""" | |
if pulses is None or pulses < 0: | |
pulses = 0 | |
if beats is None or beats < 0: | |
beats = 0 | |
if pulses > beats: | |
beats, pulses = pulses, beats | |
if beats == 0: | |
return [] | |
rests = beats - pulses | |
result = [1] * pulses | |
pivot = 1 | |
interval = 2 | |
while rests > 0: | |
if pivot > len(result): | |
pivot = 1 | |
interval += 1 | |
result.insert(pivot, 0) | |
pivot += interval | |
rests -= 1 | |
return result | |
if __name__ == '__main__': | |
import unittest | |
class EuclideanRhythmTest(unittest.TestCase): | |
def test_raises_when_called_with_no_args(self): | |
with self.assertRaises(Exception): | |
euclidean_rhythm() | |
def test_returns_empty_list_when_pulses_and_beats_0(self): | |
self.assertEqual([], euclidean_rhythm(0, 0)) | |
def test_returns_zero_pulses_when_pulses_none(self): | |
self.assertEqual([0, 0], euclidean_rhythm(2, None)) | |
def test_returns_zero_pulses_when_pulses_negative(self): | |
self.assertEqual([0, 0], euclidean_rhythm(2, -1)) | |
def test_returns_zero_beats_when_beats_none(self): | |
self.assertEqual([], euclidean_rhythm(None, 0)) | |
def test_returns_zero_beats_when_beats_negative(self): | |
self.assertEqual([], euclidean_rhythm(-1, 0)) | |
def test_swaps_beats_pulses_when_pulses_greater_than_beats(self): | |
self.assertEqual(8, len(euclidean_rhythm(5, 8))) | |
def test_returns_empty_list_when_beats_0(self): | |
self.assertEqual([], euclidean_rhythm(0, 0)) | |
def test_expected_output(self): | |
test_cases = ( | |
(1, 0, [0]), | |
(1, 1, [1]), | |
(2, 1, [1, 0]), | |
(3, 1, [1, 0, 0]), | |
(8, 5, [1, 0, 1, 0, 1, 0, 1, 1]), | |
(7, 3, [1, 0, 0, 1, 0, 1, 0]), | |
) | |
for beats, pulses, expected in test_cases: | |
self.assertEqual(expected, euclidean_rhythm(beats, pulses)) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment