BI & Visualization/Python

Pandas | LeetCode 1683. 15자를 초과한 트윗 찾기

올리브한입 2025. 5. 26. 08:15
반응형

Table: Tweets

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| tweet_id       | int     |
| content        | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
content consists of alphanumeric characters, '!', or ' ' and no other special characters.
This table contains all the tweets in a social media app.

 

Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Tweets table:
+----------+-----------------------------------+
| tweet_id | content                           |
+----------+-----------------------------------+
| 1        | Let us Code                       |
| 2        | More than fifteen chars are here! |
+----------+-----------------------------------+
Output: 
+----------+
| tweet_id |
+----------+
| 2        |
+----------+
Explanation: 
Tweet 1 has length = 11. It is a valid tweet.
Tweet 2 has length = 33. It is an invalid tweet.

해결 방법

  1. str.len()을 이용해 문자열 길이 계산
  2. 길이가 15 초과인 행만 필터링
  3. tweet_id만 선택
import pandas as pd

def invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:
    tweets['tw_len'] = tweets['content'].str.len()
    result = tweets[tweets['tw_len'] > 15][['tweet_id']]
    return result
  • str.len()은 Pandas에서 문자열 관련 처리를 할 때 아주 자주 사용하는 함수입니다.
  • .loc 없이도 조건 필터링이 가능하므로 코드가 간결합니다.
  • 출력에서 [['tweet_id']]처럼 이중 대괄호를 쓰는 건 DataFrame 형태로 반환하기 위함입니다. ['tweet_id']는 Series 반환입니다.
반응형