Your task is to implement a class that maintains a list of numbers and has an efficient method that reports if some number occurs more than once on the list.
In a file repeatlist.py
, implement the class RepeatList
with the following methods:
append(number)
: add a number to the end of the listrepeat()
: returnTrue
if some number repeats on the list, otherwise returnFalse
Both methods should work in time
class RepeatList: def __init__(self): # TODO def append(self, number): # TODO def repeat(self): # TODO if __name__ == "__main__": numbers = RepeatList() print(numbers.repeat()) # False numbers.append(1) numbers.append(2) numbers.append(3) print(numbers.repeat()) # False numbers.append(2) print(numbers.repeat()) # True numbers.append(5) print(numbers.repeat()) # True
Here the numbers , and are first added to the list so that the list content is and there is no repeating number. Then the number is added to the list resulting in the content with a repeat of the number . Finally, the number is added resulting in the content with the number still repeating.
You can test the efficiency of your solution with the following code. In this case too the code should finish almost immediately.
numbers = RepeatList() total = 0 for i in range(10**5): numbers.append(i * 999983 % 12345) if numbers.repeat(): total += 1 print(total) # 87655