aherzfeld
aherzfeld

Reputation: 155

Can't figure out why code working in Python 3 , but not 2.7

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.

Upvotes: 2

Views: 80

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375574

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))

Upvotes: 8

Related Questions