Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the missing values in a range using any scripting language - perl, python or shell script

I got stuck in one problem of finding the missing values in a range and the range is also variable for the successive rows.

input

673 673 673 676 676 680
2667 2667 2668 2670 2671 2674

output should be like this

674 675 677 678 679
2669 2672 2673

This is just one part and the row values can be more also If you need any clarification, please let me know.

like image 248
manu Avatar asked Apr 28 '10 08:04

manu


2 Answers

Pure bash.

Use two subshells and run a diff, then clean up the results.

diff <(cat my_range_with_holes) <(seq 1 1000) | grep '>' | cut -c 3-
like image 183
owensmartin Avatar answered Oct 11 '22 22:10

owensmartin


In Python:

def report_missing_numbers(f):
    for line in f:
        numbers = [int(n) for n in line.split()]
        all_numbers = set(range(numbers[0], numbers[-1]))
        missing = all_numbers - set(numbers)
        yield missing

Note: all_numbers is a bit of a lie, since the range excludes the final number, but since that number is guaranteed to be in the set, it doesn't affect the correctness of the algorithm.

Note: I removed the [-1] from my original answer, since int(n) doesn't care about the trailing '\n'.

like image 42
Marcelo Cantos Avatar answered Oct 11 '22 22:10

Marcelo Cantos