-3

Given a number ‘n’, output its factorial using reduce().

Note: Make sure you handle the edge case of zero. As you know, 0! = 1

from functools import reduce

n = int(input())
f = reduce(lambda n : n * (n - 1) if n > 1 else n)
print(f)

Also, I need help with this type error mentioned below

TypeError: reduce expected at least 2 arguments, got 1
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • RTL(ovely)M: https://docs.python.org/3/library/functools.html#functools.reduce – maio290 Jan 03 '19 at 12:24
  • 1
    You are getting confused between recursive functions and `reduce`. How, I'm not sure. You can use `f = reduce(lambda x, y : x * y, range(1, n+1)) if n > 0 else 1`. – jpp Jan 03 '19 at 12:31
  • 1
    The canonical dupe contains _many_ ways to calc the factorial .. including those using `reduce` - I see no reason to create a "specific" question here. Research SO before asking please - this will help you faster. – Patrick Artner Jan 03 '19 at 12:33

1 Answers1

0

reduce expects two arguments. First a function expecting two args, and second an iterable. The proper code should be like this.

from functools import reduce
n = int(input())
f = 1 if n == 0 else reduce(lambda a, b : a*b, range(1, n+1))

print(f)
Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42