回文编码问题

Palindrome Coding issue

正在编写程序:

  1. 来自用户的输入字符串
  2. 打印出这个字符串是否是回文

此外,我在网上找到了一些其他代码,但想使用此代码only.m请让我知道错误

i = str(input())

for item in i:
  print(item)

  if int(i[item]) == int(i[-item]):
    print('yes')
  else:
    print('no')

使用字符串切片(i[::-1] 将反转字符串):

i = input()

if i == i[::-1]:
    print("Yes")
else:
    print("No")

这将获取用户的输入并将其与相同的输入进行反向比较。

试试这个:

word="TOT"
i=word[::-1]
if i==word:
    print("palandrom")

尽管 for item in i: 遍历了字符串中的每个字符,但您的代码行 if int(i[item]) == int(i[-item]): 存在一些问题。首先,item 将成为字符串中的一个字符。因此,如果用户键入 "hello",则 i[item] 首先查找 i['h']。由于 'h' 是字符而不是数字,这使得 Python 认为 i 是字典而不是字符串,因此告诉 Python 查找名为的字典i 和 return 键为 h 的值。这是行不通的,因为 i 是您的原始字符串,而不是字典。

看起来你在这里的意思是比较 i[0](字符串中的第一个字符)和 i[-1](字符串中的最后一个字符),然后是 i[1]i[-2],依此类推。但是,即使您循环遍历位置编号,i[-item] 也不会在数学上给您想要的东西。

这里的另一个问题是您一次检查每个字符并 returning "yes" 或 "no"。不过,您最终想要的是输出一个简单的答案:您的字符串是否为回文。

此外,没有必要将 str() 放在 input() 周围,因为 input return 无论如何都是一个字符串,即使用户只输入数字也是如此。顺便说一句,即使您使用 i 作为您的字符串变量,编程中通常的约定是使用 i 来表示某种整数,例如您在for 循环。但现在没关系。

正如其他一些答案所示,i[::-1] 是 return 字符串本身反转的快速方法。因此,如果您可以看到输出 return True 如果字符串是回文,而 False 如果不是,那么这里有一个非常简单的方法:

i = input()
print(i == i[::-1])

如果字符串 i 与自身反转相同,则 i == i[::-1] returns True。如果不是,它 returns Falseprint 语句然后打印答案。

但是,如果您真的想从长远来看,在循环中逐个字符地测试,那么这里有一种方法可以做到。您可以制作一个接受字符串并完成工作的函数:

def is_palindrome(mystring):
    # The "//2" here divides by 2 and ignores the remainder.  So if
    # there are an even number of letters, we'll test each pair.  If
    # It's an odd number, then we don't care about the middle character
    # anyway.  Compare [0] to [-1], then [1] to [-2], [2] to [-3], and so on.
    for position in range(0, len(mystring)//2):
        # If we've found a mismatched pair of letters, then we can
        # stop looking; we know it's not a palindrome.
        if mystring[position] != mystring[(-1 * position) - 1]:
            print("This is NOT a palindrome")
            return  # This breaks you out of the entire function.

    # If we've gotten this far, then the word must be a palindrome.
    print("This is a palindrome")


# Here's where we run the command to input the string, and run the function
mystring = input("Enter your string: ")
is_palindrome(mystring)