Rosetta: Range extraction

bartc bc at freeuk.com
Mon Apr 24 06:42:25 EDT 2017


On 24/04/2017 09:20, Robert L. wrote:

>> Create a function that takes a list of integers in increasing
>> order and returns a correctly formatted string in the range
>> format.
>>
>> Use the function to compute and print the range formatted
>> version of the following ordered list of integers. (The
>> correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39.)
>>
>>     0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
>>    15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
>>    25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
>>    37, 38, 39
>
>
> list = [0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
>   15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
>   25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
>   37, 38, 39]
>
> old = list[0]
> list.slice_before{|n| [n-old>1,old=n][0]}.
> map{|a| a.size<3 ? a.join(",") : [a[0],a[-1]].join("-")}.
> join ","
>
>  ===>
> "0-2,4,6-8,11,12,14-25,27-33,35-39"

Is this supposed to be Python code? Because it doesn't seem to work. I 
thought it might use advanced Python features I didn't know about.

-- 
bartc

(Regarding this particular task, one of my languages has it built-in 
(for a 'set' object not a list):

  println [0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
          15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
          25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
          37, 38, 39]

Output is:

    [0..2,4,6..8,11..12,14..25,27..33,35..39]

It uses ".." rather than "-" so that the output is legal program syntax. 
35-39 would be interpreted as -4.)



More information about the Python-list mailing list