2

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.

asked Oct 30, 2018 at 1:42

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect solution. That is valuable to know that dicts act differently in 2 and 3. Much appreciated!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.