python算法——打印菱形、对等三角、闪电
1、打印菱形
# -*- coding:utf-8 -*- # version:python3.7 ''' @ file :print_graphics @ author:zhangyangyang @ create:2020/3/22 @ remark: ''' #打印菱形 #version1:推导空格数和'*'数之间的关系,空格 + "*" = n(长度) n = 7 e = n // 2 for i in range(-e,e+1): #定义空格数:[-3,3] #if i < 0: # i = -i #print('{}{}'.format(' ' * i,(n - 2 * i) * '*')) print('{}{}'.format(' ' * abs(i),(n - 2 * abs(i)) * '*')) #abs():求绝对值
执行结果:
*
***
*****
*******
*****
***
*
#version2:居中打印 n = 7 e = n // 2 for i in range(-e,e+1): print("{:^{}}".format('*' * (n - 2 * abs(i)),n)) 执行结果: * *** ***** ******* ***** *** *
2、打印对等三角形
#vsrsion1 n = 7 e = n // 2 for i in range(-e,e+1): #print(' ' * (e - abs(i)) + '{}'.format('*' * (2*abs(i) + 1))) print('{:^{}}'.format('*' * (2 * abs(i) + 1),n)) 执行结果: ******* ***** *** * *** ***** *******
#version2 n = 7 e = n // 2 for i in range(-e,n-e): print('{}{}'.format(' ' * (e - abs(i)),'*' * (2 * abs(i) + 1))) 执行结果: ******* ***** *** * *** ***** *******
3、打印闪电
#打印闪电 n = 7 e = n // 2 x = n - e for i in range(-e,x): if i < 0: print(' ' * -i + (x + i) * '*') elif i > 0: print(' ' * e + (x - i) * '*') else: print('*' * n) 执行结果: * ** *** ******* *** ** *