Programming from zero

Sets and tuples theory + first problem: find unique client IPs from a request list

easySets and tuples Must-do

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.

flowchart LR A["request list: 6 IPs"] --> B["put into a set: repeats dropped"] --> C["3 unique IPs"] classDef input fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef set fill:#FEF3C7,stroke:#D97706,color:#92400E classDef output fill:#D1FAE5,stroke:#059669,color:#065F46 class A input class B set class C output

Common mistake: expecting a set to keep the original order.

TEXT
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:

TEXT
Unique IPs: 3
10.0.0.5
10.0.0.7
10.0.0.9

Approach

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, and sorted(...) 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)