2024. 2. 12. 16:48ㆍHackerRank-Python
Maximize It! | HackerRank
Find the maximum possible value out of the equation provided.
www.hackerrank.com
문제
=> 각 N개의 원소를 가지는 리스트 K개가 있다. 각 리스트에서 하나의 원소를 제곱하고 서로 더한 뒤 M으로 나눈 나머지를 S라고 하자. 얻을 수 있는 S의 최댓값을 구하라.
코드
from itertools import product
from itertools import accumulate
K, M = map(int, input().split())
li = []
for i in range(K):
li.append(list(input().split()[1:]))
all_combi = list(product(*li))
maxs = []
for j in all_combi:
j = list(map(int, j))
maxs.append(list(accumulate(list(x**2 for x in j)))[-1])
print(
max(list(map(lambda x: x%M, maxs)))
)
노트
step1 가능한 모든 조합 추출
K, M = map(int, input().split())
li = []
for i in range(K):
li.append(list(input().split()[1:]))
all_combi = list(product(*li))
- for반복문으로 각 리스트 받아오기(N값이 제일 먼저 input되기때문에 리스트에서 제외해줌
- product연산으로 iterable들의 모든 조합 뽑아내기
step2 제곱합들 구하기
for j in all_combi:
j = list(map(int, j))
maxs.append(list(accumulate(list(x**2 for x in j)))[-1])
- accumulate연산으로 누적합 구하기(마지막 누적합이 모든 제곱들의 합)
- list comprehension 유용하게
step3 나머지중 최댓값 구하기
print(
max(list(map(lambda x: x%M, maxs)))
)
- lambda 함수로 M으로 나눈 나머지들을 리스트에 담아냄
참조
변수 이름 for문으로 할당하는 방법(globals( ))
Python 종종 변수 이름 바꿔가면서 할당해야 하는 일이 생깁니다. 이때 어떤 식으로 변수 이름을 바꿔서 할당할 수 있는지 알아보도록 하겠습니다. 다양한 방법으로 활용하기 위해서 format 함수를
axce.tistory.com
[python] 파이썬 f-string (문자열 포매팅 방법 3)
안녕하세요. BlockDMask 입니다. 오늘은 파이썬 문자열 포매팅 방법 % 서식문자, str.format, f-string 이 세개 중 마지막인 f-string에 대해서 알아보려고 합니다.% 서식문자 [바로가기] str.format [바로가기]
blockdmask.tistory.com
024 연간 매출액을 계산하려면? ― itertools.accumulate
itertools.accumulate(iterable)은 반복 가능한 객체(iterable)의 누적합을 계산하여 이터레이터로 반환하는 함수이다. ## 문제 다음은 어떤 회사의…
wikidocs.net
3.5 람다(lambda)
오늘은 람다 형식과 그것을 이용하는 여러 가지 함수들에 대해서 알아보겠습니다. 당장 완벽하게 소화하실 필요는 없을 것 같구요, 가벼운 마음으로 이런 것이 있다는 정도만 아셔도 되…
wikidocs.net
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Basic Data Types > Find the Runner-Up Score! (0) | 2024.03.21 |
---|---|
Prepare > Python > Python Functionals > Validating Email Addresses With a Filter (1) | 2023.10.04 |
Prepare > Python > Python Functionals > Reduce Function (0) | 2023.10.03 |
Prepare > Python > Built-Ins > ginortS (0) | 2023.10.02 |
Prepare > Python > Built-Ins > Athlete Sort (0) | 2023.10.01 |