Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Tuples Packing

Benjamin Bradshaw
Benjamin Bradshaw
3,208 Points

I want to expand my knowledge

This code here works yet I didn't use slices like it recomended. I want to know how i would use slices so that i have a greater understanding of how and why it would work

twoples.py
def multiply(*args):
    base = 1
    for arg in args:
        base = base * arg
    return base

1 Answer

Hi there!

So first, I thought I should just say, you probably wouldn't - the way you a re doing it is readable, easy to maintain, doesn't require importing anything for one operation, etc. However, to answer the question, the way to do this with slice, would be by recursion. Basically you take the first element of the array, and then pass the rest of the array back into the function, which again takes the first element of the array, and passes the rest back in, until you have only one element in the array, then each function call returns the value it holds, multiplied by the value returned by function it called:

def multiply(*args):
    def recursive_product(nums):
        if len(nums) > 1:
            return nums[0] * recursive_product(nums[1:])
        else:
            return nums[0]
    return recursive_product(args)

Note that the recursive function is inside a wrapper function that appears to do nothing, This has the effect of reducing the args into one single argument so that the len() call works after the first recursion. You could do this by unpacking the list returned by slicing and passing into the next call with recursive_product(*nums[1:]), but no need to do that every single call!

Again, you wouldn't use this in real life, just because 1) You'd hit the recursion limit pretty fast if your had very long lists, and 2) the for loop is much, much faster, while using less memory. When I timed them for 1000 element arrays, recursion was slower by a factor of 3.75 on average. My testing code is here: https://pastebin.com/KeycpyM1

I'd be happy to explain anything if it's not clear, hope it helps :)