


'''simple docstring'''




import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil



class  lowerCAmelCase				(				a							):



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= pa.array(TypedSequence([1, 2, 3]    )    )
		self.assertEqual(arr.type ,					pa.intaa()    )



	def 				lowercase     (					self    ):
		with self.assertRaises(snake_case__    ):
			lowerCAmelCase					:    int      							= pa.array(TypedSequence([1, 2, 3]    ) ,					type=pa.intaa()    )



	def 				lowercase     (					self    ):
		with self.assertRaises(snake_case__    ):
			lowerCAmelCase					:    List[Any]      							= pa.array(TypedSequence([1, 2, 3] ,					try_type=Value('bool'    ) ,					type=Value('int64'    )    )    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= pa.array(TypedSequence([1, 2, 3] ,					type=Value('int32'    )    )    )
		self.assertEqual(arr.type ,					pa.intaa()    )



	def 				lowercase     (					self    ):
		with self.assertRaises((TypeError, pa.lib.ArrowInvalid)    ):
			lowerCAmelCase					:    str      							= pa.array(TypedSequence(['foo', 'bar'] ,					type=Value('int64'    )    )    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    int      							= pa.array(TypedSequence([1, 2, 3] ,					try_type=Value('int32'    )    )    )
		self.assertEqual(arr.type ,					pa.intaa()    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= pa.array(TypedSequence(['foo', 'bar'] ,					try_type=Value('int64'    )    )    )
		self.assertEqual(arr.type ,					pa.string()    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= pa.array(TypedSequence([[[1, 2, 3]]] ,					type=ArrayaD((1, 3) ,					'int64'    )    )    )
		self.assertEqual(arr.type ,					ArrayaDExtensionType((1, 3) ,					'int64'    )    )



	def 				lowercase     (					self    ):
		with self.assertRaises((TypeError, pa.lib.ArrowInvalid)    ):
			lowerCAmelCase					:    List[Any]      							= pa.array(TypedSequence(['foo', 'bar'] ,					type=ArrayaD((1, 3) ,					'int64'    )    )    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= pa.array(TypedSequence([[[1, 2, 3]]] ,					try_type=ArrayaD((1, 3) ,					'int64'    )    )    )
		self.assertEqual(arr.type ,					ArrayaDExtensionType((1, 3) ,					'int64'    )    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Dict      							= pa.array(TypedSequence(['foo', 'bar'] ,					try_type=ArrayaD((1, 3) ,					'int64'    )    )    )
		self.assertEqual(arr.type ,					pa.string()    )



	@require_pil
	def 				lowercase     (					self    ):
		import PIL.Image

		lowerCAmelCase					:    Tuple      							= PIL.Image.fromarray(np.arange(10 ,					dtype=np.uinta    ).reshape(2 ,					5    )    )
		with patch(
		    'datasets.arrow_writer.cast_to_python_objects' ,					side_effect=snake_case__    ) as mock_cast_to_python_objects:
			lowerCAmelCase					:    Any      							= pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,					type=Image()    )    )
			lowerCAmelCase							,   lowerCAmelCase					:    Dict      							= mock_cast_to_python_objects.call_args_list[-1]
			self.assertIn('optimize_list_casting' ,					snake_case__    )
			self.assertFalse(kwargs['optimize_list_casting']    )


def 			__UpperCamelCase    (    _A    :				str					,   _A    :				int				)    ->      Tuple:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[Any]      							= pa.BufferReader(_A				) if isinstance(_A					,   pa.Buffer				) else pa.memory_map(_A				)
	lowerCAmelCase					:    Union[str, Any]      							= pa.ipc.open_stream(_A				)
	lowerCAmelCase					:    pa.Table      							= f.read_all()
	assert len(pa_table.to_batches()				) == expected_num_chunks
	assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
	del pa_table

@pytest.mark.parametrize('writer_batch_size'					,   [None, 1, 10]				)
@pytest.mark.parametrize(
    'fields'					,   [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}]				)
def 			__UpperCamelCase    (    _A    :				Any					,   _A    :				Tuple				)    ->      Optional[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[Any]      							= pa.BufferOutputStream()
	lowerCAmelCase					:    Any      							= pa.schema(_A				) if fields else None
	with ArrowWriter(stream=_A					,   schema=_A					,   writer_batch_size=_A				) as writer:
		writer.write({'col_1': 'foo', 'col_2': 1}				)
		writer.write({'col_1': 'bar', 'col_2': 2}				)
		lowerCAmelCase							,   lowerCAmelCase					:    int      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	if not fields:
		lowerCAmelCase					:    Union[str, Any]      							= {'col_1': pa.string(), 'col_2': pa.intaa()}
	assert writer._schema == pa.schema(_A					,   metadata=writer._schema.metadata				)
	_check_output(output.getvalue()					,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1				)

def 			__UpperCamelCase    (    )    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    int      							= pa.BufferOutputStream()
	lowerCAmelCase					:    List[str]      							= Features({'labels': ClassLabel(names=['neg', 'pos']				)}				)
	with ArrowWriter(stream=_A					,   features=_A				) as writer:
		writer.write({'labels': 0}				)
		writer.write({'labels': 1}				)
		lowerCAmelCase							,   lowerCAmelCase					:    Union[str, Any]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	assert writer._schema == features.arrow_schema
	assert writer._schema.metadata == features.arrow_schema.metadata
	lowerCAmelCase					:    Union[str, Any]      							= pa.BufferReader(output.getvalue()				)
	lowerCAmelCase					:    int      							= pa.ipc.open_stream(_A				)
	lowerCAmelCase					:    pa.Table      							= f.read_all()
	lowerCAmelCase					:    Dict      							= pa_table.schema
	assert pa_table.num_rows == 2
	assert schema == features.arrow_schema
	assert schema.metadata == features.arrow_schema.metadata
	assert features == Features.from_arrow_schema(_A				)

@pytest.mark.parametrize('writer_batch_size'					,   [None, 1, 10]				)
def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      Optional[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Dict      							= pa.BufferOutputStream()
	with ArrowWriter(
	    stream=_A					,   writer_batch_size=_A					,   hash_salt='split_name'					,   check_duplicates=_A					,   ) as writer:
		with pytest.raises(_A				):
			writer.write({'col_1': 'foo', 'col_2': 1}					,   key=[1, 2]				)
			lowerCAmelCase							,   lowerCAmelCase					:    Union[str, Any]      							= writer.finalize()

@pytest.mark.parametrize('writer_batch_size'					,   [None, 2, 10]				)
def 			__UpperCamelCase    (    _A    :				Dict				)    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[int]      							= pa.BufferOutputStream()
	with ArrowWriter(
	    stream=_A					,   writer_batch_size=_A					,   hash_salt='split_name'					,   check_duplicates=_A					,   ) as writer:
		with pytest.raises(_A				):
			writer.write({'col_1': 'foo', 'col_2': 1}					,   key=10				)
			writer.write({'col_1': 'bar', 'col_2': 2}					,   key=10				)
			lowerCAmelCase							,   lowerCAmelCase					:    int      							= writer.finalize()

@pytest.mark.parametrize('writer_batch_size'					,   [None, 2, 10]				)
def 			__UpperCamelCase    (    _A    :				Dict				)    ->      Dict:




	"""simple docstring"""





	lowerCAmelCase					:    Dict      							= pa.BufferOutputStream()
	with ArrowWriter(
	    stream=_A					,   writer_batch_size=_A					,   hash_salt='split_name'					,   check_duplicates=_A					,   ) as writer:
		writer.write({'col_1': 'foo', 'col_2': 1}					,   key=1				)
		writer.write({'col_1': 'bar', 'col_2': 2}					,   key=2				)
		lowerCAmelCase							,   lowerCAmelCase					:    List[str]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	_check_output(output.getvalue()					,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1				)

@pytest.mark.parametrize('writer_batch_size'					,   [None, 1, 10]				)
@pytest.mark.parametrize(
    'fields'					,   [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}]				)
def 			__UpperCamelCase    (    _A    :				str					,   _A    :				Dict				)    ->      Tuple:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[int]      							= pa.BufferOutputStream()
	lowerCAmelCase					:    Any      							= pa.schema(_A				) if fields else None
	with ArrowWriter(stream=_A					,   schema=_A					,   writer_batch_size=_A				) as writer:
		writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]}				)
		writer.write_batch({'col_1': [], 'col_2': []}				)
		lowerCAmelCase							,   lowerCAmelCase					:    str      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	if not fields:
		lowerCAmelCase					:    List[Any]      							= {'col_1': pa.string(), 'col_2': pa.intaa()}
	assert writer._schema == pa.schema(_A					,   metadata=writer._schema.metadata				)
	_check_output(output.getvalue()					,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1				)

@pytest.mark.parametrize('writer_batch_size'					,   [None, 1, 10]				)
@pytest.mark.parametrize(
    'fields'					,   [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}]				)
def 			__UpperCamelCase    (    _A    :				Any					,   _A    :				Optional[Any]				)    ->      List[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= pa.BufferOutputStream()
	lowerCAmelCase					:    Optional[Any]      							= pa.schema(_A				) if fields else None
	with ArrowWriter(stream=_A					,   schema=_A					,   writer_batch_size=_A				) as writer:
		writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]}				)				)
		lowerCAmelCase							,   lowerCAmelCase					:    Optional[Any]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	if not fields:
		lowerCAmelCase					:    Optional[int]      							= {'col_1': pa.string(), 'col_2': pa.intaa()}
	assert writer._schema == pa.schema(_A					,   metadata=writer._schema.metadata				)
	_check_output(output.getvalue()					,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1				)

@pytest.mark.parametrize('writer_batch_size'					,   [None, 1, 10]				)
@pytest.mark.parametrize(
    'fields'					,   [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}]				)
def 			__UpperCamelCase    (    _A    :				int					,   _A    :				Dict				)    ->      Optional[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= pa.BufferOutputStream()
	lowerCAmelCase					:    Optional[Any]      							= pa.schema(_A				) if fields else None
	with ArrowWriter(stream=_A					,   schema=_A					,   writer_batch_size=_A				) as writer:
		writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]}				)				)
		writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]}				)				)
		lowerCAmelCase							,   lowerCAmelCase					:    Optional[int]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	if not fields:
		lowerCAmelCase					:    List[Any]      							= {'col_1': pa.string(), 'col_2': pa.intaa()}
	assert writer._schema == pa.schema(_A					,   metadata=writer._schema.metadata				)
	_check_output(output.getvalue()					,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1				)

def 			__UpperCamelCase    (    )    ->      Any:




	"""simple docstring"""





	with tempfile.TemporaryDirectory() as tmp_dir:
		lowerCAmelCase					:    Optional[int]      							= {'col_1': pa.string(), 'col_2': pa.intaa()}
		lowerCAmelCase					:    List[Any]      							= os.path.join(_A					,   'test.arrow'				)
		with ArrowWriter(path=_A					,   schema=pa.schema(_A				)				) as writer:
			writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]}				)
			lowerCAmelCase							,   lowerCAmelCase					:    Any      							= writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		assert writer._schema == pa.schema(_A					,   metadata=writer._schema.metadata				)
		_check_output(_A					,   1				)

def 			__UpperCamelCase    (    _A    :				str				)    ->      Union[str, Any]:




	"""simple docstring"""





	if pa.types.is_list(_A				):
		return get_base_dtype(arr_type.value_type				)
	else:
		return arr_type

def 			__UpperCamelCase    (    _A    :				Tuple					,   _A    :				Union[str, Any]				)    ->      int:




	"""simple docstring"""





	if isinstance(lst[0]					,   _A				):
		change_first_primitive_element_in_list(lst[0]					,   _A				)
	else:
		lowerCAmelCase					:    Dict      							= value

@pytest.mark.parametrize('optimized_int_type, expected_dtype'					,   [(None, pa.intaa()), (Value('int32'				), pa.intaa())]				)
@pytest.mark.parametrize('sequence'					,   [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]				)
def 			__UpperCamelCase    (    _A    :				Union[str, Any]					,   _A    :				Tuple					,   _A    :				Dict				)    ->      List[str]:




	"""simple docstring"""





	lowerCAmelCase					:    int      							= pa.array(TypedSequence(_A					,   optimized_int_type=_A				)				)
	assert get_base_dtype(arr.type				) == expected_dtype

@pytest.mark.parametrize(
    'col, expected_dtype'					,   [
        ('attention_mask', pa.inta()),
        ('special_tokens_mask', pa.inta()),
        ('token_type_ids', pa.inta()),
        ('input_ids', pa.intaa()),
        ('other', pa.intaa()),
    ]					,   )
@pytest.mark.parametrize('sequence'					,   [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]				)
def 			__UpperCamelCase    (    _A    :				List[Any]					,   _A    :				Union[str, Any]					,   _A    :				List[str]				)    ->      List[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[int]      							= pa.array(OptimizedTypedSequence(_A					,   col=_A				)				)
	assert get_base_dtype(arr.type				) == expected_dtype

	# not in range
	if col != "other":
		# avoids errors due to in-place modifications
		lowerCAmelCase					:    List[str]      							= copy.deepcopy(_A				)
		lowerCAmelCase					:    Dict      							= np.iinfo(expected_dtype.to_pandas_dtype()				).max + 1
		change_first_primitive_element_in_list(_A					,   _A				)
		lowerCAmelCase					:    Tuple      							= pa.array(OptimizedTypedSequence(_A					,   col=_A				)				)
		assert get_base_dtype(arr.type				) == pa.intaa()

@pytest.mark.parametrize('raise_exception'					,   [False, True]				)
def 			__UpperCamelCase    (    _A    :				List[Any]					,   _A    :				Tuple				)    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= str(tmp_path / 'dataset-train.arrow'				)
	try:
		with ArrowWriter(path=_A				) as writer:
			if raise_exception:
				raise pa.lib.ArrowInvalid()
			else:
				writer.stream.close()
	except pa.lib.ArrowInvalid:
		pass
	finally:
		assert writer.stream.closed

def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      Optional[Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Dict      							= 'mock://dataset-train.arrow'
	with ArrowWriter(path=_A					,   storage_options=mockfs.storage_options				) as writer:
		assert isinstance(writer._fs					,   type(_A				)				)
		assert writer._fs.storage_options == mockfs.storage_options
		writer.write({'col_1': 'foo', 'col_2': 1}				)
		writer.write({'col_1': 'bar', 'col_2': 2}				)
		lowerCAmelCase							,   lowerCAmelCase					:    List[str]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	assert mockfs.exists(_A				)

def 			__UpperCamelCase    (    )    ->      int:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= pa.BufferOutputStream()
	with ParquetWriter(stream=_A				) as writer:
		writer.write({'col_1': 'foo', 'col_2': 1}				)
		writer.write({'col_1': 'bar', 'col_2': 2}				)
		lowerCAmelCase							,   lowerCAmelCase					:    Optional[int]      							= writer.finalize()
	assert num_examples == 2
	assert num_bytes > 0
	lowerCAmelCase					:    Tuple      							= pa.BufferReader(output.getvalue()				)
	lowerCAmelCase					:    pa.Table      							= pq.read_table(_A				)
	assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}

@require_pil
@pytest.mark.parametrize('embed_local_files'					,   [False, True]				)
def 			__UpperCamelCase    (    _A    :				Union[str, Any]					,   _A    :				Optional[int]				)    ->      str:




	"""simple docstring"""





	import PIL.Image

	lowerCAmelCase					:    List[Any]      							= str(tmp_path / 'test_image_rgb.jpg'				)
	PIL.Image.fromarray(np.zeros((5, 5)					,   dtype=np.uinta				)				).save(_A					,   format='png'				)
	lowerCAmelCase					:    Tuple      							= pa.BufferOutputStream()
	with ParquetWriter(
	    stream=_A					,   features=Features({'image': Image()}				)					,   embed_local_files=_A				) as writer:
		writer.write({'image': image_path}				)
		writer.finalize()
	lowerCAmelCase					:    int      							= pa.BufferReader(output.getvalue()				)
	lowerCAmelCase					:    pa.Table      							= pq.read_table(_A				)
	lowerCAmelCase					:    Optional[Any]      							= pa_table.to_pydict()
	if embed_local_files:
		assert isinstance(out['image'][0]['path']					,   _A				)
		with open(_A					,   'rb'				) as f:
			assert out["image"][0]["bytes"] == f.read()
	else:
		assert out["image"][0]["path"] == image_path
		assert out["image"][0]["bytes"] is None






def 			__UpperCamelCase    (    )    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= pa.schema([pa.field('col_1'					,   pa.string()					,   nullable=_A				)]				)
	lowerCAmelCase					:    Union[str, Any]      							= pa.BufferOutputStream()
	with ArrowWriter(stream=_A				) as writer:
		writer._build_writer(inferred_schema=_A				)
		assert writer._schema == pa.schema([pa.field('col_1'					,   pa.string()				)]				)




'''simple docstring'''




from typing import Any



class  lowerCAmelCase				:



	def __init__(					self ,					snake_case__    ):
		lowerCAmelCase					:    Optional[int]      							= data
		lowerCAmelCase					:    Optional[Any]      							= None



	def __repr__(					self    ):
		return f"Node({self.data})"



class  lowerCAmelCase				:



	def __init__(					self    ):
		lowerCAmelCase					:    Dict      							= None



	def __iter__(					self    ):
		lowerCAmelCase					:    Optional[Any]      							= self.head
		while node:
			yield node.data
			lowerCAmelCase					:    Optional[int]      							= node.next



	def __len__(					self    ):
		return sum(1 for _ in self    )



	def __repr__(					self    ):
		return "->".join([str(snake_case__    ) for item in self]    )



	def __getitem__(					self ,					snake_case__    ):
		if not 0 <= index < len(self    ):
			raise ValueError('list index out of range.'    )
		for i, node in enumerate(self    ):
			if i == index:
				return node
		return None



	def __setitem__(					self ,					snake_case__ ,					snake_case__    ):
		if not 0 <= index < len(self    ):
			raise ValueError('list index out of range.'    )
		lowerCAmelCase					:    Any      							= self.head
		for _ in range(snake_case__    ):
			lowerCAmelCase					:    List[str]      							= current.next
		lowerCAmelCase					:    int      							= data



	def 				lowercase     (					self ,					snake_case__    ):
		self.insert_nth(len(self    ) ,					snake_case__    )



	def 				lowercase     (					self ,					snake_case__    ):
		self.insert_nth(0 ,					snake_case__    )



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__    ):
		if not 0 <= index <= len(self    ):
			raise IndexError('list index out of range'    )
		lowerCAmelCase					:    List[str]      							= Node(snake_case__    )
		if self.head is None:
			lowerCAmelCase					:    int      							= new_node
		elif index == 0:
			lowerCAmelCase					:    List[Any]      							= self.head  # link new_node to head
			lowerCAmelCase					:    List[Any]      							= new_node
		else:
			lowerCAmelCase					:    List[Any]      							= self.head
			for _ in range(index - 1    ):
				lowerCAmelCase					:    Union[str, Any]      							= temp.next
			lowerCAmelCase					:    Any      							= temp.next
			lowerCAmelCase					:    str      							= new_node



	def 				lowercase     (					self    ):  # print every node data
		print(self    )



	def 				lowercase     (					self    ):
		return self.delete_nth(0    )



	def 				lowercase     (					self    ):  # delete from tail
		return self.delete_nth(len(self    ) - 1    )



	def 				lowercase     (					self ,					snake_case__ = 0    ):
		if not 0 <= index <= len(self    ) - 1:  # test if index is valid
			raise IndexError('List index out of range.'    )
		lowerCAmelCase					:    List[str]      							= self.head  # default first node
		if index == 0:
			lowerCAmelCase					:    Tuple      							= self.head.next
		else:
			lowerCAmelCase					:    Dict      							= self.head
			for _ in range(index - 1    ):
				lowerCAmelCase					:    Tuple      							= temp.next
			lowerCAmelCase					:    Dict      							= temp.next
			lowerCAmelCase					:    Tuple      							= temp.next.next
		return delete_node.data



	def 				lowercase     (					self    ):
		return self.head is None



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= None
		lowerCAmelCase					:    Any      							= self.head

		while current:
			# Store the current node's next node.
			lowerCAmelCase					:    List[str]      							= current.next
			# Make the current node's next point backwards
			lowerCAmelCase					:    int      							= prev
			# Make the previous node be the current node
			lowerCAmelCase					:    int      							= current
			# Make the current node the next node (to progress iteration)
			lowerCAmelCase					:    Optional[Any]      							= next_node
		# Return prev in order to put the head at the end
		lowerCAmelCase					:    List[Any]      							= prev


def 			__UpperCamelCase    (    )    ->      None:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= LinkedList()
	assert linked_list.is_empty() is True
	assert str(_A				) == ""

	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(10				):
		assert len(_A				) == i
		linked_list.insert_nth(_A					,   i + 1				)
	assert str(_A				) == "->".join(str(_A				) for i in range(1					,   11				)				)

	linked_list.insert_head(0				)
	linked_list.insert_tail(11				)
	assert str(_A				) == "->".join(str(_A				) for i in range(0					,   12				)				)

	assert linked_list.delete_head() == 0
	assert linked_list.delete_nth(9				) == 10
	assert linked_list.delete_tail() == 11
	assert len(_A				) == 9
	assert str(_A				) == "->".join(str(_A				) for i in range(1					,   10				)				)

	assert all(linked_list[i] == i + 1 for i in range(0					,   9				)				) is True

	for i in range(0					,   9				):
		lowerCAmelCase					:    Optional[Any]      							= -i
	assert all(linked_list[i] == -i for i in range(0					,   9				)				) is True

	linked_list.reverse()
	assert str(_A				) == "->".join(str(_A				) for i in range(-8					,   1				)				)

def 			__UpperCamelCase    (    )    ->      None:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[int]      							= [
	    -9,
	    1_00,
	    Node(77_34_51_12				),
	    'dlrow olleH',
	    7,
	    55_55,
	    0,
	    -1_92.5_55_55,
	    'Hello, world!',
	    77.9,
	    Node(10				),
	    None,
	    None,
	    12.20,
	]
	lowerCAmelCase					:    Dict      							= LinkedList()

	for i in test_input:
		linked_list.insert_tail(_A				)

	# Check if it's empty or not
	assert linked_list.is_empty() is False
	assert (
	    str(_A				) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
	    "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
	)

	# Delete the head
	lowerCAmelCase					:    Optional[Any]      							= linked_list.delete_head()
	assert result == -9
	assert (
	    str(_A				) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
	    "Hello, world!->77.9->Node(10)->None->None->12.2"
	)

	# Delete the tail
	lowerCAmelCase					:    List[str]      							= linked_list.delete_tail()
	assert result == 12.2
	assert (
	    str(_A				) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
	    "Hello, world!->77.9->Node(10)->None->None"
	)

	# Delete a node in specific location in linked list
	lowerCAmelCase					:    List[str]      							= linked_list.delete_nth(10				)
	assert result is None
	assert (
	    str(_A				) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
	    "Hello, world!->77.9->Node(10)->None"
	)

	# Add a Node instance to its head
	linked_list.insert_head(Node('Hello again, world!'				)				)
	assert (
	    str(_A				)
	    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
	    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
	)

	# Add None to its tail
	linked_list.insert_tail(_A				)
	assert (
	    str(_A				)
	    == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
	    "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
	)

	# Reverse the linked list
	linked_list.reverse()
	assert (
	    str(_A				)
	    == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
	    "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
	)

