Skip to content

Instantly share code, notes, and snippets.

@devvyn
Last active September 9, 2017 17:22
Show Gist options
  • Save devvyn/6bc3c2e788ce19ddd5592fcf5d46174d to your computer and use it in GitHub Desktop.
Save devvyn/6bc3c2e788ce19ddd5592fcf5d46174d to your computer and use it in GitHub Desktop.
scratch.py
# 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))
@devvyn
Copy link
Author

devvyn commented Sep 9, 2017

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 well
  • fb1 was the first idea off the top of my head
  • fb2 would be perfect for refactoring in various ways
  • fb4 and fb5 are too extreme, so DRYness doesn't pay off

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment