A DHCP server lends addresses from a pool, one by one, and remembers who has which.
What to build
A program that gives each client an address from a pool in the order the clients arrive.
Requirements
- The pool runs from the first to the last address, in order; both are in the same /24, so only the last number changes.
- A client that already has an address gets the same address again.
- A new client gets the next unused address, or
noneif the pool is used up. - Print
client addressfor each request.
Input
Line 1: the first and the last address of the pool. Line 2: the number of requests n. Then n lines, each a client name.
Output
n lines like phone 192.168.1.100.
Constraints
1 ≤ n ≤ 50; the pool has 1 to 50 addresses.
Example
Input:
192.168.1.100 192.168.1.102
4
phone
laptop
phone
tv
Output:
phone 192.168.1.100
laptop 192.168.1.101
phone 192.168.1.100
tv 192.168.1.102
Why it works
Handing out addresses in order and remembering each client in a dict gives every client one address. Counting the addresses used tells us when the pool is empty.
Examples
192.168.1.100 192.168.1.102 4 phone laptop phone tv
phone 192.168.1.100 laptop 192.168.1.101 phone 192.168.1.100 tv 192.168.1.102
10.0.0.5 10.0.0.5 2 a b
a 10.0.0.5 b none
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep a dict from client name to address. If the client is in it, print the same address.
Hint 2
The next free address is the pool start plus the number already given out.
Hint 3
When the number given out equals the pool size, new clients get none.
Solution
Show one correct solution (try it yourself first)
first, last = input().split()
prefix = first.rsplit(".", 1)[0]
low = int(first.rsplit(".", 1)[1])
high = int(last.rsplit(".", 1)[1])
n = int(input())
given = {}
for _ in range(n):
client = input().strip()
if client not in given:
if low + len(given) <= high:
given[client] = prefix + "." + str(low + len(given))
else:
given[client] = "none"
print(client, given[client])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step