简体   繁体   English

为什么我的代码不适用于所有回文?

[英]Why won't my code work for all palindromes?

I've been writing some code to take a string and check it to see if it is a palindrome or not. 我一直在写一些代码来取一个字符串并检查它是否是回文。 It seems to work on most things except for "axya" or any other non palindrome that starts and ends with the same letters. 除了“axya”或以相同字母开头和结尾的任何其他非回文外,它似乎适用于大多数事物。 What am I doing wrong? 我究竟做错了什么?

Code is written in python. 代码是用python编写的。

str = str.replace(' ','')
str = list(str)
var_a = 0
var_b = 0
var_c = 0

while var_a < len(str) - 1:
  var_b = str[var_a]
  if len(str) - var_a == len(str) - 1:
    var_c = str[len(str) -2]
  else:
    if len(str) - var_a < len(str) - 1:
      var_a = var_a + 1
      var_c = str[len(str) - var_a]
    else:
      var_c = str[len(str) - 1]\
  if var_b == var_c:
    return 'true'
  else:
    return 'false'
  var_a += 1

Note this part: 注意这部分:

while var_a < len(str) - 1:
  # ...
  if var_b == var_c:
    return 'true'
  else:
    return 'false'

The function returns no matter var_b equals or not equals to var_c , so the loop only iterates once, that's why it only tests the start and end characters. 函数返回无论var_b等于或等于var_c ,所以循环只迭代一次,这就是为什么它只测试开始和结束字符。 You should keep looping to test the rest characters if they are the same. 如果它们是相同的,你应该继续循环测试其余的字符。

While there certainly could be a way to do this with loops, there is no need for this: 虽然肯定有办法用循环来做到这一点,但是没有必要这样做:

>>> a = "racecar"
>>> a == a[::-1]
True
>>> b = "axya"
>>> b == b[::-1]
False
>>> 

The [] is an excellent operator for strings and lists. []是字符串和列表的优秀运算符。 string[::-1] will return the string reversed. string[::-1]将返回反转的字符串。 Check if that's the same as the string forwards, and you've got a palindrome! 检查这是否与字符串前进相同,你有一个回文!

To actually answer your question though :P 实际上回答你的问题:P

You're returning 'false' before checking all your letters. 在检查所有信件之前,你正在返回'false'

  if var_b == var_c:
    return 'true'
  else:
    return 'false'

should be more like: 应该更像是:

# if these letters are different, the word is not a palindrome
if var_b != var_c:
  return 'false'
else:
  pass # keep looping

your program should not return true until the loop has terminated from var_a reaching the end, without finding any differences along the way. 你的程序不应该返回true,直到循环从var_a到达终点结束,而不会发现任何差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM