Python 알고리즘 문제 풀이(feat. LeetCode)

윤현묵·2021년 7월 15일
0
post-thumbnail

파이썬 실력 향상을 위해 쉬운 단계의 알고리즘 문제부터 차근차근 풀어보도록 하겠습니다.
초반에는 LeetCode 사이트에서 Easy 난이도의 문제 위주로 진행할 예정입니다.

문제: 1480. Running Sum of 1d Array(Easy, 88.9%)

(주어진 배열에서 첫번째 인덱스에서 각 인덱스까지의 누적 합으로 새로운 배열을 생성)

Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

나의 풀이

class Solution():
    def runningSum(self, nums):       
        self.nums = nums
        sum = 0
        out = []
        for i in self.nums:
            sum += int(i)
            out.append(sum)

        return out
            
output = Solution()
print(output.runningSum(list(map(int,input().split(",")))))
  • 반복문을 이용하여 sum 변수에 누적합을 할당하고, out.append를 이용하여 리스트에 하나씩 추가하였습니다.

참고할 만한 다른 풀이

from itertools import accumulate

class Solution:
    def runningSum(self, nums):
        return list(accumulate(nums))

output = Solution()
print(output.runningSum(list(map(int,input().split(",")))))
  • acuumulate(누적 합을 계산해주는 함수)를 사용하여 매우 간단히 풀 수 있었습니다...😢
    작은 input 값의 경우 큰 차이가 없겠지만 계산이 필요한 값이 커지는 경우 acuumulate를 이용하는 것이 속도에서 더 빠른 이점이 있습니다.
profile
진정성 있는 개발자를 꿈꾼다

0개의 댓글