题目

Range Extraction

描述

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.

表示有序整数列表的一种格式是使用逗号分隔的

  • 单个整数
  • 或者一个整数范围,由起始整数表示,该范围内的结束整数用破折号“-”分隔。范围包括区间内的所有整数,包括两个端点。除非它跨越至少3个数字,否则它不被视为一个范围。例如“12,13,15-17”

完成该解决方案,使其以递增顺序获取整数列表,并以范围格式返回格式正确的字符串。

例子

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

思路

从上面的描述来看,这题题意其实很简单,就是把一个列表转变成字符串,但是呢需要处理,如果出现三个及以上相连的数字,我们需要整合起来,只要开头和结尾的两个数字,然后中间用"-"连起来,然后不同的分组之间用","隔开就行。

看到上面的分析,肯定需要两个变量:start and end,用来记录开头和结尾

# 创建两个值
    start,end = args[0],args[0]

这里还需要一个计数的变量,判断此时是几个连续的数字,当然可以不同,到时候直接end - start即可

分为三种情况去得到结果

# 判断start是否等于end
if start == end:
    result += str(start) + ","
# 判断是否只是两个值连续
elif count == 1:
    result += str(start) + "," + str(end) + ","
# 3个以上连续
else:
    result += str(start) + "-" + str(end) + ","

完整代码

def solution(args):
    # 创建两个值
    start,end = args[0],args[0]
    result = ""
    # 计数判断我此时连续的值是否等于1
    count = 0

    # 遍历列表
    for i in range(0,len(args)):
        # 处理当前的end + 1是否等于下一个args,如果是就说明是连续的,不是就说明是断开的
        if (i < (len(args) - 1)) and (end + 1 == args[i + 1]):
            end = args[i + 1]
            count += 1
            continue
        else:
            # 判断start是否等于end
            if start == end:
                result += str(start) + ","
            # 判断是否只是两个值连续
            elif count == 1:
                result += str(start) + "," + str(end) + ","
            # 3个以上连续
            else:
                result += str(start) + "-" + str(end) + ","
            # 重新定位start,end值
            if i != len(args) - 1:
                start,end = args[i + 1],args[i + 1]
            count = 0
    
    # 切片,删除最后一个“,”
    return result[:len(result) - 1]