+---------------+---------+
| Column Name | Type |
+---------------+---------+
| log_id | int |
+---------------+---------+
log_id is the column of unique values for this table.
Each row of this table contains the ID in a log Table.
Write a solution to find the start and end number of continuous ranges in the table Logs.
Input:
Logs table:+------------+| log_id |+------------+|1||2||3||7||8||10|+------------+Output:
+------------+--------------+| start_id | end_id |+------------+--------------+|1|3||7|8||10|10|+------------+--------------+Explanation:
The result table should contain all ranges in table Logs.From 1 to 3is contained in the table.From 4 to 6is missing in the table
From 7 to 8is contained in the table.Number 9is missing from the table.Number 10is contained in the table.
To find continuous ranges, sort the log IDs and use the difference between the log ID and its row number to identify groups of consecutive numbers. Each group forms a continuous range.
SELECTMIN(log_id) AS start_id, MAX(log_id) AS end_id
FROM (
SELECT log_id, log_id - ROW_NUMBER() OVER (ORDERBY log_id) AS grp
FROM Logs
) t
GROUPBY grp
ORDERBY start_id;
1
2
3
4
5
6
7
SELECTMIN(log_id) AS start_id, MAX(log_id) AS end_id
FROM (
SELECT log_id, log_id - ROW_NUMBER() OVER (ORDERBY log_id) AS grp
FROM Logs
) t
GROUPBY grp
ORDERBY start_id;
1
2
3
4
5
6
7
8
import pandas as pd
deffind_continuous_ranges(logs: pd.DataFrame) -> pd.DataFrame:
logs = logs.sort_values('log_id').reset_index(drop=True)
logs['grp'] = logs['log_id'] - range(len(logs))
grouped = logs.groupby('grp')['log_id']
res = pd.DataFrame({'start_id': grouped.min(), 'end_id': grouped.max()}).reset_index(drop=True)
return res