美文网首页python
书的页码连续缩写

书的页码连续缩写

作者: Python_Camp | 来源:发表于2020-10-15 22:05 被阅读0次

    https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python
    ​连续整数的缩写

    表达整数有序列表的格式是使用逗号分隔的列表,其内容包括一个整数范围,用破折号'-'隔开起始整数和结束整数。范围包括区间内的所有整数,包括两个端点。除非它跨越至少3个数字,否则不被认为是一个范围。例如("12,13,15-17")。

    完成解题,使其以递增顺序接收一个整数列表,并以范围格式返回一个正确格式化的字符串。
    ​输入:
    [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]

    输出:"-6,-3-1,3-5,7-11,14,15,17-20"

    任务选自codewars题库难度 4kyu:
    A format for expressing an ordered list of integers is to use a comma separated list of either

    individual integers
    or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")
    Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

    Example:

    solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])

    returns "-6,-3-1,3-5,7-11,14,15,17-20"

    Test.describe("Sample Test Cases")

    Test.it("Simple Tests")
    Test.assert_equals(solution([-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]), '-6,-3-1,3-5,7-11,14,15,17-20')
    Test.assert_equals(solution([-3,-2,-1,2,10,15,16,18,19,20]), '-3--1,2,10,15,16,18-20')

    def solution(args):
        out = []
        beg = end = args[0]
    
        for n in args[1:] + [""]:
            if n != end + 1:
                if end == beg:
                    out.append(str(beg))
                elif end == beg + 1:
                    out.extend([str(beg), str(end)])
                else:
                    out.append(str(beg) + "-" + str(end))
                beg = n
            end = n
    
        return ",".join(out)
    

    相关文章

      网友评论

        本文标题:书的页码连续缩写

        本文链接:https://www.haomeiwen.com/subject/xqqapktx.html