Something went wrong. Try again.
CMU Coding Bootcamp
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041from typing import List, Optional, TypeVar
T = TypeVar("T")
def repeatingPattern(L: List[T]) -> Optional[List[T]]: """Returns the smallest repeating pattern of a list or None if no pattern exists.""" if len(L) < 2: return None repeat_options = list( reversed([i for i in range(2, max(len(L) // 2 + 1, 3)) if len(L) % i == 0]) ) M = [L[0]] for repeat in repeat_options: M = L[: len(L) // repeat] if M * repeat == L: return M if len(M) > len(L): return None return None
print("Testing repeatingPattern()...", end="")assert repeatingPattern([1, 2, 1, 2]) == [1, 2]assert repeatingPattern([1, 2, 1, 2, 1, 2, 1, 2]) == [1, 2]assert repeatingPattern([1, 2, 3, 1, 2, 3]) == [1, 2, 3]assert repeatingPattern([1, 1]) == [1]assert repeatingPattern([]) == Noneassert repeatingPattern([42]) == Noneassert repeatingPattern([1, 2, 3, 1, 2]) == Noneassert repeatingPattern([121, 212, 12]) == NoneL = [1, 2, 3, 4]assert repeatingPattern(L * 20) == L
# Finally, verify that the function is non-mutatingL = [1, 2, 1, 2]repeatingPattern(L)assert L == [1, 2, 1, 2]print("Passed!")