Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a word is a palindrome?

Tags:

r

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!

like image 683
user2373707 Avatar asked Jun 10 '13 20:06

user2373707


People also ask

How will you verify a word as palindrome?

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.

How do you check if a string is 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.

How do you check if a word is a palindrome Java?

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.


4 Answers

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"
like image 75
BenBarnes Avatar answered Oct 13 '22 03:10

BenBarnes


is.palindrome <- function (word) {
  identical(word, paste(rev(strsplit(word, "")[[1]]), collapse=""))
}

is.palindrome("kayak")
[1] TRUE

is.palindrome("love")
[1] FALSE
like image 31
asb Avatar answered Oct 13 '22 02:10

asb


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
like image 20
eddi Avatar answered Oct 13 '22 01:10

eddi


is_palindrome <- function(word){
  charsplit <- strsplit(word, "")[[1]]
  revchar <- rev(charsplit)

  all(charsplit==revchar)
}

is_palindrome("love")
is_palindrome("otto")
like image 3
baptiste Avatar answered Oct 13 '22 01:10

baptiste