본문 바로가기
Data Analysis/Query

리트코드 : 1667. Fix Names in a Table

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

리트코드 : 1667. Fix Names in a Table


문제

Table: Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+
user_id is the primary key (column with unique values) for this table.
This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.


Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.

Return the result table ordered by user_id.

The result format is in the following example.



Example 1:

Input: 
Users table:
+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | aLice |
| 2       | bOB   |
+---------+-------+
Output: 
+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | Alice |
| 2       | Bob   |
+---------+-------+
  • 앞 글자를 대문자롭 변경하기

문제 풀이

MySQL

SELECT USER_ID, CONCAT(UPPER(LEFT(NAME,1)),LOWER(RIGHT(NAME,LENGTH(NAME)-1))) AS NAME
FROM USERS
ORDER BY USER_ID
  • CONCAT으로 첫 글짜 바꾸고, 나머지는 모두 소문자로 바꾸기.

Pandas

import pandas as pd

def fix_names(users: pd.DataFrame) -> pd.DataFrame:
    users['name'] = users['name'].apply(lambda x: x.capitalize())
    return users.sort_values('user_id')
  • 파이썬은 대문자 변환해주는 함수가 있다.
  • 한 단어는 title, 모든 단어 앞 글자 대문자는 capitalize

코멘트

  • 테케 21번에 띄어쓰기로 구분된 케이스가 있어서 title말고 capitalize로 써야한다.
  • 악질인게 SQL이랑 PANDAS 답이 다르다.
  • SQL에서는 맨 앞글자만 대문자다.

댓글