리트코드 : 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로 변환해서 넣는다.
코멘트
- 쉬운 문제
'Data Analysis > Query' 카테고리의 다른 글
리트코드 : 196. Delete Duplicate Emails (0) | 2024.03.26 |
---|---|
185. Department Top Three Salaries (0) | 2024.03.26 |
리트코드: 184. Department Highest Salary (0) | 2024.03.25 |
리트코드 : 178. Rank Scores (0) | 2024.03.25 |
리트코드 : 177. Nth Highest Salary (0) | 2024.03.24 |
리트코드 : 176. Second Highest Salary (0) | 2024.03.24 |
[MySQL] 프로그래머스 Lv.4 Lv.5 (0) | 2024.03.04 |
댓글