본문 바로가기

코딩테스트/코딩 테스트 입문

k의 개수

문제

 

 

# 내 풀이

def solution(i, j, k):
    answer = 0
    
    for num in range(i, j+1):
        for a in str(num):
            if str(k) == a:
                answer += 1
        
    return answer

 

 

 

# GPT 풀이

def solution(i, j, k):
    return sum(str(num).count(str(k)) for num in range(i, j + 1))
  • num 문자열에 k 문자가 중첩되지 않고 등장하는 횟수를 돌려준다.

 

 

 

# sum(iterable, /, start=0) :

start 및 iterable의 항목들을 왼쪽에서 오른쪽으로 합하고 합계를 돌려준다. iterable의 항목은 일반적으로 숫자며 시작 값은 문자열이 될 수 없습니다.

 

 

 

# str.count(sub[, start[, end]]) :

범위 [start, end]에서 부분 문자열 sub가 중첩되지 않고 등장하는 횟수를 돌려준다. 선택적 인자 start와 end는 슬라이스 표기법으로 해석된다.

text = "apple"
count = text.count('p')
count_in_range = text.count('p', 1, 4)  # 인덱스 1부터 4까지의 범위에서 "p" 세기. 출력: 1

 

 

 

# 출처 :

https://docs.python.org/ko/3.13/library/functions.html#sum

https://docs.python.org/ko/3.13/library/stdtypes.html#str.count

 

Built-in Types

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...

docs.python.org

 

'코딩테스트 > 코딩 테스트 입문' 카테고리의 다른 글

진료 순서 정하기  (0) 2025.03.15
A로 B 만들기  (0) 2025.03.12
2차원으로 만들기  (0) 2025.03.11
모스부호  (0) 2025.03.11
합성수 찾기  (0) 2025.03.10