感谢有人可以帮助我,新手在python中。
我将提示用户保留端口,即20-25,80,90-100。
预期产出应为1-19,26-79,81-89,101-65335。
感谢您的期待。
答案 0 :(得分:1)
def is_good(num, bad_ranges):
return all(x not in range(elem[0], elem[1] + 1) for elem in bad_ranges)
bad_ranges = [[20, 25], [80, 80], [90, 100]]
print(is_good(19, bad_ranges)) # returns True
print(is_good(21, bad_ranges)) # returns False
答案 1 :(得分:0)
以下是硬编码值的工作示例:
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
但有一条建议,下次尝试提供mcve一次尝试你的一次,否则人们会在这个问题上看到你的情况下非常失败; - )