


'''simple docstring'''



import argparse
import copy



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Optional[Any]				)	->						Optional[int]:
     __lowerCamelCase  :      Optional[Any]														=						{}

     with open(UpperCAmelCase_				) as f:
          for line in f:
               if line.split()[0] not in dict_of_neighbours:
                    __lowerCamelCase  :      str														=						[]
                    _list.append([line.split()[1], line.split()[2]]				)
                    __lowerCamelCase  :      Any														=						_list
               else:
                    dict_of_neighbours[line.split()[0]].append(
                        [line.split()[1], line.split()[2]]				)
               if line.split()[1] not in dict_of_neighbours:
                    __lowerCamelCase  :      List[Any]														=						[]
                    _list.append([line.split()[0], line.split()[2]]				)
                    __lowerCamelCase  :      Optional[Any]														=						_list
               else:
                    dict_of_neighbours[line.split()[1]].append(
                        [line.split()[0], line.split()[2]]				)

     return dict_of_neighbours



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Optional[int] ,       UpperCAmelCase_       :							Tuple				)	->						str:

     with open(UpperCAmelCase_				) as f:
          __lowerCamelCase  :      str														=						f.read(1				)
     __lowerCamelCase  :      Any														=						start_node

     __lowerCamelCase  :      str														=						[]

     __lowerCamelCase  :      Dict														=						start_node

     __lowerCamelCase  :      List[str]														=						0
     while visiting not in first_solution:
          __lowerCamelCase  :      List[str]														=						1_00_00
          for k in dict_of_neighbours[visiting]:
               if int(k[1]				) < int(UpperCAmelCase_				) and k[0] not in first_solution:
                    __lowerCamelCase  :      Tuple														=						k[1]
                    __lowerCamelCase  :      List[str]														=						k[0]

          first_solution.append(UpperCAmelCase_				)
          __lowerCamelCase  :      Dict														=						distance_of_first_solution + int(UpperCAmelCase_				)
          __lowerCamelCase  :      List[Any]														=						best_node

     first_solution.append(UpperCAmelCase_				)

     __lowerCamelCase  :      Optional[Any]														=						0
     for k in dict_of_neighbours[first_solution[-2]]:
          if k[0] == start_node:
               break
          position += 1

     __lowerCamelCase  :      Union[str, Any]														=						(
         distance_of_first_solution
         + int(dict_of_neighbours[first_solution[-2]][position][1]				)
         - 1_00_00
     )
     return first_solution, distance_of_first_solution



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							Any				)	->						int:
     __lowerCamelCase  :      Optional[Any]														=						[]

     for n in solution[1:-1]:
          __lowerCamelCase  :      Optional[int]														=						solution.index(UpperCAmelCase_				)
          for kn in solution[1:-1]:
               __lowerCamelCase  :      Any														=						solution.index(UpperCAmelCase_				)
               if n == kn:
                    continue

               __lowerCamelCase  :      Dict														=						copy.deepcopy(UpperCAmelCase_				)
               __lowerCamelCase  :      Optional[Any]														=						kn
               __lowerCamelCase  :      int														=						n

               __lowerCamelCase  :      Tuple														=						0

               for k in _tmp[:-1]:
                    __lowerCamelCase  :      List[Any]														=						_tmp[_tmp.index(UpperCAmelCase_				) + 1]
                    for i in dict_of_neighbours[k]:
                         if i[0] == next_node:
                              __lowerCamelCase  :      Union[str, Any]														=						distance + int(i[1]				)
               _tmp.append(UpperCAmelCase_				)

               if _tmp not in neighborhood_of_solution:
                    neighborhood_of_solution.append(_tmp				)

     __lowerCamelCase  :      Any														=						len(neighborhood_of_solution[0]				) - 1

     neighborhood_of_solution.sort(key=lambda UpperCAmelCase_				: x[index_of_last_item_in_the_list]				)
     return neighborhood_of_solution



