티스토리 뷰
1. count() 함수
문자열 혹은 리스트 안에서 찾고 싶은 문자(혹은 문자열)의 개수를 찾아주는 함수
대소문자 구분 가능
카운팅하는 범위 지정 가능
1) 문자열에서의 사용
strLen = "HelloWorld!"
strLen.count("o")
=> 2
2) 리스트에서의 사용
lis = [2,5,6,2,7,8,5,6,2,1]
lis.count(2)
=> 3
3) 카운팅 범위 지정해주기
strLen = "HelloWorld!"
strLen.count("o",3,5)
=> 1
~응용~
백준 2577번
<숫자의 개수>

처음 내가 쓴 코드
a = int(input())
b = int(input())
c = int(input())
d = a * b * c
lis = []
x0 = 0
x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0
x7 = 0
x8 = 0
x9 = 0
for i in range(len(str(d))):
if(str(d)[i] == '0'):
x0 += 1;
elif(str(d)[i] == '1'):
x1 += 1;
elif(str(d)[i] == '2'):
x2 += 1;
elif(str(d)[i] == '3'):
x3 += 1;
elif(str(d)[i] == '4'):
x4 += 1;
elif(str(d)[i] == '5'):
x5 += 1;
elif(str(d)[i] == '6'):
x6 += 1;
elif(str(d)[i] == '7'):
x7 += 1;
elif(str(d)[i] == '8'):
x8 += 1;
else:
x9 += 1;
print(x0)
print(x1)
print(x2)
print(x3)
print(x4)
print(x5)
print(x6)
print(x7)
print(x8)
print(x9)
머리가 나쁘면...손발이 고생....
count()함수를 이용해 다시 쓴 코드
a = int(input())
b = int(input())
c = int(input())
res = str(a*b*c)
for i in range(10):
print(res.count(str(i)))

'🦖 Programming' 카테고리의 다른 글
[Python] 백준 알고리즘 1110번 : 더하기 사이클 (0) | 2022.07.05 |
---|---|
[Python] sys.stdin.readline() 사용 (0) | 2022.07.04 |