Trying to Combine in Python

What about Combine?

Unlike in Snap!, combine as a function is not very friendly to use in Python (it's actually called reduce), so we won't be talking about it here, but if you want to find out more, here is a link to the Python documentation for reduce (note that you must import functools to use reduce).

Exercise 5: Combine

A better way to combine the items of a list is by using a for loop that you write yourself.

Try writing your own version of combine in Python that takes in a list of numbers OR strings and returns the combined result.

You may not use reduce from the functools library to write this function.

Hint: think about what the + operator does for strings and for numbers.


>>> nums = [1, 2, 3, 4, 5]
>>> strings = ["hello ", "my ", "name ", "is ", "someone?"]
>>> combine(nums)
15
>>> combine(strings)
"hello my name is someone?"
        

Hint: For the most elegant solution, use recursion. The rough equivalent of "all but first of" in Python is [1:].

anteriorpróximo