高尔夫代码:数字范围 [英] Code Golf: Numeric Ranges

查看:306
本文介绍了高尔夫代码:数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过用范围替换连续运行来精简一长串数字.

Compactify a long list of numbers by replacing consecutive runs with ranges.

1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
输入内容按升序保证,并且不包含重复项.

1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
The input is guaranteed to be in ascending order and will not contain duplicates.

1 - 4, 7, 8, 10, 12 - 15
请注意,两个数字的范围应保留不变. (7, 8;不是7 - 8)

1 - 4, 7, 8, 10, 12 - 15
Note that ranges of two numbers should be left as is. (7, 8; not 7 - 8)

您可以从命令行或标准输入中接受整数(或等效数据类型)的排序列表作为方法参数.(选择任一选项会导致较短的代码)
您可以通过打印字符串或返回单个字符串或一组字符串来输出字符串列表.

You can accept a sorted list of integers (or equivalent datatype) as a method parameter, from the commandline, or from standard in. (pick whichever option results in shorter code)
You can output a list of strings by printing them, or by returning either a single string or set of strings.

(C#)

IEnumerable<string> Sample(IList<int> input) {
    for (int i = 0; i < input.Count; ) {
        var start = input[i];
        int size = 1;
        while (++i < input.Count && input[i] == start + size)
            size++;

        if (size == 1)
            yield return start.ToString();
        else if (size == 2) {
            yield return start.ToString();
            yield return (start + 1).ToString();
        } else if (size > 2)
            yield return start + " - " + (start + size - 1);
    }
}

推荐答案

Python,83个字符

def f(l,a=2):
 for x in l:
  b,a=a,(x+1in l)*(x-1in l)
  if a<1:print',- '[b],`x`,

演示:

>>> l=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
>>> f(l)
  1 - 4 , 7 , 8 , 10 , 12 - 15

这篇关于高尔夫代码:数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