最近在做Hackerrank的練習(xí),Designer Door Mat是python練習(xí)中的一題。題目并不難,但是在完成題目后查看討論區(qū)大神的回答后還是感受到了差距,具體如下:
題目
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be N * M. (N is an odd natural number, and M is 3 times N.)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
Size: 11 x 33
---------------.|.---------------
------------.|..|..|.------------
---------.|..|..|..|..|.---------
------.|..|..|..|..|..|..|.------
---.|..|..|..|..|..|..|..|..|.---
-------------WELCOME-------------
---.|..|..|..|..|..|..|..|..|.---
------.|..|..|..|..|..|..|.------
---------.|..|..|..|..|.---------
------------.|..|..|.------------
---------------.|.---------------
解答
My Answer
# Enter your code here. Read input from STDIN. Print output to STDOUT
N, M = map(int,input().split())
string = [0 for _ in range(N)]
for i in range(N//2+1):
tmp = ''
if i == N // 2:
for _ in range((M-7)//2):
tmp += '-'
tmp += 'WELCOME'
for _ in range((M-7)//2):
tmp += '-'
string[i] = tmp
else:
for _ in range((M-3*(2*i+1))//2):
tmp += '-'
for _ in range(2*i+1):
tmp += '.|.'
for _ in range((M-3*(2*i+1))//2):
tmp += '-'
string[i] = tmp
string[len(string)-i-1]=tmp
print('\n'.join(string))
我的解法是比較愚蠢的直男型解法了,分別處理了WELCOME行和其他行并分別構(gòu)成每行的字符串,存入列表后再以join的方式輸出。再來看大神的解答
Elegant Answer
n, m = map(int,input().split())
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
除去解決輸入的那一行,僅僅使用兩行代碼就解決了這一問題。
大神的解釋如下:
('.|.'*(2*i + 1)).center(m, '-')將重復(fù)出現(xiàn)的.|.用string的center()方法將其設(shè)定為居中,并以-符號填充滿字符串。
將該字符串通過for循環(huán)構(gòu)成pattern列表,此時(shí)列表的內(nèi)容會包含
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
之后再輸出時(shí)加入WELCOME行['WELCOME'.center(m, '-')]和倒序的pattern列表pattern[::-1]
拓展
str.center()方法
str.center(width, [fillchar])
返回width寬度的將str居中的字符串,空缺的部分以fillchar填滿。
參數(shù):
width -- 字符串的總寬度。
fillchar -- 填充字符。
如果 width 小于字符串寬度直接返回字符串,不會截?cái)唷illchar默認(rèn)為空格且fillchar只支持單個(gè)字符。
list[::-1] Extended Slices
對于string,list,tuple,可以使用如下方法進(jìn)行切片:
<object_name>[<start_index>, <stop_index>, <step>]
切片會從start index開始,到stop index結(jié)束(不包含stop index),并且以step的大小來對index進(jìn)行操作。step默認(rèn)為1
example 1:
a = '1234'
print a[::2]
將會輸出13
example 2:
a = '1234'
print a[3:0:-1]
將會輸出 432
若step為負(fù)數(shù),這回從stop開始逆向輸出該字符串。list[;;-1]是常見的將列表逆序輸出的操作方式。
hackerrank designer-door-mat 原題
what is [::-1] in stackoverflow
python3 str.center()
Extended Slices - Python Document