본문 바로가기
Data Analysis/Query

리트코드 : 180. Consecutive Numbers

by 베짱이28호 2024. 3. 25.

리트코드 : 180. Consecutive Numbers

Consecutive Numbers - LeetCode


문제

Table: Logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
In SQL, id is the primary key for this table.
id is an autoincrement column.
 

Find all numbers that appear at least three times consecutively.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Logs table:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
Output: 
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three times.

 

문제풀이

import pandas as pd

def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:

    answer = set()
    number = logs['num']
    length = len(number)
    if length >= 3:
        for i in range(1,length-1):
            if (number[i] == number[i-1]) and (number[i] == number[i+1]):
                answer.add(number[i])
    return pd.DataFrame({'ConsecutiveNums' : list(answer)})
  • SQL에서는 LEAD같은 함수를 사용해줘야 하지만 파이썬에서는 1부터 길이-1까지 반복문만 돌려준다.
  • DataFrame을 만들 때 순서를 고려해야하니 set 자료형에서 list로 변환해서 넣는다.

코멘트

  • 쉬운 문제

댓글