【每日一题0822】合并区间

:woman_mage:对于一个有序的纯数字列表的描述方式可以有两种,第一种是由[ ] 包围,以逗号分隔的单独的数字。例如[-6, -3, -2, -1, 0, 1, 3] ;第二种是以字符串表示,其中对于相邻连续的数字,使用- 符号的区间表示,例如[-6, -3, -2, -1, 0, 1, 3] 可以写成"-6,-3-1,3" 。我们今天的任务是,编写一个python3函数,将输入的第一种列表进行转换,返回第二种表达方式的结果。

备注:(1)数字列表是有序的(2)区间包含连续数字的起点数字和终点数字(3)区间至少包含3个数字,例如12,13,14 可以写成12-14 ,而22,23 则不可以写成22-23

题目难度:中等
题目来源:codewars

def solution(nums:list) -> str:
    pass

assert solution([-3,-2,-1,2,10,15,16,18,19,20]) == "-3--1,2,10,15,16,18-20"
assert 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"

def solution(nums: list) -> str:
    length = len(nums)
    left = 0
    right = 1
    result = []
    while left < length - 1 and right < length - 1:
        # 步长
        step = 1
        while right < length and nums[right] - nums[left] == 1:
            # 符合 x-y=1 步长+1 前进一步
            left += 1
            right += 1
            step += 1
        else:
            # 当跳出循环时判断步长
            # 大于2的格式化输出
            if step > 2:
                result.append(f"{nums[right - step]}-{nums[right - 1]}")
            # 等于2的证明是连续数字
            elif step == 2:
                result.append(nums[left-1])
                result.append(nums[right-1])
            # 其余单个数字
            else:
                result.append(nums[left])
            # 进行下一次循环判断
            left = right
            right = left + 1
    from functools import reduce
    # 去重
    result = reduce(lambda x, y: x if y in x else x + [y], [[], ] + result)
    return ",".join([str(i) for i in result])


assert solution([-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]) == "-3--1,2,10,15,16,18-20"

assert 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"
def solution(nums:list) -> str:
    from itertools import groupby
    
    results= []
    fun = lambda x: x[1] - x[0]
    for k, g in groupby(enumerate(nums), fun):
        l1 = [j for i, j in g]
        if len(l1) > 1:
            if len(l1) >= 3:
                res = str(min(l1)) + '-' + str(max(l1))
                results.append(res)
            else:
                results.extend([str(i) for i in l1])
        else:
            res = str(l1[0])
            results.append(res)
    return ','.join(results)
def solution(nums:list) -> str:
    mid = []  # 获取连续自然数列表
    ret = []  # 存取符合条件的数据
    # 获取连续自然数列表
    for i in range(len(nums)):
        if not mid:
            mid.append([nums[i]])
        elif nums[i - 1] + 1 == nums[i]:
            ## res 中最后一个元素 append 连续数据
            mid[-1].append(nums[i])
        else:
            mid.append([nums[i]])
    # 存取符合条件的数据
    for i in mid:
        if len(i) == 1:
            ret.append(str(i[0]))
        elif len(i)==2:
            ret.append(str(i[0]))
            ret.append(str(i[1]))
        else:
            ret.append('-'.join([str(i[0]), str(i[-1])]))
    return ",".join(ret)
assert solution([-3,-2,-1,2,10,15,16,18,19,20]) == "-3--1,2,10,15,16,18-20"
assert 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"
1 Like
def solution(nums:list) -> str:
    count = 1
    new_list=[]
    for i in range(1,len(nums)):
        if nums[i] - nums[i-1] == 1:
            count = count+1
        else:
            if count >= 3:
                new_list.append(str(nums[i - count]) + '-' + str(nums[i-1]))
            elif count == 2:
                new_list.append(str(nums[i-2]))
                new_list.append(str(nums[i-1]))
            else:
                new_list.append(str(nums[i-1]))
            count = 1
        if i == len(nums)-1 and  count >= 3:
            new_list.append(str(nums[i -count+1]) + '-' + str(nums[i]))
        elif i == len(nums)-1 and  count == 2:
            new_list.append(str(nums[i-1]))
            new_list.append(str(nums[i]))
        elif i == len(nums)-1 and  count == 1:
            new_list.append(str(nums[i]))
    return ','.join(new_list)
def solution(nums: list) -> str:
    from itertools import groupby
    result=[]
    groupby_iterable=enumerate(nums)
    groupby_key=lambda x:x[1]-x[0]
    for k,v in groupby(groupby_iterable,groupby_key):
        group_list=[str(j) for i,j in v]
        result.append(group_list[0]+'-'+group_list[-1]) if len(group_list) >= 3 else result.extend(group_list)
    return ','.join(result)
def solution(nums:list) -> str:
    li = []
    li1 = []
    i=0
    while i<len(nums):
        if i<len(nums)-1 and nums[i]+1 == nums[i+1]:
            if nums[i] in li1:
                li1.append(str(nums[i + 1]))
            else:
                li1.append(str(nums[i]))
                li1.append(str(nums[i + 1]))

        else:
            if li1 != []:
                li.append(li1)
                li1 = []
            else:
                li.append(str(nums[i]))
        i += 1
    s = [f"{i[0]}-{i[-1]}" if len(i) > 2 else i for i in li]
    s1 = []
    for i in s:
        if type(i)==list:
            s1.extend(i)
        else:
            s1.append(i)
    return ",".join(s1)
assert solution([-3,-2,-1,2,10,15,16,18,19,20]) == "-3--1,2,10,15,16,18-20"
assert 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"

对于小白的我来说,代码简洁,思路又易懂。respect !!! :heart:

关闭