美文网首页python
查找连续整数并且简化压缩表达

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

作者: Python_Camp | 来源:发表于2020-10-07 11:36 被阅读0次

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]

相关文章

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

    https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/tr...

  • 查找整数

    查找整数时间限制:1.0s 内存限制:256.0MB 锦囊1使用循环语句、判断语句和跳出循环语句。锦囊2将所有...

  • Kotlin (五)在集合里面感受Lambda

    5.1 简化表达 举个Android里面最常用的例子,java总普遍的用法 翻译成kotlin并且简化 带有接收者...

  • golang实现二分查找

    一组数据要进行二分查找,那么这个要查找的元素是有序,并且是连续存放(数组)。这样才可以进行二分查找。

  • 二分查找 (lintcode:first-position-of

    二分查找 给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第...

  • 128. Longest Consecutive Sequenc

    题目描述:给一个未排序的整数数组,查找其中最长连续元素序列的长度。如[100, 4, 200, 1, 3, 2]找...

  • 二分查找

    二分查找 描述 给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到targ...

  • redis笔记:压缩列表

    本人博客同步发表,排版更佳 概述 压缩列表是列表、哈希的底层实现之一 当列表只包含少量列表项,并且要么是小整数值、...

  • 2021-07-03

    今天看了java8中Lambda表达式的相关视频并且跟着视频敲了代码,收获最大的就是知道Lambda表达式简化了匿...

  • 9.查找整数

    问题描述给出一个包含n个整数的数列,问整数a在数列中的第一次出现是第几个。 输入格式第一行包含一个整数n。第二行包...

网友评论

    本文标题:查找连续整数并且简化压缩表达

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