[프로그래머스] Lv.1 | 음양 더하기 (Python)

김찬미·2024년 8월 16일

코딩 테스트 (Python)

목록 보기
47/54

☯️ 음양 더하기


💻 최종 코드

def solution(absolutes, signs):
    return sum(absolute if sign else -absolute for absolute,sign in zip(absolutes,signs))

시간 복잡도: O(n)


❤️‍🩹 개선점

def solution(absolutes, signs):
    return sum(absolutes[i] if signs[i] else -absolutes[i] for i in range(len(signs)))

range() -> zip()

이전 코드에서는 range(), len() 함수를 이용해 문제를 풀었지만, 이번에는 zip() 함수를 이용해 풀이를 해보았다.

여기서 zip() 함수란 iterable한 객체, 즉 순환 가능한 객체들을 인자로 받아 처리를 할 수 있다. 특히 zip() 함수는 2개 이상의 객체를 사용할 때 유용하다.


❗ 포인트

zip(absolutes,signs)

두 개 이상의 순환 가능한 객체를 사용할 때에는 zip() 함수를 이용하자!

profile
백엔드 지망 학부생

0개의 댓글