def      UpperCAmelCase__   (      UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							Any ,       UpperCAmelCase_       :							Any ,       UpperCAmelCase_       :							Dict ,       UpperCAmelCase_       :							Optional[Any]				)	->						Optional[int]:
     __lowerCamelCase  :      Union[str, Any]														=						1
     __lowerCamelCase  :      Union[str, Any]														=						first_solution
     __lowerCamelCase  :      str														=						[]
     __lowerCamelCase  :      Optional[int]														=						distance_of_first_solution
     __lowerCamelCase  :      Union[str, Any]														=						solution

     while count <= iters:
          __lowerCamelCase  :      Any														=						find_neighborhood(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      Optional[Any]														=						0
          __lowerCamelCase  :      Optional[Any]														=						neighborhood[index_of_best_solution]
          __lowerCamelCase  :      List[str]														=						len(UpperCAmelCase_				) - 1

          __lowerCamelCase  :      Union[str, Any]														=						False
          while not found:
               __lowerCamelCase  :      List[Any]														=						0
               while i < len(UpperCAmelCase_				):
                    if best_solution[i] != solution[i]:
                         __lowerCamelCase  :      Optional[Any]														=						best_solution[i]
                         __lowerCamelCase  :      str														=						solution[i]
                         break
                    __lowerCamelCase  :      Union[str, Any]														=						i + 1

               if [first_exchange_node, second_exchange_node] not in tabu_list and [
                   second_exchange_node,
                   first_exchange_node,
               ] not in tabu_list:
                    tabu_list.append([first_exchange_node, second_exchange_node]				)
                    __lowerCamelCase  :      List[Any]														=						True
                    __lowerCamelCase  :      List[str]														=						best_solution[:-1]
                    __lowerCamelCase  :      List[Any]														=						neighborhood[index_of_best_solution][best_cost_index]
                    if cost < best_cost:
                         __lowerCamelCase  :      Dict														=						cost
                         __lowerCamelCase  :      str														=						solution
               else:
                    __lowerCamelCase  :      List[Any]														=						index_of_best_solution + 1
                    __lowerCamelCase  :      List[Any]														=						neighborhood[index_of_best_solution]

          if len(UpperCAmelCase_				) >= size:
               tabu_list.pop(0				)

          __lowerCamelCase  :      Optional[Any]														=						count + 1

     return best_solution_ever, best_cost



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Any=None				)	->						Union[str, Any]:
     __lowerCamelCase  :      Optional[Any]														=						generate_neighbours(args.File				)

     __lowerCamelCase							,			__lowerCamelCase  :      str														=						generate_first_solution(
         args.File ,       UpperCAmelCase_				)

     __lowerCamelCase							,			__lowerCamelCase  :      Optional[int]														=						tabu_search(
         UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       args.Iterations ,       args.Size ,       )

     print(F'Best solution: {best_sol}, with total distance: {best_cost}.'				)


if __name__ == "__main__":
      A__						:   Dict				=    argparse.ArgumentParser(description="""Tabu Search""")
      parser.add_argument(
          """-f""",
          """--File""",
          type=str,
          help="""Path to the file containing the data""",
          required=True,
      )
      parser.add_argument(
          """-i""",
          """--Iterations""",
          type=int,
          help="""How many iterations the algorithm should perform""",
          required=True,
      )
      parser.add_argument(
          """-s""", """--Size""", type=int, help="""Size of the tabu list""", required=True
      )

      # Pass the arguments to main method
      main(parser.parse_args())













import re
import tempfile
from pathlib import Path

import pytest
import yaml

from datasets.utils.readme import ReadMe


# @pytest.fixture
# def example_yaml_structure():

A       :   Dict					= yaml.safe_load(
    '''\
name: ""
allow_empty: false
allow_empty_text: true
subsections:
  - name: "Dataset Card for X" # First-level markdown heading
    allow_empty: false
    allow_empty_text: true
    subsections:
      - name: "Table of Contents"
        allow_empty: false
        allow_empty_text: false
        subsections: null
      - name: "Dataset Description"
        allow_empty: false
        allow_empty_text: false
        subsections:
          - name: "Dataset Summary"
            allow_empty: false
            allow_empty_text: false
            subsections: null
          - name: "Supported Tasks and Leaderboards"
            allow_empty: true
            allow_empty_text: true
            subsections: null
          - name: Languages
            allow_empty: false
            allow_empty_text: true
            subsections: null
'''
)


