Python中的字母回文三角形

时间:2016-11-17 12:25:02

标签: python

这个词是“赛车”,这是我应该得到的三角形: -

   e
  cec 
 aceca
racecar

我正在使用python 2.7 我正在尝试使用for循环。谢谢。 这是我得到的输出

e
e c c
e c a a c
e c a r r a c
e c a r r r r a c

我找到了中间价值并尝试打印它。但是我得到的输出总是在开头。我无法在e之前和之后获得字母表来打印。

m="racecar"
mid=len(m)/2

for i in range(0,5):
    for k in range(0,i):
        print m[mid-k],
    for j in range(i,0,-1):
        print m[mid-j],

    print

我尝试了更多,但不知怎的,我没有按照正确的顺序获得输出。

1 个答案:

答案 0 :(得分:0)

我建议KISS。有了一些绝地技巧,你可以在那里得到它:

def isItAPalindrome( wordPalindrome ):

    wordLengh = len( wordPalindrome )

    if wordLengh % 2 != 0 and wordLengh:

        return True

    return False

import sys
wordPalindrome = "racecar"

if not isItAPalindrome( wordPalindrome ):

    sys.exit()

middlePoint = len( wordPalindrome )/2

for currentRange in range( 0, middlePoint + 1 ):

    # print empty spaces
    for k in range( 0, middlePoint - currentRange ):

        # print without new line
        sys.stdout.write( " " )

    # print the Palindrome "racecar"
    for k in range( middlePoint - currentRange, middlePoint + currentRange + 1 ):

        sys.stdout.write( wordPalindrome[ k ] )

    # print new line
    sys.stdout.write( "\n" )

输出示例:

   e
  cec
 aceca
racecar

     f
    efe
   defed
  cdefedc
 bcdefedcb
abcdefedcba

参考文献:

  1. How do I abort the execution of a Python script?
  2. Python: avoid new line with print command