def 			__UpperCamelCase    (    )    ->      List[Any]:




	"""simple docstring"""





	from doctest import testmod

	testmod()

	lowerCAmelCase					:    Optional[Any]      							= LinkedList()
	linked_list.insert_head(input('Inserting 1st at head '				).strip()				)
	linked_list.insert_head(input('Inserting 2nd at head '				).strip()				)
	print('\nPrint list:'				)
	linked_list.print_list()
	linked_list.insert_tail(input('\nInserting 1st at tail '				).strip()				)
	linked_list.insert_tail(input('Inserting 2nd at tail '				).strip()				)
	print('\nPrint list:'				)
	linked_list.print_list()
	print('\nDelete head'				)
	linked_list.delete_head()
	print('Delete tail'				)
	linked_list.delete_tail()
	print('\nPrint list:'				)
	linked_list.print_list()
	print('\nReverse linked list'				)
	linked_list.reverse()
	print('\nPrint list:'				)
	linked_list.print_list()
	print('\nString representation of linked list:'				)
	print(_A				)
	print('\nReading/changing Node data using indexing:'				)
	print(F"Element at Position 1: {linked_list[1]}"				)
	lowerCAmelCase					:    Tuple      							= input('Enter New Value: '				).strip()
	print('New list:'				)
	print(_A				)
	print(F"length of linked_list is : {len(_A				)}"				)


if __name__ == "__main__":
				main()