A       :   str					= {
    '''name''': '''root''',
    '''text''': '''''',
    '''is_empty_text''': True,
    '''subsections''': [
        {
            '''name''': '''Dataset Card for My Dataset''',
            '''text''': '''''',
            '''is_empty_text''': True,
            '''subsections''': [
                {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []},
                {
                    '''name''': '''Dataset Description''',
                    '''text''': '''Some text here.''',
                    '''is_empty_text''': False,
                    '''subsections''': [
                        {
                            '''name''': '''Dataset Summary''',
                            '''text''': '''Some text here.''',
                            '''is_empty_text''': False,
                            '''subsections''': [],
                        },
                        {
                            '''name''': '''Supported Tasks and Leaderboards''',
                            '''text''': '''''',
                            '''is_empty_text''': True,
                            '''subsections''': [],
                        },
                        {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []},
                    ],
                },
            ],
        }
    ],
}


A       :   Union[str, Any]					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''


A       :   int					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
#### Extra Ignored Subsection
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   Optional[int]					= {
    '''name''': '''root''',
    '''text''': '''''',
    '''is_empty_text''': True,
    '''subsections''': [
        {
            '''name''': '''Dataset Card for My Dataset''',
            '''text''': '''''',
            '''is_empty_text''': True,
            '''subsections''': [
                {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []},
                {
                    '''name''': '''Dataset Description''',
                    '''text''': '''Some text here.''',
                    '''is_empty_text''': False,
                    '''subsections''': [
                        {
                            '''name''': '''Dataset Summary''',
                            '''text''': '''Some text here.''',
                            '''is_empty_text''': False,
                            '''subsections''': [
                                {
                                    '''name''': '''Extra Ignored Subsection''',
                                    '''text''': '''''',
                                    '''is_empty_text''': True,
                                    '''subsections''': [],
                                }
                            ],
                        },
                        {
                            '''name''': '''Supported Tasks and Leaderboards''',
                            '''text''': '''''',
                            '''is_empty_text''': True,
                            '''subsections''': [],
                        },
                        {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []},
                    ],
                },
            ],
        }
    ],
}

A       :   str					= '''\
---
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   Optional[Any]					= (
    '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.'''
)

A       :   List[Any]					= '''\
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   Union[str, Any]					= (
    '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.'''
)

A       :   int					= '''\
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   Dict					= '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.'''

A       :   List[Any]					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
### Supported Tasks and Leaderboards
### Languages
Language Text
'''
A       :   str					= '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).'''


A       :   Optional[int]					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
'''
A       :   Optional[int]					= '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.'''

A       :   Optional[int]					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Languages
Language Text
'''

A       :   List[str]					= '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.'''


A       :   Optional[int]					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
'''

A       :   Optional[Any]					= '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.'''

A       :   List[Any]					= '''\
---
language:
- zh
- en
---

## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''
A       :   Optional[Any]					= '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.'''

A       :   int					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
# Dataset Card My Dataset
'''

A       :   Dict					= '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.'''

A       :   str					= '''\
---
language:
- zh
- en
---

# Dataset Card My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   int					= '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.'''

A       :   str					= ''''''

A       :   Optional[Any]					= '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.'''

A       :   int					= '''\
---
language:
- zh
- en
---

# Dataset Card for My Dataset
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
'''

A       :   List[Any]					= '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.'''







