所以,我正在编写一个代码来检查输入的字符串是否是回文,我已经编写了以下代码,但是它没有正常工作,例如,如果我输入" race"它仍然说是真的,虽然它应该说FALSE,请帮忙。 这是代码
string = input("Please enter any word: ")
a = 0
string_length = len(string)
for string_index in range(string_length-1, -1, -1):
character = string[string_index]
if string[a] == character:
a = a + 1
b = "TRUE"
else:
b = "FALSE"
print(b)
答案 0 :(得分:2)
正确的代码:
ClassCastException
答案 1 :(得分:2)
当反转时,您可以轻松地比较您的输入本身 - 列表理解使这一点变得微不足道:
简单的单字和案例感知测试:
library(shiny)
library(dplyr)
dat <- data.frame(outcome=sample(c("died","survived",NA), 20, TRUE),
cntr=sample(c("hospa","hospb"), 20, TRUE),
s=rnorm(20),
t=rnorm(20), stringsAsFactors=FALSE)
ui <- navbarPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("s"="s", "t"="t"),
selected = "s"),
selectInput(inputId = "z",
label = "Color by:",
choices = c("outcome", "cntr"),
selected = "outcome")
),
mainPanel(
tabsetPanel(id="tabspanel", type = "tabs",
tabPanel(title = "Wilcox",
verbatimTextOutput(outputId = "p")))
)
)
)
server <- function(input, output, session) {
df <- reactive({
data.frame(dat[[input$y]], dat[[input$z]])
})
output$p <- renderPrint({
wilcox.test(df()[,1] ~ df()[,2])
})
}
shinyApp(ui=ui, server=server)
不区分大小写并允许标点符号
可从两侧读取回文。根据palindrom-ness的规则,你可能允许忽略套管,甚至腾出空白和 标点符号。
word = "SomemoS"
print(word == word[::-1]) # word[::-1] simply reverses the word and prints True if same
应用于lower()
答案 2 :(得分:0)
string = input("Please enter any word: ")
string_length = len(string)
start_index = 0
count = 0
end_index = string_length - 1
for string_index in range(int(string_length/2)):
if string[start_index] == string[end_index]:
start_index = start_index + 1
end_index = end_index - 1
count += 1
else:
pass
print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")
说明: 为了检查古院系统字符串,比较第一个和最后一个字符,直到比较到达字符串的中间
for string_index in range(int(string_length/2)):
比较第一个字符和最后一个字符:
if string[start_index] == string[end_index]:
更新start_index和end_index并计算:
start_index = start_index + 1
end_index = end_index - 1
count += 1
如果count等于字符串长度的一半那么它肯定是一个综合症
print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")