Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
IP Networks splitting calculator
# IP Network splitting calculator # python 3.4.0 def raise_f(arg): raise arg class DefaultDict(dict): def __init__(self, default_factory=lambda key: raise_f(KeyError(key))): self.default_factory = default_factory def __missing__(self, key): value = self.default_factory(key) self[key] = value return value @DefaultDict def uint(length_in_bits): max_value = (1<<length_in_bits) - 1 _type = type( 'uint[{}]'.format(length_in_bits), (int,), dict( __slots__ = (), __repr__ = lambda self: "{}({!r})".format(type(self).__name__, str(self)), __invert__ = lambda self: type(self)(self ^ max_value), ) ) def __new__(cls, arg=_type(0)): if isinstance(arg, cls): return arg else: _int = super(_type, cls).__new__(cls, arg) if 0 <= _int <= max_value: return _int else: raise ValueError('{} cannot be represented using only {} bits'.format(arg, length_in_bits)) _type.__new__ = __new__ return _type from functools import reduce class IPAddress(uint[32]): __slots__ = () def _bytes(self): for i in range(24, -1, -8): yield (self>>i) & 0xFF def __str__(self): return '.'.join(map(str, self._bytes())) __IPAddress__ = lambda self: self def __new__(cls, arg): try: result = arg.__IPAddress__() if isinstance(result, cls): return result else: raise TypeError('{!r}.__IPAddress__() returned {!r}, when caller expected instance of {}.'.format(arg, result, cls)) except AttributeError: pass try: _list = arg.split('.', 3) except AttributeError: pass if len(_list) != 4: raise ValueError(repr(arg) + " does not represent four 8-bit integers separeted by dots.") _list = map(uint[8], _list) return super(IPAddress, cls).__new__(cls, reduce(lambda x, y: (x<<8) | y, _list)) __add__ = lambda self, other: super(IPAddress, type(self)).__new__(IPAddress, super(IPAddress, self).__add__(other)) __sub__ = lambda self, other: super(IPAddress, type(self)).__new__(IPAddress, super(IPAddress, self).__sub__(other)) __xor__ = lambda self, other: super(IPAddress, type(self)).__new__(IPAddress, super(IPAddress, self).__xor__(other)) __or__ = lambda self, other: super(IPAddress, type(self)).__new__(IPAddress, super(IPAddress, self).__or__(other)) __and__ = lambda self, other: super(IPAddress, type(self)).__new__(IPAddress, super(IPAddress, self).__and__(other)) __mul__ = __truediv__ = __floordiv__ = __mod__ = __divmod__ = __pow__ = __abs__ = __pos__ = __neg__ = __complex__ = __float__ = __round__ = __floor__ = lambda *_, **__: raise_f(TypeError('Using this method on object of type IPAddress is not allowed.')) IPAddress.__new__.__defaults__ = (int.__new__(IPAddress),) class Mask(uint[5]): __slots__ = () def _neg_bin(self): return uint[32].__new__(IPAddress, 0xFFFFFFFF >> self) def bin(self): return ~self._neg_bin() class IPAddressWithMask(tuple): __slots__ = () __IPAddress__ = lambda self: self[0] __Mask__ = lambda self: self[1] ip_address = property(__IPAddress__) mask = property(__Mask__) def __new__(cls, ip_address, mask=None): if mask is None: try: new_object = ip_address.__IPAddressWithMask__() if isinstance(new_object, cls): return new_object else: raise TypeError('{!r}.__IPAddressWothMask__() returned {!r}, when caller expected instance of {}.'.format(arg, result, cls)) except AttributeError: pass try: # assuming ip_address is string ip_address, mask = ip_address.split('/') except ValueError: raise ValueError(repr(ip_address) + ' does not represent valid IP address with mask.') from None return super(IPAddressWithMask, cls).__new__(cls, (IPAddress(ip_address), Mask(mask))) def __IPAddressWithMask__(self): return self network = __Network__ = lambda self: IPAddressWithMask.__new__(Network, self.ip_address & self.mask.bin(), self.mask) def broadcast(self): return self.ip_address | self.mask._neg_bin() def __str__(self): return '{}/{}'.format(self.ip_address, self.mask) def __repr__(self): return "{}({!r})".format(type(self).__name__, str(self)) def getitem_by_call(container): return lambda *args: container[args] from math import log, ceil class Network(IPAddressWithMask): __slots__ = () #_instances = DefaultDict(lambda key super(Network, Network).__new__(Network, *key)) def __new__(cls, *args): new_object = super(Network, Network).__new__(Network, *args) #_instances[args] if (new_object.ip_address & new_object.mask.bin()) == new_object.ip_address: return new_object else: raise ValueError(repr(new_object) + " is not network's IP address.") def ips(self): return 0xFFFFFFFF >> self.mask def hosts(self): return self.ips() -2 def split(self, shift=1): new_mask = Mask(self.mask + shift) difference = 0x100000000 >> new_mask for i in range(2**shift): yield Network(self.ip_address + i * difference, new_mask) @staticmethod def _get_network(source_list, mask): current_cell = source_list[mask] if current_cell is None: to_return, to_save = Network._get_network(source_list, mask-1).split() source_list[mask] = to_save return to_return else: source_list[mask] = None return current_cell def custom_split(self, *hosts_needed): max_mask = (Mask(32 - ceil(log(i, 2))) for i in hosts_needed) available_networks = [None]*32 available_networks[self.mask] = self for i in max_mask: try: yield self._get_network(available_networks, i) except ValueError: raise ValueError("Split seems to be impossible.") from None return available_networks network = __Network__ = lambda self: self if __name__ == '__main__': while True: try: line = input() except EOFError: break else: try: network, target = line.split('into') except ValueError: print("Expected format of input: network's_address into sizes of target networks") else: try: network, target = Network(network), (int(i)+2 for i in target.split()) print('{}:'.format(network)) for i in network.custom_split(*target): print(' ', i) print() except Exception as e: print('{}: {}'.format(type(e).__name__, e))
run
|
edit
|
history
|
help
0
gj1
Сумма цифр пятизначного числа
global 3
ConstructorBehaviourInInheritance
🙆👌
quizcorrect
probl2_203700377
linked_lists_2
nnnn
Mixing string with number