본문 바로가기

Python

[Python/level 0] 길이에 따른 연산 - 181879, prod()

문제 설명

 

정수가 담긴 리스트 num_list가 주어질 때, 리스트의 길이가 11 이상이면 리스트에 있는 모든 원소의 합을 10 이하이면 모든 원소의 곱을 return하도록 solution 함수를 완성해주세요.

 

prod()

  • The math.prod() method returns the product of the elements from the given iterable.
    요소의 을 반환합니다.
  • math.prod(iterable,start)
    math에 있는 함수이기 때문에 사용 시 import math를 먼저 해 주어야 합니다.
Parameter Description
iterable Required. Specifies the elements of the iterable whose product is computed by the function
start Optional. Specifies the starting value of the product. Default value is 1

 

Code - 1차

def solution(num_list):
    answer = 1
    if (len(num_list) >= 11):
        return (sum(num_list))
    else:
        for i in num_list:
            answer *= i
        return answer
  • if문 → sum
    • len(num_list) 리스트의 길이가 11 이상이라면 sum 함수를 이용해 num_list의 요소를 더합니다.
  • else → answer *= i
    • 11 미만이라면 answer에 i의 값을 곱합니다. 이때 answer의 초기값은 1로 설정합니다.(0이면 i를 계속 곱해도 0만 반환됨)

 

Code - 2차

import math

def solution(num_list):
    if len(num_list) >= 11:
        return sum(num_list)
    else:
        return math.prod(num_list)
  • prod
    • else때 math.pord 함수를 이용해 각 요소를 곱합니다.

 

반응형