For this next exercise, you‘ll need to complete the function gen_pattern, which, when called with a string of length ≥≥ 1, will print an ASCII art pattern of concentric diamonds using those characters. The following are examples of patterns printed by the function (note the newline at the end of the last line!
> gen_pattern(‘X‘)
X
> gen_pattern(‘XY‘)
..Y..
Y.X.Y
..Y..
> gen_pattern(‘WXYZ‘)
......Z......
....Z.Y.Z....
..Z.Y.X.Y.Z..
Z.Y.X.W.X.Y.Z
..Z.Y.X.Y.Z..
....Z.Y.Z....
......Z......
You ought to find the string join and center methods helpful in your implementation. They are demonstrated here:
> ‘*‘.join(‘abcde‘)
‘a*b*c*d*e‘
> ‘hello‘.center(11, ‘*‘)
‘***hello***‘
Complete the gen_pattern function, below:
def gen_pattern(chars): maxchars=len(chars)*2-1 def ques(a,b): a="".join(reversed(a))[:b] s=a+"".join(reversed(a))[1:] return s maxlen= len(‘.‘.join(ques(chars,len(chars)))) for i in range(1,int(maxchars/2+1)): c=ques(chars,i) d=‘.‘.join(c).center(maxlen,‘.‘) print(d) for i in range(int(maxchars/2+1),0,-1): c=ques(chars,i) d=".".join(c).center(maxlen,".") print(d)
原文:https://www.cnblogs.com/ladyrui/p/12981192.html