user1619524 user1619524 - 3 months ago 10
Python Question

Find numbers not in range

appreciate if someone can help me, newbie in python.

I am to prompt user for ports to be reserved, i.e. 20-25, 80, 90-100.

Expected output should be range i.e. 1-19, 26-79, 81-89,101-65335.

Thanks in anticipation.

BPL BPL
Answer

Here's a working example with hardcoded values:

from itertools import groupby

ranges = ["20 - 25", "80", "90 - 100"]
out = [0] * 200

for r in ranges:
    tokens = r.split()
    if len(tokens) == 3:
        a = int(tokens[0])
        b = int(tokens[2])
        out[a:b + 1] = [1] * (b - a + 1)
    elif len(tokens) == 1:
        a = int(tokens[0])
        out[a] = 1

index = 0
free_ports = []
busy_ports = []
for k, g in groupby(out):
    lg = list(g)
    a = 1 if index == 0 else index
    index += len(lg)
    b = index
    port_range = [a, b - 1] if a != (b - 1) else [a]

    if k == 1:
        busy_ports.append(port_range)
        continue
    free_ports.append(port_range)

print "Ports in use:", busy_ports
print "Ports not used:", free_ports

One advice though, next time try to provide a mcve with one attempt of yours, otherwise people will downvote you badly as you can see in this question ;-)