@pytest.mark.parametrize(
    """readme_md, expected_dict"""       ,	[
        (README_CORRECT, CORRECT_DICT),
        (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
    ]       ,	)
def   __lowerCamelCase   (				__a  :Union[str, Any]       ,	__a  :List[Any]       )						->							List[Any]:






		"""simple docstring"""

		assert ReadMe.from_string(__a       ,	__a       ).to_dict() == expected_dict







@pytest.mark.parametrize(
    """readme_md, expected_error"""       ,	[
        (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
        (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
        (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
        (README_EMPTY, EXPECTED_ERROR_README_EMPTY),
        (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
        (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
        (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
        (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
        (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
        (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
        (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
    ]       ,	)
def   __lowerCamelCase   (				__a  :Any       ,	__a  :Union[str, Any]       )						->							Dict:






		"""simple docstring"""

		with pytest.raises(__a       ,	match=re.escape(expected_error.format(path="""root"""       )       )       ):
				A__     =  ReadMe.from_string(__a       ,	__a       )
				readme.validate()







@pytest.mark.parametrize(
    """readme_md, expected_error"""       ,	[
        (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
    ]       ,	)
def   __lowerCamelCase   (				__a  :List[str]       ,	__a  :Tuple       )						->							Dict:






		"""simple docstring"""

		with pytest.raises(__a       ,	match=re.escape(expected_error.format(path="""root"""       )       )       ):
				ReadMe.from_string(__a       ,	__a       )







@pytest.mark.parametrize(
    """readme_md,"""       ,	[
        (README_MULTIPLE_SAME_HEADING_1),
    ]       ,	)
def   __lowerCamelCase   (				__a  :Any       )						->							List[str]:






		"""simple docstring"""

		ReadMe.from_string(__a       ,	__a       ,	suppress_parsing_errors=__a       )







@pytest.mark.parametrize(
    """readme_md, expected_dict"""       ,	[
        (README_CORRECT, CORRECT_DICT),
        (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
    ]       ,	)
def   __lowerCamelCase   (				__a  :List[Any]       ,	__a  :Optional[int]       )						->							Optional[int]:






		"""simple docstring"""

		with tempfile.TemporaryDirectory() as tmp_dir:
				A__     =  Path(__a       ) / """README.md"""
				with open(__a       ,	"""w+"""       ) as readme_file:
						readme_file.write(__a       )
				A__     =  ReadMe.from_readme(__a       ,	__a       ).to_dict()
				assert out["name"] == path
				assert out["text"] == ""
				assert out["is_empty_text"]
				assert out["subsections"] == expected_dict["subsections"]







@pytest.mark.parametrize(
    """readme_md, expected_error"""       ,	[
        (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
        (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
        (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
        (README_EMPTY, EXPECTED_ERROR_README_EMPTY),
        (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
        (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
        (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
        (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
        (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
        (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
        (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
    ]       ,	)
def   __lowerCamelCase   (				__a  :List[str]       ,	__a  :Union[str, Any]       )						->							List[str]:






		"""simple docstring"""

		with tempfile.TemporaryDirectory() as tmp_dir:
				A__     =  Path(__a       ) / """README.md"""
				with open(__a       ,	"""w+"""       ) as readme_file:
						readme_file.write(__a       )
				A__     =  expected_error.format(path=__a       )
				with pytest.raises(__a       ,	match=re.escape(__a       )       ):
						A__     =  ReadMe.from_readme(__a       ,	__a       )
						readme.validate()







@pytest.mark.parametrize(
    """readme_md, expected_error"""       ,	[
        (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
    ]       ,	)
def   __lowerCamelCase   (				__a  :List[Any]       ,	__a  :Any       )						->							int:






		"""simple docstring"""

		with tempfile.TemporaryDirectory() as tmp_dir:
				A__     =  Path(__a       ) / """README.md"""
				with open(__a       ,	"""w+"""       ) as readme_file:
						readme_file.write(__a       )
				A__     =  expected_error.format(path=__a       )
				with pytest.raises(__a       ,	match=re.escape(__a       )       ):
						ReadMe.from_readme(__a       ,	__a       )







@pytest.mark.parametrize(
    """readme_md,"""       ,	[
        (README_MULTIPLE_SAME_HEADING_1),
    ]       ,	)
def   __lowerCamelCase   (				__a  :Union[str, Any]       )						->							Optional[Any]:






		"""simple docstring"""

		with tempfile.TemporaryDirectory() as tmp_dir:
				A__     =  Path(__a       ) / """README.md"""
				with open(__a       ,	"""w+"""       ) as readme_file:
						readme_file.write(__a       )
				ReadMe.from_readme(__a       ,	__a       ,	suppress_parsing_errors=__a       )



