编写函数,接受一个n,n为正整数,左右两种打印方式。要求数字必须对齐
12 11 10 9 8 7 6 5 4 3 2 1 11 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1 7 6 5 4 3 2 1 6 5 4 3 2 1 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 11 10 9 8 7 6 5 4 3 2 1 12 11 10 9 8 7 6 5 4 3 2 1
补空格法
def trangle2(n): nums = [i for i in range(n,0,-1)] length = len(nums) for i in range(length): for j in range(length): if i<=j: print('{:>{}}'.format(nums[j],len(str(nums[j]))+1),end='') else: print('{}'.format(' '*(len(str(nums[j]))+1)),end='') print() for i in range(length): for j in range(length,0,-1): if i+1>=j: print('{:>{}}'.format(nums[-j],len(str(nums[-j]))+1),end='') else: print('{}'.format(' '*(len(str(nums[-j]))+1)),end='') print()
靠右对齐法
def trangle_print(n): nums = ' '.join(str(i) for i in range(n,0,-1)) width = len(nums) start = -1 step = 2 points = {10**i for i in range(1,3)} for i in range(1,n+1): print('{:>{}}'.format(nums[start:],width)) if i+1 in points: step += 1 start = start -step
字符串切割法
def trangle1(n): nums = ' '.join([str(i) for i in range(n,0,-1)]) length = len(nums) print(nums) for i in range(len(nums)): if nums[i] ==' ': print('{}{}'.format(' '*(i+1),nums[(i+1):])) for j in range(len(nums)-1,0,-1): if nums[j] == ' ': print('{}{}'.format(' '*(j),nums[j:])) print(nums)