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






class      __lowercase					(    _A    ):

						def __init__(	self				:      Tuple   )							->		Union[str, Any]:


									'''simple docstring'''

									self.test()

						def        __a		(	self				:      int   )							->		Union[str, Any]:


									'''simple docstring'''

									lowercase							=		0
									lowercase							=		False
									while not completed:
												if counter == 1:
															self.reset()
												lowercase							=		self.advance()
												if not self.does_advance(__lowerCamelCase   ):
															raise Exception(
															    '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'''   )

												lowercase		,lowercase		,lowercase							=		self.update(__lowerCamelCase   )
												counter += 1

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

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

						@abstractmethod
						def        __a		(	self				:      Tuple   )							->		str:


									'''simple docstring'''

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

						@abstractmethod
						def        __a		(	self				:      Optional[int]							,							__lowerCamelCase				:      int   )							->		List[Any]:


									'''simple docstring'''

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

						@abstractmethod
						def        __a		(	self				:      Any							,							__lowerCamelCase				:      int   )							->		Optional[Any]:


									'''simple docstring'''

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

						@abstractmethod
						def        __a		(	self				:      Tuple   )							->		int:


									'''simple docstring'''

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

						@abstractmethod
						def        __a		(	self				:      Dict   )							->		Optional[int]:


									'''simple docstring'''

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



						@abstractmethod
						def        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      List[Any]=False   )							->		Union[str, Any]:


									'''simple docstring'''

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






class      __lowercase					(    _A    ):

						def __init__(	self				:      Any							,							__lowerCamelCase				:      List[int]   )							->		Tuple:


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

									lowercase							=		token_ids

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

						def        __a		(	self				:      int   )							->		str:


									'''simple docstring'''

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

						def        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      int   )							->		List[str]:


									'''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        __a		(	self				:      Tuple							,							__lowerCamelCase				:      int   )							->		Optional[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   )}'   )

									lowercase							=		False
									lowercase							=		False
									lowercase							=		False

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

						def        __a		(	self				:      str   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		False
									lowercase							=		0

						def        __a		(	self				:      str   )							->		List[str]:


									'''simple docstring'''

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



						def        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      Optional[Any]=False   )							->		Optional[Any]:


									'''simple docstring'''

									lowercase							=		PhrasalConstraint(self.token_ids   )

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

									return new_constraint






class      __lowercase					:

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


									'''simple docstring'''

									lowercase							=		max([len(__lowerCamelCase   ) for one in nested_token_ids]   )

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

															lowercase							=		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}.'   )

									lowercase							=		root

						def        __a		(	self				:      str							,							__lowerCamelCase				:      Dict   )							->		int:


									'''simple docstring'''

									lowercase							=		self.trie

									for current_token in current_seq:
												lowercase							=		start[current_token]

									lowercase							=		list(start.keys()   )

									return next_tokens

						def        __a		(	self				:      Dict							,							__lowerCamelCase				:      Optional[Any]   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		self.next_tokens(__lowerCamelCase   )

									return len(__lowerCamelCase   ) == 0

						def        __a		(	self				:      List[str]							,							__lowerCamelCase				:      Union[str, Any]   )							->		Tuple:


									'''simple docstring'''

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



						def        __a		(	self				:      Dict							,							__lowerCamelCase				:      Optional[int]							,							__lowerCamelCase				:      Tuple   )							->		Union[str, Any]:


									'''simple docstring'''

									lowercase							=		self.count_leaves(__lowerCamelCase   )
									return len(__lowerCamelCase   ) != leaf_count






class      __lowercase					(    _A    ):

						def __init__(	self				:      Tuple							,							__lowerCamelCase				:      List[List[int]]   )							->		Union[str, Any]:


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

									lowercase							=		DisjunctiveTrie(__lowerCamelCase   )
									lowercase							=		nested_token_ids

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

						def        __a		(	self				:      int   )							->		Any:


									'''simple docstring'''

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

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

						def        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      int   )							->		Any:


									'''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   )}'   )

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

									return token_id in next_tokens

						def        __a		(	self				:      Tuple							,							__lowerCamelCase				:      int   )							->		Tuple:


									'''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   )}'   )

									lowercase							=		False
									lowercase							=		False
									lowercase							=		False

									if self.does_advance(__lowerCamelCase   ):
												self.current_seq.append(__lowerCamelCase   )
												lowercase							=		True
									else:
												lowercase							=		True
												self.reset()

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

									return stepped, completed, reset

						def        __a		(	self				:      Dict   )							->		str:


									'''simple docstring'''

									lowercase							=		False
									lowercase							=		[]

						def        __a		(	self				:      List[str]   )							->		Dict:


									'''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        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      Any=False   )							->		List[str]:


									'''simple docstring'''

									lowercase							=		DisjunctiveConstraint(self.token_ids   )

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

									return new_constraint






