首页 > 解决方案 > R中的函数,它返回句子中的第一个单词,该单词的长度是偶数,也是最长的偶数单词

问题描述

这个函数应该返回最长的偶数词(字符串),它是第一次出现的具有最大偶数长度的字符串。如果没有偶数长度,它应该返回 00。

约束 - 句子字符串由空格组成,句子范围在 1 到 10^5 之间。

例如,句子 1-“Time &潮汐等待无”。在这里,即使字符是 time &潮汐 & none,有 4 个字母。但是,时间首先出现,所以应该显示时间。句子 2-“以牙还牙”。在这句话中 no even 所以它应该返回 00。句子 3-“眼睛是人思想的镜子”在这里,思想是偶数词中最大的偶数词眼睛,镜子。

标签: r

解决方案


您可以使用流行的 stringr 和 dplyr 库来做到这一点。

library(dplyr)
library(stringr)

df <- tibble(
  sentence = c(
    "Time & tide waits for none",
    " Tit for tat",
    "Eyes are mirror of person's thoughts",
    "Some Other Sentence",
    "Odd sentences failure"
  )
)

df <- df %>%
  # Split the sentence and store it in a new column
  mutate(split_sentence = str_split(sentence," ")) %>%
  # Do the next step row wise because we will be dealing with a vector of vectors
  rowwise() %>%
  # Keep only words that have a remainder of 0 when divided by 2 (str_length modulo 2)
  mutate(split_sentence = list(split_sentence[str_length(split_sentence) %% 2 == 0])) %>%
  # Only keep non-null strings !""
  mutate(split_sentence = list(split_sentence[str_length(split_sentence) > 0])) %>%
  # Find the first word with the longest length
  mutate(split_sentence = list(split_sentence[which.max(str_length(split_sentence))])) %>%
  # Keep only the first word left in the vector or return NA if none left
  mutate(first_even = first(split_sentence)) %>%
  # Ungroup because we don't need to work rowwise anymore
  ungroup() %>%
  # Convert any NA values to "00" per question
  mutate(first_even = ifelse(is.na(first_even),"00",first_even)) %>%
  select(-split_sentence)

# A tibble: 5 x 2
#   sentence                             first_even
#   <chr>                                <chr>     
# 1 Time & tide waits for none           Time      
# 2 " Tit for tat"                       00        
# 3 Eyes are mirror of person's thoughts person's  
# 4 Some Other Sentence                  Sentence  
# 5 Odd sentences failure                00       

在您的描述中,您说这thoughts将是最长的单词,但我的算法发现它person's也一样长。str_remove_all()如果您想删除撇号,您可以使用该功能弄清楚如何做到这一点。我会把它留给你。


推荐阅读