python3实现如下所示的打印:
#size 3 ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c---- #size 5 --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- #size 10 ------------------j------------------ ----------------j-i-j---------------- --------------j-i-h-i-j-------------- ------------j-i-h-g-h-i-j------------ ----------j-i-h-g-f-g-h-i-j---------- --------j-i-h-g-f-e-f-g-h-i-j-------- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- j-i-h-g-f-e-d-c-b-a-b-c-d-e-f-g-h-i-j --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ --------j-i-h-g-f-e-f-g-h-i-j-------- ----------j-i-h-g-f-g-h-i-j---------- ------------j-i-h-g-h-i-j------------ --------------j-i-h-i-j-------------- ----------------j-i-j---------------- ------------------j------------------
代码如下:
def print_rangoli(size): endchar = chr(96+size) for i in range(2*size-1): midlechar = chr(abs(i-size+1)+97) str = midlechar while midlechar!=endchar: tmp = chr(ord(midlechar)+1) str= tmp+'-'+str+'-'+tmp midlechar = tmp print(str.center(4*size-3,'-')) if __name__ == '__main__': n = int(input()) print_rangoli(n)
用到的函数包括:
chr ord,这两个函数分别实现字符与asc2的互转
abs,取绝对值