by klipt · 3y ago · 0 comments
> Use reservoir sampling to get 100 random lines from a dictionary that doesn’t fit into memory. Give me an implementation in Python.
> Reservoir sampling is a great choice for randomly selecting a fixed number of items from a stream of unknown size, especially when the entire dataset cannot fit into memory. Here's a Python implementation for selecting 100 random lines from a large file, like a dictionary, using reservoir sampling:
```python
import random
def reservoir_sampling(file_name, k):
reservoir = []
with open(file_name, 'r') as file:
for i, line in enumerate(file):
if i < k:
# Fill the reservoir array
reservoir.append(line.strip())
else:
# Randomly replace elements in the reservoir
# with a decreasing probability.
# Choose an integer between 0 and i (inclusive)
j = random.randint(0, i)
if j < k:
reservoir[j] = line.strip()
return reservoir
# Example usage
file_path = 'path_to_your_large_file.txt' # Replace with your file path
sampled_lines = reservoir_sampling(file_path, 100)
print(sampled_lines)
```
> This script opens a file and reads through it line by line. For the first 100 lines, it adds them directly to the reservoir. For each subsequent line, it randomly decides whether to replace an existing line in the reservoir with the new line. The probability of replacing decreases as it progresses through the file, ensuring each line has an equal chance of being included in the final sample.I laid out the constraints, but I did not mention reservoir sampling at all. The script seems to work as expected when I run it against a dictionary file.
Can you use random access into the file to sample k lines in O(k) time instead of O(n) time?
Here is the provided solution and some discussion of the problems with the problem itself: https://chat.openai.com/share/54807663-17ca-4e7d-bc76-cd3cf3...
I'd prefer to think it's more like a real engineering problem, and less like a simple interview question :-)
And it definitely shows the limits of GPT here: it pointed out that the ends of the file might be tricky, but ignored the very conceptually simple solution of considering the file as circular (if you go past either end you simply wrap around).
And it misses the real problem with its implementation: the probability of sampling each line is now directly proportional to the length of the line before it (because it seeks into that line first and then skips it!)
So the word after "begins" is twice as likely to come up as the word after "and".
PS in the case of dictionary words with a length limit of say 30 letters, there is still an O(k) general solution using rejection sampling.