HackerRank: Designer Door Mat 讲解

HackerRank Designer Door Mat 笔记和题解。

然

Table of Contents

背景

这一题(Designer Door Mat)我觉得很适合作为 Text Alignment 后面的巩固题,用来加强对 python 中 .center() 的理解。

题目

题目的输入会给 N, M 两个数,N 是奇数,而 M 是 N 的3倍。5 < N < 101, 15 < M < 303, 要求你画出来符合下面规律的图。

    Size: 7 x 21 
    ---------.|.---------
    ------.|..|..|.------
    ---.|..|..|..|..|.---
    -------WELCOME-------
    ---.|..|..|..|..|.---
    ------.|..|..|.------
    ---------.|.---------
    
    Size: 11 x 33
    ---------------.|.---------------
    ------------.|..|..|.------------
    ---------.|..|..|..|..|.---------
    ------.|..|..|..|..|..|..|.------
    ---.|..|..|..|..|..|..|..|..|.---
    -------------WELCOME-------------
    ---.|..|..|..|..|..|..|..|..|.---
    ------.|..|..|..|..|..|..|.------
    ---------.|..|..|..|..|.---------
    ------------.|..|..|.------------
    ---------------.|.---------------

题解

其实最关键的就是要观察到,只有".|."这一个图形在进行重复,而每行就呈现 1, 3, 5, 7 这样的递增,跟我们在这篇笔记中提到的一样。最中间的就是一个 "WELCOME" 居中。

我的做法是,将第一行到 "WELCOME" 那行的打出来,打印过程中,将含有 ".|." 的行数以类似 stack 的方式存在 list 里面,然后再一次性用 join 把下半部分打印出来:

# Enter your code here. Read input from STDIN. Print output to STDOUT
n,m = map(int,input().split())

mid = int((n+1)/2)
bottom = []
for i in range(mid-1):
	result = (".|."*(2*i+1)).center(m,"-")
	print(result)
	bottom.insert(0,result+"\n")
    
print("WELCOME".center(m,"-"))
print("".join(bottom))

这样比 Editorial 给的答案应该要更快一点。

希望我这篇文章对你有所帮助!😊😊

HackerRankPython简单难度算法

Comments