본문 바로가기
프로그래밍/알고리즘 & 자료구조

[프로그래머스] 7의 개수 with 파이썬

by Play_With 2023. 4. 4.
반응형

[프로그래머스] 7의 개수 with 파이썬

정수배열을 string으로 바꿔서 count() 적용하기. string으로 바꿔야 각 자리 숫자를 비교할 수 있다.

arr = [7, 77, 17]

 

1. 이중반복문 : for in

def solution(arr):
    chr = []
    for i in arr:
        chr.append(str(i))

    result = 0
    for i in chr:
        for j in i:
            if j == '7':
                result += 1
    return result

 

2. str/list.count()

def solution2(arr):
    chr = ''
    for i in arr:
        chr += str(i)
    return chr.count('7')

 

3. list를 string으로 변경하는 방법
3-1. ''.join(list) : map()을 통해 arr에 있는 정수를 모두 str로 변

def solution3(arr):
    return ''.join(map(str, arr)).count('7')

 

3-2. str(list)

def solution4(arr):
    return str(arr).count('7')

 

3-3. 반복문

def solution5(arr):
    return sum([str(i).count('7') for i in arr])

 

반응형

댓글