I would like to write a function which checks if a word is a palindrome. the return should tell me like
palindrome "love" is not a palindrome
the function should contain the word (not as a vector) as argument (I don't really understand what it means)
I tried
Palindrome <- function(character){
charsplit <- strsplit(as.character(character), "")
revchar <- rev(unlist(charsplit))
palinum <- as.numeric(paste(revchar, collapse=""))
character==palinum
}
but
Palindrome ("love")
returns
NA
thanks for any help!
A string is said to be palindrome if the reverse of the string is the same as the string. For example, “abba” is a palindrome because the reverse of “abba” will be equal to “abba” so both of these strings are equal and are said to be a palindrome, but “abbc” is not a palindrome.
Solution approach We can use the isPalindrome() function to check if a string is a palindrome. We pass our input string as an argument and the function will return true if the string is a palindrome and false otherwise.
Similarly, a number that is equal to the reverse of that same number is called a palindrome number. For example, 3553, 12321, etc. To check a Palindrome in Java, we first reverse the string or number and compare the reversed string or number with the original value.
Without using strsplit
:
is.palindrome <- function(word) {
rawWord <- charToRaw(tolower(word)) ## converts to lower case
sprintf("%s is %sa palindrome", word,
c("not ", "")[identical(rawWord, rev(rawWord)) + 1])
}
> is.palindrome("otto")
[1] "otto is a palindrome"
> is.palindrome("love")
[1] "love is not a palindrome"
> is.palindrome("Otto")
[1] "Otto is a palindrome"
is.palindrome <- function (word) {
identical(word, paste(rev(strsplit(word, "")[[1]]), collapse=""))
}
is.palindrome("kayak")
[1] TRUE
is.palindrome("love")
[1] FALSE
This would work:
a = "blahalb"
identical(strsplit(a, "")[[1]], rev(strsplit(a, "")[[1]]))
#[1] TRUE
a = "love"
identical(strsplit(a, "")[[1]], rev(strsplit(a, "")[[1]]))
#[1] FALSE
Also, check out the Kmisc
package for presumably faster results:
library(Kmisc)
a = c("blahalb", "love")
str_rev(a) == a
#[1] TRUE FALSE
is_palindrome <- function(word){
charsplit <- strsplit(word, "")[[1]]
revchar <- rev(charsplit)
all(charsplit==revchar)
}
is_palindrome("love")
is_palindrome("otto")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With