0

I need to sum objects (strings, ints, etc.) in one function (don't create other function, it can be done within one). It should work this way: When given my_sum([[['s'],'ta'],['c',['k']]]), it should return 'stack'.

I came up with this:

def my_sum(array):

    if not array: #empty array
        return None

    else:

        for item in array:

            if type(item) == list:
                my_sum(item)

            else:
                print(item)

It of course is not doing what it should be, I was just playing around with it trying to come up with something. This code above returns this:

s
ta
c
k

I think I am not that far from result as I have what I need, but here is the problem how can I sum up those items ? I can't write result = '' anywhere in the function and then return it, because it would be deleting every time there would be recursion call. Also I don't want global variables (if anyone would think of that). Maybe I am just being stupid and can't see that it is one simple thing, pardon me if it is so.

Thank you for every answer!

2
  • I got a deja-vu here. Commented Mar 3, 2015 at 20:58
  • 1
    You need another argument to your my_sum function, try an accumulator value so that instead of returning None you can return that value. def my_sum(array, acc=None): ... Commented Mar 3, 2015 at 21:08

1 Answer 1

4

The common accumulating pattern is:

result = <init value>
for item in argument:
     result = result <operator> item
return result

(this can be written more concisely, but that's not the point for now).

Applied to your problem:

def my_sum(items):
    result = ''
    for item in items:
        if type(item) == list:
            result += my_sum(item)
        else:
            result += item
    return result

Note that type(x) == y is frowned upon in Python, isinstance is considered better style.

Homework: extend the function so that it works for these arguments too:

print my_sum([[['s'],'ta'],('c',('k')), {('over'), ('flow')}])
Sign up to request clarification or add additional context in comments.

1 Comment

And even then, isinstance should be use sparingly, as it will, for example, fail if the input is a tuple even though it would be perfectly valid (as your followup question is designed to point out, I assume)

Your Answer

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.