2020-06-3 Markdown渲染器 100分 python 思路清晰
这个题首先你要先读清楚题,知道它的渲染规则,我来解释下:它题目中说首先将属于同一类(段落或项目列表)的各行先去掉首尾的连续空格然后再用空格连接起来逐行渲染。实际上写代码也是模仿了这个过程。不过要首先判断它是什么类型。
我说下我的代码思路:首先判断它的类型是段落还是项目,如果是段落的话就先将属于这个段落的各行用空格连起来,等到把这个段落的所有行都找完了,就计算它占了多少行,这个可以专门写一个cal函数来计算,如果是项目列表的话同样,如果碰到空行的话,分两种情况:如果他前面不是空行,那么就行数加一,否则不变。
本体较为棘手的几点:
- 判断项目列表或者段落是否已经找完了,需要终止,我这里老是数组越界或者没考虑全,就专门写了两个judge函数作为判断循环是否终止的条件。
- 判断行数是否需要额外加一。由题目我们可以知道段落和项目列表以及空行之间在渲染时需要加一,我用了一个flag标志来表示上一行为什么类型。
ps:这个题我的思路,我之前无论怎么改都是20分,后来发现我没考虑开头和结尾出现空行的情况,这种请况下是不需要加一的,一改直接100分了。
下面是我的代码:
import sys
text=[]
for i in sys.stdin.readlines():
text.append(i)
w=int(text[0])
# while text[-1]=="\n":
# text.pop()
# while text[0]=="\n":
# text=text[1:len(text)]
def cal(s,w):
"""
:param s: 处理好的字符串
:param w: 终端宽度
:return: 需要的终端行数
"""
if s=="":
return 1
count=0
while len(s):
if len(s)<=w:
count+=1
break
elif s[0]==" ":
s=s.strip()
else:
s=s[w:len(s)]
count+=1
return count
def judge1(text,i):
if i >= len(text):#越界
return False
if text[i].strip()=="":#为空行
return False
if len(text[i])==1:
return False
if text[i][:2]==" ":
return True
else:
return False
def judge2(text,i):
if i >= len(text):#越界
return False
if text[i].strip() == "": # 为空行
return False
if len(text[i])==1:
return True
elif text[i][:2]=="* ":
return False
else:
return True
i=1
line=0
flag=-2#0:段落 1:项目列表 -1:空行
k=-1
while i < len(text):
t=text[i]
if t[:2]=="* ":
b=t[2:len(t)].strip()
i+=1
while judge1(text,i):
b+=" "+text[i].strip()
i+=1
if flag==0:#判断上一行是段落加一
line+=1
flag=1
line+=cal(b,w-3)
elif t.strip()=="" and flag!=-1:
if i==len(text)-1:
break
if i==1:
line-=1
line+=1
i+=1
flag=-1
continue
elif t.strip()=="" and flag==-1:
i+=1
flag=-1
continue
else:
b=text[i].strip()
i+=1
while judge2(text,i):
b+=" "+text[i].strip()
i+=1
if flag==1:
line+=1
line+=cal(b,w)
flag=0
# print(line,b)
print(line)