【问题标题】:Find the longest even word in a sentence, if two or more words have same length, then the first occurring word must be returned查找句子中最长的偶数词,如果两个或多个词的长度相同,则必须返回第一个出现的词
【发布时间】:2020-01-21 06:36:18
【问题描述】:

我正在尝试这个问题,其中我需要在给定的输入句子中找到最长的偶数单词,如果两个或多个单词是最长偶数长度的单词,则必须返回第一个出现的单词。

例如:如果“这是一首很棒的歌” 该函数应返回“this”,因为它是句子中第一个出现的最长偶数长度的单词。

这个问题之前被问过并使用 dplyr 回答过, Function in R that returns first word in a sentence that is having a length which is an even number & also longest even word

我想尝试使用我的代码:

下面是我的代码:

sentence <- function(ip_sen) {
  sentence_split <- strsplit(ip_sen, split = ' ')[[1]] #splitting the sentence into words
  word_lengths_vector <- vector() #empty vector to store even length words

  for (word in sentence_split) {
    word_split <- strsplit(word, split = '')[[1]] #splitting each word
    word_length <- length(word_split)

    if (word_length %% 2 == 0) { # checking if the word is even
      word_lengths_vector <- c(word_lengths_vector, word) #adding such words to the empty vector
    }
  }

  for (w in 1:(length(word_lengths_vector)-1)) { #finding the longest word
    if (nchar(word_lengths_vector[w]) >  nchar(word_lengths_vector[w+1])) {
      word_lengths_vector <- word_lengths_vector[-(w+1)] #removing smaller length words
    }
  }

  word_lengths_vector[1] #returning the first word in the vector which will be the first occurring longest word
}

sentence('this is a great song')

但我遇到以下错误:

if (nchar(word_lengths_vector[w]) > nchar(word_lengths_vector[w +
: 需要 TRUE/FALSE 的缺失值

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: r string


    【解决方案1】:

    我们可以稍微简化一下函数

    sentence <- function(ip_sen) {
       #split the text on whitespace
       all_words <- strsplit(ip_sen, " ")[[1]]
       #Get number of characters in each word
       all_chars <- nchar(all_words)
       #Filter only those words with even characters and select the first max
       all_words[which.max(all_chars[all_chars %% 2 == 0])]
    }
    
    sentence('this is a great song')
    #[1] "this"
    
    sentence('What is your complete name?')
    #[1] "complete"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2012-02-02
      • 2013-06-12
      • 2014-09-26
      • 2017-03-30
      • 2023-03-04
      • 2022-12-04
      相关资源
      最近更新 更多