Python练习:菱形字母表

题目

请大家写一个Python程序,用户输入菱形的中心字母,得到对应的菱形。

比如:输入字母K,得到如下图形

          A
         ABA
        ABCBA
       ABCDCBA
      ABCDEDCBA
     ABCDEFEDCBA
    ABCDEFGFEDCBA
   ABCDEFGHGFEDCBA
  ABCDEFGHIHGFEDCBA
 ABCDEFGHIJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
 ABCDEFGHIJIHGFEDCBA
  ABCDEFGHIHGFEDCBA
   ABCDEFGHGFEDCBA
    ABCDEFGFEDCBA
     ABCDEFEDCBA
      ABCDEDCBA
       ABCDCBA
        ABCBA
         ABA
          A



答案与解析

















































答案

maxchar = input('请输入菱形的中心字母:')

maxchar = maxchar[0].upper()

# 得到输入字符对应的数字

intmaxchar = ord(maxchar)
intcharA  = ord('A')
halfLen = intmaxchar-intcharA

def printline(halfLen,startPos):

    curMaxChar = chr(intmaxchar-startPos)

    outStr = ''
    # 先填入对应的空格数量
    outStr += ' '*startPos

    tmp = []
    for ch in range(intcharA,intcharA+halfLen-startPos):
        tmp.append(chr(ch))

    outStr += ''.join(tmp)
    outStr += curMaxChar
    tmp.reverse()
    outStr += ''.join(tmp)

    print(outStr)

for startpos in range(halfLen,-1,-1):
    printline(halfLen,startpos)

for startpos in range(1,halfLen+1):
    printline(halfLen,startpos)