Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Excel BI’s Excel Challenge #307 — solved in R
Defining the Puzzle:
Today ExcelBI gave us another puzzle, this time based on string manipulation rather than numbers.
List all Palindromic phrases.
A Palindromic phrase is that which is same when read from backwards. When you are reading from backwards, only English alphabets need to be considered. Don’t consider spaces, questions marks or any other character which is not English alphabet.
Ex. No lemon, no melon
Loading Data from Excel:
As usual our host gave us column of data to check, and column with correct solution. Let get this file and read it.
library(tidyverse) library(readxl) library(stringi) input = read_excel(“Palindromic Phrase.xlsx”, range = “A1:A10”) test = read_excel(“Palindromic Phrase.xlsx”, range = “B1:B6”)
What we have to do is: clean phrase from punctuation and whitespaces, then unified case of letters (I will make them all lower). Finally we have to check if read backwards phrase is exactly the same.
Approach 1: Tidyverse with purrr
result = input %>% mutate(phrase = Phrase %>% str_remove_all(“[[:punct:]]”) %>% str_remove_all(“ “) %>% str_to_lower(), is_palindromic = phrase == stri_reverse(phrase)) %>% filter(is_palindromic) %>% select(`Answer Expected` = Phrase)
Approach 2: Base R
result_base <- subset(input, { phrase <- tolower(gsub(“[[:punct:]]|\\s”, “”, Phrase)) is_palindromic <- phrase == stri_reverse(phrase) is_palindromic })
Approach 3: Data.table
# Convert to data.table input_dt = setDT(input) input_dt[, phrase := tolower(gsub(“[[:punct:]]|\\s”, “”, Phrase))] input_dt[, is_palindromic := phrase == stringi::stri_reverse(phrase)] result_dt <- input_dt[is_palindromic == TRUE, .(`Answer Expected` = Phrase)]
Validating Our Solutions:
identical(test, result) #> [1] TRUE identical(test$`Answer Expected`, result_base$Phrase) #> [1] TRUE identical(test$`Answer Expected`, result_dt$`Answer Expected`) #> [1] TRUE
If you like my publications or have your own ways to solve those puzzles in R, Python or whatever tool you choose, let me know.
Palindromic Phrase was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.