Sets and tuples theory + first problem: find unique client IPs from a request list
Problem statement
A set is a collection where every value appears at most once. Add the same IP ten times and the set still holds it once, so a set removes duplicates for you. In the Lists section you did this by hand with a seen list. A set does it automatically, and checking whether a value is in a set stays fast even when the set is huge.
Java has Set (such as HashSet and TreeSet), and C++ has std::set and std::unordered_set.
A tuple is a different tool: a small, fixed group of values kept in a set order, like ("web-01", "10.0.0.5", 8080). You will use one in the third problem of this section.
Common mistake: expecting a set to keep the original order.
Wrong: print(unique_ips) (expecting "10.0.0.5" to come first)A Python set has no order at all, and the order it prints can even change between runs. If you need a predictable order, sort before printing. Java's TreeSet and C++'s std::set keep their items sorted automatically. Java's HashSet and C++'s unordered_set do not.
Your task: given the client IPs from six requests, ["10.0.0.5", "10.0.0.9", "10.0.0.5", "10.0.0.7", "10.0.0.9", "10.0.0.5"], find the unique IPs. Print how many there are, then print each one in sorted order, one per line.
Expected output:
Unique IPs: 310.0.0.510.0.0.710.0.0.9Approach
Put the whole list into a set, then count and print it in order:
- Python:
set(ips)builds a set from a list.len(...)counts it, andsorted(...)gives the items in order. - Java:
new TreeSet<>(ips)builds a set that keeps itself sorted..size()counts it. - C++:
std::set<std::string> uniqueIps(ips.begin(), ips.end())builds a set from a list, and it stays sorted..size()counts it.
DSA connection: a set is a hash set, used for "have I seen this before?" and for removing duplicates in many DSA problems.
ips = ["10.0.0.5", "10.0.0.9", "10.0.0.5", "10.0.0.7", "10.0.0.9", "10.0.0.5"]
unique_ips = set(ips)
print(f"Unique IPs: {len(unique_ips)}")
for ip in sorted(unique_ips):
print(ip)