For a given sequence of numbers [0, 1, 2, 3, 4, 5, 6] output a sequence of factorials: 0!, 1!, 2!, ..., n! The task must be solved in a functional style.

My problem is that if is present in the program, but it cannot be used. Also, do not use cycles. Tell me how to get rid of if-s. Here is my code. Thank you in advance.

from itertools import accumulate a = [0, 1, 2, 3, 4, 5, 6] a = map(lambda x: 1 if x == 0 else x, a) # [1, 1, 2, 3, 4, 5, 6] print(*accumulate(a, lambda x, y: x * y)) 

    3 answers 3

    Well, if just a[0] = 1 is no good at all, then so:

     from itertools import accumulate a = [0, 1, 2, 3, 4, 5, 6] a = map(lambda x: max(x,1), a) print(*accumulate(a, lambda x, y: x * y)) 
    • Brilliant! Thank! - Belyaev Evgeniy

    lambda x: 1 if x == 0 else x, a this and any if can be converted to

     def func(x): try: assert x == 0 return 1 except AsertationError: return x 
    • Sorry, the style is not functional =) - Amaro Vita
     #!/usr/bin/env python3 from math import factorial numbers = [0, 1, 2, 3, 4, 5, 6] print(*map(factorial, numbers)) 

    Conclusion:

     1 1 2 6 24 120 720 

    If desired, you can independently determine math.factorial() :

     #!/usr/bin/env python3 import operator from functools import reduce def factorial(n): return reduce(operator.mul, range(1, n + 1), 1) numbers = [0, 1, 2, 3, 4, 5, 6] print(*map(factorial, numbers)) 

    The conclusion is the same.

    Both methods work for an arbitrary sequence of natural numbers - in any order. If your input numbers always go in a row, then itertools.accumulate() really itertools.accumulate() :

     #!/usr/bin/env python3 import itertools import operator numbers = [0, 1, 2, 3, 4, 5, 6] print(*itertools.accumulate([1] + numbers[1:], operator.mul)) # -> 1 1 2 6 24 120 720 

    For unlimited input, you can go to itertools.chain and itertools.islice .