Code Review Asked by deed02392 on December 14, 2021
The below algorithm is supposed to take a list of input IPs/networks and a list of IPs/networks to exclude, and return a list of networks that don’t include any of the IPs/networks to exclude…
Please review it and provide me with some feedback!
import ipaddress
from ipaddress import IPv4Network
def recurse_exclude(supernet_list, exclude_list):
# For some reason, this only works if we force the generators into lists
for supernet in list(supernet_list):
for exclude in exclude_list:
try:
excluded_list = recurse_exclude(list(supernet.address_exclude(exclude)), exclude_list)
except ValueError:
# Ignore when the IP/net to exclude was not in the supernet
continue
else:
return list(excluded_list)
return supernet_list
supernet_list = [IPv4Network('1.1.0.0/24')]
output = recurse_exclude(supernet_list, exclude_list=[IPv4Network('1.1.0.0/25'),IPv4Network('1.1.0.128/26')])
Python and recursion are not the best match, instead use loops
It could even be done with list comprehension
return [ip if ip not in exclude for ip in subnet]
Alter your imports to use one of the two not both
I suggest to use from ipaddress import IPv4Network
because that seems to be only thing imported from the library.
Use sets!
Lists are O(N), while sets are O(1)!
Secondly it's quite easy to subtract sets simply use set(c) = set(a) - set(b)
from ipaddress import IPv4Network
exclude = set(IPv4Network('1.1.0.0/25')) | set(IPv4Network('1.1.0.128/26'))
net = set(IPv4Network('1.1.0.0/24'))
print(net - exclude)
Answered by Ludisposed on December 14, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP