【问题标题】:Function in R that returns first word in a sentence that is having a length which is an even number & also longest even wordR中的函数返回句子中的第一个单词,该单词的长度是偶数,也是最长的偶数单词
【发布时间】:2018-12-20 21:33:53
【问题描述】:

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

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

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

【问题讨论】:

  • 你能展示一下你已经尝试过的事情吗?
  • 这样做的目的是什么?你试过什么?你在哪里卡住了?你的方法没有用怎么办?
  • 我尝试获得偶数函数,但是当我尝试获得第一个出现的最大偶数函数时失败了。

标签: r


【解决方案1】:

您可以使用流行的 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() 函数弄清楚如何做到这一点。我会把它留给你。

【讨论】:

  • 非常感谢 Adam。这有帮助。如果你能帮助我,我还有一个问题。而不是手动输入句子。我们不能以类似句子字符串的格式输入句子仅由 ascii [a-z,A-Z] 范围内的空格和字符组成?考虑一个字符串,以空格为中心的单词的句子,其中每个单词都是仅由英文字母组成的子字符串?
  • 你绝对可以做到这一点。查看stringr::str_remove_all("This is a string. In addition, this is a string!","[^A-Za-z ]+"),它会删除所有不在 A-Z 或 a-z 或空格之间的字符。在拆分字符串和 bam 之前将其放入。
猜你喜欢
  • 2019-02-13
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2012-02-02
  • 2021-05-19
  • 2012-10-27
  • 1970-01-01
相关资源
最近更新 更多