请使用任意语言在屏幕上打印出一个n行n列的菱形。(输入参数为n,使用递增和递减数字填充输出)请注意需要对异常情况进行处理。
例如N=5时输出屏幕为
**1**
*121*
12321
*121*
**1**
1
"1"
5
"**1**|*121*|12321|*121*|**1**"
4
""
注意:换行符请用"|"替代!!!
class Solution: def print_diamond(self , n ): if not n % 2: # 处理特殊情况 return "" res = "" for i in range(n//2, -1, -1): left = "*" * ((n-2*i-1)//2) + "".join(list(map(str, [j for j in range(1, i+1)]))) # 每一行的输出 = 左字符串 + 中间的一个数字 + 翻转后的左字符串 temp = left + str(i+1) + left[::-1] if i == n//2: res = res + temp else: res = temp + "|" + res + "|" + temp # 利用对称,简化运算 return res