checkio Create Intervals

题目:
From a set of ints you have to create a list of closed intervals as tuples, so the intervals are covering all the values found in the set.

A closed interval includes its endpoints! The interval 1…5, for example, includes each value x that satifies the condition 1 <= x <= 5.

Values can only be in the same interval if the difference between a value and the next smaller value in the set equals one, otherwise a new interval begins. Of course, the start value of an interval is excluded from this rule.
A single value, that does not fit into an existing interval becomes the start- and endpoint of a new interval.

Input: A set of ints.

Output: A list of tuples of two ints, indicating the endpoints of the interval. The Array should be sorted by start point of each interval

Examples:
create_intervals({1, 2, 3, 4, 5, 7, 8, 12}) == [(1, 5), (7, 8), (12, 12)]
create_intervals({1, 2, 3, 6, 7, 8, 4, 5}) == [(1, 8)]
链接:
https://py.checkio.org/en/mission/create-intervals/
代码:

def create_intervals(data):
    a = data
    b = list(a)
    c = sorted(b)
    if len(c) < 1:
        r = []
    elif len(c) == 1:
        r = [(c[0],c[0])]
    else:
        x = [c[0]]
        y = []        
        for i in range(1, len(c)):
            if c[i] == c[i-1]+1:
                x.append(c[i])
                if c[i] == c[-1]:
                    y.append(x)
        
            elif c[i] != c[i-1]+1 and c[i]!=c[-1]:
                y.append(x)
                x = [c[i]]
            else: #c[i] != c[i-1]+1 and c[i] == c[-1]:
                y.append(x)
                y.append([c[-1]])
        yy = []
        for i in y:
            yy.append((i[0],i[-1]))
        r = yy
    return r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值