how to multiply all the numbers in a sequence (python)
Solution 1
Since you are trying to learn to code, I won't give you a total solution, but I'll give you a few hints instead:
Have a
for
loop that runs up from 1 to n (usingrange(1, n+1)
) instead of yourwhile
-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be a bit tricky withwhile
loops sometimes).Have a variable named
product
to store the result of the multiplications each time through the loop.Initialize
product
before you enter thefor
-loop. Once inside you'll be just updating the value ofproduct
.After you are done with the loop, you can use the
return
statement to return the value ofproduct
.Finally, for testing purposes, you may want to start out with a small value of
n
, like 4, and print out the values you are computing inside the loop to verify how your code is working.
There are more terse and pythonic ways to do this, but this uses the code structure you have already set up. And of course recursively as well as you mention too.
Once you master the basics, you'll appreciate the more idiomatic ways of writing this, or calling the appropriate functions that do this for you.
Solution 2
Well, here's another Pythonic approach.
>>> import operator
>>> numbers = range(1, 11)
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce(operator.mul, numbers)
3628800
Solution 3
Assuming you what you meant is factorial function, you can simply just use the math.factorial()
:
>>> import math
>>> math.factorial(10)
3628800
Solution 4
You are trying to find the factorial of a number n, essentially. For finding the factorial of a number, there are 2 methods
- Using a Loop structure
- Using Recursion (as you've mentioned)
As a new programmer, you would be better off with a simple loop structure that runs from 1 to n and puts the multiplied value at each iteration into a variable. That variable is your answer. But also know that recursion will also work and make the code look elegant. Happy Programming !
Solution 5
This is called the factorial. 10! is equivalent to 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
def factorial(n):
product = 1
while n > 0:
product *= n
n -= 1
return product
By the way, in practice, just use math.factorial
.
Billy Thompson
Updated on June 20, 2022Comments
-
Billy Thompson almost 2 years
Like if i told the program
n=10
, how would I make it return10*9*8*7*6*5....1
?I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence.
My current code looks like this
def product(n): i=n a=n-1 while a>0: return i * a b=i * a a=a-1 i=i-1
Are there any better ways to do it without using recursion? Sorry for the incredibly beginner question, but I'm trying to teach myself how to code. You gotta start somewhere!
Thanks!