Strip Comments (Codewars 4kyu Python)

题目:

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.

Example:

Given an input string of:

apples, pears # and bananas
grapes
bananas !apples
The output expected would be:

apples, pears
grapes
bananas
The code would be called like so:

result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
# result should == "apples, pears\ngrapes\nbananas"

我的思路:

可以先把string根据 “\n” 分割成每一行的句子,每一行分别去掉maker后的内容,并且检查maker前的内容,如果末尾有多余空格要去掉。

我的解答:

def solution(string,markers):
    s = string.split("\n")
    result = ""
    for i in s:
        trimmed = ""
        for j in i:
            if j not in markers:
                trimmed += j
            else:
                break
        trimmed = trimmed.rstrip()
        result = result + trimmed + "\n"
    return result[:-1]

Most Clever:

做完题目看一下题后投票clever最多的答案:

def solution(string,markers):
    parts = string.split('\n')
    for s in markers:
        parts = [v.split(s)[0].rstrip() for v in parts]
    return '\n'.join(parts)

其中主要语句:

v.split(s)[0].rstrip()

就是用maker把parts里的每个分割成小段,取其中第一个小段,然后去掉右边多余的空格。

总结:

思路基本一致,Most Clever中用maker把parts里的每个分割成小段,取其中第一个小段,比我的检查每行,逐位获取,遇到maker结束,要灵活便捷一些。

你可能感兴趣的:(刷题,#,Codewars)