What I remember from my Data Science skills interviews - Part 1
As someone who wants to be more comfortable doing skills tests, I find myself applying to jobs sometimes for the sole purpose of having a feel of the test and challenging myself to complete it on time. On some occasions I really do well and on some I am left thinking "I wish there was no pressure to complete this test in the given time".
I would also note that the example below is not an exact replica of any test I have done.
#A FUNCTION THAT CHECKS IF A WORD(S) IS A PALINDROME
(The Code is in R)
palindrome_check = function(k){
k <- tolower(gsub(" ","",k))
newname <- c()
for (i in 1:nchar(k)) {
newname[i] <- (unlist(strsplit(k, split = "")))[nchar(k)-(i-1)]
}
k_new <- paste(newname, collapse = "")
ifelse(k_new == k, "This is a palindrome", "This is not a palindrome")
}
Examples
palindrome_check("civic")
Result: "This is a palindrome"
palindrome_check("mother")
Result: "This is not a palindrome"
palindrome_check("bird rib")
Result: "This is a palindrome"
palindrome_check("Kayak")
Result: "This is a palindrome"
Breakdown
gsub() is used to find any spaces and remove them. str_remove_all can be used here too.
tolower() is used to deal with an exception that may rise since R is case sensitive.
There are easier ways to reverse the order of characters in a string like:
Using the function rev()
string_example <- "civic"
paste(rev(unlist(strsplit(string_example, split = ""))), collapse = "")
Breakdown
#split the string by characters
strsplit(string_example, split = "")
- The result is a list and we need to undo that using the unlist() function.
#Unlist split characters
unlist(...)
#Reverse the order of the characters
rev(...)
#Bind the characters together
paste(..., collapse = "")
Happy exploring!!
~NMN
Comments
Post a Comment