r/shittyprogramming • • Apr 10 '19

One Line of Code™

https://gist.github.com/WorryingWonton/ce8a3a74b0298f0b734fe4dd0a883a63
101 Upvotes

22 comments sorted by

View all comments

Show parent comment

1

u/overactor Apr 12 '19 edited Apr 12 '19

My solution was also wrong, it doesn't handle [13, 13, 1] correctly

def sum13(nums, acc=0, wasunlucky=False):
    if nums == []:
        return acc
    unlucky = nums[0] == 13
    return sum13(nums[1:], acc + (0 if wasunlucky or unlucky else nums[0], unlucky

I wrote this on my phone and didn't try it out, but that should be correct and tail call optimised. (Does python do TCO?)

edit: I just looked it up and found out that python does not do TCO, at which point I transform my recursion into a reduce and end up with the solution OP had.