상세 컨텐츠

본문 제목

[LeetCode][Python]2125. Number of Laser Beams in a Bank

공부

by 근성 2024. 1. 4. 00:01

본문

https://leetcode.com/problems/number-of-laser-beams-in-a-bank/description/?envType=daily-question&envId=2024-01-03

 

Number of Laser Beams in a Bank - LeetCode

Can you solve this real interview question? Number of Laser Beams in a Bank - Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix.

leetcode.com


문제를 간단하게 설명하자면, 아래 그림에서 막대의 수를 구하는것이다.

주어진 Input은 List이다.

bank = ["011001","000000","010100","001000"]

 

여기서 나의 접근은

모두가 0인 list 원소를 없애고나서 1의갯수끼리 곱한것을 계속 더해서 반환하는 것이다.

 

그러기 위해서는 예시 bank의 두번째 원소를 지워야하는데, 나는 파이썬의 반복문을 계속 탐색하면서 지우는 방법을 몰랐다.

왜냐하면 지우면서 인덱스가 의도치 못하게 바뀌기 때문이다.

        for i in bank[:]:
            if i.count('1') == 0:
                bank.remove(i)

위와 같은 방법인 콜론(:)을 추가해서 지우면 된다. 

for i in bank -> for i in bank[:]

이렇게 하면 반복문을 계속 탐색하면서 지울 수 있다.

 

그 후, bank.count('1')을 통해서 1의 갯수를 카운팅하고 곱하면된다.

        for i in range(len(bank)-1):
            answer += bank[i].count('1') * bank[i+1].count('1')

 

 

정답 코드

class Solution:
    def numberOfBeams(self, bank: List[str]) -> int:
        answer = 0
        for i in bank[:]:
            if i.count('1') == 0:
                bank.remove(i)
        for i in range(len(bank)-1):
            answer += bank[i].count('1') * bank[i+1].count('1')
        return answer

관련글 더보기

댓글 영역