Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
Simple recursive sum function | what's the cause of the weird behaviour?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Russel Walker, post: 5104137"] 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 is equivalent to, AFAIK, this So to overcome that you just have to do Which creates a new list. So any variables which were pointing to the same list as a, are unaffected. Summary - - - - [1, 2, 3] [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 '' [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
Simple recursive sum function | what's the cause of the weird behaviour?
Top