Simple recursive sum function | what's the cause of the weird behaviour?

Russel Walker russ.pobox at gmail.com
Sun Jul 7 18:13:19 CEST 2013


I read through all of the posts and thanks for helping. What was supposed to be simple a (recursively) straightforward, turned out to be quite tricky.

I've set up a small testing bench and tried all of the proposed solutions including my own but none pass. I'll post it below.

I've also discovered something about lists that explains the very first "weird" result I was observing, which I realized was because lists are mutable etc, but more specifically:

This

>>> a = [1, 2]
>>> a += [3]

is equivalent to, AFAIK, this

>>> a = [1, 2]
>>> a.extend([3])

So to overcome that you just have to do

>>> a = [1, 2]
>>> a = a + [3]

Which creates a new list. So any variables which were pointing to the same list as a, are unaffected.

Summary
- - - -

>>> # --- Bad ---
>>> a = [1, 2]
>>> b = a
>>> a += [3]
>>> print a
[1, 2, 3]
>>> print b
[1, 2, 3]

>>> # --- Good ---
>>> a = [1, 2]
>>> b = a
>>> a = a + [3]
>>> print a
[1, 2, 3]
>>> print b
[1, 2]


And as for the testbench:

def supersum(seq, start=0):
    return


# ---------------- Testing -------------------------------- >

testcases = [

    # (seq,                 start, result)

    # arithmetic sums
    ([],                    0,      0),
    ([[], []],              0,      0),
    ([[], [[],[]]],         0,      0),
    ([1],                   0,      1),
    ([[], [1]],             0,      1),
    ([[], [[],[1, 1]]],     0,      2),
    ([[1], [1]],            0,      2),
    ([[1], [[1],[1, 1]]],   0,      4),
    ([[1], [[1],[1, 1]]],   1,      5),

    # list flattening
    ([],                    [],     []),
    ([[], []],              [],     []),
    ([[], [[],[]]],         [],     []),
    ([],                    [1],    [1]),
    ([[], []],              [1],    [1]),
    ([[], [[],[]]],         [1],    [1]),
    ([1],                   [1],    [1, 1]),
    ([[1], [1]],            [1],    [1, 1]),
    ([[1], [[1],[1]]],      [1],    [1, 1, 1, 1]),

    ]


for seq, start, result in testcases:
    try:
        assert supersum(seq, start) == result
    except Exception as er:
        print "seq:%s\t start:%s" % (seq, start)
        if type(er) is AssertionError:
            print "expected:", result
            print "got:     ", supersum(seq, start)
        else:
            print repr(er)
        print ''




More information about the Python-list mailing list