Solution: Taking
from coursepy.funcy.utils import proc, first, rest
from coursepy.typing import Pred, Fn, Sequence
def takewhile[T](alive: Pred[T], seq: Sequence[T], invert: bool = False, debug: bool = False) -> Sequence[T]:
"""Return items from seq while alive(item) is true."""
def shift(state: tuple[Sequence[T], Sequence[T]]) -> tuple[Sequence[T], Sequence[T]]:
return (*state[0], state[1][0]), state[1][1:]
def alive_state(state: tuple[Sequence[T], Sequence[T]]) -> bool:
return alive(state[1][0])
return proc(([],seq), alive_state, shift, debug=debug)[int(invert)]
takewhile(lambda x: x < 5, [1,2,3,4,5,6,7])
(1, 2, 3, 4)
takewhile(lambda x: x < 5, [1,2,3,4,5,6,7], invert=True)
[5, 6, 7]
takewhile(lambda x: x < 5, [1,2,3,4,5,6,7], debug=True)
Starting process with: ([], [1, 2, 3, 4, 5, 6, 7])
((1,), [2, 3, 4, 5, 6, 7])
((1, 2), [3, 4, 5, 6, 7])
((1, 2, 3), [4, 5, 6, 7])
((1, 2, 3, 4), [5, 6, 7])
(1, 2, 3, 4)
takewhile(lambda x: x < 5, [1,2,3,4,5,6,7], invert=True, debug=True)
Starting process with: ([], [1, 2, 3, 4, 5, 6, 7])
((1,), [2, 3, 4, 5, 6, 7])
((1, 2), [3, 4, 5, 6, 7])
((1, 2, 3), [4, 5, 6, 7])
((1, 2, 3, 4), [5, 6, 7])
[5, 6, 7]