Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Tuples Packing

returning product

Where does slices come into play in this task. I keep getting 'try again' messages

twoples.py
def multiply(base, *args):
    num = base
    for value in args:
        num = value*
    return num    

3 Answers

Philip Schultz
Philip Schultz
11,437 Points

Hey, just accept *args as a parameter. then declare the base inside and make it equal to 1 at first. Like so.

def multiply(*args):
    base = 1
    for item in args:
        base *= item
    return base

I'm still trying to figure out how to use it with slices also.....

Philip Schultz
Philip Schultz
11,437 Points

Hey Craig Dennis , This is driving me crazy. I can't seem to find anyone solving this using slices in past posts for this challenge. Is there a way to use slices to solve this problem that would be considered more efficient than the results above?

Craig Dennis
Craig Dennis
Treehouse Teacher

This is the version using the slice hint.

def multiply(*args):
    result = args[0]
    # Here's the slice...all except the first one
    for arg in args[1:]:
        result *= arg
    return result

That make sense?

Ah I see :)

Philip Schultz
Philip Schultz
11,437 Points

Ok, that is interesting. Thanks Craig

I'm not sure where slices come into play, but this challenge can be accomplished using an accumulating variable holding the current product, and every iteration as you loop through the numbers, you multiply the accumulating variable by it.

def multiply(*nums):
    acc = 1
    for num in nums:
        acc *= num
    return acc

Or, if you like using FP (Functional Programming), you can use the reduce method from functools

from functools import reduce

def multiply(*nums):
    return reduce(lambda x, y : x * y, nums)
Craig Dennis
Craig Dennis
Treehouse Teacher

Don't forget operator.mul!

reduce(operator.mul, nums)

Thanks Craig