Groups of different sizes need blocks of different sizes. VLSM gives each group the smallest block that fits it.
What to build
A program that fits groups of hosts into one network and prints the subnet of each group.
Requirements
- A group of h hosts needs a block of 2 to the power k addresses, with the smallest k such that 2^k ≥ h + 2 (and at least 4 addresses, a /30).
- Place blocks starting at the beginning of the base network, largest first (ties keep their input order), each block right after the previous one.
- If a block does not fit inside the base network, that group gets
no spaceand later groups are still tried. - Print one line per group, in the input order:
NAME network/prefixorNAME no space.
Input
Line 1: the base network, like 192.168.1.0/24. Line 2: the number of groups n. Then n lines name hosts.
Output
n lines, in the input order.
Constraints
1 ≤ n ≤ 20; 1 ≤ hosts ≤ 65000; the base prefix is from 8 to 28 and its host bits are 0.
Example
Input:
192.168.1.0/24
3
staff 50
servers 10
link 2
Output:
staff 192.168.1.0/26
servers 192.168.1.64/28
link 192.168.1.80/30
Why it works
Placing the largest block first keeps every block aligned: block sizes are powers of two, so each block starts at a multiple of its own size. A block that would pass the end of the base network cannot be used.
Examples
192.168.1.0/24 3 staff 50 servers 10 link 2
staff 192.168.1.0/26 servers 192.168.1.64/28 link 192.168.1.80/30
10.0.0.0/24 2 a 100 b 100
a 10.0.0.0/25 b 10.0.0.128/25
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Each group needs hosts + 2 addresses (network and broadcast); the block size is the next power of 2 that holds them, at least 4.
Hint 2
Place groups from the largest to the smallest; on a tie, keep the input order. The next block starts where the last one ended.
Hint 3
If a block would run past the end of the base network, print no space for that group and go on with the next one. Print results in the input order.
Solution
Show one correct solution (try it yourself first)
def to_number(ip):
n = 0
for part in ip.split("."):
n = n * 256 + int(part)
return n
def to_ip(n):
return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))
base, n = input().strip(), int(input())
ip, prefix = base.split("/")
start = to_number(ip)
end = start + 2 ** (32 - int(prefix))
groups = []
for i in range(n):
name, hosts = input().split()
groups.append((int(hosts), i, name))
result = {}
pos = start
for hosts, i, name in sorted(groups, key=lambda g: (-g[0], g[1])):
k = 2
while 2 ** k < hosts + 2:
k += 1
size = 2 ** k
pos = (pos + size - 1) // size * size
if pos + size > end:
result[i] = name + " no space"
else:
result[i] = name + " " + to_ip(pos) + "/" + str(32 - k)
pos += size
for i in range(n):
print(result[i])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step