개발자 99% 커뮤니티에서 수다 떨어요!
💡 연습문제
15. How many numbers are in the series 0, 5, 10, 15, ..., 100?(0, 5, 10, 15, ..., 100 사이에 몇 개의 숫자가 있습니까?)
✅ 풀이 과정
문제는 0부터 100까지 5씩 증가하는 수열에 전체 개수를 세는 것
먼저 python의 range함수를 이용해서 0부터 100까지 5씩 증가하는 배열을 작성.
start = 0
end = 100
step=5
array = list(range(start, end, 5)
print(array)
# 결과
# > [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
range로 단순하게 end에 0을 넣어줘서 생성하는 배열은 100이 들어가지 않았다
도큐먼트를 보니 For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
, 즉 r[i] < stop
이므로 end자리에 넣은 숫자는 배열에 들어가지 않는다.
따라서 range의 end인수를 아래와 같이 수정
array = list(range(start, end + 1, 5)
print(array)
# 결과
# > [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
제대로 100까지 들어간 걸 확인하고, 이 배열의 개수를 세어주었다
print(len(array))
# 결과
> 21
따라서 답은 21이다
💡 책에 있는 해답
There are 21 terms in the series. If you said 20, you just experienced a fencepost error (not knowing whether to count the fenceposts or the spaces between them).
fencepost error(울타리 기둥 에러), 경계에 있는 숫자(문제에서는 0,100)에 대해 신경을 쓰지 않아서 일어나는 에러에 대한 문제였다. 프로그래밍 하면서 한 번 쯤은 빠져봤을 에러 인 듯 하다 ㅎㅎ
✅ 참고 링크
- range에 대해서(https://docs.python.org/3/library/stdtypes.html#typesseq-range)
- fencepost error(https://en.wikipedia.org/wiki/Off-by-one_error)