A seen-set can't answer what needs the whole input
A seen-set answers questions about what came before. Some questions need the whole input first.
word = "swiss"
counts = Counter(word)
print(next(ch for ch in word if counts[ch] == 1))
w
The first character that appears exactly once in "swiss" is w. You can't know that at the first s, because the second s hasn't come yet. So count everything in one pass, then decide in a second. A seen-set can't do this: at any moment it only knows the past.
The practice problem hits exactly this. Two files can be duplicates only if they have the same size. A size is free to read, and the content is not. So you want to open only the files whose size another file shares.
Try it with a seen-set on five files and their sizes:
files = [("a.jpg", 17), ("b.jpg", 17), ("c.txt", 10), ("d.mov", 9000), ("e.txt", 10)]
seen, flagged = set(), []
for path, size in files:
if size in seen:
flagged.append(path)
seen.add(size)
print(flagged)
['b.jpg', 'e.txt']
It misses a.jpg and c.txt, the first file of each size. When you meet them, their twin hasn't come along yet. Counting the sizes first gets all four:
| File | Size | Seen-set before | Seen-set says | Size count |
|---|---|---|---|---|
| a.jpg | 17 | { } | no: missed | 2: read |
| b.jpg | 17 | {17} | yes | 2: read |
| c.txt | 10 | {17} | no: missed | 2: read |
| d.mov | 9000 | {17, 10} | no | 1: skip |
| e.txt | 10 | {17, 10, 9000} | yes | 2: read |
A generator hands out its values one at a time, and only once:
g = (n for n in [1, 2])
print(list(g), list(g))
[1, 2] []
The first list(g) used the values up, so the second gets nothing. A function that walks a generator twice sees an empty second pass.
In the editor, write worth_reading(files). files holds (path, size) pairs, and it may be a generator that you can walk only once. Return the paths whose size at least one other file shares, in the order they came.