繁体   English   中英

我需要帮助使我的程序更加精简,因为我确信我遗漏了很多东西

[英]I need help making my program more streamline, as I am sure where are many things I am missing

测试字符串是否是回文并且应该是 O(n) 运行时。 我们不能使用任何导入语句或可以使用任何其他辅助方法。

所以基本上我的程序是接收一个输入,它是一个可以包含任何内容的字符串。 如果该字符串中的某些内容不是字母表的一部分,则忽略它,例如空格或逗号。 我的程序目前可以运行,但似乎应该有办法让我的程序变得更好,通过减少代码或我不知道的东西。

一个例子是字符串 ' EUV, vV V,U,E' 所以我做的第一件事就是它转到 string[0] ,它只是一个空格和shorts,用于用 isPalindrome(string[1]:len (string)-1) 所以 isPalindrome('EUV, vV V,U,E')。

def isPalindrome (string):
    if len(string) <=1:                 # Basecase to check if the string has less than or equal to 1 element remaining in the string so that the recursion may end
            return True
    if string.isalpha():                    # Checks if the string is all letters of the alphabet and proceeds if true
            if (string[0].lower() == string[len(string)-1].lower()):                    # Compares the lowercase form of the first element and the last element and if they are equal the program will proceed
                    return isPalindrome(string[1:len(string)-1])                    # Function is calling itself with the next elements in the string
            else:
                    return False
    else:
            if string[0].isalpha():                 # Checks if the first element in the string is part of the alphabet and proceeds if true
                    if string[len(string)-1].isalpha():                 # Checks if the last element of the string is part of the element and proceeds if true
                            if (string[0].lower()== string[len(string)-1].lower()):                 # Both the first and last element have been confirmed as being part of the alphabet and will not be compared to each other, program proceeds if true
                                    return isPalindrome(string[1:len(string)-1])                    # Function is calling itself with the next elements in the string
                            else:
                                    return False                    # Program return false when some elements do not equal each other
                    else:
                            return isPalindrome(string[0:len(string)-1])                    # Function is calling itself with the next elements in the string
            else:
                    return isPalindrome(string[1:len(string)])                  # Function is calling itself with the next elements in the string

嗯,这是很多用于回文检查的代码。

本质上,回文是一个字符串,如果从末尾读取,则等于自身。 您可以使用字符串上的切片符号进行检查。 现在要清除所有不是字母的字符串,一个小的列表理解就可以了。

def isPalindrome(text):
    text = "".join([x for x in text if x.isalpha()])
    return text==text[::-1]

暂无
暂无

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

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