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 trialMathew Yangang
4,433 Pointsreturning product
Where does slices come into play in this task. I keep getting 'try again' messages
def multiply(base, *args):
num = base
for value in args:
num = value*
return num
3 Answers
Philip Schultz
11,437 PointsHey, 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.....
Alexander Davison
65,469 PointsI'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
Treehouse TeacherDon't forget operator.mul
!
reduce(operator.mul, nums)
Mathew Yangang
4,433 PointsThanks Craig
Philip Schultz
11,437 PointsPhilip Schultz
11,437 PointsHey 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
Treehouse TeacherCraig Dennis
Treehouse TeacherThis is the version using the slice hint.
That make sense?
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsAh I see :)
Philip Schultz
11,437 PointsPhilip Schultz
11,437 PointsOk, that is interesting. Thanks Craig