본문 바로가기
Algorithm/코딩테스트 (Python)

[프로그래머스][구현] k의 개수

by 싱브이 2023. 10. 6.
728x90
반응형

문제 설명

1부터 13까지의 수에서, 1은 1, 10, 11, 12, 13 이렇게 총 6번 등장합니다. 정수 i, j, k가 매개변수로 주어질 때, i부터 j까지 k가 몇 번 등장하는지 return 하도록 solution 함수를 완성해주세요.

 

초기 코드)

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

 

다른 사람의 코드)

def solution(i, j, k):
    answer = sum([ str(i).count(str(k)) for i in range(i,j+1)])
    return answer

 

count()를 활용할 방법을 왜 생각하지 못했을까 !

 

 

 

 

  • Counter
    Counter는 Python의 collections 모듈이다. Counter는 요소의 개수를 세는 데 사용되며, 주로 리스트, 튜플, 문자열과 같은 반복 가능한(iterable) 객체에서 각 요소의 개수를 셀 때 유용합니다.
from collections import Counter
my_string = "hello"
my_counter = Counter(my_string)
print(my_counter)

# Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

print(my_counter.most_common(2))  # 가장 많이 나타나는 상위 2개 요소 출력
# 출력: [('l', 2), ('h', 1)]

 

  • count
my_list = [1, 2, 2, 3, 4, 2]
count_of_2 = my_list.count(2)
print(count_of_2)  
# 출력: 3 


my_string = "hello, world! hello!"
count_of_hello = my_string.count("hello")
print(count_of_hello)  
# 출력: 2
728x90
반응형

댓글