I wrote and tested the code below with Python 3 and it works fine:
def format_duration(seconds):
dict = {'year': 86400*365, 'day': 86400, 'hour': 3600, 'minute': 60, 'second': 1}
secs = seconds
count = []
for k, v in dict.items():
if secs // v != 0:
count.append((secs // v, k))
secs %= v
list = [str(n) + ' ' + (unit if n == 1 else unit + 's') for n, unit in count]
if len(list) > 1:
result = ', '.join(list[:-1]) + ' and ' + list[-1]
else:
result = list[0]
return result
print(format_duration(62))
In Python3 the above returns:
1 minute and 2 seconds
However, the same code in Python 2.7 returns:
62 seconds
I can't for the life of me figure out why. Any help would be greatly appreciated.
1 Answer 1
The answers are different because the items in your dict are used in a different order in the two versions.
In Python 2, dicts are unordered, so you need to do more to get the items in the order you want.
BTW, don't use "dict" or "list" as variable names, it makes debugging harder.
Here's fixed code:
def format_duration(seconds):
units = [('year', 86400*365), ('day', 86400), ('hour', 3600), ('minute', 60), ('second', 1)]
secs = seconds
count = []
for uname, usecs in units:
if secs // usecs != 0:
count.append((secs // usecs, uname))
secs %= usecs
words = [str(n) + ' ' + (unit if n == 1 else unit + 's') for n, unit in count]
if len(words) > 1:
result = ', '.join(words[:-1]) + ' and ' + words[-1]
else:
result = words[0]
return result
print(format_duration(62))
answered Oct 30, 2018 at 1:47
Ned Batchelder
378k77 gold badges583 silver badges675 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
aherzfeld
Perfect solution. That is valuable to know that dicts act differently in 2 and 3. Much appreciated!
lang-py