class      __lowercase					:

						def __init__(	self				:      Union[str, Any]							,							__lowerCamelCase				:      List[Constraint]   )							->		Any:


									'''simple docstring'''

									lowercase							=		constraints

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

									self.init_state()

						def        __a		(	self				:      Optional[int]   )							->		List[str]:


									'''simple docstring'''

									lowercase							=		[]
									lowercase							=		None
									lowercase							=		[constraint.copy(stateful=__lowerCamelCase   ) for constraint in self.constraints]

						def        __a		(	self				:      str   )							->		Any:


									'''simple docstring'''

									lowercase							=		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        __a		(	self				:      Tuple   )							->		Tuple:


									'''simple docstring'''

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


									'''simple docstring'''

									self.init_state()

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

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

						def        __a		(	self				:      List[str]							,							__lowerCamelCase				:      int   )							->		Union[str, Any]:


									'''simple docstring'''

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

									lowercase		,lowercase							=		False, False

									if self.completed:
												lowercase							=		True
												lowercase							=		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

												lowercase		,lowercase		,lowercase							=		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   )   )
															lowercase							=		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   )
															lowercase							=		None

															if len(self.pending_constraints   ) == 0:
																		# we're done!
																		lowercase							=		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   ):
																		lowercase		,lowercase		,lowercase							=		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   )
																					lowercase							=		None

																		if not complete and stepped:
																					lowercase							=		pending_constraint

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

																					lowercase							=		(
																					    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.

																								lowercase							=		True

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

									return complete, stepped



						def        __a		(	self				:      Tuple							,							__lowerCamelCase				:      int=True   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		ConstraintListState(self.constraints   )  # we actually never though self.constraints objects
									# throughout this process. So it's at initialization state.

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

									return new_state






from __future__ import annotations

from collections.abc import MutableSequence






class      __lowercase					:

						def __init__(	self				:      Optional[Any]							,							__lowerCamelCase				:      int							,							__lowerCamelCase				:      MutableSequence[float]   )							->		None:


									'''simple docstring'''

									if len(__lowerCamelCase   ) != degree + 1:
												raise ValueError(
												    '''The number of coefficients should be equal to the degree + 1.'''   )

									lowercase							=		list(__lowerCamelCase   )
									lowercase							=		degree

						def __add__(	self				:      Any							,							__lowerCamelCase				:      Polynomial   )							->		Polynomial:


									'''simple docstring'''

									if self.degree > polynomial_a.degree:
												lowercase							=		self.coefficients[:]
												for i in range(polynomial_a.degree + 1   ):
															coefficients[i] += polynomial_a.coefficients[i]
												return Polynomial(self.degree							,							__lowerCamelCase   )
									else:
												lowercase							=		polynomial_a.coefficients[:]
												for i in range(self.degree + 1   ):
															coefficients[i] += self.coefficients[i]
												return Polynomial(polynomial_a.degree							,							__lowerCamelCase   )

						def __sub__(	self				:      str							,							__lowerCamelCase				:      Polynomial   )							->		Polynomial:


									'''simple docstring'''

									return self + polynomial_a * Polynomial(0							,							[-1]   )

						def __neg__(	self				:      str   )							->		Polynomial:


									'''simple docstring'''

									return Polynomial(self.degree							,							[-c for c in self.coefficients]   )

						def __mul__(	self				:      List[str]							,							__lowerCamelCase				:      Polynomial   )							->		Polynomial:


									'''simple docstring'''

									lowercase							=		[0] * (self.degree + polynomial_a.degree + 1)
									for i in range(self.degree + 1   ):
												for j in range(polynomial_a.degree + 1   ):
															coefficients[i + j] += (
															    self.coefficients[i] * polynomial_a.coefficients[j]
															)

									return Polynomial(self.degree + polynomial_a.degree							,							__lowerCamelCase   )

						def        __a		(	self				:      List[str]							,							__lowerCamelCase				:      int | float   )							->		int | float:


									'''simple docstring'''

									lowercase							=		0
									for i in range(self.degree + 1   ):
												result += self.coefficients[i] * (substitution**i)
									return result

						def __str__(	self				:      str   )							->		str:


									'''simple docstring'''

									lowercase							=		''''''
									for i in range(self.degree							,							-1							,							-1   ):
												if self.coefficients[i] == 0:
															continue
												elif self.coefficients[i] > 0:
															if polynomial:
																		polynomial += " + "
												else:
															polynomial += " - "

												if i == 0:
															polynomial += str(abs(self.coefficients[i]   )   )
												elif i == 1:
															polynomial += str(abs(self.coefficients[i]   )   ) + "x"
												else:
															polynomial += str(abs(self.coefficients[i]   )   ) + "x^" + str(__lowerCamelCase   )

									return polynomial

						def __repr__(	self				:      Tuple   )							->		str:


									'''simple docstring'''

									return self.__str__()

						def        __a		(	self				:      Union[str, Any]   )							->		Polynomial:


									'''simple docstring'''

									lowercase							=		[0] * self.degree
									for i in range(self.degree   ):
												lowercase							=		self.coefficients[i + 1] * (i + 1)
									return Polynomial(self.degree - 1							,							__lowerCamelCase   )

						def        __a		(	self				:      Union[str, Any]							,							__lowerCamelCase				:      int | float = 0   )							->		Polynomial:


									'''simple docstring'''

									lowercase							=		[0] * (self.degree + 2)
									lowercase							=		constant
									for i in range(self.degree + 1   ):
												lowercase							=		self.coefficients[i] / (i + 1)
									return Polynomial(self.degree + 1							,							__lowerCamelCase   )

						def __eq__(	self				:      Tuple							,							__lowerCamelCase				:      object   )							->		bool:


									'''simple docstring'''

									if not isinstance(__lowerCamelCase							,							__lowerCamelCase   ):
												return False

									if self.degree != polynomial_a.degree:
												return False

									for i in range(self.degree + 1   ):
												if self.coefficients[i] != polynomial_a.coefficients[i]:
															return False

									return True



						def __ne__(	self				:      Tuple							,							__lowerCamelCase				:      object   )							->		bool:


									'''simple docstring'''

									return not self.__eq__(__lowerCamelCase   )





