Skip to content

Latest commit

 

History

History
64 lines (56 loc) · 1.64 KB

626_exchange_seats.md

File metadata and controls

64 lines (56 loc) · 1.64 KB

Table: Seat

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| student     | varchar |
+-------------+---------+
id is the primary key (unique value) column for this table.
Each row of this table indicates the name and the ID of a student.
id is a continuous increment.

Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.

Return the result table ordered by id in ascending order.

The result format is in the following example.

Example 1:

Input: 
Seat table:
+----+---------+
| id | student |
+----+---------+
| 1  | Abbot   |
| 2  | Doris   |
| 3  | Emerson |
| 4  | Green   |
| 5  | Jeames  |
+----+---------+
Output: 
+----+---------+
| id | student |
+----+---------+
| 1  | Doris   |
| 2  | Abbot   |
| 3  | Green   |
| 4  | Emerson |
| 5  | Jeames  |
+----+---------+
Explanation: 
Note that if the number of students is odd, there is no need to change the last one's seat.

Solution

import pandas as pd

def exchange_seats(seat: pd.DataFrame) -> pd.DataFrame:
    seat_no = list(range(1, len(seat) + 1))
    for i in range(1, len(seat), 2):
        seat_no[i], seat_no[i-1] = seat_no[i-1], seat_no[i]
    seat['id'] = seat_no
    return seat.sort_values('id')


if __name__ == '__main__':
    data = [[1, 'Abbot'], [2, 'Doris'], [3, 'Emerson'], [4, 'Green'], [5, 'Jeames']]
    seat = pd.DataFrame(data, columns=['id', 'student']).astype({'id': 'Int64', 'student': 'object'})
    print(exchange_seats(seat))