使用Python的循环和if语句创建回文检查器

问题描述 投票:0回答:1

我正在尝试按照说明创建回文。我得到了一半的功能,我必须填补空白。我目前无法使循环正常工作。我也不确定如何在不使用+或逗号的情况下将字符添加到字符串的开头或结尾。我不认为这是我要做的。这是说明;

is_palindrome函数检查字符串是否是回文...如果传递的字符串是回文,则在此函数中填写空白以返回True,否则返回False。

def is_palindrome(input_string):
    # We'll create two strings, to compare them
    new_string = input_string.replace(" ", "")
    reverse_string = input_string.replace(" ", "")
    # Traverse through each letter of the input string
    for word in input_string: # Originally, I was only given the a FOR statement here, I wrote in the rest
        new_string+=word.replace(" ","").upper()
        # Add any non-blank letters to the 
        # end of one string, and to the front
        # of the other string. 

    if ___:
        new_string = ___
        reverse_string = ___
    # # Compare the strings
      if ___:
          return True
          return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True

我已经删除了空白处,并使所有内容都一样。我已经将字符分配给了new_string,但是看起来我应该使用join来添加字符,但是当我这样做时,print语句不会打印任何内容。我不确定如何以相反的顺序添加项目。我什至不确定自己是否步入正轨,因为我不确定IF声明的要求是什么。我认为我应该能够使用循环创建字符串,然后比较两个字符串。

[另外,有人可以解释一下为什么new_string.join(word)不打印任何内容吗?我如何使用不正确?

非常感谢您的协助。

python loops palindrome
1个回答
0
投票

这似乎有效

def is_palindrome(input_string):
    new_string = input_string.replace(" ", "")

    halfway = int(len(new_string)/2)

    if (len(new_string) % 2) == 0:
        firstpart, secondpart = new_string[:halfway], new_string[halfway:]
    else:
        firstpart, secondpart = new_string[:halfway+1], new_string[halfway:]

    firstlist = list(firstpart.lower())
    secondlist = list(secondpart.lower())
    secondlist.reverse()

    return firstlist == secondlist

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
print(is_palindrome("civic")) # Should be True
print(is_palindrome("no a palindrome")) # Should be False
© www.soinside.com 2019 - 2024. All rights reserved.