[python] int형 list 원소들의 곱

써니·2023년 6월 30일
1

Python

목록 보기
8/9
  1. traversal : for loop
    def multiplyList(myList):
      result = 1
      for x in myList:
          result = result * x
      return result
    • time complexity : O(n)
    • Auxiliary space : O(1)
  1. numpy.prod
    import numpy
    list1 = [1, 2, 3]
    result1 = numpy.prod(list1)
    print(result1)
    • time complexity : O(n)
    • Auxiliary space : O(1)
  1. lambda w/ numpy.array

    from functools import reduce
    list1 = [1, 2, 3]
    result1 = reduce((lambda x,y : x*y), list1)
    print(result1)
    • time complexity : O(n)
    • Auxiliary space : O(1)
  2. math.prod

    import math
    list1 = [1, 2, 3]
    result1 = math.prod(list1)
    print(result1)
    • time complexity : O(n)
    • Auxiliary space : O(1)
  3. mul() function from operator

    from operator import *
    list1 = [1, 2, 3]
    m = 1
    
    for i in list1:
    	m = mul(i,m)
    
    print(m)
    • time complexity : O(n)
    • Auxiliary space : O(1)




참고 : https://www.geeksforgeeks.org/python-multiply-numbers-list-3-different-ways/

0개의 댓글