





"""simple docstring"""




from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available





def 		UpperCAmelCase__						(	_UpperCAmelCase   ):






  """simple docstring"""





  if is_torch_available():
    import torch

    if isinstance(_UpperCAmelCase					,   torch.Tensor   ):
      return True

  return isinstance(_UpperCAmelCase					,   np.ndarray   )





class 					_UpperCAmelCase    (  UpperCAmelCase__						):



      '''simple docstring'''

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        A_    :			Dict									=    fields(self    )

        # Safety and consistency checks
        if not len(snake_case_    ):
          raise ValueError(F"""{self.__class__.__name__} has no fields."""    )

        A_    :			Dict									=    getattr(self   , class_fields[0].name    )
        A_    :			str									=    all(getattr(self   , field.name    ) is None for field in class_fields[1:]    )

        if other_fields_are_none and isinstance(snake_case_   , snake_case_    ):
          for key, value in first_field.items():
            A_    :			Optional[Any]									=    value
        else:
          for field in class_fields:
            A_    :			List[Any]									=    getattr(self   , field.name    )
            if v is not None:
              A_    :			Any									=    v

      def __delitem__(	self   , *snake_case_   , **snake_case_    ):

        """simple docstring"""

        raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""    )

      def    lowerCamelCase_     (	self   , *snake_case_   , **snake_case_    ):

        """simple docstring"""

        raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""    )

      def    lowerCamelCase_     (	self   , *snake_case_   , **snake_case_    ):

        """simple docstring"""

        raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""    )

      def    lowerCamelCase_     (	self   , *snake_case_   , **snake_case_    ):

        """simple docstring"""

        raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance."""    )

      def __getitem__(	self   , snake_case_    ):

        """simple docstring"""

        if isinstance(snake_case_   , snake_case_    ):
          A_    :			str									=    dict(self.items()    )
          return inner_dict[k]
        else:
          return self.to_tuple()[k]

      def __setattr__(	self   , snake_case_   , snake_case_    ):

        """simple docstring"""

        if name in self.keys() and value is not None:
          # Don't call self.__setitem__ to avoid recursion errors
          super().__setitem__(snake_case_   , snake_case_    )
        super().__setattr__(snake_case_   , snake_case_    )

      def __setitem__(	self   , snake_case_   , snake_case_    ):

        """simple docstring"""

        super().__setitem__(snake_case_   , snake_case_    )
        # Don't call self.__setattr__ to avoid recursion errors
        super().__setattr__(snake_case_   , snake_case_    )

      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        return tuple(self[k] for k in self.keys()    )

'''simple docstring'''





class 			UpperCamelCase__	:






 def __init__(      self	:Optional[Any]						,					_A	:Tuple      )					->      Tuple:







       '''simple docstring'''



       __A													=      data
       __A													=      None
       __A													=      None






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







       '''simple docstring'''



       return F'{self.data}'


class 			UpperCamelCase__	:






 def __init__(      self	:List[Any]      )					->      Any:







       '''simple docstring'''



       __A													=      None
       __A													=      None






 def __iter__(      self	:Optional[int]      )					->      List[Any]:







       '''simple docstring'''



       __A													=      self.head
       while node:
             yield node.data
             __A													=      node.next






 def __str__(      self	:Dict      )					->      Union[str, Any]:







       '''simple docstring'''



       return "->".join([str(_A      ) for item in self]      )






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







       '''simple docstring'''



       return sum(1 for _ in self      )






 def 						lowercase_    (      self	:List[str]						,					_A	:Any      )					->      str:







       '''simple docstring'''



       self.insert_at_nth(0						,					_A      )






 def 						lowercase_    (      self	:Dict						,					_A	:Optional[Any]      )					->      Tuple:







       '''simple docstring'''



       self.insert_at_nth(len(self      )						,					_A      )






 def 						lowercase_    (      self	:Optional[int]						,					_A	:int						,					_A	:Optional[int]      )					->      int:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length:
             raise IndexError('list index out of range'      )
       __A													=      Node(_A      )
       if self.head is None:
             __A													=      __A													=      new_node
       elif index == 0:
             __A													=      new_node
             __A													=      self.head
             __A													=      new_node
       elif index == length:
             __A													=      new_node
             __A													=      self.tail
             __A													=      new_node
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      new_node
             __A													=      temp.previous
             __A													=      temp
             __A													=      new_node






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







       '''simple docstring'''



       return self.delete_at_nth(0      )






 def 						lowercase_    (      self	:Any      )					->      Tuple:







       '''simple docstring'''



       return self.delete_at_nth(len(self      ) - 1      )






 def 						lowercase_    (      self	:Dict						,					_A	:int      )					->      List[str]:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length - 1:
             raise IndexError('list index out of range'      )
       __A													=      self.head  # default first node
       if length == 1:
             __A													=      __A													=      None
       elif index == 0:
             __A													=      self.head.next
             __A													=      None
       elif index == length - 1:
             __A													=      self.tail
             __A													=      self.tail.previous
             __A													=      None
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      temp
             __A													=      temp.previous
             __A													=      temp.next
       return delete_node.data






 def 						lowercase_    (      self	:List[str]						,					_A	:Dict      )					->      str:







       '''simple docstring'''



       __A													=      self.head

       while current.data != data:  # Find the position to delete
             if current.next:
                   __A													=      current.next
             else:  # We have reached the end an no value matches
                   raise ValueError('No data matching given value'      )

       if current == self.head:
             self.delete_head()

       elif current == self.tail:
             self.delete_tail()

       else:  # Before: 1 <--> 2(current) <--> 3
             __A													=      current.next  # 1 --> 3
             __A													=      current.previous  # 1 <--> 3
       return data






 def 						lowercase_    (      self	:List[str]      )					->      Tuple:







       '''simple docstring'''



       return len(self      ) == 0





def 							snake_case				(		)->      None:







      """simple docstring"""
      __A													=      DoublyLinkedList()
      assert linked_list.is_empty() is True
      assert str(UpperCAmelCase						) == ""

      try:
            linked_list.delete_head()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      try:
            linked_list.delete_tail()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      for i in range(1_0						):
            assert len(UpperCAmelCase						) == i
            linked_list.insert_at_nth(UpperCAmelCase   ,	i + 1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_1						)						)

      linked_list.insert_at_head(0						)
      linked_list.insert_at_tail(1_1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(0   ,	1_2						)						)

      assert linked_list.delete_head() == 0
      assert linked_list.delete_at_nth(9						) == 1_0
      assert linked_list.delete_tail() == 1_1
      assert len(UpperCAmelCase						) == 9
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_0						)						)


if __name__ == "__main__":
 from doctest import testmod

 testmod()






