0

factorial of a series of first n natural number not using function

3rd Nov 2016, 1:31 PM
fahma
4 Respostas
+ 3
While loop version: def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num Recursive version: def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
3rd Nov 2016, 2:07 PM
Simone Trombiero
+ 2
# for loop a=1 n=3 ## change this for i in range(n): a *= (i+1) print(a) # list comprehension n=4 ## change this >>> [j for j in [1] for i in range(n) for j in [j * (i+1)]][-1] Explanation: Initialize j to 1 (so last multiply works) Iterate i from 0..n-1 Build a list, appending as the last element the accumulator (last value of j) * (i-1). Cut /display the last element (at index -1) Possible disadvantage: This saves all the intermediate products, only clipping off the last product at the end. The for loop solution just keeps the running total.
3rd Nov 2016, 3:19 PM
Kirk Schafer
Kirk Schafer - avatar
0
Actually, pure recursive version will be slow, so here comes to place memoization, it makes it much faster.
3rd Nov 2016, 3:21 PM
Daniel Oravec
Daniel Oravec - avatar
0
jola
4th Nov 2016, 6:28 PM
Daniel
Daniel - avatar