A Data Science Central Community
"-" has been used to set the reference in the global environment so as to avoid any scoping issues in recursive calls.
# Palindrome Calling Function
palindrome <- function(astr) {
# house keepging removing blanks and punctuation etc through a pattern
# make all to lower case
regex <- "^[ \t]+|[ \t]+$|\\.|\\'|[ \t]+|,|!|-"
astr.clean <- gsub(regex,'',astr)
str.refined <- tolower(astr.clean)
shortstring <- palindromecal(str.refined)
return(shortstring)
}
Test cases are shown for reference:
# Test1 :: True
palindrome('aa')
# > palindrome('aa')
# [1] TRUE
palindrome('A but tuba.')
# > palindrome('A but tuba.')
# [1] TRUE
palindrome('A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!')
# > palindrome('A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!')
# [1] TRUE
palindrome(' ')
# > palindrome(' ')
# [1] TRUE
palindrome('aaaabbaaaa')
# > palindrome('aaaabbaaaa')
# Test2 :: False
palindrome('..a.....b')
# > palindrome('..a.....b')
# [1] FALSE
palindrome('abcdefghijklmnopqrstuvwxyz')
# > palindrome('abcdefghijklmnopqrstuvwxyz')
# [1] FALSE
Lastly any R discussion would be incomplete without a reference to the vectorization, this function can be used with other standard vector functions such as "lapply and sapply".
list.string <- list('abc',"aa",'aaa','ab')
list.new <- lapply(list.string,palindrome)
vec.new <- sapply(list.string,palindrome)
Tags: http://jishnub-r-prog1.blogspot.in/2013/11/palindrome-string-detection-by-r.html
I can still remember when palindrome detection was made like this:
is_palindrome (s:STRING):BOOL is
do
Return s==s.reverse
end
(In Eiffel, a long forgotten software architecture...)
© 2021 TechTarget, Inc.
Powered by
Badges | Report an Issue | Privacy Policy | Terms of Service
Most Popular Content on DSC
To not miss this type of content in the future, subscribe to our newsletter.
Other popular resources
Archives: 2008-2014 | 2015-2016 | 2017-2019 | Book 1 | Book 2 | More
Most popular articles