我似乎無法弄清楚在我的回圈中我沒有回傳參考相同的索引值來驗證回文的位置。
我嘗試了代碼,應該會看到“這是回文”,但它回傳相反的結果
uj5u.com熱心網友回復:
一種更簡單的方法是檢查字串的所有元素是否與反轉字串的所有元素匹配:
is_palindrome <- function(s) {
x <- strsplit(s, "")[[1]]
all(x == rev(x))
}
is_palindrome("radar")
#> [1] TRUE
is_palindrome("reader")
#> [1] FALSE
如果由于某種原因你需要使用回圈,你可以這樣做:
is_palindrome <- function(s) {
x <- strsplit(s, "")[[1]]
for(i in 1:length(x)) {
if(x[i] != x[length(x) 1 - i]) {
return(paste0("'", s, "' is not a palindrome"))
}
}
return(paste0("'", s, "' is a palindrome"))
}
is_palindrome("radar")
#> [1] "'radar' is a palindrome"
is_palindrome("reader")
#> [1] "'reader' is not a palindrome"
使用reprex v2.0.2創建于 2022-10-29
uj5u.com熱心網友回復:
rev您可以使用 嘗試下面的代碼utf8ToInt
isPalindrome <- function(s) s == intToUtf8(rev(utf8ToInt(s)))
uj5u.com熱心網友回復:
利用seq_along
編輯
索引也有錯誤x:必須是 len-i 1
最后我做了一些修改
s <-"radar"
x <- strsplit(s, "")[[1]]
len <-length(x)
#find the middle
middle <- ceiling(length(x)/2)
### Loop to the middle
answer <- "The word is a palindrome"
for (i in seq_along(x)){
if (i < middle){
#check for index position to match the other side
if (x[i] != x[len-i 1]){
answer <- "The word is not a palindrome"
break;
}
}
}
print(answer)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/525181.html
標籤:r循环回文
上一篇:生成隨機字符
