강의

멘토링

로드맵

Inflearn Community Q&A

shji03273's profile image
shji03273

asked

Introduction to Python Algorithm Problem Solving (Coding Test Preparation)

5. Sum of numbers

코드 오류

Written on

·

174

1

강의를 듣기전에 문제를 풀어볼 때 아래 코드처럼 이중for문으로 풀었습니다.  제대로된 값이 안나오는데 어느부분에서 오류가 있는지 모르겠습니다.

import sys
sys.stdin = open("input.txt", "rt")

N, M = map(int, input().split())
a = list(map(int, input().split()))
cnt = 0
for i in range(len(a)):
    sum = a[i]
    for j in range(i+1, len(a)):
        if sum != M:
            sum += a[j]
        elif sum == M:
            cnt += 1
            break
print(cnt)
python코테 준비 같이 해요!

Answer 1

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

sum+=a[j]을 하면 바로 sum==M인지 확인해야 하는데 이 코드는 한 박자 느리게 확인을 합니다.

문제의 있는 입력예시로 보자면 맨 마지막 3이 되는 경우인 1 2 의 경우를 카운팅하지 않습니다.

elif sum==M: 대신에 if sum==M: 으로 바꾸면 될겁니다. 

shji03273's profile image
shji03273

asked

Ask a question