Implement repeated, which takes in an iterator t and returns the first value in t that appears k times in a row.
时间: 2024-02-25 15:51:33 浏览: 85
Sure, here's a possible implementation of the `repeated` function in Python:
```python
def repeated(t, k):
last = None
count = 0
for item in t:
if item == last:
count += 1
else:
last = item
count = 1
if count == k:
return item
return None
```
The `repeated` function takes two arguments: `t` is the iterator we want to search for repeated values, and `k` is the number of times a value must appear in a row to be considered repeated. The function initializes a `last` variable to `None` to keep track of the last value seen, and a `count` variable to 0 to keep track of the number of times the last value has been seen in a row. The function iterates over the items in `t` and updates the `last` and `count` variables accordingly. If the `count` variable reaches `k`, the function returns the current item (i.e., we have found a repeated value). If we reach the end of the iterator without finding a repeated value, the function returns `None`.
For example, we can use the function like this:
```python
it = iter([1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5])
print(repeated(it, 3)) # Output: 3
```
In this example, we create an iterator `it` over a list with repeated values. We then call `repeated(it, 3)` to search for a value that appears 3 times in a row, and it returns 3.
阅读全文