Create list of factorials using list comprehension

前端 未结 3 1641
挽巷
挽巷 2021-01-23 11:26

I\'m trying to build a list of the first ten factorials

[1,1,2,6,24,120,720,5040,40320,362880]

using only list comprehension. Is that possible

相关标签:
3条回答
  • 2021-01-23 11:44

    Just for fun:

    One-liner mega-hack using list comprehension and an auxililary accumulator to reuse previously computed value

    s=[];  s=[s[-1] for x in range(1,10) if not aux.append(x*s[-1] if aux else 1)]
    

    result:

    [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
    

    note: The math.factorial answer is the way when elements are random. Here it's faster because we can reuse previous results.

    There's also another drawback: the need to store all elements in a list because python does not allow if and assignment like C does. So we have to append to a list and negate the None it returns so if test is True

    As I said: fun, but still a hack.

    0 讨论(0)
  • 2021-01-23 12:00

    You can use math.factorial():

    import math
    
    [math.factorial(n) for n in range(10)]
    

    Output:

    >>> import math
    >>> 
    >>> [math.factorial(n) for n in range(10)]
    [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
    
    0 讨论(0)
  • 2021-01-23 12:09

    Your attempt does not work because the list comprehension works element-wise, you cannot refer to lst[i-1] like that. There is a factorial function in math module, however, since you mentioned generators, you can use one like this

    def mygenerator():
        total = 1
        current = 1
        while True:
            total *= current
            yield total
            current += 1
    
    factorial = mygenerator()
    output = [next(factorial) for i in range(10)]
    
    0 讨论(0)
提交回复
热议问题