반응형

본 프로그램은 python 2.7.13에서 제작되었습니다.



이번에는 str에 내장함수로 존재하는 count를 만들어보고자 한다.


우선 python에서 기본적으로 제공하는 str 내장함수 count 메서드는 다음과 같다.


count(sub[, start[, end]]) -> int


이 의미는 count를 하기 위해 문자열(sub)는 필수로 입력하고, 시작 인덱스인 start와 끝 인덱스인 end는 선택사항이라는 의미이다.


start와 end를 인자로 넣지 않으면 default값으로 0, len(str) 값이 들어간다.


우선 기본적인 코드로 count가 어떻게 돌아가는지 이해해보자.


1
2
3
4
5
6
7
8
9
10
11
#-*- coding: utf-8 -*-
 
string = 'd worldd'
 
print string.count('d')
print string.count('d'1)
print string.count('d'07)
print string.count('d'0len(string))
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus



여기서 결과값은 

3

2

2

3

이 나온다.


첫번째 print는 'd'를 string에서 찾아달라 했으니 총 3개

두번째 print는 'd'를 인덱스를 1부터 시작해서 찾아달라 했으니 총 2개

세번째 print는 'd'를 인덱스 0부터 7까지 찾아달라 했으니 0<= idx < 7로 해석이 되어 총 2개

네번째 print는 'd'를 인덱스 0부터 len(string)까지 찾아달라 했으니 0<= idx < 8로 해석이 되어 총 3개가 나온다. 




그럼 이제 이 내용을 기반으로 count라는 함수를 만들어보자.

아래 코드를 통해 이야기 해보려 한다.




예제 코드 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#-*- coding: utf-8 -*-
 
def count(string, search, start = -1, end = -1):
    cnt = 0
    pos = 0
    
    # start, end인자를 전달 받지 않았을 때
    if start == -and end == -1:
        while True:
            pos = string.find(search, pos)
            
            if pos == -1:
                break
            
            cnt+=1
            pos += 1
            
    # start 인자만 전달받았을 때
    elif start != -and end == -1:
        while True:
            pos = string.find(search, start + pos)
            if pos == -1:
                break
 
            cnt += 1
            pos += 1
 
    # start, end 인자 모두 전달 받았을 때
    else:
        while True:
            pos = string.find(search, start + pos, end)
 
            if pos == -1:
                break
 
            cnt += 1
            pos += 1
            
    return cnt
 
fruit = 'This banana is bigger than that banana'
 
print 'no start, end argument'
print 'use user\'s count function :: ', count(fruit, 'banana')
print 'use original count function :: ', fruit.count('banana'), '\n'
 
print 'no end argument'
print 'use user\'s count function :: ', count(fruit, 'banana'33)
print 'use original count function :: ', fruit.count('banana'33), '\n'
 
print 'use start, end argument'
print 'use user\'s count function :: ', count(fruit, 'banana',132)
print 'use original count function :: ', fruit.count('banana'132), '\n'
 
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


아래 코드를 통해 이야기 해보려 한다.

첫번째 if문인 start 인자와 end 인자 두개 모두 전달 받지 못했을 때, find 함수를 통해 'banana'의 시작 인덱스를 찾고

pos가 -1이 되기전까지 cnt++를 해준다.(find 메서드는 일치하는 결과가 없을 때 -1을 리턴한다.)

두번째 elif문에서는 start 인자만 받았다면 count('banana', start)와 같은 방식으로 동작하게 되는 과정을 표현하고 있다.

세번째 else문에서는 start, end 인자를 모두 전달 받았다면 동일하게 
find 메서드에 substring, start + pos, end를 넣고 위와 같은 행동을 취해주면 된다.



반응형