Python回文编程

时间:2014-12-16 13:46:08

标签: python

代码有点混乱,但重点是将其划分为不同的函数。

我知道您可以测试回文,但是如何使用布尔变量,而不是直接说明打印功能。

def trial():
    palindrome = True

    c = str(input("Hey: "))

    for i in range(len(c)):
        a = c[i]
        s = c[-(i+1)]
    if  (a == s):       
        return 
    break
    else:
        print ("No, its not a plaindrome")
    break

    return palindrom 

def output():
    print True


trial()
output()

3 个答案:

答案 0 :(得分:4)

您可以在其他功能中使用return

def isPalindrome(s):
    return s == s[::-1]

def output(s):
    if isPalindrome(s):           # We use the return value of the above function
        print('it is a palindrome')
    else:
        print('not a palindrome')

例如

>>> output('hello')
not a palindrome

>>> output('abcba')
it is a palindrome

答案 1 :(得分:0)

您的编程理念的一些背景 - 我称之为(也可能是其他人)见证。这是什么意思?这意味着我们假设somethnig是True - 直到我们被证明是错误的。在现代法庭上也是如此,除非被证明有罪,否则有人是无辜的。

现在让我们看看代码:

# let's go on to the trial!
def trial():
    # the string is a palindrome, or "innocent" (this is redundant in this case)
    palindrome = True
    c = str(input("Hey: "))

    # this iterates the string twice, you actually need half
    # but that's only an optimization.
    for i in range(len(c)):
        a = c[i]
        s = c[-(i+1)]
        # if we found characters that are not mirrored - this is not a palindrome.
        # these are our witnesses!
        if  (a != s):        
            return False # naive: palindrome = False
    # we've gone over the string and found no witnesses to say it's "guilty"
    return True # naive: return palindrome

请记住,在使用这种风格时,你只关心"有罪"部分,然后你可以立即return

答案 2 :(得分:-1)

这是一种检查回文的简单方法:

def is_palindromic(s):
    return s == s[::-1]

然后使用if语句中的返回值。

if is_palindromic(s):
    print "Yay!"
else:
    print "Too bad"