高尔夫代码:数字范围

编程入门 行业动态 更新时间:2024-10-10 06:21:40
本文介绍了高尔夫代码:数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

高尔夫代码:数字范围

本文发布于:2023-11-29 09:36:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高尔夫   代码   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!