Python补充练习1

题目1

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

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

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


答案与解析



题目2

请写一个函数 where_is_wired ,参数是一个二维列表,请找出里面和其他元素不同的那个元素的坐标。

坐标的下标从1开始,而不是从0开始

比如

where_is_wired([
  ["A", "A", "A"],
  ["A", "A", "A"],
  ["A", "B", "A"]
]) 
返回结果应该是 [3, 2]


where_is_wired([
  ["c", "c", "c", "c"],
  ["c", "c", "c", "d"]
]) 
返回结果应该是  [2, 4]


where_is_wired([
  ["O", "O", "O", "O"],
  ["O", "O", "O", "O"],
  ["O", "O", "O", "O"],
  ["O", "O", "O", "O"],
  ["P", "O", "O", "O"],
  ["O", "O", "O", "O"]
]) 
返回结果应该是 [5, 1]


答案与解析


扫码分享给朋友,一起学更有动力哦


















































题目1-答案

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)

题目2-答案