查找连续整数并且简化压缩表达

https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python

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):
    i,j = 0,1
    ans = []
    conseq = list(range(min(args),max(args)+1))
    #stnd = [min(args),max(args)+1]
    #ans = ','.join([str(i) if i in args else '' for i in conseq])
    #res = re.sub(r'[,]','-',ans)
    sl = [i if i in args else '' for i in conseq]
    sl = [str(i) for i in sl]
    sl.append('')
    pro, temp = [], []
    for i in sl:
        if not i == '':
            temp.append(i)
        else:
            if not len(temp) == 0:
                pro.append(temp)
                temp = []
    opt = ""
    for i in pro:
        if len(i) >= 3:
            opt += i[0]+'-'+i[-1]+','
        elif len(i) == 2:
            opt += i[0]+','+i[1]+','
        else:
            opt += i[0]+','
    return opt[:-1]

你可能感兴趣的:(查找连续整数并且简化压缩表达)