"""simple docstring"""


from abc import ABC, abstractmethod
from typing import List, Optional


class 				a (						lowerCAmelCase_      ):


    def __init__(    self		:     List[str]    ):
      # test for the above condition
      self.test()


    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      _UpperCAmelCase         =					0
      _UpperCAmelCase         =					False
      while not completed:
        if counter == 1:
          self.reset()
        _UpperCAmelCase         =					self.advance()
        if not self.does_advance(__lowerCAmelCase    ):
          raise Exception(
              """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."""    )

        _UpperCAmelCase       , _UpperCAmelCase       , _UpperCAmelCase         =					self.update(__lowerCAmelCase    )
        counter += 1

        if counter > 1_0000:
          raise Exception("""update() does not fulfill the constraint."""    )

      if self.remaining() != 0:
        raise Exception("""Custom Constraint is not defined correctly."""    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     List[str]    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     int      , __lowerCAmelCase		:     int    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     int    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     List[str]    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     Any    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


    @abstractmethod
    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     Optional[Any]=False    ):
      raise NotImplementedError(
          f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )



class 				a (						lowerCAmelCase_      ):


    def __init__(    self		:     Any      , __lowerCAmelCase		:     List[int]    ):
      super(__lowerCAmelCase      , self    ).__init__()

      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) or len(__lowerCAmelCase    ) == 0:
        raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.'''    )
      if any((not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) or token_id < 0) for token_id in token_ids    ):
        raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''    )

      _UpperCAmelCase         =					token_ids

      _UpperCAmelCase         =					len(self.token_ids    )
      _UpperCAmelCase         =					-1  # the index of the currently fulfilled step
      _UpperCAmelCase         =					False


    def    lowerCAmelCase_     (    self		:     List[Any]    ):
      if self.completed:
        return None
      return self.token_ids[self.fulfilled_idx + 1]


    def    lowerCAmelCase_     (    self		:     Dict      , __lowerCAmelCase		:     int    ):
      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase    )}'''    )

      if self.completed:
        return False

      return token_id == self.token_ids[self.fulfilled_idx + 1]


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     int    ):
      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase    )}'''    )

      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					False

      if self.does_advance(__lowerCAmelCase    ):
        self.fulfilled_idx += 1
        _UpperCAmelCase         =					True
        if self.fulfilled_idx == (self.seqlen - 1):
          _UpperCAmelCase         =					True
        _UpperCAmelCase         =					completed
      else:
        # failed to make progress.
        _UpperCAmelCase         =					True
        self.reset()
      return stepped, completed, reset


    def    lowerCAmelCase_     (    self		:     Union[str, Any]    ):
      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					0


    def    lowerCAmelCase_     (    self		:     Any    ):
      return self.seqlen - (self.fulfilled_idx + 1)


    def    lowerCAmelCase_     (    self		:     Any      , __lowerCAmelCase		:     Tuple=False    ):
      _UpperCAmelCase         =					PhrasalConstraint(self.token_ids    )

      if stateful:
        _UpperCAmelCase         =					self.seqlen
        _UpperCAmelCase         =					self.fulfilled_idx
        _UpperCAmelCase         =					self.completed

      return new_constraint



class 				a :


    def __init__(    self		:     List[str]      , __lowerCAmelCase		:     List[List[int]]      , __lowerCAmelCase		:     int=True    ):
      _UpperCAmelCase         =					max([len(__lowerCAmelCase    ) for one in nested_token_ids]    )

      _UpperCAmelCase         =					{}
      for token_ids in nested_token_ids:
        _UpperCAmelCase         =					root
        for tidx, token_id in enumerate(__lowerCAmelCase    ):
          if token_id not in level:
            _UpperCAmelCase         =					{}

          _UpperCAmelCase         =					level[token_id]

      if no_subsets and self.has_subsets(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(
            """Each list in `nested_token_ids` can't be a complete subset of another list, but is"""
            f''' {nested_token_ids}.'''    )

      _UpperCAmelCase         =					root


    def    lowerCAmelCase_     (    self		:     str      , __lowerCAmelCase		:     Dict    ):
      _UpperCAmelCase         =					self.trie

      for current_token in current_seq:
        _UpperCAmelCase         =					start[current_token]

      _UpperCAmelCase         =					list(start.keys()    )

      return next_tokens


    def    lowerCAmelCase_     (    self		:     List[Any]      , __lowerCAmelCase		:     Tuple    ):
      _UpperCAmelCase         =					self.next_tokens(__lowerCAmelCase    )

      return len(__lowerCAmelCase    ) == 0


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     Dict    ):
      _UpperCAmelCase         =					list(root.values()    )
      if len(__lowerCAmelCase    ) == 0:
        return 1
      else:
        return sum([self.count_leaves(__lowerCAmelCase    ) for nn in next_nodes]    )


    def    lowerCAmelCase_     (    self		:     str      , __lowerCAmelCase		:     List[Any]      , __lowerCAmelCase		:     Optional[int]    ):
      _UpperCAmelCase         =					self.count_leaves(__lowerCAmelCase    )
      return len(__lowerCAmelCase    ) != leaf_count



class 				a (						lowerCAmelCase_      ):


    def __init__(    self		:     str      , __lowerCAmelCase		:     List[List[int]]    ):
      super(__lowerCAmelCase      , self    ).__init__()

      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) or len(__lowerCAmelCase    ) == 0:
        raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''    )
      if any(not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) for token_ids in nested_token_ids    ):
        raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''    )
      if any(
          any((not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ) or token_id < 0) for token_id in token_ids    )
          for token_ids in nested_token_ids    ):
        raise ValueError(
            f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''    )

      _UpperCAmelCase         =					DisjunctiveTrie(__lowerCAmelCase    )
      _UpperCAmelCase         =					nested_token_ids

      _UpperCAmelCase         =					self.trie.max_height
      _UpperCAmelCase         =					[]
      _UpperCAmelCase         =					False


    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					self.trie.next_tokens(self.current_seq    )

      if len(__lowerCAmelCase    ) == 0:
        return None
      else:
        return token_list


    def    lowerCAmelCase_     (    self		:     Union[str, Any]      , __lowerCAmelCase		:     int    ):
      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase    )}'''    )

      _UpperCAmelCase         =					self.trie.next_tokens(self.current_seq    )

      return token_id in next_tokens


    def    lowerCAmelCase_     (    self		:     int      , __lowerCAmelCase		:     int    ):
      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase    )}'''    )

      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					False

      if self.does_advance(__lowerCAmelCase    ):
        self.current_seq.append(__lowerCAmelCase    )
        _UpperCAmelCase         =					True
      else:
        _UpperCAmelCase         =					True
        self.reset()

      _UpperCAmelCase         =					self.trie.reached_leaf(self.current_seq    )
      _UpperCAmelCase         =					completed

      return stepped, completed, reset


    def    lowerCAmelCase_     (    self		:     Tuple    ):
      _UpperCAmelCase         =					False
      _UpperCAmelCase         =					[]


    def    lowerCAmelCase_     (    self		:     int    ):
      if self.completed:
        # since this can be completed without reaching max height
        return 0
      else:
        return self.seqlen - len(self.current_seq    )


    def    lowerCAmelCase_     (    self		:     Optional[Any]      , __lowerCAmelCase		:     Any=False    ):
      _UpperCAmelCase         =					DisjunctiveConstraint(self.token_ids    )

      if stateful:
        _UpperCAmelCase         =					self.seqlen
        _UpperCAmelCase         =					self.current_seq
        _UpperCAmelCase         =					self.completed

      return new_constraint



class 				a :


    def __init__(    self		:     Optional[int]      , __lowerCAmelCase		:     List[Constraint]    ):
      _UpperCAmelCase         =					constraints

      # max # of steps required to fulfill a given constraint
      _UpperCAmelCase         =					max([c.seqlen for c in constraints]    )
      _UpperCAmelCase         =					len(__lowerCAmelCase    )
      _UpperCAmelCase         =					False

      self.init_state()


    def    lowerCAmelCase_     (    self		:     str    ):
      _UpperCAmelCase         =					[]
      _UpperCAmelCase         =					None
      _UpperCAmelCase         =					[constraint.copy(stateful=__lowerCAmelCase    ) for constraint in self.constraints]


    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					0
      if self.inprogress_constraint:
        # extra points for having a constraint mid-fulfilled
        add += self.max_seqlen - self.inprogress_constraint.remaining()

      return (len(self.complete_constraints    ) * self.max_seqlen) + add


    def    lowerCAmelCase_     (    self		:     Optional[Any]    ):
      _UpperCAmelCase         =					[]
      if self.inprogress_constraint is None:
        for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
          _UpperCAmelCase         =					constraint.advance()
          if isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
            token_list.append(__lowerCAmelCase    )
          elif isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
            token_list.extend(__lowerCAmelCase    )
      else:
        _UpperCAmelCase         =					self.inprogress_constraint.advance()
        if isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
          token_list.append(__lowerCAmelCase    )
        elif isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
          token_list.extend(__lowerCAmelCase    )

      if len(__lowerCAmelCase    ) == 0:
        return None
      else:
        return token_list


    def    lowerCAmelCase_     (    self		:     Optional[int]      , __lowerCAmelCase		:     Optional[List[int]]    ):
      self.init_state()

      if token_ids is not None:
        for token in token_ids:
          # completes or steps **one** constraint
          _UpperCAmelCase       , _UpperCAmelCase         =					self.add(__lowerCAmelCase    )

          # the entire list of constraints are fulfilled
          if self.completed:
            break


    def    lowerCAmelCase_     (    self		:     Dict      , __lowerCAmelCase		:     int    ):
      if not isinstance(__lowerCAmelCase      , __lowerCAmelCase    ):
        raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.'''    )

      _UpperCAmelCase       , _UpperCAmelCase         =					False, False

      if self.completed:
        _UpperCAmelCase         =					True
        _UpperCAmelCase         =					False
        return complete, stepped

      if self.inprogress_constraint is not None:
        # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
        # job, simply update the state

        _UpperCAmelCase       , _UpperCAmelCase       , _UpperCAmelCase         =					self.inprogress_constraint.update(__lowerCAmelCase    )
        if reset:
          # 1. If the next token breaks the progress, then we must restart.
          #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

          #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
          #     constraint, not the full list of constraints.

          self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCAmelCase    )    )
          _UpperCAmelCase         =					None

        if complete:
          # 2. If the next token completes the constraint, move it to completed list, set
          #     inprogress to None. If there are no pending constraints either, then this full list of constraints
          #     is complete.

          self.complete_constraints.append(self.inprogress_constraint    )
          _UpperCAmelCase         =					None

          if len(self.pending_constraints    ) == 0:
            # we're done!
            _UpperCAmelCase         =					True

      else:
        # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
        # of constraints?

        for cidx, pending_constraint in enumerate(self.pending_constraints    ):
          if pending_constraint.does_advance(__lowerCAmelCase    ):
            _UpperCAmelCase       , _UpperCAmelCase       , _UpperCAmelCase         =					pending_constraint.update(__lowerCAmelCase    )

            if not stepped:
              raise Exception(
                  """`constraint.update(token_id)` is not yielding incremental progress, """
                  """even though `constraint.does_advance(token_id)` is true."""    )

            if complete:
              self.complete_constraints.append(__lowerCAmelCase    )
              _UpperCAmelCase         =					None

            if not complete and stepped:
              _UpperCAmelCase         =					pending_constraint

            if complete or stepped:
              # If we made any progress at all, then it's at least not a "pending constraint".

              _UpperCAmelCase         =					(
                  self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
              )

              if len(self.pending_constraints    ) == 0 and self.inprogress_constraint is None:
                # If there's no longer any pending after this and no inprogress either, then we must be
                # complete.

                _UpperCAmelCase         =					True

              break  # prevent accidentally stepping through multiple constraints with just one token.

      return complete, stepped


    def    lowerCAmelCase_     (    self		:     Dict      , __lowerCAmelCase		:     List[Any]=True    ):
      _UpperCAmelCase         =					ConstraintListState(self.constraints    )  # we actually never though self.constraints objects
      # throughout this process. So it's at initialization state.

      if stateful:
        _UpperCAmelCase         =					[
            constraint.copy(stateful=__lowerCAmelCase    ) for constraint in self.complete_constraints
        ]
        if self.inprogress_constraint is not None:
          _UpperCAmelCase         =					self.inprogress_constraint.copy(stateful=__lowerCAmelCase    )
        _UpperCAmelCase         =					[constraint.copy() for constraint in self.pending_constraints]

      return new_state

