task 3.2 · chapter 3 of 8: loops, conditionals and functions · 25 min
VLAN ranges
objective
Turn a list of VLAN numbers into the compact form a trunk’s allowed list uses: [10, 11, 12, 20] becomes "10-12,20". Unsorted, duplicated and empty lists included.
netlab/interfaces.pyopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| Your function | netlab/interfaces.py: vlan_ranges() at TODO 3.2 |
|---|---|
| The rules | sort, drop duplicates; two or more numbers in a row become first-last; no VLANs give "" |
| sw1's VLANs | 10 users, 11 voice, 12 printers, 20 servers |
new to this? step by stepbeginner
python, thensorted(set([20, 12, 10, 11, 11])): sorted, and no duplicates.- Loop over the sorted list with
enumerate()and compare each number with the next one. - Challenge: write
vlan_ranges()underTODO 3.2. make check T=3.2.
more in meet the lab
Runs of numbers
The notation
On an IOS-style switch, the VLANs a trunk carries are written as a list with ranges folded up:
switchport trunk allowed vlan 10-12,20
10-12 means 10, 11 and 12. 20 stands alone. sw1’s four VLANs, [10, 11, 12, 20], written that way are
10-12,20. Two numbers in a row are a range too: [5, 6] is 5-6.
Thinking in runs
A run is a stretch of numbers where each is one more than the one before. Walk the sorted list from the left and every number does one of two things: it carries on the run you’re in, or it starts a new one. A run ends when the next number isn’t one more than this one, or when there is no next number.
| Number | Next | The run so far | What happens |
|---|---|---|---|
| 10 | 11 | 10 | carries on |
| 11 | 12 | 10, 11 | carries on |
| 12 | 20 | 10, 11, 12 | ends: write 10-12 |
| 20 | none | 20 | ends: write 20 |
So you need to remember where the current run started, and look at the next number.
in one sentence Sort first. Then a run ends where the next number isn’t this one plus one, or where the list ends.
Don’t touch what you were given
A function that receives a list shouldn’t reorder it: the caller may still need it as it was. vlans.sort()
sorts the list in place, the caller’s list included. sorted(vlans) makes a sorted copy and leaves the
original alone.
In and out
The examples from the function’s docstring and the check’s edge cases:
vlans | vlan_ranges(vlans) |
|---|---|
[10, 11, 12, 20] | '10-12,20' |
[20, 12, 10, 11, 11, 30, 31] | '10-12,20,30-31' |
[20, 10, 11, 10, 12, 20] | '10-12,20' |
[1, 3, 5] | '1,3,5' |
[5, 6] | '5-6' |
[4094, 4093] | '4093-4094' |
[1] | '1' |
[] | '' |
The check also tries 100 random lists, and checks that the list you were given is unchanged afterwards. A version that sorts in place and never folds anything up fails all four checks, for instance:
E AssertionError: assert '10,11,12,20' == '10-12,20'
...
E AssertionError: vlan_ranges changed the list it was given: sort a copy (sorted() makes one)
E assert [10, 10, 20, 30] == [30, 10, 20, 10]
In pytest’s assert ... == ... line, your answer is on the left and the expected one on the right.
Sort, then look next door
Start the REPL. A set is a collection with no duplicates and no order;
sorted()turns anything you can loop over into a new, sorted list:run in the terminalpython>>> set([20, 12, 10, 11, 11]) {10, 11, 20, 12} >>> sorted(set([20, 12, 10, 11, 11])) [10, 11, 12, 20]The set dropped the second 11, and came out in an order of its own. Never rely on a set’s order: sort it.
See the difference between
sorted()and.sort():>>> trunk = [30, 10, 20, 10] >>> sorted(trunk) [10, 10, 20, 30] >>> trunk [30, 10, 20, 10] >>> trunk.sort() >>> trunk [10, 10, 20, 30]sorted()gave back a copy and lefttrunkalone..sort()returned nothing and changedtrunkitself.Walk a sorted list with
enumerate(), which gives each number’s position as well. The position tells you whether this is the last number, and lets you look at the next one:>>> vlans = [10, 11, 12, 20] >>> for n, vlan in enumerate(vlans): ... print(n, vlan, n == len(vlans) - 1) ... 0 10 False 1 11 False 2 12 False 3 20 True >>> for n in range(len(vlans) - 1): ... print(vlans[n], vlans[n + 1], vlans[n + 1] == vlans[n] + 1) ... 10 11 True 11 12 True 12 20 FalseThe
Falsein the second loop is where a run ends: 12 is followed by 20, not 13.
in one sentence sorted(set(...)) for a clean copy; the position from enumerate() to look at the next number.
vlan_ranges()
Write vlan_ranges(vlans) under TODO 3.2, in place of the raise NotImplementedError(...) line, so that
every row in the table above comes out right, and the list it’s given is left as it was.
hint
Make the clean list first: numbers = sorted(set(vlans)). Then collect the pieces as strings in a list,
parts = [], and finish with ",".join(parts). An empty list of parts joins to "", which is the right
answer for no VLANs.
hint
Keep a variable for where the current run started, start = None. In the loop, if start is None, this
number starts a run. Then ask: is this the last number, or is the next one not n + 1? If so, the run ends
here.
hint
When a run ends at n, it’s one number if start == n (write str(n)) and a range otherwise (write
f"{start}-{n}"). Then set start = None so the next number starts a new run.
show the solutionnetlab/interfaces.py
or pull it into your lab: make solve T=3.2, then git diff --staged shows what changed
def vlan_ranges(vlans):
parts = []
numbers = sorted(set(vlans))
start = None
for i, n in enumerate(numbers):
if start is None:
start = n
last = i == len(numbers) - 1
if last or numbers[i + 1] != n + 1:
parts.append(str(start) if start == n else f"{start}-{n}")
start = None
return ",".join(parts)
sorted(set(vlans)) is a new list, so the caller’s list is never touched. start remembers where the run
began, and None means no run open. The test last or numbers[i + 1] != n + 1 relies on how or works:
Python stops at the first true part, so on the last number it never looks at numbers[i + 1], which would be
past the end. Each run becomes one string, and join puts commas between them. The result is the form you’d
write in a trunk’s config, and the one a report should print: 10-12,20 reads better than four numbers.
5 check: run it, then prove it
$ make check T=3.2when it's right, you'll see
task 3.2 checks/test_3_2.py
checks/test_3_2.py::test_the_example PASSED [ 25%]
checks/test_3_2.py::test_edges PASSED [ 50%]
checks/test_3_2.py::test_unseen_lists PASSED [ 75%]
checks/test_3_2.py::test_leaves_the_list_alone PASSED [100%]
============================== 4 passed in 0.01s ===============================
✓ task 3.2 done