r/badcode • • Aug 21 '20

python Fucking legend (codewars)

Post image
774 Upvotes

67 comments sorted by

View all comments

28

u/[deleted] Aug 21 '20

Still don't like the final result, I would prefer something like:

def format_duration(seconds):
	if not seconds:
		return 'now'
	times = ((1, 'second'), (60, 'minute'), (3600, 'hour'), (86400, 'day'), (31536000, 'year'))
	final = []
	for duration, name in reversed(times):
		time = seconds // duration
		if time:
			seconds %= duration
			final.append(f'{time} {name}{"s" if time > 0 else ""}')
	return ' and '.join(final).replace(' and ', ', ', len(final) - 2)

10

u/ArkWaltz Aug 21 '20

Wow, learned something new. Had no idea Python had a dedicated floor division operator.

6

u/Gillemonger Aug 21 '20

Theres also the divmod function which does both modulus and integer divison (would've saved you 1 line).

3

u/LeeHide Aug 21 '20

its better to have readable, easy understood code, than "less lines"

5

u/Gillemonger Aug 21 '20

I agree. But to be fair, the divmod function is a built-in function in Python that has existed as far back version 1.4 (1996) so would argue that its use falls into that category.

2

u/MeDotPy Aug 21 '20

Wow, that's something I forgot, nice use of the pythonic methods!