


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







class     _lowercase				(							lowercase__):


       """simple docstring"""




       def __init__(     self							:    Optional[int] ):


             '''simple docstring'''



             self.test()





       def 		lowerCAmelCase  (     self							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						0
             lowerCamelCase__	:       List[Any]					=						False
             while not completed:
                   if counter == 1:
                         self.reset()
                   lowerCamelCase__	:       List[str]					=						self.advance()
                   if not self.does_advance(__lowerCamelCase ):
                         raise Exception(
                             "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true." )

                   lowerCamelCase__					,     lowerCamelCase__					,     lowerCamelCase__	:       Dict					=						self.update(__lowerCamelCase )
                   counter += 1

                   if counter > 10000:
                         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[Any] ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )





       @abstractmethod
       def 		lowerCAmelCase  (     self							:    List[Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )





       @abstractmethod
       def 		lowerCAmelCase  (     self							:    Any      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )





       @abstractmethod
       def 		lowerCAmelCase  (     self							:    List[Any] ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )





       @abstractmethod
       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )





       @abstractmethod
       def 		lowerCAmelCase  (     self							:    Tuple      ,   __lowerCamelCase							:    Any=False ):


             '''simple docstring'''



             raise NotImplementedError(
                 f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )







class     _lowercase				(							lowercase__):


       """simple docstring"""




       def __init__(     self							:    Optional[int]      ,   __lowerCamelCase							:    List[int] ):


             '''simple docstring'''



             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}." )

             lowerCamelCase__	:       Optional[Any]					=						token_ids

             lowerCamelCase__	:       int					=						len(self.token_ids )
             lowerCamelCase__	:       Tuple					=						-1  # the index of the currently fulfilled step
             lowerCamelCase__	:       Any					=						False





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             if self.completed:
                   return None
             return self.token_ids[self.fulfilled_idx + 1]





       def 		lowerCAmelCase  (     self							:    Union[str, Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             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							:    List[Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             if not isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                   raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}" )

             lowerCamelCase__	:       List[str]					=						False
             lowerCamelCase__	:       Any					=						False
             lowerCamelCase__	:       Union[str, Any]					=						False

             if self.does_advance(__lowerCamelCase ):
                   self.fulfilled_idx += 1
                   lowerCamelCase__	:       Dict					=						True
                   if self.fulfilled_idx == (self.seqlen - 1):
                         lowerCamelCase__	:       Union[str, Any]					=						True
                   lowerCamelCase__	:       Any					=						completed
             else:
                   # failed to make progress.
                   lowerCamelCase__	:       Dict					=						True
                   self.reset()
             return stepped, completed, reset





       def 		lowerCAmelCase  (     self							:    int ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						False
             lowerCamelCase__	:       int					=						0





       def 		lowerCAmelCase  (     self							:    List[Any] ):


             '''simple docstring'''



             return self.seqlen - (self.fulfilled_idx + 1)





       def 		lowerCAmelCase  (     self							:    List[str]      ,   __lowerCamelCase							:    List[Any]=False ):


             '''simple docstring'''



             lowerCamelCase__	:       Dict					=						PhrasalConstraint(self.token_ids )

             if stateful:
                   lowerCamelCase__	:       Any					=						self.seqlen
                   lowerCamelCase__	:       str					=						self.fulfilled_idx
                   lowerCamelCase__	:       List[Any]					=						self.completed

             return new_constraint







class     _lowercase				:


       """simple docstring"""




       def __init__(     self							:    Optional[int]      ,   __lowerCamelCase							:    List[List[int]]      ,   __lowerCamelCase							:    Optional[int]=True ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						max([len(__lowerCamelCase ) for one in nested_token_ids] )

             lowerCamelCase__	:       Optional[int]					=						{}
             for token_ids in nested_token_ids:
                   lowerCamelCase__	:       int					=						root
                   for tidx, token_id in enumerate(__lowerCamelCase ):
                         if token_id not in level:
                               lowerCamelCase__	:       List[str]					=						{}

                         lowerCamelCase__	:       Any					=						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}." )

             lowerCamelCase__	:       str					=						root





       def 		lowerCAmelCase  (     self							:    List[Any]      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Dict					=						self.trie

             for current_token in current_seq:
                   lowerCamelCase__	:       List[str]					=						start[current_token]

             lowerCamelCase__	:       List[Any]					=						list(start.keys() )

             return next_tokens





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						self.next_tokens(__lowerCamelCase )

             return len(__lowerCamelCase ) == 0





       def 		lowerCAmelCase  (     self							:    List[Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						list(root.values() )
             if len(__lowerCamelCase ) == 0:
                   return 1
             else:
                   return sum([self.count_leaves(__lowerCamelCase ) for nn in next_nodes] )





       def 		lowerCAmelCase  (     self							:    int      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    str ):


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						self.count_leaves(__lowerCamelCase )
             return len(__lowerCamelCase ) != leaf_count







class     _lowercase				(							lowercase__):


       """simple docstring"""




       def __init__(     self							:    str      ,   __lowerCamelCase							:    List[List[int]] ):


             '''simple docstring'''



             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}." )

             lowerCamelCase__	:       int					=						DisjunctiveTrie(__lowerCamelCase )
             lowerCamelCase__	:       Union[str, Any]					=						nested_token_ids

             lowerCamelCase__	:       Tuple					=						self.trie.max_height
             lowerCamelCase__	:       str					=						[]
             lowerCamelCase__	:       Optional[int]					=						False





       def 		lowerCAmelCase  (     self							:    List[Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						self.trie.next_tokens(self.current_seq )

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





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             if not isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                   raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}" )

             lowerCamelCase__	:       Union[str, Any]					=						self.trie.next_tokens(self.current_seq )

             return token_id in next_tokens





       def 		lowerCAmelCase  (     self							:    Optional[Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             if not isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                   raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}" )

             lowerCamelCase__	:       List[Any]					=						False
             lowerCamelCase__	:       List[Any]					=						False
             lowerCamelCase__	:       Optional[Any]					=						False

             if self.does_advance(__lowerCamelCase ):
                   self.current_seq.append(__lowerCamelCase )
                   lowerCamelCase__	:       Union[str, Any]					=						True
             else:
                   lowerCamelCase__	:       Tuple					=						True
                   self.reset()

             lowerCamelCase__	:       int					=						self.trie.reached_leaf(self.current_seq )
             lowerCamelCase__	:       Tuple					=						completed

             return stepped, completed, reset





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						False
             lowerCamelCase__	:       List[str]					=						[]





       def 		lowerCAmelCase  (     self							:    int ):


             '''simple docstring'''



             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							:    Dict      ,   __lowerCamelCase							:    Dict=False ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						DisjunctiveConstraint(self.token_ids )

             if stateful:
                   lowerCamelCase__	:       List[str]					=						self.seqlen
                   lowerCamelCase__	:       List[str]					=						self.current_seq
                   lowerCamelCase__	:       Optional[Any]					=						self.completed

             return new_constraint







class     _lowercase				:


       """simple docstring"""




       def __init__(     self							:    List[str]      ,   __lowerCamelCase							:    List[Constraint] ):


             '''simple docstring'''



             lowerCamelCase__	:       Dict					=						constraints

             # max # of steps required to fulfill a given constraint
             lowerCamelCase__	:       List[Any]					=						max([c.seqlen for c in constraints] )
             lowerCamelCase__	:       List[str]					=						len(__lowerCamelCase )
             lowerCamelCase__	:       List[str]					=						False

             self.init_state()





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						[]
             lowerCamelCase__	:       List[str]					=						None
             lowerCamelCase__	:       Tuple					=						[constraint.copy(stateful=__lowerCamelCase ) for constraint in self.constraints]





       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       str					=						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							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       str					=						[]
             if self.inprogress_constraint is None:
                   for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                         lowerCamelCase__	:       List[Any]					=						constraint.advance()
                         if isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                               token_list.append(__lowerCamelCase )
                         elif isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                               token_list.extend(__lowerCamelCase )
             else:
                   lowerCamelCase__	:       List[Any]					=						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							:    Union[str, Any]      ,   __lowerCamelCase							:    Optional[List[int]] ):


             '''simple docstring'''



             self.init_state()

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

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





       def 		lowerCAmelCase  (     self							:    Any      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             if not isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                   raise ValueError(f"`token_id` should be an `int`, but is `{token_id}`." )

             lowerCamelCase__					,     lowerCamelCase__	:       Optional[Any]					=						False, False

             if self.completed:
                   lowerCamelCase__	:       List[Any]					=						True
                   lowerCamelCase__	:       List[Any]					=						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

                   lowerCamelCase__					,     lowerCamelCase__					,     lowerCamelCase__	:       List[Any]					=						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 ) )
                         lowerCamelCase__	:       Optional[int]					=						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 )
                         lowerCamelCase__	:       Any					=						None

                         if len(self.pending_constraints ) == 0:
                               # we're done!
                               lowerCamelCase__	:       Any					=						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 ):
                               lowerCamelCase__					,     lowerCamelCase__					,     lowerCamelCase__	:       Dict					=						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 )
                                     lowerCamelCase__	:       Union[str, Any]					=						None

                               if not complete and stepped:
                                     lowerCamelCase__	:       Dict					=						pending_constraint

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

                                     lowerCamelCase__	:       List[Any]					=						(
                                         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.

                                           lowerCamelCase__	:       Union[str, Any]					=						True

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

             return complete, stepped





       def 		lowerCAmelCase  (     self							:    Union[str, Any]      ,   __lowerCamelCase							:    Optional[Any]=True ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						ConstraintListState(self.constraints )  # we actually never though self.constraints objects
             # throughout this process. So it's at initialization state.

             if stateful:
                   lowerCamelCase__	:       Any					=						[
                       constraint.copy(stateful=__lowerCamelCase ) for constraint in self.complete_constraints
                   ]
                   if self.inprogress_constraint is not None:
                         lowerCamelCase__	:       List[Any]					=						self.inprogress_constraint.copy(stateful=__lowerCamelCase )
                   lowerCamelCase__	:       Any					=						[constraint.copy() for constraint in self.pending_constraints]

             return new_state






def    lowercase_	(	_A    :					int		):

      """simple docstring"""




      if not isinstance(_A					,      _A		):
            lowerCamelCase__	:       List[str]					=						F"Input value of [number={number}] must be an integer"
            raise TypeError(_A		)
      if number < 0:
            return False
      lowerCamelCase__	:       Dict					=						number * number
      while number > 0:
            if number % 10 != number_square % 10:
                  return False
            number //= 10
            number_square //= 10
      return True


if __name__ == "__main__":
    import doctest

    doctest.testmod()