"""simple docstring"""


from __future__ import annotations






def 			__UpperCAmelCase    (	lowercase      ,lowercase						):







  """simple docstring"""
  _UpperCAmelCase         =					get_failure_array(lowercase						)

  # 2) Step through text searching for pattern
  _UpperCAmelCase       , _UpperCAmelCase         =					0, 0  # index into text, pattern
  while i < len(lowercase						):
    if pattern[j] == text[i]:
      if j == (len(lowercase						) - 1):
        return True
      j += 1

    # if this is a prefix in our pattern
    # just go back far enough to continue
    elif j > 0:
      _UpperCAmelCase         =					failure[j - 1]
      continue
    i += 1
  return False






def 			__UpperCAmelCase    (	lowercase						):







  """simple docstring"""
  _UpperCAmelCase         =					[0]
  _UpperCAmelCase         =					0
  _UpperCAmelCase         =					1
  while j < len(lowercase						):
    if pattern[i] == pattern[j]:
      i += 1
    elif i > 0:
      _UpperCAmelCase         =					failure[i - 1]
      continue
    j += 1
    failure.append(lowercase						)
  return failure


if __name__ == "__main__":
    # Test 1)
    UpperCAmelCase__     						=  """abc1abc12"""
    UpperCAmelCase__     						=  """alskfjaldsabc1abc1abc12k23adsfabcabc"""
    UpperCAmelCase__     						=  """alskfjaldsk23adsfabcabc"""
    assert kmp(pattern, texta) and not kmp(pattern, texta)

    # Test 2)
    UpperCAmelCase__     						=  """ABABX"""
    UpperCAmelCase__     						=  """ABABZABABYABABX"""
    assert kmp(pattern, text)

    # Test 3)
    UpperCAmelCase__     						=  """AAAB"""
    UpperCAmelCase__     						=  """ABAAAAAB"""
    assert kmp(pattern, text)

    # Test 4)
    UpperCAmelCase__     						=  """abcdabcy"""
    UpperCAmelCase__     						=  """abcxabcdabxabcdabcdabcy"""
    assert kmp(pattern, text)

    # Test 5)
    UpperCAmelCase__     						=  """aabaabaaa"""
    assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
