문제 설명
정수가 담긴 리스트 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 |
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 함수를 이용해 각 요소를 곱합니다.
https://github.com/seonmin5/codingtest_Python
GitHub - seonmin5/codingtest_Python
Contribute to seonmin5/codingtest_Python development by creating an account on GitHub.
github.com
반응형
'Python' 카테고리의 다른 글
[Python/level 0] 제곱수 판별하기 - 120909, isqrt(), is_integer() (1) | 2024.08.17 |
---|---|
[Python/level 0] A 강조하기 - 181874, lower(), replace() (0) | 2024.08.17 |
[Python/level 0] 대문자와 소문자 - 120893, swapcase() (0) | 2024.08.17 |
[Python/level 0] 특정한 문자를 대문자로 바꾸기 - 181873, replace() (0) | 2024.08.17 |
[Python/level 0] 문자 반복 출력하기 - 120825, join() (1) | 2024.08.17 |