Last active
September 9, 2017 17:22
-
-
Save devvyn/6bc3c2e788ce19ddd5592fcf5d46174d to your computer and use it in GitHub Desktop.
scratch.py
This file contains hidden or 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
# readable, but not DRY | |
def fb1(number): | |
return ''.join(( | |
('fizz' if (not number % 3) else ''), | |
('buzz' if (not number % 4) else ''))) or str(number) | |
# fully DRY, easy to maintain | |
def fb2(number): | |
a = {3: 'fizz', | |
4: 'buzz'} | |
f = lambda x, d: x % d == 0 | |
test_output = (text for divisor, text in a.items() if f(number, divisor)) | |
conditional_text = ''.join(test_output) | |
return conditional_text or str(number) | |
# no lambda, no dict.items() | |
def fb3(number): | |
a = ((3, 'fizz'), | |
(4, 'buzz')) | |
test_output = (text for divisor, text in a if number % divisor == 0) | |
conditional_text = ''.join(test_output) | |
return conditional_text or str(number) | |
# no lambda, no dict.items(), fewer variables | |
def fb4(number): | |
a = ((3, 'fizz'), | |
(4, 'buzz')) | |
return ''.join((text for divisor, text in a if number % divisor == 0)) or str(number) | |
# no lambda, no dict, inline expressions (DRY but harder to maintain) | |
def fb5(number): | |
return ''.join((text for divisor, text in ((3, 'fizz'), (4, 'buzz')) if number % divisor == 0)) or str(number) | |
for fb in (fb1, fb2, fb3, fb4, fb5): | |
# 17, fizzbuzz, fizz, buzz | |
print(fb(17), fb(12), fb(33), fb(44)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was just for fun. The matter I was exploring is the balance between readability and DRYness.
fb3
is my favourite, because it's readable and performs wellfb1
was the first idea off the top of my headfb2
would be perfect for refactoring in various waysfb4
andfb5
are too extreme, so DRYness doesn't pay off