{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Data Exploration\n",
    "\n",
    "Quick view of the data I've generated through my scripts. Used for fast prototyping of hypotheses I have."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import with_autogenerated_test_cases.testing_autogenerated_test_cases as script\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.18032786885245902\n"
     ]
    }
   ],
   "source": [
    "\n",
    "def pass_at_k(k, df):\n",
    "    '''\n",
    "    pass@k from first k selected programs.\n",
    "    '''\n",
    "\n",
    "    def unbiased_estimate(n, c, k):\n",
    "        \"\"\"\n",
    "        :param n: total number of samples\n",
    "        :param c: number of correct samples\n",
    "        :param k: k in pass@$k$\n",
    "        \"\"\"\n",
    "        if n - c < k:\n",
    "            return 1.0\n",
    "        return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))\n",
    "\n",
    "    # Get all possible prompt ids\n",
    "    generated_prompt_ids = set(df['Prompt id'])\n",
    "\n",
    "    num_correct = 0\n",
    "    for prompt_id in generated_prompt_ids:\n",
    "        progs_from_prompt_id = df[df[\"Prompt id\"] == prompt_id]\n",
    "\n",
    "        num_correct_samples = progs_from_prompt_id[\"Correct\"].sum()\n",
    "\n",
    "        num_correct += unbiased_estimate(len(progs_from_prompt_id),\n",
    "                                         num_correct_samples, k)\n",
    "    return num_correct/len(generated_prompt_ids)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def baseline_model(df):\n",
    "    '''\n",
    "    Baseline model if the first sampled program is selected with no extra processing.\n",
    "    '''\n",
    "    # Get all possible prompt ids\n",
    "    generated_prompt_ids = set(df['Prompt id'])\n",
    "\n",
    "    set_corr = set()\n",
    "    num_correct = 0\n",
    "    for prompt_id in generated_prompt_ids:\n",
    "        first_program_row = df[df[\"Prompt id\"]\n",
    "                                               == prompt_id].iloc[0]\n",
    "\n",
    "\n",
    "        if first_program_row[\"Correct\"]:\n",
    "            set_corr.add(first_program_row.name)\n",
    "        num_correct += first_program_row[\"Correct\"]\n",
    "    return num_correct/len(generated_prompt_ids), set_corr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "def naive_matching(df, num_test_cases_to_solve=3):\n",
    "    '''\n",
    "    First model. Naively selects the program that solves the most of the test cases that are solved by the most programs.\n",
    "\n",
    "    Selects the first {num_test_cases_to_solve} most solved test cases to be regarded as the \"ground truth test cases\",\n",
    "    and the first program to solve all {num_test_cases_to_solve} test cases is selected.\n",
    "\n",
    "    If no program solves all {num_test_cases_to_solve} test cases, then the program that solves the most is selected.\n",
    "    If there's a tie in the number of test cases solved, then the \"rank\" of each test case is computed (how many programs\n",
    "    solve it), and the program with the highest rank sum is chosen.\n",
    "    '''\n",
    "\n",
    "    # Get all possible prompt ids\n",
    "    generated_prompt_ids = set(df['Prompt id'])\n",
    "\n",
    "    num_correct = 0\n",
    "    \n",
    "    corr_set = set()\n",
    "\n",
    "    counter = 0\n",
    "    for prompt_id in generated_prompt_ids:\n",
    "        gen_from_prompt_id = df[df[\"Prompt id\"] == prompt_id]\n",
    "\n",
    "        most_solved_test_cases = gen_from_prompt_id.groupby(\n",
    "            by=\"Generated Test Case ID\")[\"Result\"].sum().sort_values(ascending=False)[:num_test_cases_to_solve]\n",
    "\n",
    "        test_case_set = set(most_solved_test_cases.index)\n",
    "\n",
    "        programs_from_test_cases = gen_from_prompt_id[gen_from_prompt_id[\"Generated Test Case ID\"].isin(\n",
    "            test_case_set)].copy(deep=True)\n",
    "\n",
    "        # Create a new column with a value based on how widespread the test cases were - this is used for a\n",
    "        # tiebreaker scenario where two programs have solved the same number of test cases but different test cases\n",
    "        programs_from_test_cases[\"Rank\"] = programs_from_test_cases[\"Generated Test Case ID\"].apply(\n",
    "            lambda id: most_solved_test_cases[id])\n",
    "\n",
    "        def rank(df):\n",
    "            new_df = {}\n",
    "\n",
    "            new_df[\"Result\"] = df[\"Result\"].sum()\n",
    "\n",
    "            new_df[\"Rank\"] = df[df[\"Result\"]][\"Rank\"].sum()\n",
    "\n",
    "            return pd.Series(new_df)\n",
    "\n",
    "        programs_solving_tests = programs_from_test_cases.groupby(\n",
    "            by=[\"Generated Program ID\", \"Is generated program correct\"]).apply(rank)\n",
    "\n",
    "        programs_solving_tests = programs_solving_tests.sort_values(\n",
    "            ['Result', 'Rank'], ascending=[False, False])\n",
    "\n",
    "        best_program_id, is_program_correct = programs_solving_tests.index[0]\n",
    "        \n",
    "        if is_program_correct:\n",
    "            corr_set.add(best_program_id)\n",
    "\n",
    "        num_correct += is_program_correct\n",
    "        counter += 1\n",
    "\n",
    "    return num_correct/len(generated_prompt_ids), corr_set"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluating Program Performance\n",
    "Performance of programs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pass at 1 Model\n",
    "Pass at 1 performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.24299999999999997"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "program_df = pd.read_csv(\"is_test_prog_cor.csv\")\n",
    "\n",
    "pass_at_k(1, program_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Syntax Error Model\n",
    "Checking error rates if just programs w/ syntax errors are removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.2788482603567743"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "syntax_error_df = program_df[program_df[\"Error\"] != \"SyntaxError\"]\n",
    "\n",
    "pass_at_k(1, syntax_error_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.32"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "accu_se, baseline_se_set = baseline_model(syntax_error_df)\n",
    "accu_se\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Baseline Model\n",
    "Selects the first model\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.28"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "accu_bm, baseline_set = baseline_model(program_df)\n",
    "accu_bm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Naive Matching\n",
    "Naive matching model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.46"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "program_and_test_case_df = pd.read_csv(\"gen_test_prog.csv\")\n",
    "accu_nm, naive_matching_set = naive_matching(program_and_test_case_df)\n",
    "accu_nm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Diff from baseline : naive-matching size -  23, baseline size - 14, diff - 10\n",
      "Diff from baseline syntax-free: naive-matching size -  23, baseline size - 16, diff - 9\n"
     ]
    }
   ],
   "source": [
    "print(f\"Diff from baseline : naive-matching size -  {len(naive_matching_set)}, baseline size - {len(baseline_set)}, diff - {len(naive_matching_set.difference(baseline_set))}\")\n",
    "\n",
    "print(f\"Diff from baseline syntax-free: naive-matching size -  {len(naive_matching_set)}, baseline size - {len(baseline_se_set)}, diff - {len(naive_matching_set.difference(baseline_se_set))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluating Test Case Performance\n",
    "\n",
    "Performance of test cases"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pass at 1 Model\n",
    "Pass at 1 performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.2801958718983016"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "program_df = pd.read_csv(\"is_test_test_correct.csv\")\n",
    "\n",
    "pass_at_k(1, program_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Syntax Error Model\n",
    "Checking error rates if just programs w/ syntax errors are removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.2956223418201476"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "syntax_error_df = pd.read_csv(\"is_test_test_correct.csv\")\n",
    "\n",
    "syntax_error_df = syntax_error_df[syntax_error_df[\"Error\"] != \"SyntaxError\"]\n",
    "\n",
    "pass_at_k(1, syntax_error_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Random Data Exploration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "def exchange(lst1, lst2):\n",
      "    \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n",
      "    and determines whether it is possible to perform an exchange of elements\n",
      "    between them to make lst1 a list of only even numbers.\n",
      "    There is no limit on the number of exchanged elements between lst1 and lst2.\n",
      "    If it is possible to exchange elements between the lst1 and lst2 to make\n",
      "    all the elements of lst1 to be even, return \"YES\".\n",
      "    Otherwise, return \"NO\".\n",
      "    For example:\n",
      "    exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n",
      "    exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n",
      "    It is assumed that the input lists will be non-empty.\n",
      "    \"\"\"\n",
      "    \n",
      "    #Build a 1D Tensorflow.SparseTensor to contain the Biadjacency List for the bipartite prediction graph\n",
      "    indices = np.concatenate(\n",
      "        (np.zeros((len(range(len(lst1))), 1)),\n",
      "        np.array([range(len(range(len(lst1))))])[:, None]), axis=1).astype(int)\n",
      "    values = np.array([1] * len(indices))\n",
      "    shape = (len(lst1), len(range(len(lst1))))\n",
      "    sparse_lst1_idx = tf.SparseTensorValue(indices, values, shape)\n",
      "\n",
      "    #Use np.tile to build a tile array of ones. We will use this along with a tf SparseTensor to build the bicliques in the Tensorflow Graph.\n",
      "    #The \"key\" to solving this problem is that the MLP for each biclique will be trained to predict whether there exits ONE configuration of\n",
      "    #interger numbers that solves the problem. This is more efficiently solved by a sigmoid activation on the last layer and binary cross entropy\n",
      "    #for the loss function. In the main loop of the Graph, we use a tf.while_loop with GradientTape and AdamOptimizer to update the parameters\n",
      "    #of the MLP until it finds such a configuration (see below).\n",
      "    ones = np.tile((np.array(range((len(lst1)) * (len(lst2)) * (len(lst2) *\n",
      "                    (len(range(len(lst1)))))) // ((len(lst2) *\n",
      "                    (len(lst2) * (len(range(len(lst1))))))))[:, None],\n",
      "                    ((len(lst2) * (len(lst2) * (len(range(len(lst1))))))), 1)\n",
      "    lst2_idx_list = []\n",
      "    lst2_val_list = []\n",
      "    for lst2_1 in range(len(lst2)):\n",
      "        for lst2_2 in range(len(lst2)):\n",
      "            for lst1_idx in range(len(range(len(lst1)))):\n",
      "\n",
      "                #build tf.SparseTensor tile arrays to fill the Biadjacency lists for the biclique's MLP training graph\n",
      "                indices = np.concatenate(\n",
      "                    ((np.array([lst2_1] * (len(lst1))) + (len(lst1) * ones))[:,\n",
      "                    None], np.array([range(len(lst1))])[:, None]), axis=1).astype(int)\n",
      "                values = np.array([1] * len(lst1)).astype(float)\n",
      "                shape = (len(lst2) * (len(lst2) * (len(range(\n",
      "                    len(lst1))))), len(lst1))\n",
      "                lst2_idx_list.append(tf.SparseTensorValue(\n",
      "                    indices, values, shape))\n",
      "                indices = np.concatenate(\n",
      "                    ((np.array([lst2_2] * (len(lst1))) + (len(lst1) * ones))[:,\n",
      "                    None], np.array([range(len(lst1))])[:, None]), axis=1).astype(int) + (len(lst1))\n",
      "                values = np.array([1] * len(lst1)).astype(float)\n",
      "                shape = (len(lst2) * (len(lst2) * (len(range(len(lst1))))), len(lst1))\n",
      "                lst2_idx_list.append(tf.SparseTensorValue(\n",
      "                    indices, values, shape))\n",
      "                lst2_val_list.append(np.array([int(x) for x in np.char.mod(\n",
      "                    '%d', (lst2[lst2_1] * ones + (lst1[lst1_idx])))]))\n",
      "-----------------------------\n",
      "\n",
      "def exchange(lst1, lst2):\n",
      "    \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n",
      "    and determines whether it is possible to perform an exchange of elements\n",
      "    between them to make lst1 a list of only even numbers.\n",
      "    There is no limit on the number of exchanged elements between lst1 and lst2.\n",
      "    If it is possible to exchange elements between the lst1 and lst2 to make\n",
      "    all the elements of lst1 to be even, return \"YES\".\n",
      "    Otherwise, return \"NO\".\n",
      "    For example:\n",
      "    exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n",
      "    exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n",
      "    It is assumed that the input lists will be non-empty.\n",
      "    \"\"\"\n",
      "    # 1: if each number in the first list can be found in the second\n",
      "    # e.g. like a palindrome\n",
      "        # exchange both in and index?\n",
      "        # each one in the even lst is in the other lst and\n",
      "            # it's index is the index of the odd in that list?\n",
      "            # branch it as a palindrome\n",
      "    # at least e.g. 1 - 0, 2 - 1\n",
      "    ## END of initial Problems\n",
      "\n",
      "    # One of these things his not like the other!\n",
      "    if type(lst1) != type(lst2):\n",
      "        return \"dICKS\"\n",
      "    if len(lst1) != len(lst2):\n",
      "        return \"NO\"\n",
      "    if len(lst1) == 1 or 2:\n",
      "        if lst1[0] % 2 == 0 or 2:\n",
      "            return \"YES\"\n",
      "        return \"NO\"\n",
      "\n",
      "    if len(lst1) % 2 != 0:\n",
      "        return \"dICKS\"\n",
      "\n",
      "    evens = list(filter(lambda x: x % 2 == 0, lst1))\n",
      "    odds = list(filter(lambda x: x % 2 != 0, lst1))\n",
      "    # lst1_indices = list(filter(lambda x: x % 2 != 0, lst2))\n",
      "\n",
      "    # print(\"Evens: \", evens)\n",
      "    # print(\"Odds: \", odds)\n",
      "    # print(\"Evens: \", evens)\n",
      "\n",
      "    even_odd = False\n",
      "    for odd in odds:\n",
      "        try:\n",
      "            # FIND the odd in the evens\n",
      "            index_of_odd = evens.index(odd)\n",
      "            print(\"numbers\", odd, evens[index_of_odd])\n",
      "            # lst1_indices[index_of_odd]\n",
      "        except ValueError:\n",
      "            print(\"Values_err\")\n",
      "            even_odd = False\n",
      "            continue\n",
      "        else:\n",
      "            print(\"number: \", index_of_odd) # even number index\n",
      "            print(\"list_index: \", lst1.index(evens[index_of_odd])) # odd number index\n",
      "            is_pali = True  # could this be a palindrome?\n",
      "            possible_result_vectors = [odd, evens[index_of_odd]]\n",
      "            even_odd = True\n",
      "    for even in evens:\n",
      "        try:\n",
      "            # FIND with respect to the odd numbers\n",
      "            index_of_even = odds.index(even) # returns index if found in evens\n",
      "            print(\"numbers: \", even, odds)\n",
      "        except ValueError:\n",
      "            print(\"Value_err\")\n",
      "            even_odd = False\n",
      "            continue\n",
      "        else:\n",
      "            print(\"number: \", index_of_odd) # even number index\n",
      "            print(\"list_index: \", lst1.index(evens[index_of_odd])) # odd number index\n",
      "            is_pali = True  # could this be a palindrome?\n",
      "            possible_result_vectors = [odd, evens[index_of_odd]]\n",
      "            even_odd = True\n",
      "\n",
      "    # # POP, POP\n",
      "    # popd_even = evens.pop(popd)\n",
      "    # popd_odd = odds.pop(popd)\n",
      "    #\n",
      "    print(\"vector: \", possible_result_vectors)\n",
      "    pal_auth = set(possible_result_vectors)\n",
      "    print(\"authors: \", pal_auth)\n",
      "\n",
      "    # ## if palihandrome:\n",
      "    if even_odd and len(pal_auth) == len(evens):\n",
      "        print(\"markov chains\")\n",
      "        return \"YES\"\n",
      "\n",
      "    return \"NO\"\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "print(\"NO: \", exchange([1, 2, 3, 4], [1, 7, 3, 4]))  #\n",
      "print(\"hell-Yest: \", exchange([1, 2, 4], [1, 4, 9]))  #\n",
      "print(\"NO: \", exchange([1, 2, 3], [1, 3, 3]))  #\n",
      "print(\"YES: \", exchange([1, 1, 2, 4, 5], [3, 5, 6, 8, 10]))\n",
      "-----------------------------\n",
      "\n",
      "def exchange(lst1, lst2):\n",
      "    \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n",
      "    and determines whether it is possible to perform an exchange of elements\n",
      "    between them to make lst1 a list of only even numbers.\n",
      "    There is no limit on the number of exchanged elements between lst1 and lst2.\n",
      "    If it is possible to exchange elements between the lst1 and lst2 to make\n",
      "    all the elements of lst1 to be even, return \"YES\".\n",
      "    Otherwise, return \"NO\".\n",
      "    For example:\n",
      "    exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n",
      "    exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n",
      "    It is assumed that the input lists will be non-empty.\n",
      "    \"\"\"\n",
      "    lst1_sum = 0\n",
      "    lst2_sum = 0\n",
      "    for num in lst1:\n",
      "        lst1_sum += num\n",
      "    for num in lst2:\n",
      "        lst2_sum += num\n",
      "    totals = [i+j for i in lst1 for j in lst2]\n",
      "    # print(totals)\n",
      "    while totals:\n",
      "        if totals[0] % 2 == 0:\n",
      "            return \"YES\"\n",
      "        del totals[0]\n",
      "        # print(totals)\n",
      "        if not totals:\n",
      "            return \"NO\"\n",
      "    else:\n",
      "        return \"NO\"\n",
      "    # total = lst1[0]+lst1[1]+lst1[2]+lst2[0]+lst2.pop(1)+lst2[2]\n",
      "\n",
      "    # print(total)\n",
      "    # if total % 2 == 0:\n",
      "    #     return \"YES\"\n",
      "    # totals = [i+j for i in lst1 for j in lst2]\n",
      "    # # print(totals)\n",
      "    # while totals:\n",
      "    #     if totals[0] % 2 == 0:\n",
      "    #         return \"YES\"\n",
      "    #     del totals[0]\n",
      "    #     # print(totals)\n",
      "    #     if not totals:\n",
      "    #         return \"NO\"\n",
      "    # else:\n",
      "    #     return \"NO\"\n",
      "\n",
      "\n",
      "\"\"\"Write a function findSubstring() that takes two arguments.\n",
      "The first argument is the search word and the second argument is\n",
      "the list to search in.\n",
      "1. Each element in the list is a tuple of one string and an index number.\n",
      "   An example list is [(“uram”,4),(“garazs”,2),(“ut”,12),(“szam”,7)]\n",
      "   Each tuple, has the searchable word and an index, counting\n",
      "   from the first character of the given list.\n",
      "2. Determine whether the search word is a substring of one of the tuples\n",
      "   in the list. If it is, then return the tuple where the substring is found.\n",
      "   Otherwise return the empty list (=list with zero elements).\n",
      "3. In the given list of tuples the false match be found as well\n",
      "   (see the following example at “uram” substring).\n",
      "   So, as the result of the findSubstring() call, the\n",
      "   tuple with lower index is returned.\n",
      "4. If two or more tuples contain the search word then the tuple with lower index\n",
      "   is returned.\n",
      "   For example, findSubstring(“am”,…) will return the tuple (“garazs”,2),\n",
      "   instead of tuple (“ut”,12).\n",
      "Another example:\n",
      "print(findSubstring(\"am\", [(“uram”,4),(“gha”,8),(“sgart”,2),(“sssss”,9)]))\n",
      "(“gha”,8)\n",
      "print(findSubstring(\"tuit\", [(“ghad”,8),(“tui”,5),(“aa”,11),(“hhee”,7)]))\n",
      "    #findSubstring(\"\", [(“ghad”,8),(“tui”,5),(“aa”,11),(“hhee”,7)])\n",
      "    #findSubstring(\"d\", [(“ghad”,8),(“tui”,5),(“aa”,11),(“hhee”,7)])\n",
      "    #findSubstring(\"x\", [(“ghad”,8),(“tui”,5),(“aa”,11),(“hhee”,7)])\n",
      "    #findSubstring(\"a\", [(“ghad”,8),(“tui”,5),(“aa”,11),(“hhee”,7)])\n",
      "    #findSubstring(\"uie\", [(\n",
      "-----------------------------\n",
      "\n",
      "def histogram(test):\n",
      "    \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n",
      "    of the letter with the most repetition and containing the corresponding count.\n",
      "    If several letters have the same occurrence, return all of them.\n",
      "    \n",
      "    Example:\n",
      "    histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n",
      "    histogram('a b b a') == {'a': 2, 'b': 2}\n",
      "    histogram('a b c a b') == {'a': 2, 'b': 2}\n",
      "    histogram('b b b b a') == {'b': 4}\n",
      "    histogram('') == {}\n",
      "\n",
      "    \"\"\"\n",
      "    \n",
      "    histo_dict = {} #initial empty dictionary\n",
      "    histo_list = test.split(' ') #full of letter and int\n",
      "    letter_list = []\n",
      "    int_list = []\n",
      "    \n",
      "    for element in histo_list: #element being letter alone or letter and digit\n",
      "        if element[0].isalpha() and element[-1].isnumeric():\n",
      "            letter_element = element[0]\n",
      "            int_element = int(element[1:])\n",
      "            if not letter_element in letter_list:\n",
      "                letter_list.append(letter_element) #only appends the FIRST letter (which is the main point of the program)\n",
      "            if not int_element in int_list:\n",
      "                int_list.append(int_element)        \n",
      "    print '\\nhistogram(test): A string representing a space separated lowercase letter and number. Returns dictionary of most frequent letter. Letters alone are counted as 1. Letters with numbers are counted as certain amount (int value of the number).'\n",
      "    print '\\nOriginal: ', histo_list\n",
      "    print '\\nLetters: ', letter_list\n",
      "    print '\\nIntegers: ', int_list\n",
      "    print '\\n********'\n",
      "    \n",
      "    for i in range(0, len(letter_list)):\n",
      "        if i < len(int_list):\n",
      "            histo_dict[letter_list[i]] = int_list[i]\n",
      "        else:\n",
      "            histo_dict[letter_list[i]] = 1\n",
      "    return histo_dict\n",
      "\n",
      "\n",
      "print 'Solution 1 Tests: histogram(\\\"\\\")'\n",
      "print histogram('')\n",
      "print 'Solution 1 Tests: histogram(\\\"a\\\")'\n",
      "print histogram('a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b\\\")'\n",
      "print histogram('a b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b c\\\")'\n",
      "print histogram('a b c')\n",
      "print 'Solution 1 Tests: histogram(\\\" a b c\\\")'\n",
      "print histogram(' a b c')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b c \\\")'\n",
      "print histogram('a b c ')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b a\\\")'\n",
      "print histogram('a b a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b b a\\\")'\n",
      "print histogram('a b b a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a b c a b c\\\")'\n",
      "print histogram('a b c a b c')\n",
      "print 'Solution 1 Tests: histogram(\\\"b b b b a\\\")'\n",
      "print histogram('b b b b a')\n",
      "print 'Solution 1 Tests: histogram(\\\"b b b b b\\\")'\n",
      "print histogram('b b b b b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a b b\\\")'\n",
      "print histogram('a a a b b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a b b c c\\\")'\n",
      "print histogram('a a b b c c')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a\\\")'\n",
      "print histogram('a a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a\\\")'\n",
      "print histogram('a a a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a a\\\")'\n",
      "print histogram('a a a a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a a a\\\")'\n",
      "print histogram('a a a a a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a a a a\\\")'\n",
      "print histogram('a a a a a a')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a a b\\\")'\n",
      "print histogram('a a a a b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a a b b\\\")'\n",
      "print histogram('a a a b b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a b b b\\\")'\n",
      "print histogram('a a b b b')\n",
      "print 'Solution 1 Tests: histogram(\\\"a a\n",
      "-----------------------------\n",
      "\n",
      "def histogram(test):\n",
      "    \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n",
      "    of the letter with the most repetition and containing the corresponding count.\n",
      "    If several letters have the same occurrence, return all of them.\n",
      "    \n",
      "    Example:\n",
      "    histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n",
      "    histogram('a b b a') == {'a': 2, 'b': 2}\n",
      "    histogram('a b c a b') == {'a': 2, 'b': 2}\n",
      "    histogram('b b b b a') == {'b': 4}\n",
      "    histogram('') == {}\n",
      "\n",
      "    \"\"\"\n",
      "    hist = {}\n",
      "    for ch in test.split(): #Also use sp_test = test.split(' ') or take test = 'juststring' string\n",
      "        hist[ch] = hist.get(ch,0) + 1\n",
      "    return hist\n",
      "varfreqdict = histogram(\"\"\" 1  4  23 53 73 37 58 56 52 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 77 71 53 44 36 false Null Null Null Null Null Null Null Null Null Null Null Null Null Null Null Null 0945 0130 0600 1238 0002 0000 0415 JITENDRA PRASAD  A K SOKHI DR. VIKAS SRIVASTAVA  MRS. NIVEDITA A ARORA  PRASANTA KUMAR DAS  SUKHWINDER KAUR  U. SHAILAJA  KUSUMAM AMMA S ABDUL HAMEED DR. S. POORNA CHANDRA  G. PLUNDENGA KESHARI  A. B. PRADEEP  K HEMALATA  DEVI PRASAD  JAVED AHMED KAZI  N. V. RAMESH CHANDRA  P. SURESH RAJU  VAYASELVAN G  KIRAN  SHALINI NAIR  BISHWANATH MAJI  SURESH  G S MURTHY  GIMURTHY.B  NISHA D. HEGDE  PRANAY MEHTALSHA RAMANI JUDGE PRAVEEN  KUM KALPANA  KACHARLA  HARI PRASAD  MAHABIR SINGH  SALWA KAMAL  S. VENKATESWARA SARMA DR. T.V. SUNDARAM  DR. TOM GIRIOLI  K. M. ABDUL  SHAJI PAUL GERALD KHEMANI  RAM GAURAV AGARWAL  BOLESWAR RAI  NISHA GRACE JAMES  DR. SUBRATA RAY  DR. S. SREERAM MURTHY  DR. A. JOTHIRAJU  K. HEMA BHASKARAN RAKESH SAXENA  VANLALNUMA  T. R. SRINIVASAN  JASWANTHINDER KAUR  UNIDENTIFIED DEATH  RADHESHYAM AGGARWAL  SUDHA SHIVAJI NAIK  ANSARI YOUSAF BASHIR  NALINI  R. TULSIRAJ  DR. AZAD HUSSAIN  DR. C. PADMANABHA  M. R. SRINIVAS  MADAN MOHAN DAS  B. SARALA  BENPLAS PHENOLIK SUMATHI A. CONGLOMERATE MR. NARASIMHAMURTHY  P.K. NADKARNI  BONES SHAFI ZAKIR  NAGESWARA RAO  HARI  V.V. RANGADURAI  GRACE BUCKLAND  MRS VINAYA  SATISH CHANDRA SAXENA   CST VADEVARAPURA SUDHIR & V M RAO  PIYUSHKUMAR CHANDARSHANKAR  SHRAVAN  BANERJEE SOUMYAJIT   L TRONGHAI LEONARD MADERIAS  PRAKASH D DIGWADI  VAGENSA GRACE MENGHARENSISS  KARANAM RAMESH KUMAR  MANAS H. SANTRA  REKHA SHARMA  RINA VINOD GARG METHUTHA VINOTHAN  GEORGE VARGHESE MM  MILLIA GONZALEVICMO DR. S.V. VENKATA  UNIDENTIFIED MALE  RAJIV KUMAR  C. SUNDARARAJAN  SARBIN SINGH  MRS. NISHA PILLAI  SHAHID\n",
      "-----------------------------\n",
      "\n",
      "def intersection(interval1, interval2):\n",
      "    \"\"\"You are given two intervals,\n",
      "    where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n",
      "    The given intervals are closed which means that the interval (start, end)\n",
      "    includes both start and end.\n",
      "    For each given interval, it is assumed that its start is less or equal its end.\n",
      "    Your task is to determine whether the length of intersection of these two \n",
      "    intervals is a prime number.\n",
      "    Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n",
      "    which its length is 1, which not a prime number.\n",
      "    If the length of the intersection is a prime number, return \"YES\",\n",
      "    otherwise, return \"NO\".\n",
      "    If the two intervals don't intersect, return \"NO\".\n",
      "\n",
      "\n",
      "    [input/output] samples:\n",
      "    intersection((1, 2), (2, 3)) ==> \"NO\"\n",
      "    intersection((-1, 1), (0, 4)) ==> \"NO\"\n",
      "    intersection((-3, -1), (-5, 5)) ==> \"YES\"\n",
      "    \"\"\"\n",
      "    #  Although these intervals are given as a pair of integers, \n",
      "    #  this challenge is best solved in some programming languages with the datatype \n",
      "    #  'Interval', 'Segment' or 'Range'. Feel free to use this datatype in your code \n",
      "    #  when you solve this challenge on these platforms.\n",
      "    \"\"\"\n",
      "    if interval1[0]==interval2[0]:\n",
      "        if interval1[1]==interval2[1] :\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):     #to check if the length of interval is a prime number or not\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval1[1]<interval2[1]:\n",
      "            l=len(interval2)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval2[1]<interval1[1]:\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "    elif interval2[0]==interval1[0]:\n",
      "        if interval1[1]==interval2[1] :\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):     #to check if the length of interval is a prime number or not\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval2[1]<interval1[1]:\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval1[1]<interval2[1]:\n",
      "            l=len(interval2)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "\n",
      "    elif interval1[1]==interval2[1]:\n",
      "        if interval1[0]<interval2[0]:\n",
      "            l=len(interval2)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval2[0]<interval2[0]:\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "    elif interval2[1]==interval1[1]:\n",
      "        if interval2[0]<interval1[0]:\n",
      "            l=len(interval1)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "        elif interval1[0]<interval2[0]:\n",
      "            l=len(interval2)\n",
      "            if is_prime(l):\n",
      "                return \"YES\"\n",
      "            else:\n",
      "                return \"NO\"\n",
      "\n",
      "    elif interval2[0]<interval1[0] and interval1[1]<interval2[1]:\n",
      "        l=len(interval1)\n",
      "        if is_prime(l):\n",
      "            return \"YES\"\n",
      "        else:\n",
      "            return \"NO\"\n",
      "\n",
      "    elif interval1[0]<interval2[0] and interval2[1]<interval1[1]:\n",
      "        l=len(interval2)\n",
      "        if is_prime(l):\n",
      "            return \"YES\"\n",
      "        else:\n",
      "            return \"NO\"\n",
      "    else:\n",
      "    return \"NO\"\n",
      "    \"\"\"\n",
      "    if interval2[0]<interval1[0] and interval1[1]<interval2[1]:\n",
      "        l=len(interval1)\n",
      "        print l\n",
      "        if is_prime(l):\n",
      "            return \"YES\"\n",
      "        else:\n",
      "            return \"NO\"\n",
      "\n",
      "    elif interval1[0]<interval2[0] and interval2[1]<interval1[1]:\n",
      "        l=len(interval1)\n",
      "        print l\n",
      "        if is_prime(l):\n",
      "            return \"YES\"\n",
      "        else:\n",
      "-----------------------------\n",
      "\n",
      "def intersection(interval1, interval2):\n",
      "    \"\"\"You are given two intervals,\n",
      "    where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n",
      "    The given intervals are closed which means that the interval (start, end)\n",
      "    includes both start and end.\n",
      "    For each given interval, it is assumed that its start is less or equal its end.\n",
      "    Your task is to determine whether the length of intersection of these two \n",
      "    intervals is a prime number.\n",
      "    Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n",
      "    which its length is 1, which not a prime number.\n",
      "    If the length of the intersection is a prime number, return \"YES\",\n",
      "    otherwise, return \"NO\".\n",
      "    If the two intervals don't intersect, return \"NO\".\n",
      "\n",
      "\n",
      "    [input/output] samples:\n",
      "    intersection((1, 2), (2, 3)) ==> \"NO\"\n",
      "    intersection((-1, 1), (0, 4)) ==> \"NO\"\n",
      "    intersection((-3, -1), (-5, 5)) ==> \"YES\"\n",
      "    \"\"\"\n",
      "    from math import sqrt\n",
      "    from functools import reduce\n",
      "\n",
      "    def isPrime(num):\n",
      "        for n in range(2, int(sqrt(abs(num)))+2):\n",
      "            if num % n == 0:\n",
      "                return False\n",
      "\n",
      "        return True\n",
      "\n",
      "\n",
      "    def gcd(a,b):\n",
      "        \"\"\" Function will return the GCD of two numbers using the Euclidean method \"\"\"\n",
      "        while (b):\n",
      "            a,b = b,a%b\n",
      "\n",
      "        if a >= 0:\n",
      "            return a\n",
      "        else:\n",
      "            return a*-1\n",
      "\n",
      "\n",
      "    def lcm(a,b):\n",
      "        \"Function will return the LCM of two numbers\"\n",
      "        return a*b//gcd(a,b)\n",
      "\n",
      "\n",
      "    def gcd_array(lst):\n",
      "        \"\"\" Input: Array/List consisting of integers\n",
      "            Output: Greatest common divisor of all elements in this list.\n",
      "            Function will return the gcd of a list of numbers \"\"\"\n",
      "        return reduce(gcd,lst)\n",
      "\n",
      "\n",
      "    def lcm_array(lst):\n",
      "        \"\"\" Input: Array/List consisting of integers\n",
      "            Output: Lowest common multiple of all elements in this list.\n",
      "            Function will return the lcm of a list of numbers \"\"\"\n",
      "        return reduce(lcm,lst)\n",
      "\n",
      "\n",
      "    def generate_prime_ranges(n):\n",
      "        \"\"\" Sieve of Eratosthenes to generate prime number ranges.\n",
      "        The prime factorization of a semiprime is a power of a prime,\n",
      "        except some other factors that divide evenly into the number.\n",
      "        A number that is not a prime is called a composite number. For example,\n",
      "        the number of 4 only have the factor 2 and 1, which is not counted.\n",
      "        The number of 6 has 2, 3 and 1 as factors, 2 and 3 will be the factors that counted.\n",
      "\n",
      "        A composite number has a prime factorization with a prime number multiplied with another\n",
      "        number that might be a prime or a composite. A composite number with only two prime factors is called\n",
      "        a semiprime. With the example shown in 3 we know that the factor of 15 is 6, 3 and 1,\n",
      "        all three numbers are multiplied, however only number 6 as the power of 2 that is counted.\n",
      "        By definition, semiprime is a natural number which has exactly two prime number,\n",
      "        so the prime factorization of a semiprime is a power of a prime,\n",
      "        except some other factors that just divide evenly into the number.\n",
      "        Because the prime factorization of a semiprime is a power of a prime,\n",
      "        Using the sieve of Eratosthenes technique, all of the multiples of the\n",
      "        prime number are factorised and made composite by crossing off any remaining value.\n",
      "        By counting up crosses we will have odd composite numbers that identify\n",
      "        prime, 2, and the all other prime multiples which begin at 3. By looping across\n",
      "        the whole number which is the product of that prime, we can able to reactivate\n",
      "        all of those numbers by crossing off multiples of the squares of the prime.\n",
      "\n",
      "        ** Eratosthenes sieve **\n",
      "\n",
      "        - Make a list of consecutive natural numbers from 2 to n.\n",
      "        - Initially let p equal 2, the smallest prime.\n",
      "        - Repeatedly mark as composite (i.e. not prime) the multiples\n",
      "            of p starting from 2p, 3p, 4p and so on not exceeding n.\n",
      "        - Find the first number greater than p in the list that was unmarked.\n",
      "        - If there was no such number, stop. Otherwise,\n",
      "        - Let p now equal this number (which is the next prime),\n",
      "            and repeat from 3.\n",
      "\n",
      "        This will no longer work if the number or list is prime or didn't have a complete number range,\n",
      "        and that is there is only 2 composite number for 2 and for every prime numbers\"\"\"\n",
      "\n",
      "        primes = list(range(2, n+1))\n",
      "        # print(f'List: {primes}')\n",
      "\n",
      "        marks = [[x] for x in primes]\n",
      "        # print(f'P: {marks}')\n",
      "\n",
      "        for p in marks:\n",
      "            value_index = marks.index(p)\n",
      "\n",
      "            if p == [2\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    def _dp(k):\n",
      "        \"\"\"\n",
      "        We will use a 2D Dynamic Programming matrix (dp) \n",
      "        in order to find shortest path at every given step \n",
      "        & row. The idea is to use dp with indexes (i, v(i)) \n",
      "        where i is row index and v(i) is grid[i] position of \n",
      "        the kth smallest value. We break up all possible values \n",
      "        into different partitions. Then, we assert another \n",
      "        different partition as a possible value from that \n",
      "        separate cell, thus creating another partition. We will \n",
      "        complete one k-th step for all possible partitions, \n",
      "        and choose the partition that leads through the \n",
      "        shortest path and has the kth smalles value at \n",
      "        the kth position.\n",
      "        \"\"\"\n",
      "        n = V = len(grid)\n",
      "        ranges = {}\n",
      "        for i in range(n):\n",
      "            for j in range(n):\n",
      "                if grid[i][j] not in ranges:\n",
      "                    ranges[grid[i][j]] = [(i, j)]\n",
      "                ranges[grid[i][j]].append((i, j))\n",
      "        max_range = max(ranges) + 1\n",
      "        dp = {0: {(0, 0): 0}}\n",
      "        get_v = len(ranges[min(ranges)])\n",
      "        range_pos = get_v - 1\n",
      "        while range_pos < k:\n",
      "            min_val = min(ranges)\n",
      "            vals = ranges[min_val]\n",
      "            old = dp\n",
      "            new = {}\n",
      "            for step, paths in old.items():\n",
      "                for start in vals:\n",
      "                    for end in paths:\n",
      "                        val_step = step + abs(end[0] - start[0] + end[1] - start[1]) - 1\n",
      "                        prevVal = abs(start[0] - end[0]) + abs(start[1] - end[1])\n",
      "                        val = paths[end] + prevVal\n",
      "                        if val_step not in new:\n",
      "                            new[val_step] = {start: val}\n",
      "                        elif start not in new[val_step]:\n",
      "                            new[val_step][start] = val\n",
      "                        elif val < new[val_step][start]:\n",
      "                            new[val_step][start] = val\n",
      "            dp = new\n",
      "            end_step = max(dp)\n",
      "            vals.reverse()\n",
      "            ranges.pop(min_val)\n",
      "            step_vals = set()\n",
      "            for i in range(n):\n",
      "                for j in range(n):\n",
      "                    if i in [l[0] for l in vals] and j in [l[1] for l in vals]:\n",
      "                        step_vals.add(grid[i][j])\n",
      "            for step, paths in dp.items():\n",
      "                dp_vals = []\n",
      "                top_paths = get_kth_smallest_numbers(paths, V)\n",
      "                for start in top_paths:\n",
      "                    path = [start[0]]\n",
      "                    v = get_ladder_path(start, path, step, grid)\n",
      "                    dp_vals += v\n",
      "                rev = [max_range - x for x in step_vals]\n",
      "                step_vals |= set(dp_vals)\n",
      "                step_vals |= set(rev)\n",
      "                for n in range(max_range):\n",
      "                    if n in step_vals and grid[start[0]][start[1]] == min_val:\n",
      "                        continue\n",
      "                    add_range(ranges, ranges_pos, n, start)\n",
      "                    ranges_pos[n] += 1\n",
      "            ranges_pos = {key: 0 for key in ranges}\n",
      "            range_pos += get_v\n",
      "        keys = sorted(dp)\n",
      "        step = keys[len(keys) - 1]\n",
      "        paths = dp[step]\n",
      "        topK = get_kth_smallest_numbers(paths, k)\n",
      "        sorted_paths = []\n",
      "        res = []\n",
      "        for start in topK:\n",
      "            path = [start[0]]\n",
      "            v = get_ladder_path(start,\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "\n",
      "    nums = [cell for row in grid for cell in row]\n",
      "    deque = [[nums[0], []], [nums[1], []], [nums[2], []], [nums[3], []]]\n",
      "    minPath = [nums[0], nums[1], nums[2], nums[3]]\n",
      "    node_weights = {}\n",
      "    h, w = len(grid), len(grid[0])\n",
      "\n",
      "    for r in range(4):\n",
      "        for i in range(4):\n",
      "            x, y = r1, c1 = r // 2, r % 2 * 1\n",
      "            x1, y1 = r2, c2 = (i // 2 + h // 2) % h, (i % 2 * 1 + w // 2) % h\n",
      "            if x1 > x:\n",
      "                m1 = min(k, x1 - x)\n",
      "                for j in range(1, m1 + 1):\n",
      "                    node_weights[grid[x1 - j][y1]] = j\n",
      "            else:\n",
      "                m1 = min(k, x - x1)\n",
      "                for j in range(1, m1 + 1):\n",
      "                    node_weights[grid[x1 + j][y1]] = j\n",
      "\n",
      "            if y1 > y:\n",
      "                m2 = min(k, y1 - y)\n",
      "                for j in range(1, m2 + 1):\n",
      "                    node_weights[grid[x1][y1 - j]] = j\n",
      "            else:\n",
      "                m2 = min(k, y - y1)\n",
      "                for j in range(1, m2 + 1):\n",
      "                    node_weights[grid[x1][y1 + j]] = j\n",
      "\n",
      "    # our root node for Dijkstra, is the uppermost left cell of our grid\n",
      "    # then we start to evaluate its all neighbors, lower left and right cells,\n",
      "    # these are the possible nodes we can visit with tse minimum weight given,\n",
      "    # so we put them in a double ended queue, since we will compare\n",
      "    # their weights after and pop the one wth the least weight\n",
      "    for i in range(4):\n",
      "        for c in range(4):\n",
      "            if (grid[i // 2][i % 2 * 1]) in node_weights:\n",
      "                deque[i][1].append(node_weights[grid[i // 2][i % 2 * 1]])\n",
      "\n",
      "    # our track to visit each cell once and only once, hold all distances from\n",
      "    # the root node of starting cells on grid\n",
      "    distances = [sum(deque[0][1]), sum(deque[1][1]), sum(deque[2][1]), sum(deque[3][1])]\n",
      "    tracks = [deque[0][0], deque[1][0], deque[2][0], deque[3][0]]\n",
      "    while True:\n",
      "        # get the smallest value and and its index\n",
      "        index = distances.index(min(distances))\n",
      "        _, indices = deque[index]\n",
      "        x, y = r // 2, r % 2 * 1\n",
      "\n",
      "        # append all neighbor nodes to the deque with the new path weights\n",
      "        # and update the distance whether it is larger or smaller than what\n",
      "        # we already have, finally pop once we have visited all cells and\n",
      "        # come back to our root note\n",
      "        for i in range(4):\n",
      "            for j in range(4):\n",
      "                if grid[i // 2][i % 2 * 1] in node_weights:\n",
      "                    estimated = node_weights[grid[i // 2][i % 2 * 1]] +\\\n",
      "                        sum(indices + [distances[i]])\n",
      "                    if estimated > k:\n",
      "                        pass\n",
      "                    elif estimated < distances[i]:\n",
      "                        distances[i] = estimated\n",
      "                        deque[i][0] = tracks[index] +\\\n",
      "                            [grid[i // 2][i % 2 * 1]]\n",
      "                    elif estimated < distances[i]:\n",
      "                        continue\n",
      "\n",
      "        # store the calculated path after each iteration, calculate the\n",
      "        # lexicographic weight for each path, then pop its smallest weight\n",
      "        # from the deque, check if its lexicographic weight\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    m = len(grid)\n",
      "    n = len(grid[0])\n",
      "    \n",
      "    def isValid(i, j, v):\n",
      "            \n",
      "        if i == 0:\n",
      "            return j>=1 and abs(grid[i][j] - v) <= k\n",
      "\n",
      "        if j == 0:\n",
      "            return i>=1 and abs(grid[i][j] - v) <= k and abs(grid[i-1][j] - grid[i][j]) > k\n",
      "        \n",
      "        return i>=1 and j>=1 and abs(grid[i][j] - v) <= k and abs(grid[i-1][j] - grid[i][j]) > k and abs(grid[i][j-1] - grid[i][j]) > k\n",
      "    \n",
      "    def helper(i, j, s_i, s_j, sum, v, level):\n",
      "        \n",
      "        nonlocal result, ctn, ttl\n",
      "        \n",
      "        if level >= ctn:\n",
      "            return\n",
      "        \n",
      "        if i < 0 or j < 0:\n",
      "            return\n",
      "\n",
      "\n",
      "        if grid[i][j] == 1:\n",
      "    \n",
      "            if (s_i, s_j) in seen:\n",
      "\n",
      "                i_mask = seen[(s_i, s_j)][0]\n",
      "                j_mask = seen[(s_i, s_j)][1]\n",
      "\n",
      "            else:\n",
      "                i_mask = tuple()\n",
      "                j_mask = tuple()\n",
      "            \n",
      "                curr = (i, j)\n",
      "                delta = [(-1, 0), (0,1), (1, 0)]\n",
      "                stack = [curr]\n",
      "                \n",
      "                while stack:\n",
      "                    idx = stack.pop()\n",
      "                    i2, j2 = idx\n",
      "                    \n",
      "                    for delta_i, delta_j in delta:\n",
      "                        tmp_i, tmp_j = i2+delta_i, j2+delta_j\n",
      "                        if -1<tmp_i<n and -1<tmp_j<m and \\\n",
      "                            ((tmp_i, tmp_j) not in i_mask) and grid[tmp_i][tmp_j] == v:\n",
      "\n",
      "                            i_mask += (tmp_i, )\n",
      "                            j_mask += (tmp_j, )\n",
      "                            stack.append((tmp_i, tmp_j))\n",
      "                    \n",
      "                seen[(s_i, s_j)] = (i_mask, j_mask)\n",
      "\n",
      "\n",
      "            cands = []\n",
      "                    \n",
      "            for t_i, t_j in zip(i_mask, j_mask):\n",
      "                \n",
      "                if isValid(t_i, t_j, v+1):\n",
      "                    cands.append((t_i, t_j))\n",
      "\n",
      "            for t_i, t_j in cands:\n",
      "                if level == ctn-1:\n",
      "                    \n",
      "                    if sum < result:\n",
      "\n",
      "                        ctn = level + 1\n",
      "                        ttl = [(i,j)]\n",
      "                        result = sum\n",
      "                    \n",
      "                elif v > grid[t_i][t_j]:\n",
      "                    helper(t_i, t_j, i, j, sum+abs(t_i-i)+abs(t_j-j), v+1, level+1)\n",
      "                    \n",
      "                else:\n",
      "                    helper(t_i, t_j, i, j, sum+abs(t_i-i)+abs(t_j-j), grid[t_i][t_j], level+(v-grid[t_i][t_j]))\n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "            \n",
      "        \n",
      "    result = math.inf\n",
      "    ctn = math.inf\n",
      "\n",
      "    ttl = list()\n",
      "    seen = dict()\n",
      "    \n",
      "    for i in range(n):\n",
      "        for j in range(m):\n",
      "            helper(i, j, i, j, 0, grid[i][j], 0)\n",
      "            \n",
      "    ttl = sorted(ttl)\n",
      "\n",
      "\n",
      "    l = list()\n",
      "    for item in ttl:\n",
      "        i, j = item\n",
      "        l.append(grid[i\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n",
      "\n",
      "    n = len(grid)\n",
      "\n",
      "    # Where there are duplicates, the lexicographical criteria ar\n",
      "    # esn't enough to identify a single path.\n",
      "    if n**0.5 > k + 1:\n",
      "        return [0] * k + [1]\n",
      "\n",
      "    # xc, yc denote the coordinates of the south-west corner of the \n",
      "    # subgrid under consideration within grid.\n",
      "    def next_subgrid(mat):\n",
      "        n = len(mat)\n",
      "        xc, yc = 0, 0\n",
      "\n",
      "        subgrid = []\n",
      "        for j in range(n):\n",
      "            for i in range(n):\n",
      "                subgrid.append(mat[i + xc][j + yc])\n",
      "\n",
      "        return subgrid, xc, yc\n",
      "\n",
      "    # The conner is the value at thats in the local subgrid that is\n",
      "    # the destination for the global path going through grid.\n",
      "    def possible_subgrids(subgrid):\n",
      "        n = int(len(subgrid)**0.5)\n",
      "        adjacencies = []\n",
      "\n",
      "        for i in range(n - 1):\n",
      "            for j in range(n - 1):\n",
      "                if subgrid[i * n + j] == max(subgrid):\n",
      "                    corners = list({subgrid[i*n + j + di] \\\n",
      "                        for di in dirs}.intersection(set(subgrid)))\n",
      "                    adjacencies.append((subgrid[i*n + j + 1], i, j + 1))\n",
      "\n",
      "        return adjacencies\n",
      "\n",
      "    class Solve:\n",
      "\n",
      "        tm = textwrap.TextWrapper(subsequent_indent='  ')\n",
      "\n",
      "        def get_subgrid(self, subgrid, x, y):\n",
      "            return 'x'\n",
      "\n",
      "        def __init__(self, mat):\n",
      "            self.rolled = dict()\n",
      "            self.grid = mat\n",
      "\n",
      "        def how_low(self, lst):\n",
      "            for i in range(len(lst)):\n",
      "                for j in range(len(lst) - 1, i, -1):\n",
      "                    if lst[j - 1] < lst[j]:\n",
      "                        lst[j - 1], lst[j] = lst[j], lst[j - 1]\n",
      "            return lst\n",
      "\n",
      "        def solve(self, k, current_path=None, current_iter=0, runningtos=dict()):\n",
      "            n = len(self.grid)\n",
      "\n",
      "            if current_path is None:\n",
      "                current_path = [(0, 0)]\n",
      "            if current_iter == 0:\n",
      "                current_temp_path = current_path\n",
      "            else:\n",
      "                current_temp_path = current_path[:current_iter + 1]\n",
      "\n",
      "            if (self.rolling_hash(current_temp_path), k) in runningtos:\n",
      "                return runningtos[(self.rolling_hash(current_temp_path), k)]\n",
      "\n",
      "            if current_iter >= k - natceil(n**0.5):\n",
      "                # Rethink which dimension to filter on.\n",
      "                # For this case, each cell in a row has to be seen by the spanning\n",
      "                # subtree.\n",
      "                base, xc, yc = next_subgrid(self.subgrid(current_path))\n",
      "                # tm.wrap()\n",
      "                tracker = []\n",
      "                print()\n",
      "                print(f'cells {current_temp_path}')\n",
      "                print()\n",
      "                while len(base) > 1:\n",
      "                    base, xc, yc = next_subgrid(self.subgrid(current_temp_path + tracker))\n",
      "                    possible = possible_subgrids(base)\n",
      "                    print(f'Length(subgrid)={len(subgrid)}, KC={k - current_iter}, n={n}, '\n",
      "                        f'len possible={len(possible)}, possible: ')\n",
      "                    for c in possible:\n",
      "                        print(self.tm.fill(str(c)))\n",
      "                    \n",
      "                    self.next_subgrids(subgrid)\n",
      "                    if len(possible) > current_iter -\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    assert 0 < k\n",
      "    assert 2 <= len(grid) and len(grid) <= 10 ** 5\n",
      "    assert all(len(x) == len(grid) for x in grid)\n",
      "    assert len(grid) ** 2 >= max(k, max(max(row) for row in grid)) >= 1\n",
      "\n",
      "    m = len(grid)\n",
      "\n",
      "    min_path = [[ [None, -1] for j in range(m) ] for i in range(m)]\n",
      "\n",
      "    const = 10 ** 5\n",
      "\n",
      "    for i in range(m):\n",
      "        for j in range(m):\n",
      "            if min_path[i][j][0] is not None:\n",
      "                continue\n",
      "\n",
      "            # Get the path of length 1 from cell [i,j]\n",
      "            cell = grid[i][j]\n",
      "\n",
      "            prev_cell = -1\n",
      "\n",
      "            if i > 0:\n",
      "                prev_cell = min(prev_cell, min_path[i-1][j][0])\n",
      "            if i < m-1:\n",
      "                prev_cell = min(prev_cell, min_path[i+1][j][0])\n",
      "            if j > 0:\n",
      "                prev_cell = min(prev_cell, min_path[i][j-1][0])\n",
      "            if j < m-1:\n",
      "                prev_cell = min(prev_cell, min_path[i][j+1][0])\n",
      "\n",
      "            prev_cell = int(prev_cell > 0) * (prev_cell + 1)\n",
      "\n",
      "            min_cell = const\n",
      "\n",
      "            if prev_cell > 0:\n",
      "                # Check if [i,j] > prev_cell\n",
      "                list_A = [cell]\n",
      "                list_B = [prev_cell]\n",
      "\n",
      "                for i in range(len(list_A)):\n",
      "                    if list_A[i] == list_B[i]:\n",
      "                        continue\n",
      "\n",
      "                    if list_A[i] > list_B[i]:\n",
      "                        min_cell = min(min_cell, list_B[i])\n",
      "                    else:\n",
      "                        min_cell = min(min_cell, list_A[i])\n",
      "\n",
      "                    break\n",
      "\n",
      "            # Set cell_value, prev_cell and delta\n",
      "            if i == 0 and j == 0:\n",
      "                cell_value = int(min_cell == const) * (min_cell + 1)\n",
      "\n",
      "                min_path[i][j] = [cell_value, -1]\n",
      "\n",
      "                continue\n",
      "\n",
      "            if min_cell == const:\n",
      "                min_path[i][j] = [prev_cell + 1, -1]\n",
      "\n",
      "                continue\n",
      "\n",
      "            if min_cell > prev_cell:\n",
      "                min_path[i][j] = [min_cell + 1, 1]\n",
      "            else:\n",
      "                min_path[i][j] = [prev_cell + 1, 0]\n",
      "\n",
      "    visited_set = [[ False for j in range(m) ] for i in range(m)]\n",
      "\n",
      "    res = []\n",
      "\n",
      "    min_cost = [const]\n",
      "    min_acc_sum = [const]\n",
      "    min_acc_idx = [const]\n",
      "    min_prev_pos = [-1, -1]\n",
      "    min_curr_pos = [0, 0]\n",
      "\n",
      "    visited_set[0][0] = True\n",
      "    res.append(grid[0][0])\n",
      "    acc_sum = grid[0][0]\n",
      "    acc = 1\n",
      "\n",
      "    DFS(grid, m, 1, k-1, visited_set, res, \n",
      "        min_cost, const, 0,\n",
      "        min_acc_sum, acc_sum,\n",
      "        min_acc_idx, acc,\n",
      "        min_prev_pos, min_curr_pos)\n",
      "\n",
      "    visited_set[0][0] ^= True\n",
      "\n",
      "    i, j = min_prev_pos\n",
      "    prev_cell = min_path[i][j][0]\n",
      "    delta = min_path[i][j][1]\n",
      "    min_path[i][j][0] += min_cost[0]\n",
      "    min_path[i][j][1] += delta\n",
      "\n",
      "    while k > 0:\n",
      "        next_pos = [i, j]\n",
      "        if i > 0:\n",
      "            if min_path\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "\n",
      "    def manhatann_distance(a, b):\n",
      "        \"\"\"\n",
      "        Calcuates the Manhattan Distance between two gridcells\n",
      "        \"\"\"\n",
      "\n",
      "        return abs(a[0]-b[0])+abs(a[1]-b[1])\n",
      "\n",
      "    def NoGenerator(N):\n",
      "        \"\"\"\n",
      "        Generates the coordinates sequence to go through the grid cell in order\n",
      "        \"\"\"\n",
      "        if N%2 != 0:\n",
      "            coords = [(3*j-1+b, N-i+a) for i in range(1, N+1) for j in range(1, N+1) for a in range(0,2) for b in range(0,2) if((i+j)%2==1 and (a+b)%2==1)]\n",
      "            return coords[:2*(N**2-1)] + coords[2*(N**2-1):]\n",
      "        coords = [(3*j-2+b, N-i+a) for i in range(1, N+1) for j in range(1, N+1) for a in range(0,2) for b in range(0,2) if((i+j)%2==1 and (a+b)%2==1)]\n",
      "        return coords[:2*(N**2-1)] + coords[2*(N**2-1):]\n",
      "\n",
      "    def BFS(x, y, h):\n",
      "        \"\"\"\n",
      "        Breadth first search starting with (x,y). We keep track of the path length\n",
      "        through the additional parameter \"h\" and the path taken through the paths \n",
      "        list\n",
      "        \"\"\"\n",
      "        if (x, y) == coords[-1]:\n",
      "            return None, k\n",
      "        pair_queue.append((x, y, h))\n",
      "        \n",
      "        while pair_queue[0] != None:\n",
      "            curr, dist = pair_queue.pop(0)\n",
      "            if dist == k:\n",
      "                paths.append(path[1:])\n",
      "                continue\n",
      "\n",
      "            #Next four if statements check for bounded traversal\n",
      "            if grid[curr[0]-1][curr[1]-1] != '#':\n",
      "                if dist + manhatann_distance((curr[0]-1, curr[1]-1), coords[-1]) <= k:\n",
      "                    pair_queue.append(((curr[0]-1, curr[1]-1), dist+1))\n",
      "                    path.append(grid[curr[0]-1] [curr[1]-1])\n",
      "\n",
      "            if grid[curr[0]][curr[1]-1] != '#':\n",
      "                if dist + manhatann_distance((curr[0], curr[1]-1), coords[-1]) <= k:\n",
      "                    pair_queue.append(((curr[0], curr[1]-1), dist+1))\n",
      "                    path.append(grid[curr[0]] [curr[1]-1])\n",
      "\n",
      "            if grid[curr[0]+1][curr[1]-1] != '#':\n",
      "                if dist + manhatann_distance((curr[0]+1, curr[1]-1), coords[-1]) <= k:\n",
      "                    pair_queue.append(((curr[0]+1, curr[1]-1), dist+1))\n",
      "                    path.append(grid[curr[0]+1] [curr[1]-1])\n",
      "\n",
      "            if grid[curr[0]-1][curr[1]] != '#':\n",
      "                if dist + manhatann_distance((curr[0]-1, curr[1]), coords[-1]) <= k:\n",
      "                    pair_queue.append(((curr[0]-1, curr[1]), dist+1))\n",
      "                    path.append(grid[curr[0]-1] [curr[1]])\n",
      "\n",
      "            if grid[curr[0]+1][curr[1]] != '#':\n",
      "                if dist + manhatann_distance((curr[0]+1, curr[1]), coords[-1]) <= k:\n",
      "                    pair_queue.append(((curr[\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    all_unique.check(1, [({\n",
      "        'grid': [[5, 9, 3], [4, 1, 6], [7, 8, 2]],\n",
      "        'k': 1,\n",
      "    }), ({\n",
      "        'grid': [[5, 9, 3], [4, 1, 6], [7, 8, 2]],\n",
      "        'k': 2,\n",
      "    }), ({\n",
      "        'grid': [[5, 9, 3], [4, 1, 6], [7, 8, 2]],\n",
      "        'k': 3,\n",
      "    }), ({\n",
      "        'grid': [[4, 5, 4], [3, 3, 1], [3, 4, 8]],\n",
      "        'k': 2,\n",
      "    }), ({\n",
      "        'grid': [[7, 1, 2], [1, 6, 5], [4, 2, 9]],\n",
      "        'k': 3,\n",
      "    })])\n",
      "    # Key function. Returns the current value at the given cell.\n",
      "    cell_value = lambda x, y: grid[y][x]\n",
      "    # Location of each number.\n",
      "    locations = {}\n",
      "    for x in range(0, len(grid)):\n",
      "        for y in range(0, len(grid)):\n",
      "            locations[cell_value(x, y)] = (x, y)\n",
      "    # What numbers N are reachable from number 1 in exactly k steps?\n",
      "    # Stop early when traversing if the current step count exceeds k.\n",
      "    from collections import deque\n",
      "    reachable = {1: None}\n",
      "    queue = deque()\n",
      "    queue.append((1, (locations[1],), len(grid), None))\n",
      "    while queue:\n",
      "        current, path, step_count, previous = queue.pop()\n",
      "        # Optimization. Break if step count exceeds k.\n",
      "        if step_count > k:\n",
      "            False\n",
      "        elif current == 1:\n",
      "            # Optimization. Break if missing a factor of n.\n",
      "            False\n",
      "        else:\n",
      "            if current not in reachable or step_count < reachable[current]:\n",
      "                reachable[current] = step_count\n",
      "            for step_num in range(0, step_count + 1):\n",
      "                coords = list(path)[step_num]\n",
      "                for direction in (UP, DOWN, LEFT, RIGHT):\n",
      "                    step = apply_direction(coords, direction)\n",
      "                    if (len(grid) > step[0] >= 0 and len(grid) > step[1] >= 0 and\n",
      "                        (previous is None or previous != [coords, step] or step_num < step_count - 1)):\n",
      "                        next_val = cell_value(*step)\n",
      "                        next_path = list(path)\n",
      "                        next_path.insert(step_num, step)\n",
      "                        queue.append((\n",
      "                            next_val,\n",
      "                            tuple(next_path),\n",
      "                            step_count if next_val == current else step_count + 1,\n",
      "                            [coords, step]\n",
      "                        ))\n",
      "    # Paths of length k and the set of values backed on that path.\n",
      "    paths = map(lambda path: (path, {path[0][0]}), get_k_nn(grid, k, cell_value, locations))\n",
      "    for _, value_set in paths:\n",
      "        break_outer = False\n",
      "        for x in range(1, (len(grid) * len(grid)) + 1):\n",
      "            if x not in reachable or x in value_set:\n",
      "                continue\n",
      "            branch = None\n",
      "            for y in empty_queue():\n",
      "                if branch:\n",
      "                    break\n",
      "                for z in empty_queue():\n",
      "                    if ([x, z[0]], z) in branch and z[0] in value_set:\n",
      "                        branch.add((z[0], z))\n",
      "                    else:\n",
      "                        break\n",
      "            if branch:\n",
      "                # Inclusion possible.\n",
      "                value_set.add(x)\n",
      "                del reachable[x]\n",
      "                break_outer = True\n",
      "                break\n",
      "        else:\n",
      "            # Every number was reachable from the current path!\n",
      "            print(path)\n",
      "        if break_outer:\n",
      "            break\n",
      "    # Prune to the length\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    assert k > 0 and len(grid) > 0 and len(grid[0]) > 0\n",
      "    ans = []\n",
      "\n",
      "    # Calculate the cell indexes for each of 9 values in the grid.\n",
      "    cells = defaultdict(list)\n",
      "    for i in range(0, len(grid)):\n",
      "        for j in range(0, len(grid[0])):\n",
      "            cells[grid[i][j]] += (i, j),\n",
      "    totalCellNum = len(grid) * len(grid[0])\n",
      "\n",
      "    def dfsShortestPath(idx: int, k: int, path: List[Any]):\n",
      "        if k <= 0 and k > 0:\n",
      "            return -1, (0,0), path, []\n",
      "\n",
      "        r, c = cells[idx][0]\n",
      "        dr, dc = r - sR, c - sC\n",
      "        nr, nc = sR + dr * k, sC + dc * k\n",
      "\n",
      "        if nr < 0 or nc < 0 or nr >= len(grid) or nc >= len(grid[0]):\n",
      "            return -1, (0,0), path, []\n",
      "\n",
      "        minval = grid[nr][nc]\n",
      "        if minval in path:\n",
      "            return -1, (0,0), path, []\n",
      "\n",
      "        minval = grid[nr][nc] if minval >= minCellVal else minCellVal\n",
      "        path.append(minval)\n",
      "\n",
      "        if k == 1:\n",
      "            return 1, (nr, nc), path, k + 1\n",
      "\n",
      "        nr, nc = nr + nextr[dirr], nc + nextc[dirr]\n",
      "        minval = grid[nr][nc]\n",
      "        step = 1\n",
      "\n",
      "        while True:\n",
      "            if nr < 0 or nc < 0 or nr >= len(grid) or nc >= len(grid[0]):\n",
      "                return -1, (0,0), path, []\n",
      "            minval = min(minval, grid[nr][nc])\n",
      "            if minval == grid[nr][nc] and minval not in path:\n",
      "                path.append(minval)\n",
      "                step += 1\n",
      "                if step == k:\n",
      "                    break\n",
      "            elif minval >= idx:\n",
      "                if minval > idx:\n",
      "                    return 1, (nr, nc), path, step + 1\n",
      "                if idx not in path:\n",
      "                    return -1, (0,0), path, []\n",
      "            nr, nc = nr + nextr[dirr], nc + nextc[dirr]\n",
      "        \n",
      "        assert min(path) == minval\n",
      "        return 1, (nr, nc), path, k + 1\n",
      "\n",
      "        #assert min(path) < minCellVal, 'min(path) == minCellVal : {} != {}' \\\n",
      "        #    .format(min(path), minCellVal)\n",
      "        #return 1, (nr, nc), path, k + 1\n",
      "\n",
      "    def dfsBoarderPath(idx: int, k: int, path: List[Any]):\n",
      "        assert idx > minCellVal\n",
      "        if k <= 0 and k > 0:\n",
      "            assert path[-1] == minCellVal, 'path[-1] := {} != {}'.format(path[-1], minCellVal)\n",
      "            return 1, (0,0), path, k + 1\n",
      "\n",
      "        r, c = cells[idx][0]\n",
      "        dr, dc = r - sR, c - sC\n",
      "        nr, nc = sR + dr * k, sC + dc * k\n",
      "\n",
      "        assert nr < 0 or nc < 0 or nr >= len(grid) or nc >= len(grid[0])\n",
      "\n",
      "        path.append(minCellVal)\n",
      "        \n",
      "        if k == 1:\n",
      "            assert path[-1] == minCellVal, 'path[-1] := {} != {}'.format(path[-1], minCellVal)\n",
      "            return 1, (nr, nc), path, k + 1\n",
      "        a, b, c, d = 0, 0, [], 0\n",
      "        if 0 <= nr < len(grid) and 0 <= nc < len\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "\n",
      "    n = len(grid)\n",
      "    coordinate = []\n",
      "    values = {}\n",
      "    # Convert the matrix representation to a dict representation.\n",
      "    # Get the coordinates of each value.\n",
      "    # Use 1-dimension index as key, and use value as value of the dict.\n",
      "    for i in range(n):\n",
      "        for j in range(n):\n",
      "            values[grid[i][j]] = []\n",
      "            coordinate.append([i + 1, j + 1])\n",
      "    if sum(coordinate) != (n * (n + 1)) / 2 * 2:\n",
      "        raise ValueError('The input matrix is wrong.')\n",
      "    for index, value in enumerate(coordinate):\n",
      "        values[grid[index // n][index % n]].append(value)\n",
      "    for key in values:\n",
      "        if len(values[key]) > 1:\n",
      "            raise ValueError('The input matrix is wrong.')\n",
      "    keys = sorted(values)\n",
      "\n",
      "    # In this problem, the destination of the path is itself, so the destination\n",
      "    # is set to the value 1 which is fixed start value.\n",
      "    max_index = keys.index(1)\n",
      "\n",
      "    # Define a movement cycle. User CANNOT jump out of the movement circle.\n",
      "    # The cycle is from the key with index 1 (the start value is 1) to the key\n",
      "    # with the maximum index in keys, and the user shall not jump back to the\n",
      "    # start position.\n",
      "    min_path_value_list = [1]\n",
      "\n",
      "    for index in range(1, len(keys)):\n",
      "        # Let the biggest value (the end value) be the last path\n",
      "        if index == 1:\n",
      "            jump_dict = {\n",
      "                keys[max_index]: 1\n",
      "            }\n",
      "            # Record the jump times. The jump has to be at least 1\n",
      "            # in this step because we don't allow the minimum path\n",
      "            # jump back to the start position.\n",
      "        elif min_path_value_list[-1] != keys[max_index]:\n",
      "            jump_dict = {\n",
      "                keys[max_index]: index\n",
      "            }\n",
      "        # Mainly focused which key value shall be the next jump.\n",
      "        # This try statement is mainly used to prevent user jump\n",
      "        # out of movement range.\n",
      "        path = [-2] * k\n",
      "        if len(set(min_path_value_list)) <= (n - 1):\n",
      "            for i in range(1, k):\n",
      "                if min_path_value_list[-1] == 1:\n",
      "                    path[-1] = -1\n",
      "                    break\n",
      "                temp_list = []\n",
      "                for index, value in enumerate(keys):\n",
      "                    if (jump_dict.get(value) or jump_dict.get(value, 0) <= k):\n",
      "                        temp_list.append(value)\n",
      "                for choice in temp_list:\n",
      "                    if cod(coordinate, min_path_value_list[-1], grid) in values.get(choice):\n",
      "                        path[-1] = choice\n",
      "                        break\n",
      "        # The tag is used to start detection in this get input section.\n",
      "        path[-1] = -1\n",
      "\n",
      "        while -1 in path:\n",
      "            # Get input in this section.\n",
      "            tag_1 = False\n",
      "            while not tag_1:\n",
      "                minimum_paths = []\n",
      "                # Use tag to detect whether user input is a legit number.\n",
      "                tag = True\n",
      "                try:\n",
      "                    if path[-1] == -1:\n",
      "                        get_input = input('Please enter a digit: ')\n",
      "                        # Convert the string to an integer.\n",
      "                        get_input = int(get_input.strip())\n",
      "                        # The tag is used to see whether the user chose\n",
      "                        # the value which is out of the cycle.\n",
      "                        tag = keys.index(get_input) <= max_index\n",
      "                    else:\n",
      "                        get_input = choice\n",
      "                        tag = choice == grid[n - 2][n - 2]\n",
      "                except ValueError:\n",
      "                    tag_1 = False\n",
      "                else:\n",
      "                    if tag:\n",
      "                        try:\n",
      "                            # The index of the input is stored.\n",
      "                            index = keys.index(get_input)\n",
      "                            # The coordinates of\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    def isSafe(i, j):\n",
      "        return i >= 0 and j >= 0 and i < rows and j < cols and kVal[i][j]\n",
      "\n",
      "    rows, cols = len(grid), len(grid[0])\n",
      "    if rows == 1 and cols == 1:\n",
      "        return [grid[0][0]]\n",
      "    temp, total = 0, 0 # total to store score of different paths\n",
      "    for i in range(rows):\n",
      "        for j in range(cols):\n",
      "            temp += xsum(grid[i][j])\n",
      "\n",
      "    minV = rows * cols * pow(10, len(str(temp)) - 1) # {max_len + 1}\n",
      "    res = []\n",
      "    # kVal[i][j] stores when is the kth value to be placed in\n",
      "    kVal = [[None] * cols for _ in range(rows)]\n",
      "    print(kVal)\n",
      "\n",
      "    def f(i, j, keys, path, visited):\n",
      "        \"\"\"\n",
      "        Returns all integers local maxima in some path\n",
      "        by performing the operation of adition operation {k} sometimes.\n",
      "        \"\"\"\n",
      "        print(path, visited)\n",
      "        print(res)\n",
      "        nonlocal minV\n",
      "        keys += 1 # at first i and j are given at least\n",
      "\n",
      "        # end point\n",
      "        if keys == k:\n",
      "            total, _ = 0, 1\n",
      "            for _ in range(len(path)):\n",
      "                total += xsum(path[_]) * _\n",
      "            if total < minV:\n",
      "                minV = total\n",
      "                res.append(path)\n",
      "            return\n",
      "\n",
      "        # node by node \n",
      "        directions = {(-1, 0), (1, 0), (0, -1), (0, 1)}\n",
      "        for r, c in directions:\n",
      "            # go through 4 directions\n",
      "            di, dj = r + i, c + j\n",
      "\n",
      "            # given all the k-step, we can do it backtracking\n",
      "            if all((isSafe(di, dj), keys >= kVal[di][dj], not visited[di][dj])):\n",
      "                visited[di][dj], path[len(path)] = True, grid[di][dj]\n",
      "                f(di, dj, keys, path, visited)\n",
      "                # nonlocal minV\n",
      "                minV = minV if minV < current else current # max sum\n",
      "                visited[di][dj], path[len(path)-1] = False, None\n",
      "            else:\n",
      "                continue\n",
      "\n",
      "    # use the bfs method\n",
      "    visited = [[False] * cols for _ in range(rows)]\n",
      "    # visited[0][0], path, g[0][0] = True, [], grid[0][0]\n",
      "    g = [[grid[_][__] for __ in range(cols)] for _ in range(rows)]\n",
      "    def bfs(i=0, j=0, keys=0, path=[], visited=[i for j in range(cols)] for i in [[False] * rows]):\n",
      "        nonlocal minV\n",
      "        # init the width and height of the node\n",
      "        directions, visited, keys = {(-1, 0), (1, 0), (0, -1), (0, 1)}, set(), 0\n",
      "        que = deque([(i, j)])\n",
      "\n",
      "        # at the same time, from the start index (0, 0) to the cardinal directions\n",
      "        # values and the numbers among them\n",
      "        while que:\n",
      "            # print(que)\n",
      "            r, c = que.popleft()\n",
      "            temp = maxV = 0\n",
      "\n",
      "            # add in the temp value when r and c are the same\n",
      "            # that fisrt number is positive or negative\n",
      "            keys += 1\n",
      "            visited.add((r, c))\n",
      "\n",
      "            if keys == k:\n",
      "                current, _ = 0, 1\n",
      "                for _ in path:\n",
      "                    maxV = xsum(_)\n",
      "                    if maxV * (1 / _) * pow(_, 2) > 0:\n",
      "                        current += 1 / _ * pow(_, 2)\n",
      "\n",
      "                if current < maxV:\n",
      "                    maxV = current\n",
      "                    return visiti\n",
      "\n",
      "            path.append(grid[r][c])\n",
      "            for r, c in directions:\n",
      "                di\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    def dfs(con, ls, res, i, j, k, d=0):\n",
      "        if k < 0:\n",
      "            return\n",
      "        if k == 0:\n",
      "            res.add(C(i, j))\n",
      "            return\n",
      "        if d == dp:\n",
      "            ls[-1].add(C(i, j))\n",
      "        else:\n",
      "            ls.append(set())\n",
      "            d += 1\n",
      "            if B(i + 1, j) in con and (i + 1, j) not in ls[d - 1]:\n",
      "                ls[-1].add(C(i, j))\n",
      "                dfs(con, ls, res, i + 1, j, k\n",
      "                    - 1, d)\n",
      "            if B(i - 1, j) in con and (i - 1, j) not in ls[d - 1]:\n",
      "                ls[-1].add(C(i, j))\n",
      "                dfs(con, ls, res, i - 1, j, k\n",
      "                    - 1, d)\n",
      "            if B(i, j - 1) in con and (i, j - 1) not in ls[d - 1]:\n",
      "                ls[-1].add(C(i, j))\n",
      "                dfs(con, ls, res, i, j - 1, k\n",
      "                    - 1, d)\n",
      "            if B(i, j + 1) in con and (i, j + 1) not in ls[d - 1]:\n",
      "                ls[-1].add(C(i, j))\n",
      "                dfs(con, ls, res, i, j + 1, k\n",
      "                    - 1, d)\n",
      "            ls.pop()\n",
      "\n",
      "    n = len(grid)\n",
      "    con = {C(i, j): grid[i][j] for i in range(n) for j in range(n)}\n",
      "    ll = [[2, 0], [0, 2], [1, 1]]\n",
      "    Q, dp = set(), 0\n",
      "    lc = {sum(abs(a - b) ** 2 for a, b in zip(ll[0], c)): set() for c in con}\n",
      "    _ = sorted(lc.items())\n",
      "    for i in range(n - 1):\n",
      "        for j in range(n):\n",
      "            for d in ll:\n",
      "                Q.add((i, j) + tuple(a + b for a, b in zip(ll[0], d)))\n",
      "                dp += 1\n",
      "        for j in range(n - 1):\n",
      "            for d in ll:\n",
      "                for a, b in zip(ll[1], d):\n",
      "                    Q.add((i, j) + (a, b))\n",
      "                    dp += 1\n",
      "        ll[2], ll[0] = ll[0], ll[1]\n",
      "        ll[1] = ll[2]\n",
      "        lc = {sum(abs(a - b) ** 2 for a, b in zip(ll[0], c)): set() for c in con}\n",
      "        _ = sorted(lc.items())\n",
      "    lc = {d: {} for d in lc}\n",
      "    nd, f, s, t, lst = n ** 2, set(), (0,) * n, tuple(i for i in range(n)), []\n",
      "    for i in range(k):\n",
      "        for d in lst:\n",
      "            s = tuple(a + b for a, b in zip(s, d))\n",
      "            f.add(s)\n",
      "        cl = {}\n",
      "        for p in f:\n",
      "            for s, v in _:\n",
      "                t = tuple(a + b for a, b in zip(p, v))\n",
      "                if t in con:\n",
      "                    cl[t] = s + 1\n",
      "        if cl:\n",
      "            f = set(cl.keys())\n",
      "            mm, nd = min(cl.items(), key=lambda x: x[1])\n",
      "            lst.append(nd)\n",
      "            lc[nd] = cl\n",
      "    rs = {}\n",
      "    ls = []\n",
      "    mm, nd = lc[nd].popitem()\n",
      "    ls.append(set())\n",
      "    ls[-1].add(C(*mm))\n",
      "    dfs(con, ls,\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "\n",
      "    def _minPath(grid, cell, k, memo):\n",
      "        n = len(grid)\n",
      "        direction = getDirectionValues(n, cell[0], cell[1])\n",
      "        if k == 1:\n",
      "            return [grid[direction.postToRow][direction.postToCol],]\n",
      "\n",
      "        if memo[k][cell[0]][cell[1]] is not None:\n",
      "            return memo[k][cell[0]][cell[1]]\n",
      "        \n",
      "        minPaths = []\n",
      "        if direction.up is not None:\n",
      "            upPath = _minPath(grid, (direction.postToRow, direction.postToCol), k-1, memo)\n",
      "            if upPath:\n",
      "                minPaths.append(upPath)\n",
      "        if direction.down is not None:\n",
      "            downPath = _minPath(grid, (direction.down, cell[1]), k-1, memo)\n",
      "            if downPath:\n",
      "                minPaths.append(downPath)\n",
      "        if direction.left is not None:\n",
      "            leftPath = _minPath(grid, (cell[0], direction.left), k-1, memo)\n",
      "            if leftPath:\n",
      "                minPaths.append(leftPath)\n",
      "        if direction.right is not None:\n",
      "            rightPath = _minPath(grid, (cell[0], direction.postToCol), k-1, memo)\n",
      "            if rightPath:\n",
      "                minPaths.append(rightPath)\n",
      "            \n",
      "        # print(minPaths)\n",
      "        if len(minPaths) == 0:\n",
      "            return None\n",
      "\n",
      "        # # print(minPaths)\n",
      "        # print(\"=====\")\n",
      "        sortix = lambda x: [x[0]] + list(np.tile(np.array(np.sort(np.array(x[1:]))), (10, 1))[x[1:] % 10])\n",
      "        minPathNumsOrderd = minPathNums = np.argsort(sortix(minPaths)[:,0])\n",
      "\n",
      "        # values = np.array(minPaths)[minPathNums]\n",
      "        # print(values)\n",
      "        # print(list(list(values) * ([i+1] * len(values[i]))) ** (values.shape[1] * [1]))\n",
      "        minPaths = np.array(minPaths)[minPathNums]\n",
      "        minPath = minPaths[0]\n",
      "        # print(minPaths)\n",
      "        # print(minPath)\n",
      "        # print(minPath[0])\n",
      "        # print(minPath)\n",
      "        # print(list(range(len(minPaths))) * [0])\n",
      "        same_as_first_path_indexes = np.all(\n",
      "            [np.array(minPath).reshape(-1,1)] * len(minPaths) \\\n",
      "            == minPaths,\n",
      "            axis=(-1))\n",
      "        minSameAsFirstPaths = minPaths[same_as_first_path_indexes]\n",
      "\n",
      "        # values = np.array(minSameAsFirstPaths)\n",
      "        # print(values)\n",
      "        # print(list(list(values) * ([i+1] * len(values[i]))) ** (values.shape[1] * [1]))\n",
      "\n",
      "        minSameAsFirstPathNumsOrderd = minSameAsFirstPathNums = np.argsort(\n",
      "            sortix(minSameAsFirstPaths)[:,1:])[:2]\n",
      "        if len(minSameAsFirstPathNums) == 0:\n",
      "            return None\n",
      "        elif len(minSameAsFirstPathNums) == 1:\n",
      "            minSameAsFirstPath = minSameAsFirstPaths[minSameAsFirstPathNums[0]]\n",
      "            memo[k][cell[0]][cell[1]] = [grid[direction.postToRow][direction.postToCol]] + minSameAsFirstPath\n",
      "            return [grid[direction.postToRow][direction.postToCol]] + minSameAsFirstPath\n",
      "        else:\n",
      "            # print(f\"minSameAsFirstPaths: {minSameAsFirstPaths}\")\n",
      "            valueOfMinPath = [grid[direction\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "\n",
      "    def doBfs(n, fGrid, visited, seen):\n",
      "        paths = []\n",
      "        step = 0\n",
      "        q = [(n, 0, [fGrid.get(n)])]\n",
      "        visited[n] = True\n",
      "        while q:\n",
      "            step += 1\n",
      "            nextQ = []\n",
      "            for i, j, path in q:\n",
      "                if step > k:\n",
      "                    paths.append(path)\n",
      "                    continue\n",
      "                g = fGrid.get((i + 1, j))\n",
      "                if not visited.get(g):\n",
      "                    visited[g] = True\n",
      "                    nextQ.append((i + 1, j, path + [g]))\n",
      "                g = fGrid.get((i - 1, j))\n",
      "                if not visited.get(g):\n",
      "                    visited[g] = True\n",
      "                    nextQ.append((i - 1, j, path + [g]))\n",
      "                g = fGrid.get((i, j + 1))\n",
      "                if not visited.get(g):\n",
      "                    visited[g] = True\n",
      "                    nextQ.append((i, j + 1, path + [g]))\n",
      "                g = fGrid.get((i, j - 1))\n",
      "                if not visited.get(g):\n",
      "                    visited[g] = True\n",
      "                    nextQ.append((i, j - 1, path + [g]))\n",
      "            q = nextQ\n",
      "        seen += paths\n",
      "        return seen\n",
      "\n",
      "    def hellper(n, fGrid, visited, seen):\n",
      "        # BFS + Min path\n",
      "        \"\"\"time complexity: O(k^2), space complexity: O(n^2)\"\"\"\n",
      "        path = doBfs(n, fGrid, visited, seen)\n",
      "        minPath = path[0]\n",
      "        for p in path:\n",
      "            if p < minPath:\n",
      "                minPath = p\n",
      "\n",
      "        # Back Track(DFS) + Min path (elegant, but time consuming)\n",
      "        \"\"\"\n",
      "        if k == 1:\n",
      "            return path[0]\n",
      "        d = {m: True for m in path}\n",
      "        nextPath = []\n",
      "        for item in path:\n",
      "            delitem = item[len(item) - 1]\n",
      "            item = item[:-1]\n",
      "            for j in range(4):\n",
      "                if (j == 0 and not visited.get((delitem[0] - 1, delitem[1]))) or \\\n",
      "                   (j == 1 and not visited.get((delitem[0] + 1, delitem[1]))) or \\\n",
      "                   (j == 2 and not visited.get((delitem[0], delitem[1] - 1))) or \\\n",
      "                   (j == 3 and not visited.get((delitem[0], delitem[1] + 1))):\n",
      "                    nextPath.append(item)\n",
      "                    nextPath[len(nextPath) - 1].append(fGrid.get((delitem[0] - 1, delitem[1])) if j == 0 else \\\n",
      "                                                       fGrid.get((delitem[0] + 1, delitem[1])) if j == 1 else \\\n",
      "                                                       fGrid.get((delitem[0], delitem[1] - 1)) if j == 2 else \\\n",
      "                                                       fGrid.get((delitem[0], delitem[1] + 1)))\n",
      "        nextPath = list(zip(*nextPath))\n",
      "\n",
      "        for i in range(1, len(nextPath)):\n",
      "            if d.get(nextPath[i]):\n",
      "                nextPath[i] = minPath\n",
      "\n",
      "        nextPath = list(zip(*nextPath))\n",
      "        for item in nextPath:\n",
      "            visited[fGrid.get(item[len(item) - 1])] = True\n",
      "        nextPath = hellper(item[len(item) - 1], fGrid, visited, nextPath)\n",
      "        if len(nextPath) < len(minPath):\n",
      "            minPath = nextPath\n",
      "        else:\n",
      "            minPath = minPath if minPath < nextPath else nextPath\n",
      "        \"\"\"\n",
      "        return minPath\n",
      "\n",
      "    N = len(grid[0])\n",
      "    fGrid = {}\n",
      "    result = []\n",
      "    seen = []\n",
      "    minPath = []\n",
      "    visited = {}\n",
      "\n",
      "-----------------------------\n",
      "\n",
      "def minPath(grid, k):\n",
      "    \"\"\"\n",
      "    Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n",
      "    each cell of the grid contains a value. Every integer in the range [1, N * N]\n",
      "    inclusive appears exactly once on the cells of the grid.\n",
      "\n",
      "    You have to find the minimum path of length k in the grid. You can start\n",
      "    from any cell, and in each step you can move to any of the neighbor cells,\n",
      "    in other words, you can go to cells which share an edge with you current\n",
      "    cell.\n",
      "    Please note that a path of length k means visiting exactly k cells (not\n",
      "    necessarily distinct).\n",
      "    You CANNOT go off the grid.\n",
      "    A path A (of length k) is considered less than a path B (of length k) if\n",
      "    after making the ordered lists of the values on the cells that A and B go\n",
      "    through (let's call them lst_A and lst_B), lst_A is lexicographically less\n",
      "    than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n",
      "    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n",
      "    lst_A[j] = lst_B[j].\n",
      "    It is guaranteed that the answer is unique.\n",
      "    Return an ordered list of the values on the cells that the minimum path go through.\n",
      "\n",
      "    Examples:\n",
      "\n",
      "        Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n",
      "        Output: [1, 2, 1]\n",
      "\n",
      "        Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n",
      "        Output: [1]\n",
      "    \"\"\"\n",
      "    m, n = len(grid), len(grid[0])\n",
      "    # states of the dp\n",
      "    # 2 states because u need to know where ur coming from to form the path\n",
      "    # and because you are only allowed to step once in a direction, moving diagonally during recursion/dp calculation is prohibited\n",
      "    # ((i, j), vertical/horizontal)\n",
      "    dp_vals = {} # (x,y) used so that you don't need to multiply x and y by some factor to make it unique when converting coordinates to index left over from c# version\n",
      "    dp_path = {}\n",
      "\n",
      "    # initialize the mins for everything to negative\n",
      "    for x in range(m):\n",
      "        for y in range(n):\n",
      "            dp_vals[(x,y)] = -1\n",
      "            dp_path[(x,y)] = None\n",
      "\n",
      "    res = None\n",
      "    def dfs(i, j): # make sure it stores the path in dp_path\n",
      "        nonlocal res\n",
      "        if i == 0 and j == 0:\n",
      "            dp_vals[(i,j)] = grid[i][j]\n",
      "            res = grid[i][j]\n",
      "        else:\n",
      "            dp_vals[(i,j)] = grid[i][j]\n",
      "            if i > 0 and dp_vals[(i - 1, j)] != -1 or True:\n",
      "                # optimization\n",
      "                dfs(i - 1, j) \n",
      "            if dp_vals[(i, j - 1)] != -1 or True:\n",
      "                dfs(i, j - 1)\n",
      "\n",
      "            if i > 0:\n",
      "                if dp_vals[(i - 1, j)] != -1 and (dp_vals[(i - 1, j)] + grid[i][j] < dp_vals[(i, j)] or dp_path[(i, j)] is None):\n",
      "                    dp_vals[(i, j)] = dp_vals[(i - 1, j)] + grid[i][j]\n",
      "                    dp_path[(i, j)] = \"up\"\n",
      "            if j > 0:\n",
      "                if dp_vals[(i, j - 1)] != -1 and (dp_vals[(i, j - 1)] + grid[i][j] < dp_vals[(i, j)] or dp_path[(i, j)] is None):\n",
      "                    dp_vals[(i, j)] = dp_vals[(i, j - 1)] + grid[i][j]\n",
      "                    if dp_path[(i, j - 1)] is None:\n",
      "                        dp_path[(i, j - 1)] = \"left\"\n",
      "                        dp_path[(i, j)] = \"left\"\n",
      "            if res is None or dp_vals[(i,j)] < res:\n",
      "                res = dp_vals[(i,j)]\n",
      "\n",
      "    res = None\n",
      "    dfs(0,0)\n",
      "    cur_i = 0\n",
      "    cur_j = 0\n",
      "\n",
      "    path = \"\"\n",
      "    while k > 0:\n",
      "        # use the path to get the path of k length\n",
      "        if cur_j + 1 < n and (dp_path[(cur_i, cur_j + 1)] == \"right\" or cur_j + 1 == n - 1): # move right as far as possible\n",
      "            while dp_path[(cur_i, cur_j + 1)] == \"right\":\n",
      "                cur_j+=1\n",
      "            path += \"r\"\n",
      "            cur_j += 1\n",
      "            k -= 1\n",
      "        elif dp_path[(cur_i + 1, cur_j)] == \"down\":\n",
      "            path += \"d\"\n",
      "            k -= 1\n",
      "            cur_i+= 1\n",
      "        elif dp_path[(cur_i + 1, cur_j)] == \"right\":\n",
      "            path += \"dr\"\n",
      "            k -= 2\n",
      "            cur_i+= 1\n",
      "            cur_j+= 1\n",
      "        else:\n",
      "            raise ValueError(\"NOT IMPLEMENTED\")\n",
      "\n",
      "    return path\n",
      "            \n",
      "assert minPath([ [1,2,3],\n",
      "                 [4,5\n",
      "-----------------------------\n",
      "\n",
      "def smallest_change(arr):\n",
      "    \"\"\"\n",
      "    Given an array arr of integers, find the minimum number of elements that\n",
      "    need to be changed to make the array palindromic. A palindromic array is an array that\n",
      "    is read the same backwards and forwards. In one change, you can change one element to any other element.\n",
      "\n",
      "    For example:\n",
      "    smallest_change([1,2,3,5,4,7,9,6]) == 4\n",
      "    smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n",
      "    smallest_change([1, 2, 3, 2, 1]) == 0\n",
      "    \"\"\"\n",
      "    if arr:\n",
      "        mid = len(arr) // 2\n",
      "        left = arr[:mid]\n",
      "        right = arr[mid + 1:][::-1]\n",
      "        if len(arr) % 2 == 1:\n",
      "            left += [arr[mid]]\n",
      "            count = len([i for i in range(len(left)) if left[i] != right[i]])\n",
      "        else:\n",
      "            count = len([i for i in range(len(left)) if left[i] != right[i]]) + 1\n",
      "    else:\n",
      "        count = 0\n",
      "    return count\n",
      "\n",
      "\n",
      "print(smallest_change([1, 2, 3, 5, 4, 7, 9, 6]))\n",
      "print(smallest_change([1, 2, 3, 4, 3, 2, 2]))\n",
      "print(smallest_change([1, 2, 3, 2, 1]))\n",
      "print(smallest_change([1]))\n",
      "\n",
      "\"\"\"\n",
      "Given a string make_spoonerism, generate a spoonerism of that string.\n",
      "A spoonerism is a spoken phrase in which initial consonants, vowels,\n",
      "or syllables of two or more words are switched: for example, a spoonerism for “nitpicking” is “pitting nick.”\n",
      "\n",
      "<? To generate spoonerisms, map the first character of each word to the end of the word and change the corresponding vowel/consonant.\n",
      "For example, with the word “moth” you would do an internal mapping of \"o” → “oth” and then switch the “m” and “th” on the outside. Since “o” → “th” and “o” → “h” is not a valid spoonerism, the result is “hoth”. Is that the best spoonerism possible?\n",
      "\n",
      "\n",
      "spoonerize_word(\"code\") == \"doe\"\n",
      "spoonerize_word(\"moth\") == \"both\"\n",
      "spoonerize_word(\"both\") == \"bath\"\n",
      "spoonerize_word(\"bog\") == \"bog\"\n",
      "\n",
      "from collections import OrderedDict\n",
      "spoonerize_phrase(\"nit picking\") == \"pit nicking\"\n",
      "spoonerize_phrase(\"rambling diseases\") == \"dambling raises\"\n",
      "\"\"\"\n",
      "\n",
      "all_chunks = {\"v\": [\"a\", \"e\", \"i\", \"o\", \"u\"],\n",
      "              \"c\": [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"l\", \"m\", \"n\", \"p\", \"r\", \"s\", \"t\", \"y\", \"w\", \"z\", \"k\", \"j\", \"q\", \"x\"]}\n",
      "\n",
      "prefixes = {letter[0]: [prefix + i for i in letter] for prefix in all_chunks[\"c\"] for letter in all_chunks[\"c\"] + all_chunks[\"v\"]}  # двухбуквенная часть в виде ключа массива и значений\n",
      "prefixes.update({letter[0]: [prefix + i for i in letter] for letter in all_chunks[\"c\"] + all_chunks[\"v\"] for prefix in all_chunks[\"v\"]})\n",
      "\n",
      "suffixes = {letter: [i[::-1] for i in prefix] for letter, prefix in\n",
      "            prefixes.items()}  # создаем словарь двухбуквенных частей слова с учетом заданной префиксальности, для маппинга вставочной буквы в соответствующ\n",
      "-----------------------------\n",
      "\n",
      "def smallest_change(arr):\n",
      "    \"\"\"\n",
      "    Given an array arr of integers, find the minimum number of elements that\n",
      "    need to be changed to make the array palindromic. A palindromic array is an array that\n",
      "    is read the same backwards and forwards. In one change, you can change one element to any other element.\n",
      "\n",
      "    For example:\n",
      "    smallest_change([1,2,3,5,4,7,9,6]) == 4\n",
      "    smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n",
      "    smallest_change([1, 2, 3, 2, 1]) == 0\n",
      "    \"\"\"\n",
      "    # change to 0, check that it works, then make all needed changes\n",
      "    i, j  = 0, len(arr) - 1\n",
      "    min_changes = 0\n",
      "    while i < j and arr[i] == arr[j]:\n",
      "        i += 1\n",
      "        j -= 1\n",
      "    if i < j:\n",
      "        min_changes = min_changes + 1 \n",
      "        for i in range(j - 1):\n",
      "            if arr[i] != arr[-i]:\n",
      "                min_changes = min_changes + 1\n",
      "    return min_changes\n",
      "assert(smallest_change([1,2,3,5,4,7,9,6]) == 4)\n",
      "assert(smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1)\n",
      "assert(smallest_change([1, 2, 3, 2, 1]) == 0)\n",
      "assert(smallest_change([1,2,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\n",
      "-----------------------------\n",
      "\n",
      "def even_odd_palindrome(n):\n",
      "    \"\"\"\n",
      "    Given a positive integer n, return a tuple that has the number of even and odd\n",
      "    integer palindromes that fall within the range(1, n), inclusive.\n",
      "\n",
      "    Example 1:\n",
      "\n",
      "        Input: 3\n",
      "        Output: (1, 2)\n",
      "        Explanation:\n",
      "        Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n",
      "\n",
      "    Example 2:\n",
      "\n",
      "        Input: 12\n",
      "        Output: (4, 6)\n",
      "        Explanation:\n",
      "        Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n",
      "\n",
      "    Note:\n",
      "        1. 1 <= n <= 10^3\n",
      "        2. returned tuple has the number of even and odd integer palindromes respectively.\n",
      "    \"\"\"\n",
      "    def pow_10(p):\n",
      "        if not p: return 1\n",
      "\n",
      "        if p in count:\n",
      "            return count[p]\n",
      "\n",
      "        res = pow(10, p)\n",
      "        count[p] = res\n",
      "        return res\n",
      "\n",
      "    def get_count(start, end):\n",
      "        res = (end - start + 1) // 2\n",
      "        if has_pivot:\n",
      "            res += 1\n",
      "        return res\n",
      "\n",
      "    def get_middle_num(i):\n",
      "        if not has_pivot:\n",
      "            return 0\n",
      "\n",
      "        p = pow_10(i)\n",
      "        res = pivot_palindrom**10\n",
      "        digit1 = res // p % 10\n",
      "\n",
      "        for d in xrange(1, digit1):\n",
      "            if find_num(p, d, digit1, i) is None:\n",
      "                return 0\n",
      "\n",
      "            t = compare_with_pivot(p, d, i)\n",
      "            if t > 0:\n",
      "                return sum_of_such_num(d, digit1, i) + get_middle_num(i + 1)\n",
      "\n",
      "            res += sum_of_such_num(d, digit1, i)\n",
      "        return res\n",
      "\n",
      "    def sum_of_such_num(digit1, digit0, i):\n",
      "        base = digit1 + digit0 * 10\n",
      "        p = pow_10(i)\n",
      "        return p * base\n",
      "\n",
      "    def find_num(p, d, d2, i):\n",
      "        num = p * (d + d2 * 10)\n",
      "        s = len(str(num))\n",
      "        i = (s -1) // 2\n",
      "        mid = num / pow(10, i + 1)\n",
      "        if d != int(str(mid)[::-1]):\n",
      "            return None\n",
      "        return num\n",
      "\n",
      "    def compare_with_pivot(p, d, i):\n",
      "        if not has_pivot: return 0\n",
      "\n",
      "        num = find_num(p, d, pivot_digit, i)\n",
      "        if pivot_palindrom > num:\n",
      "            return 1\n",
      "        elif pivot_palindrom < num:\n",
      "            return -1\n",
      "        else:\n",
      "            return 0\n",
      "\n",
      "    if not n: return (0, 0)\n",
      "\n",
      "    pivot_palindrom, count = None, {}\n",
      "    length, has_pivot = len(str(n)), n % 10 != n\n",
      "    pivot_digit, double_digit = None, None\n",
      "    if length % 2 == 1:\n",
      "        middle_num = n / pow(10, (length + 1) // 2)\n",
      "\n",
      "        pivot_palindrom = int(str(middle_num) + str(middle_num)[::-1])\n",
      "        if middle_num % 10:\n",
      "            pivot_digit = middle_num % 10\n",
      "        else:\n",
      "            pivot_digit = middle_num / 10 % 10\n",
      "            double_digit = True\n",
      "    else:\n",
      "        middle_num = n / pow(10, length // 2 - 1)\n",
      "        pivot_palindrom = int(str(middle_num)[:-1] + str(middle_num)[::-1])\n",
      "\n",
      "    # print \"n = \", n, \"; pivot_digit = \", pivot_digit, \"; pivot_palindrom = \", pivot_palindrom\n",
      "    if pivot_palindrom > n:\n",
      "        return get_count(10, n)\n",
      "\n",
      "    even_num = get_middle_num(1)\n",
      "    # print \"length = \", length,\"; even_num = \", even_num\n",
      "    odd_str = \"1\" + \"0\" * (length - 1) + \"1\"\n",
      "    odd_max = n / int(odd_str)\n",
      "    odd_max = pow_10(length) - 1 if odd_max > odd_str else odd_max\n",
      "    odd_mid_max = n / int(odd_str[2:]) if odd_max > odd_str else odd_max\n",
      "    odd_num = (odd_max + odd_mid_max) * length / 2\n",
      "\n",
      "    # print \"oddd Num = \", odd_num, \"; odds Max = \", odd_max, \"; odds Mid Max = \", odd_mid_max\n",
      "    return (even_num, odd_num)\n",
      "\n",
      "@fib\n",
      "\n",
      "-----------------------------\n",
      "\n",
      "def even_odd_palindrome(n):\n",
      "    \"\"\"\n",
      "    Given a positive integer n, return a tuple that has the number of even and odd\n",
      "    integer palindromes that fall within the range(1, n), inclusive.\n",
      "\n",
      "    Example 1:\n",
      "\n",
      "        Input: 3\n",
      "        Output: (1, 2)\n",
      "        Explanation:\n",
      "        Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n",
      "\n",
      "    Example 2:\n",
      "\n",
      "        Input: 12\n",
      "        Output: (4, 6)\n",
      "        Explanation:\n",
      "        Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n",
      "\n",
      "    Note:\n",
      "        1. 1 <= n <= 10^3\n",
      "        2. returned tuple has the number of even and odd integer palindromes respectively.\n",
      "    \"\"\"\n",
      "\n",
      "    import math\n",
      "\n",
      "    # Brute-Force Solution: Iterate all numbers within [0, n], then count even and odd palindrome respectively.\n",
      "    def even_odd_palindrome_1(n: int) -> tuple:\n",
      "        if n < 1 or n > 10 ** 3:\n",
      "            return -1\n",
      "\n",
      "        even_count = odd_count = 0\n",
      "\n",
      "        for i in range(n + 1):\n",
      "            if str(i) == str(i)[::-1]:\n",
      "                if i % 2 == 0:\n",
      "                    even_count += 1\n",
      "                else:\n",
      "                    odd_count += 1\n",
      "        return even_count, odd_count\n",
      "\n",
      "    # Solution 2: use a fat which is like a lookup table (CTCI problem)\n",
      "    # To construct a palindrome:\n",
      "    #   The middle character must be 1, 3, 5, 7, 9,\n",
      "    #   Only 1 case odd length palindrom within [1, 10], and there are 6 cases,\n",
      "    #   all even length palindrome such as, 22, 444, 1111, ...., 9999 are also within this range.\n",
      "    # Time and space complexity: O(n)\n",
      "\n",
      "    def even_odd_palindrome_2(n: int) -> tuple:\n",
      "        if n < 1 or n > 10 ** 3:\n",
      "            return -1\n",
      "\n",
      "        digits = int(math.log(n, 10)) + 1\n",
      "        number = {}\n",
      "        if digits % 2 == 0:\n",
      "            five = 0\n",
      "            first_portion = digits // 2 - 1\n",
      "        else:\n",
      "            five = 3\n",
      "            first_portion = digits // 2\n",
      "\n",
      "        for cond in range(5):\n",
      "            odd_gen = range(10 ** first_portion * cond, 10 ** first_portion * cond + 10 ** first_portion)\n",
      "            number[cond] = {\"odd_palindrome\": [str(i) + str(i)[::-1] for i in odd_gen],\n",
      "                            \"even_palindrome\": [str(i) + str(i)[::-1] for i in odd_gen]}\n",
      "\n",
      "        if five == 3:\n",
      "            for cond in range(5):\n",
      "                for i in number[cond][\"odd_palindrome\"]:\n",
      "                    odd_gen = number[cond][\"even_palindrome\"]\n",
      "                    number[cond][\"even_palindrome\"] = [i[:first_portion] + char + i[:first_portion] for char in odd_gen\n",
      "                                                       for i in odd_gen]\n",
      "\n",
      "                    odd_gen = number[cond][\"odd_palindrome\"]\n",
      "                    number[cond][\"odd_palindrome\"] = [i[:first_portion] + char + i[:first_portion]\n",
      "                                                      for char in [str(i) for i in range(10)]\n",
      "                                                      for i in odd_gen]\n",
      "        else:\n",
      "            for cond in range(5):\n",
      "                odd_gen = number[cond][\"even_palindrome\"]\n",
      "                number[cond][\"even_palindrome\"] = [i[:first_portion] + char + i[:first_portion] for char in odd_gen\n",
      "                                                   for i in odd_gen]\n",
      "\n",
      "        even_count = 0\n",
      "        odd_count = 5 if five == 3 else 0\n",
      "\n",
      "        if n // 10 ** digits in [0, 1, 2, 5]:\n",
      "            odd_count += 5\n",
      "            if n // 10 ** digits in [0, 1]:\n",
      "                even_count -= 1\n",
      "\n",
      "        for rem in [n % (10 ** (digit - 1)) for digit in range(digits, -1, -1)]:\n",
      "            odd_gen = number[rem // 10 ** first_portion][\"odd_palindrome\"]\n",
      "            odd_count += sum([int(i) <= n % (10 ** digits) for i in odd_gen])\n",
      "\n",
      "            odd_gen = number[rem // 10 ** first_portion][\"even_palindrome\"]\n",
      "            even_count += sum([int(i) <= n % (10 ** digits) for i in odd_gen])\n",
      "\n",
      "            if rem // 10 ** first_portion == 0 and five == 3:\n",
      "                break\n",
      "\n",
      "        return even_count, odd\n",
      "-----------------------------\n",
      "\n",
      "def any_int(x, y, z):\n",
      "    '''\n",
      "    Create a function that takes 3 numbers.\n",
      "    Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n",
      "    Returns false in any other cases.\n",
      "    \n",
      "    Examples\n",
      "    any_int(5, 2, 7) ➞ True\n",
      "    \n",
      "    any_int(3, 2, 2) ➞ False\n",
      "\n",
      "    any_int(3, -2, 1) ➞ True\n",
      "    \n",
      "    any_int(3.6, -2.2, 2) ➞ False\n",
      "  \n",
      "\n",
      "    \n",
      "    '''\n",
      "\n",
      "\n",
      "    # Solution here\n",
      "    if(type(x) is int and type(y) is int and type(z) is int):\n",
      "        return x == y+z or x == y-z or x == z-y\n",
      "    else:\n",
      "        return False;\n",
      "from onlinejudge import OnlineJudge\n",
      "import API_IJA_master.solution\n",
      "import API_IJA_master.base\n",
      "onlinejudge = OnlineJudge(API_IJA_master.solution.Solution, API_IJA_master.base.Base())\n",
      "assert onlinejudge.run([\n",
      "    \"\"\"\n",
      "    def any_int(x, y, z):\n",
      "        '''\n",
      "        Create a function that takes 3 numbers.\n",
      "        Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n",
      "        Returns false in any other cases.\n",
      "        \n",
      "        Examples\n",
      "        any_int(5, 2, 7) ➞ True\n",
      "        \n",
      "        any_int(3, 2, 2) ➞ False\n",
      "\n",
      "        any_int(3, -2, 1) ➞ True\n",
      "        \n",
      "        any_int(3.6, -2.2, 2) ➞ False\n",
      "      \n",
      "\n",
      "        \n",
      "        '''\n",
      "\n",
      "\n",
      "        # Solution here\n",
      "        if(type(x) is int and type(y) is int and type(z) is int):\n",
      "            return x == y+z or x == y-z or x == z-y\n",
      "        else:\n",
      "            return False;\n",
      "    \"\"\"\n",
      "], {'x': 5, 'y': 2, 'z': 7}, 3)\n",
      "assert onlinejudge.run([\n",
      "    \"\"\"\n",
      "    def any_int(x, y, z):\n",
      "        '''\n",
      "        Create a function that takes 3 numbers.\n",
      "        Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n",
      "        Returns false in any other cases.\n",
      "        \n",
      "        Examples\n",
      "        any_int(5, 2, 7) ➞ True\n",
      "        \n",
      "        any_int(3, 2, 2) ➞ False\n",
      "\n",
      "        any_int(3, -2, 1) ➞ True\n",
      "        \n",
      "        any_int(3.6, -2.2, 2) ➞ False\n",
      "      \n",
      "\n",
      "        \n",
      "        '''\n",
      "\n",
      "\n",
      "        # Solution here\n",
      "        if(type(x) is int and type(y) is int and type(z) is int):\n",
      "            return x == y+z or x == y-z or x == z-y\n",
      "        else:\n",
      "            return False;\n",
      "    \"\"\"\n",
      "], {'x': 3, 'y': 2, 'z': 2}, 3)\n",
      " \n",
      "assert onlinejudge.run([\n",
      "    \"\"\"\n",
      "    def any_int(x, y, z):\n",
      "        '''\n",
      "        Create a function that takes 3 numbers.\n",
      "        Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n",
      "        Returns false in any other cases.\n",
      "        \n",
      "        Examples\n",
      "        any_int(5, 2, 7) ➞ True\n",
      "        \n",
      "        any_int(3, 2, 2) ➞ False\n",
      "\n",
      "        any_int(3, -2, 1) ➞ True\n",
      "        \n",
      "        any_int(3.6, -2.2, 2) ➞ False\n",
      "      \n",
      "\n",
      "        \n",
      "        '''\n",
      "\n",
      "\n",
      "        # Solution here\n",
      "        if(type(x) is int and type(y) is int and type(z) is int):\n",
      "            return x == y+z or x == y-z or x == z-y\n",
      "        else:\n",
      "            return False;\n",
      "    \"\"\"\n",
      "], {'x': 3, 'y': -2, 'z': 1}, 3)\n",
      " \n",
      "assert onlinejudge.run([\n",
      "    \"\"\"\n",
      "    def any_int(x, y, z):\n",
      "        '''\n",
      "        Create a function that takes 3 numbers.\n",
      "        Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n",
      "        Returns false in any other cases.\n",
      "        \n",
      "        Examples\n",
      "        any_int(5, 2, 7) ➞ True\n",
      "        \n",
      "        any_\n",
      "-----------------------------\n",
      "\n",
      "def x_or_y(n, x, y):\n",
      "    \"\"\"A simple program which should return the value of x if n is \n",
      "    a prime number and should return the value of y otherwise.\n",
      "\n",
      "    Examples:\n",
      "    for x_or_y(7, 34, 12) == 34\n",
      "    for x_or_y(15, 8, 5) == 5\n",
      "    \n",
      "    \"\"\"\n",
      "    if number_is_prime(n):\n",
      "        return x\n",
      "    return y\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "x_or_y(7, 34, 12) == 34\n",
      "x_or_y(15, 8, 5) == 5\n",
      "\n",
      "-----------------------------\n",
      "\n",
      "def x_or_y(n, x, y):\n",
      "    \"\"\"A simple program which should return the value of x if n is \n",
      "    a prime number and should return the value of y otherwise.\n",
      "\n",
      "    Examples:\n",
      "    for x_or_y(7, 34, 12) == 34\n",
      "    for x_or_y(15, 8, 5) == 5\n",
      "    \n",
      "    \"\"\"\n",
      "    import math # <== it's the only mathematical statement i use in this problem\n",
      "    if n not in range(1, 1000):\n",
      "        raise ValueError('x_or_y: n should be an integer between 1 an 1000, inclusive')\n",
      "    elif n == 1 or n == 2 or n == 3 or n == 5 or n == 7:\n",
      "        return x\n",
      "    elif n == 4 or n == 6 or n == 8 or n == 9 or n == 10 or n == 12 or n == 14 or n == 15 or n == 16 or n == 18 or n == 20 or n == 21 or n == 22 or n == 24 or n == 25 or n == 27 or n == 28 or n == 30 or n == 32 or n == 33 or n == 35 or n == 36 or n == 39 or n == 40 or n == 42 or n == 44 or n == 45 or n == 48 or n == 49 or n == 50 or n == 51 or n == 52 or n == 54 or n == 55 or n == 56 or n == 57 or n == 60 or n == 63 or n == 64 or n == 65 or n == 66 or n == 68 or n == 69 or n == 70 or n == 72 or n == 72 or n == 75 or n == 77 or n == 78 or n == 80 or n == 81 or n == 84 or n == 85 or n == 88 or n == 90 or n == 91 or n == 92 or n == 96 or n == 98 or n == 99 or n == 100 or n == 102 or n == 104 or n == 105 or n == 108 or n == 110 or n == 112 or n == 114 or n == 117 or n == 119 or n == 120 or n == 121 or n == 125 or n == 126 or n == 128 or n == 130 or n == 132 or n == 133 or n == 135 or n == 136 or n == 140 or n == 144 or n == 147 or n == 148 or n == 150 or n == 152 or n == 153 or n == 156 or n == 160 or n == 162 or n == 165 or n == 168 or n == 170 or n == 174 or n == 175 or n == 176 or n == 180 or n == 182 or n == 183 or n == 185 or n == 187 or n == 189 or n == 192 or n == 195 or n == 196 or n == 198 or n == 198 or n == 200 or n == 204 or n == 207 or n == 208 or n == 210 or n == 210 or n == 216 or n == 217 or n == 219 or n == 220 or n == 224 or n == 225 or n == 228 or n == 231 or n == 234 or n == 235 or n == 237 or n == 240 or n == 240 or n == 243 or n == 245 or n == 247 or n == 250 or n ==252 or n == 253 or n == 255 or n == 260 or n == 261 or n == 264 or n == 265 or n == 267 or n == 270 or n == 272 or n == 273 or n == 275 or n == 280 or n == 285 or n == 288 or n == 288 or n == 290 or n == 291 or n == 294 or n == 295 or n == 297 or n == 300 or n == 302 or n == 308 or n == 309 or n == 312 or n == 315 or n == 315 or n == 316 or n == 319 or n == 320 or n == 320 or n == 322 or n == 323 or n == 324 or n == 330 or n == 330 or n == 336 or n == 339 or n == 340 or n == 340 or n == 342 or n == 343 or n == 345 or n == 348 or n == 350 or n == 351 or n == 352 or n == 357 or n == 360 or n == 364 or n == 365 or n == 366 or n == 368 or n == 369 or n == 370 or n == 374 or n == 375 or n == 378 or n == 380 or n == 380 or n == 385 or n == 387 or n == 390 or n == 392 or n == 396 or n == 399 or n == 400 or n == 402 or n == 405 or n == 407 or n == 408 or n == 410 or n == 412 or n == 414 or n == 415 or n == 417 or n == 420 or n == 420 or n == 423 or n == 425 or n == 428 or n == 429 or n == 432 or n == 429 or n == 434\n",
      "-----------------------------\n",
      "\n",
      "def pluck(arr):\n",
      "    \"\"\"\n",
      "    \"Given an array representing a branch of a tree that has non-negative integer nodes\n",
      "    your task is to pluck one of the nodes and return it.\n",
      "    The plucked node should be the node with the smallest even value.\n",
      "    If multiple nodes with the same smallest even value are found return the node that has smallest index.\n",
      "\n",
      "    The plucked node should be returned in a list, [ smalest_value, its index ],\n",
      "    If there are no even values or the given array is empty, return [].\n",
      "\n",
      "    Example 1:\n",
      "        Input: [4,2,3]\n",
      "        Output: [2, 1]\n",
      "        Explanation: 2 has the smallest even value, and 2 has the smallest index.\n",
      "\n",
      "    Example 2:\n",
      "        Input: [1,2,3]\n",
      "        Output: [2, 1]\n",
      "        Explanation: 2 has the smallest even value, and 2 has the smallest index. \n",
      "\n",
      "    Example 3:\n",
      "        Input: []\n",
      "        Output: []\n",
      "    \n",
      "    Example 4:\n",
      "        Input: [5, 0, 3, 0, 4, 2]\n",
      "        Output: [0, 1]\n",
      "        Explanation: 0 is the smallest value, but  there are two zeros,\n",
      "                     so we will choose the first zero, which has the smallest index.\n",
      "\n",
      "    Constraints:\n",
      "        * 1 <= nodes.length <= 10000\n",
      "        * 0 <= node.value\n",
      "    \"\"\"\n",
      "    \n",
      "    def pre_order(root=0, idx=1):\n",
      "        if len(nodes) == 0: \n",
      "            return [], 0\n",
      "        val, root, left, right = nodes[root]\n",
      "        for sub in (left, right):\n",
      "            if sub > -1:\n",
      "                if val%2==0: \n",
      "                    return [val, idx]\n",
      "                current_min_val, current_idx = pre_order(sub, idx+1)\n",
      "                if current_min_val%2==0:\n",
      "                    if (current_min_val, current_idx) < smallest:\n",
      "                        smallest = [current_min_val, current_idx]\n",
      "        return smallest\n",
      "    \n",
      "    nodes = {(a, idx): [-1, -1] for idx, a in enumerate(arr)}\n",
      "    for idx, a in enumerate(arr):\n",
      "        root_idx = (a, idx)\n",
      "        if a%2==0 and not root_idx in nodes.keys():\n",
      "            if smallest[0]%2!=0:\n",
      "                smallest = [a, idx]\n",
      "            if (a, idx) < smallest:\n",
      "                smallest = [a, idx]\n",
      "            continue\n",
      "        if a%2!=0:\n",
      "            minimun = sorted([v for v in nodes.keys() if v[0]%2==0])[0]\n",
      "            minNode = (minimun[0], minimun[1], minimun[1])\n",
      "        elif a%2==0:\n",
      "            minimun = sorted([v for v in nodes.keys() if v[0]%2==0 and root_idx!=v])[0]\n",
      "            minNode = (minimun[0], minimun[1], minimun[1])\n",
      "\n",
      "        if minNode[0] < a:\n",
      "            nodes[root_idx][0] = minNode[1]\n",
      "            nodes[minNode] = [root_idx[1], nodes[minNode][0]]\n",
      "            #rootNode = minNode\n",
      "            #parent = minNode\n",
      "            #prevNode = minNode\n",
      "        else:\n",
      "            nodes[minNode][1] = root_idx[1]\n",
      "            nodes[root_idx][1] = minNode[1]\n",
      "            rootNode = root_idx\n",
      "            parent = root_idx\n",
      "            prevNode = root_idx\n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    smallest=[2**33, -1]\n",
      "    if len(arr) == 0:\n",
      "        return []\n",
      "    print(nodes)\n",
      "    stack = [0]\n",
      "\n",
      "    while len(stack)>0:\n",
      "        top = stack[-1]\n",
      "        ss = arr[top]\n",
      "        if ss%2==0 and ss<smallest[0]:\n",
      "            smallest = [ss, top]\n",
      "        if nodes[(arr[top], top)][1] > -1:\n",
      "            stack.append(nodes[(arr[top], top)][1])\n",
      "        elif nodes[(arr[top], top)][0] > -1:\n",
      "            stack.append(nodes[(arr[top], top)][0])\n",
      "        elif nodes[(arr[top], top)][1] == -1 and nodes[(arr[top], top)][0] == -1:\n",
      "            del stack[-1]\n",
      "                                                                 \n",
      "            if arr[top]%2==0 and arr[top]<smallest[0]:\n",
      "                smallest = [arr[top], top]                                                         \n",
      "            \n",
      "    return [arr[smallest[1]], smallest[1]+1] if arr[smallest[1]]%2==0 else []\n",
      "\n",
      "\n",
      "\n",
      "cases = [\n",
      "        [[4,2,3], [2, 1]],\n",
      "        [[5, 1, 3, 0, 4, 2], [0, 3]],\n",
      "        [[1, 0, 2, 3], [0, 1]],\n",
      "        [[2, 3, 1, 4], [4, 2]],\n",
      "        [[1, 2, 4, 5, 6, 7, 8], [8, 5]],\n",
      "        [[2\n",
      "-----------------------------\n",
      "\n",
      "def can_arrange(arr):\n",
      "    \"\"\"Create a function which returns the largest index of an element which\n",
      "    is not greater than or equal to the element immediately preceding it. If\n",
      "    no such element exists then return -1. The given array will not contain\n",
      "    duplicate values.\n",
      "\n",
      "    Examples:\n",
      "    can_arrange([1,2,4,3,5]) = 3\n",
      "    can_arrange([1,2,3]) = -1\n",
      "    \"\"\"\n",
      "    left_to_right = {}\n",
      "    right_to_left = []\n",
      "    # store the max index that you can currently put element i in the\n",
      "    # dictionary to the left, and store the max index that you can currently\n",
      "    # put element i in the list to the right\n",
      "    max_lr = 0\n",
      "    for i in xrange(1, len(arr)):\n",
      "        if arr[i] >= arr[max_lr]:\n",
      "            left_to_right[arr[max_lr]] = i\n",
      "            max_lr = i\n",
      "    max_rl = len(arr) - 1\n",
      "    for i in xrange(len(arr) - 2, -1, -1):\n",
      "        if arr[i] <= arr[max_rl]:\n",
      "            right_to_left.append(arr[max_rl])\n",
      "            max_rl = i\n",
      "    # reverse the right to left list so it is easier to index\n",
      "    right_to_left.reverse()\n",
      "    # now use a greedy approach to place the elements, one at a time, in the\n",
      "    # greediest of the two locations, then eliminate that location from\n",
      "    # consideration.\n",
      "    # start from the last element\n",
      "    arr_pos = -1\n",
      "    for i in xrange(len(arr) - 1, -1, -1):\n",
      "        if not left_to_right or not right_to_left or arr_pos == -1:\n",
      "            # either you've already found the last position, or you've\n",
      "            # placed all usable elements\n",
      "            # because there are no elements left either place in which a\n",
      "            # current element can go, or there is already a misplaced element,\n",
      "            # this is impossible\n",
      "            print('no solution')\n",
      "            return\n",
      "        lr_pos = left_to_right.get(arr[i], 0)\n",
      "        rl_pos = right_to_left.index(arr[0]) + 1\n",
      "        max_contiguous = max(lr_pos, rl_pos)\n",
      "        if max_contiguous < arr_pos:\n",
      "            # cannot place in current contiguous portion\n",
      "            # check if there is a portion more contiguous that i can slide to\n",
      "            moved = False\n",
      "            for index in (left_to_right.get(v) for v in left_to_right\n",
      "                    if v < arr[arr_pos + 1]):\n",
      "                if index and index < arr_pos:\n",
      "                    # reducing arr_pos by 1 places the original misplaced\n",
      "                    # element in a contiguous spot and updates which element\n",
      "                    # index i can be slid to\n",
      "                    left_to_right[arr[arr_pos]] = 0\n",
      "                    left_to_right[arr[arr_pos + 1]] = arr_pos\n",
      "                    arr[arr_pos + 1] = arr[arr_pos]\n",
      "                    arr[arr_pos] = arr[0]\n",
      "                    arr_pos -= 1\n",
      "                    moved = True\n",
      "                    break\n",
      "            if not moved:\n",
      "                # impossible\n",
      "                # target index not reachable, therefore the item to be moved\n",
      "                # to that spot must be moved to a spot earlier in the array\n",
      "                print('no solution')\n",
      "                return\n",
      "        else:\n",
      "            # should be able to place\n",
      "            # because the current elements to the left are not greater than\n",
      "            # or equal to the element i want to slide over and the current\n",
      "            # elements to the right are not less than or equal to the\n",
      "            # element that i want to slide over, then the element that i want\n",
      "            # to slide over is giving me the greatest contiguous tuple of\n",
      "            # elements\n",
      "            arr[arr_pos + 1] = arr[arr_pos]\n",
      "            arr[arr_pos] = arr[i]\n",
      "            arr_pos += 1\n",
      "    max_dist = 0\n",
      "    max_index = -1\n",
      "    cur_index = 0\n",
      "    already_found = False\n",
      "    # find the max distance between consecutive elements\n",
      "    for i in xrange(len(arr)):\n",
      "        cur_dist = arr[i] - cur_index\n",
      "        if cur_dist > max_dist:\n",
      "            max_dist = cur_dist\n",
      "            max_index = i\n",
      "            already_found = False\n",
      "        elif cur_dist == max_dist and not already_found:\n",
      "\n",
      "-----------------------------\n",
      "\n",
      "\n",
      "def car_race_collision(n: int):\n",
      "    \"\"\"\n",
      "    Imagine a road that's a perfectly straight infinitely long line.\n",
      "    n cars are driving left to right;  simultaneously, a different set of n cars\n",
      "    are driving right to left.   The two sets of cars start out being very far from\n",
      "    each other.  All cars move in the same speed.  Two cars are said to collide\n",
      "    when a car that's moving left to right hits a car that's moving right to left.\n",
      "    However, the cars are infinitely sturdy and strong; as a result, they continue moving\n",
      "    in their trajectory as if they did not collide.\n",
      "\n",
      "    This function outputs the number of such collisions.\n",
      "    \"\"\"\n",
      "    old_road_list=list()\n",
      "    new_road_list=list()\n",
      "\n",
      "    for i in range(n):\n",
      "        old_input = input().split(' ')\n",
      "        new_input = list(old_input)\n",
      "\n",
      "        old_input = old_input[::-1]\n",
      "        car_distance = old_input[1]\n",
      "        position = old_input[2]\n",
      "\n",
      "        if position == 'L':\n",
      "            old_input[2]=0\n",
      "            old_input[1]=int(car_distance)\n",
      "\n",
      "        if position == 'R':\n",
      "            old_input[2] = 0\n",
      "            old_input[1] = -1 * int(car_distance)\n",
      "\n",
      "        old_road_list.append(old_input)\n",
      "\n",
      "        new_input[1] = car_distance\n",
      "        if position == 'L':\n",
      "            new_input[2] = 2*int(car_distance)\n",
      "        else:\n",
      "            new_input[2] = 0 - 2* int(car_distance)\n",
      "\n",
      "\n",
      "        new_road_list.append(new_input)\n",
      "\n",
      "    old_road_list = sorted(old_road_list, key=itemgetter(1,2))\n",
      "    new_road_list = sorted(new_road_list, key=itemgetter(1,2))\n",
      "\n",
      "    print('old car sorted')\n",
      "    print(old_road_list)\n",
      "    print('new car sorted')\n",
      "    print(new_road_list)\n",
      "\n",
      "    # new_car_track = []\n",
      "    # for item in new_road_list:\n",
      "    #     new_car_track.append(item[1])\n",
      "    #\n",
      "    # old_car_track = []\n",
      "    # for item in old_road_list:\n",
      "    #     old_car_track.append(item[1])\n",
      "    #\n",
      "    # print('old car track')\n",
      "    # print(old_car_track)\n",
      "    #\n",
      "    # print('new car track')\n",
      "    # print(new_car_track)\n",
      "\n",
      "\n",
      "    # i = 0\n",
      "    # j = 0\n",
      "    # while (i + j) < (2*(n-1)):\n",
      "    #     old_dis = abs(old_road_list[i][1]) #第i小的old car\n",
      "    #     new_dis = abs(new_road_list[j][1])  #第j小的new car\n",
      "    #     old_pos = old_road_list[i][2]\n",
      "    #     new_pos = new_road_list[j][2]\n",
      "\n",
      "\n",
      "    print()\n",
      "\n",
      "    old_road_car=[]\n",
      "    new_road_car = []\n",
      "    for i in range(n):\n",
      "        new_road_car.append(new_road_list[i][2])\n",
      "        old_road_car.append(old_road_list[i][2])\n",
      "\n",
      "    # place the new cars at different positions\n",
      "    new_road = dict()\n",
      "    for pos in range(n):\n",
      "        if new_road_car[pos] == 0:\n",
      "            break\n",
      "        else:\n",
      "            new_road[new_road_car[pos]] = new_road_list[pos][0]\n",
      "\n",
      "    old_road = dict()\n",
      "    for pos in range(n):\n",
      "        if old_road_car[pos] == 0:\n",
      "            break\n",
      "        else:\n",
      "            old_road[old_road_car[pos]] = old_road_list[pos][0]\n",
      "\n",
      "\n",
      "    Set=dict()\n",
      "    for i in range(n):\n",
      "        old_pos = old_road_car[i]\n",
      "        new_pos = new_road_car[i]\n",
      "\n",
      "        if abs(new_pos)>abs(old_pos):\n",
      "            if i in Set.keys():\n",
      "                Set[i].append(old_pos)\n",
      "            else:\n",
      "                Set[i]=[old_pos]\n",
      "        else:\n",
      "            if i in Set.keys():\n",
      "                Set[i].append(new_pos)\n",
      "            else:\n",
      "                Set[i] = [new_pos]\n",
      "\n",
      "    threshold = min(old_road_car[2],new_road_\n",
      "-----------------------------\n",
      "\n",
      "\n",
      "def car_race_collision(n: int):\n",
      "    \"\"\"\n",
      "    Imagine a road that's a perfectly straight infinitely long line.\n",
      "    n cars are driving left to right;  simultaneously, a different set of n cars\n",
      "    are driving right to left.   The two sets of cars start out being very far from\n",
      "    each other.  All cars move in the same speed.  Two cars are said to collide\n",
      "    when a car that's moving left to right hits a car that's moving right to left.\n",
      "    However, the cars are infinitely sturdy and strong; as a result, they continue moving\n",
      "    in their trajectory as if they did not collide.\n",
      "\n",
      "    This function outputs the number of such collisions.\n",
      "    \"\"\"\n",
      "    assert n >= 2\n",
      "    # You need the \"is None\" above because the result None would otherwise be true.\n",
      "    global_name = \"actions_{}\".format(n)\n",
      "    if globals().get(global_name) is None:\n",
      "        # with importlib.resources.path(\"dynamic_programming\", \"data/car_racing_n={}.pickle\".format(n)) as f:\n",
      "        # with pickle_resource(\"/data/car_racing_n={}.pickle\".format(n)) as f:\n",
      "        with pickle_resource(\"{\\}car_{}_data.pickle\".format(n)) as f:\n",
      "            actions = pickle.load(f)\n",
      "\n",
      "        globals()[global_name] = actions\n",
      "    # Resume code on the next uncommented line.\n",
      "    # END_YOUR_CODE\n",
      "\n",
      "    # BEGIN_YOUR_CODE\n",
      "    '''\n",
      "        Refer to algorithm analysis pdf brute force solution is n!\n",
      "        where each n represents the number of cars on the east\n",
      "        First find the right length of the array such that the number of cars on the East is n\n",
      "        length equals (n-1)+(n-1) + (n-2) + ....+ 1 because every new index to left of east there is ...\n",
      "        more car to the west that can get in front of the east's cars obviusly not including the most recently added side which is no different from the east side.\n",
      "        Length is the index of the east side's most recently placed car (0 based)\n",
      "        This can be expressed as a running sum which is the total number of blocking cars we need to keep track of at every\n",
      "        index, along with immediately knowing how to build the final result. Each step a new block is created of middle or outer.\n",
      "        If a block to the west is set at the middle position, then a collision exactly happens for all collisions for (n-1).\n",
      "        If a block to the west is set at the outer position, then n-1 of the cases are regular (n-1) if they are at the\n",
      "        middle but there should be 1 more since all of the cars get to move which has already been included in the previous\n",
      "        case if they are set at the middle. Thus this is also equal to (n-1). Hence both of these cases should add (n-1). \n",
      "\n",
      "        Definition of collision counter:\n",
      "        For example, if n=3\n",
      "        Consider the state of some object at size index l. Call the state of this middle object at the size l at index i\n",
      "        (in other words the middle object can take one of two states for each number of cars on the east)\n",
      "        \n",
      "        For 3 cars on the east, on index 4 (max index = length = 4 - 1) the inner state is 1=(1,2) and the outer\n",
      "        is 0=(0,3) where in each child distance from the index is from the middle car. {key 1=(index_i,index_j):value outer, inner}\n",
      "        for 4 cars on the east on index 5 (max index = length = 5 - 1) the inner state is 3=(2,1) and the outer is 0=(0,3)\n",
      "        in the above examples there are inner states 1, 1, 3 which is a state of length 4, hence we need 4 more trailing \n",
      "        elements to meet index 5 because in general when index l is reached we need l trailing elements to be leaving and l\n",
      "        cars entering. \n",
      "\n",
      "        we determine the collision by iterating through all possible value configurations for our state and looking at the\n",
      "        cumulative sum (collision count) and add the value in a dict. This is what is stored in a binary tree file in \n",
      "        data folder(data is for index 0 to 12 for n=3 but the file size is quite large).\n",
      "        Thankfully we don't need to keep track of collisions for a single trial when we count the number of\n",
      "        collisions. We can increment collisions by doing the same process by 1 just like how we would construct the\n",
      "        number for up to 12. You will notice that for to construct a binary encoded number for collision count\n",
      "        similar techniques must be used to keep track of no collisions as well as when collisions happen at left or\n",
      "        right index from zero. Namely we need 4 binary encoded numbers to represent\n",
      "-----------------------------\n",
      "\n",
      "\n",
      "def car_race_collision(n: int):\n",
      "    \"\"\"\n",
      "    Imagine a road that's a perfectly straight infinitely long line.\n",
      "    n cars are driving left to right;  simultaneously, a different set of n cars\n",
      "    are driving right to left.   The two sets of cars start out being very far from\n",
      "    each other.  All cars move in the same speed.  Two cars are said to collide\n",
      "    when a car that's moving left to right hits a car that's moving right to left.\n",
      "    However, the cars are infinitely sturdy and strong; as a result, they continue moving\n",
      "    in their trajectory as if they did not collide.\n",
      "\n",
      "    This function outputs the number of such collisions.\n",
      "    \"\"\"\n",
      "    # O(N) solution:\n",
      "    # initial condition:  the parameters to specify the initial positions of 2 set of cars:\n",
      "    initial_positions0 = random.randint(0, MAX_POSITIONS0, n) # for set of cars 0, moving left to right\n",
      "    initial_positions1 = random.randint(0, MAX_POSITIONS1, n) # for set of cars 1, moving right to left\n",
      "\n",
      "    sort0_time = time.perf_counter()\n",
      "    # sorted() is a built-in Python sort function; it efficiently sorts a list.\n",
      "    initial_positions0_Sorted = sorted(initial_positions0)\n",
      "    sort1_time = time.perf_counter()\n",
      "\n",
      "    sort1_time = time.perf_counter()\n",
      "    # sorted() is a built-in Python sort function; it efficiently sorts a list.\n",
      "    initial_positions1_Sorted = sorted(initial_positions1)\n",
      "    sort2_time = time.perf_counter()\n",
      "\n",
      "    print(\"sort0 duration=\", sort1_time - sort0_time, \"seconds\\n\")\n",
      "    print(\"sort1 duration=\", sort2_time - sort1_time, \"seconds\\n\")\n",
      "\n",
      "    # set up data structures for O(1) test as to whether a car is Un-used or Assigned.\n",
      "    # Before we can use a register from the Un-used list, we must first allocate it to an Assigned car.\n",
      "    # When we no longer need a car, we must return its register to the un-used list.\n",
      "    # set up the pool of un-used registers for all n cars:\n",
      "    pool, tracks0, tracks1 = [set() for _ in range(n)], [False for _ in range(n)], [False for _ in range(2*n-1)]\n",
      "\n",
      "    # first, pool will hold all the registers.  \n",
      "    # As we assign registers/tracks/roads to cars,  an increasing amount of the list will be set to False\n",
      "    pool = [False for _ in range(2*n - 1)]\n",
      "    # The 2n-1 spots on the O(1) array that is accessed as a pool hold all of the registers for all n cars.\n",
      "    # Convention:  For indices [0 to n-1), the array holds tracks0 that a set of O(N) cars can use.\n",
      "    # Convention:  For indices [n to 2*n -1), the array holds tracks1 that a set of O(N) cars can use.\n",
      "\n",
      "    FirstConsecutive = [False for _ in range(n)]\n",
      "    print(\"FirstConsecutive\", FirstConsecutive)\n",
      "\n",
      "    # When 2 sets of cars, each set of N cars, meet, each encounters a set of tracks, also N.\n",
      "    # The first set of N cars can use either Left or Right, in any order.\n",
      "    # The second set of cars may only use Right.\n",
      "    Left  = [0 for _ in range(n)]\n",
      "    Right = [0 for _ in range(n)]\n",
      "\n",
      "    # Set up all tracks.  Do this prior to assigning any cars to tracks.\n",
      "    # Set up tracks for the first set of cars: tracks0[0 to n-1]:\n",
      "    # track priority ( 0 to n-1):  determine priority of tracks used by the meeting of the 2 car sets.\n",
      "    # There are n cars in each set, so there are n tracks in total.\n",
      "    tracks0 = [(i + 1, ) for i in range(n)] # for set of cars 0, moving left to right\n",
      "\n",
      "    # Set up tracks for the second set of cars: tracks1[0 to n-1]:\n",
      "    tracks1 = [(n + j + 1, ) for j in range(n)] # for set of cars 1, moving right to left\n",
      "\n",
      "    num_collision = 0\n",
      "    count = 0\n",
      "    while not all(tracks0) and not all(tracks1):\n",
      "        # assignment:\n",
      "        # assign each car to a different randomized track.\n",
      "        # initiate the sorting function fQsort1; it returns the sorted list as: initial_positions_Sorted\n",
      "        # Sort the O(N) list into order left to right:\n",
      "        # for\n",
      "-----------------------------\n",
      "from typing import List\n",
      "\n",
      "\n",
      "def concatenate(strings: List[str]) -> str:\n",
      "    \"\"\" Concatenate list of strings into a single string\n",
      "    >>> concatenate([])\n",
      "    ''\n",
      "    >>> concatenate(['a', 'b', 'c'])\n",
      "    'abc'\n",
      "    \"\"\"\n",
      "    s = ''\n",
      "    for string in strings:\n",
      "        s = s + string\n",
      "    return s\n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\IPython\\terminal\\tests\\test_prompts.py in <module>\n",
      "      3 from IPython.testing import tools as tt, decorators as dec\n",
      "----> 4 from IPython.terminal.prompts import Token, Prompts, PromptsColor, PromptsToken\n",
      "      5 from prompt_toolkit.completion import Completion, NestedCompleter\n",
      "      6 from traitlets import Bool, TraitError, Any\n",
      "      7 \n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\IPython\\terminal\\prompts.py in <module>\n",
      "----> 1 from prompt_toolkit.completion import ThreadedCompleter\n",
      "      2 from prompt_toolkit.completion import Completion\n",
      "      3 from prompt_toolkit.completion import NestedCompleter\n",
      "      4 from prompt_toolkit.completion import CompletionItem\n",
      "      5 from prompt_toolkit.completion import _start_of_word\n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\prompt_toolkit\\completion\\__init__.py in <module>\n",
      "     13 from typing import Callable, Iterator, List, Optional, Sequence, Tuple, Union, TYPE_CHECKING\n",
      "     14 \n",
      "---> 15 from prompt_toolkit.completion.completer import Completer\n",
      "     16 from prompt_toolkit.completion.completion import Completion\n",
      "     17 from prompt_toolkit.completion.completion_engine import (\n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\prompt_toolkit\\completion\\completer.py in <module>\n",
      "      8 from __future__ import unicode_literals\n",
      "      9 \n",
      "---> 10 from typing import cast, Any, Callable, Iterator, List, Optional, Tuple, Union\n",
      "     11 \n",
      "     12 from ..auto_suggest import AutoSuggestFromHistory\n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\numpydoc\\__init__.py in <module>\n",
      "      8 # flake8: noqa\n",
      "      9 from .docscrape_sphinx import (\n",
      "---> 10     NumpyDocString, Reader, SphinxDocString, NumpyDocTreeBuilder)\n",
      "     11 \n",
      "     12 \n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\numpydoc\\docscrape_sphinx.py in <module>\n",
      "     17     Nodes, make_glossary, DocumenterBridge, ClassDoc\n",
      "     18 )\n",
      "---> 19 from sphinx.errors import ExtensionError\n",
      "     20 from sphinx.util.inspect import object_description\n",
      "     21 \n",
      "\n",
      "~\\Anaconda3\\lib\\site-packages\\sphinx\\errors.py in <module>\n",
      "      6 \n",
      "      7 if PY36:\n",
      "----> 8     from contextlib import suppress\n",
      "      9 \n",
      "     10 \n",
      "\n",
      "ModuleNotFoundError: No module named 'contextlib'\n",
      "import contextlib\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "from typing import Dict, Any, Sequence, Iterator, Union\n",
      "from IPython.core.events import Events\n",
      "from IPython.core.getipython import get_ipython\n",
      "from IPython.core.interactiveshell import InteractiveShell\n",
      "from IPython.testing import decorators as dec\n",
      "from prompt_toolkit.interface import CommandLineInterface\n",
      "from IPython.terminal.pt_inputhooks import backend_from_akenecsv\n",
      "from IPython.utils.tempdir import TemporaryDirectory\n",
      "from IPython.utils import io\n",
      "from IPython.utils.py3compat import cast_unicode, to_unicode_from_fs\n",
      "from IPython.utils.tempdir import TemporaryWorkingDirectory\n",
      "from IPython.kernel.comm.comm_manager import CommManager\n",
      "from IPython.testing.tools import send_recv_from_controlflow as srfcf\n",
      "\n",
      "from prompt_toolkit.completion import ThreadedCompleter\n",
      "from prompt_toolkit.completion import Completion\n",
      "from prompt_toolkit.completion import NestedCom\n",
      "-----------------------------\n",
      "\n",
      "def get_max_triples(n):\n",
      "    \"\"\"\n",
      "    You are given a positive integer n. You have to create an integer array a of length n.\n",
      "        For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.\n",
      "        Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n",
      "    and a[i] + a[j] + a[k] is a multiple of 3.\n",
      "\n",
      "    Example :\n",
      "        Input: n = 5\n",
      "        Output: 1\n",
      "        Explanation: \n",
      "        a = [1, 3, 7, 13, 21]\n",
      "        The only valid triple is (1, 7, 13).\n",
      "    \"\"\"\n",
      "    sum = []\n",
      "    for i in range(len(n)):\n",
      "        for j in range(i+1,len(n)):\n",
      "            for k in range(j+1,len(n)):\n",
      "                if(n[i]+n[j]+n[k]):\n",
      "                    (sum.append((n[i], n[j], n[k])))\n",
      "\n",
      "    return sum\n",
      "n = [1, 3, 7, 13, 21]\n",
      "max_x = get_max_triples(n)\n",
      "max_x\n",
      "\n",
      "matrix = [[3,7,15,76,20],[8,9,2,12,10]]\n",
      "r = []\n",
      "c = []\n",
      "find = 0\n",
      "maxi = 0\n",
      "for i in range(len(matrix)):\n",
      "    for j in range(len(matrix[i])):\n",
      "        find += 1\n",
      "        if(find%2 != 0):\n",
      "            r.append(matrix[i][j])\n",
      "        else:\n",
      "            c.append(matrix[i][j])\n",
      "print(r)\n",
      "print(c)\n",
      "for k in range(0, (len(r))*(len(c)),2):\n",
      "    if((r[k]+r[k+1]+c[k]+c[k+1])%2==0):\n",
      "        maxi = max(maxi, (r[k]+r[k+1]+c[k]+c[k+1]))\n",
      "    \n",
      "maxi\n",
      "matrix = [[3,7,15,76,20],[8,9,2,12,10],[6,1,9, 4,7]]\n",
      "r = []\n",
      "c = []\n",
      "find = 0\n",
      "maxi = 0\n",
      "for i in range(0,3):\n",
      "    for j in range(0,5):\n",
      "        find += 1\n",
      "        if(find%2 != 0):\n",
      "            r.append(matrix[i][j])\n",
      "        else:\n",
      "            c.append(matrix[i][j])\n",
      "            \n",
      "for k in range(0, (len(r))*(len(c)),2):\n",
      "    if((r[k]+r[k+1]+c[k]+c[k+1])%2==0):\n",
      "        maxi = max(maxi, (r[k]+r[k+1]+c[k]+c[k+1]))\n",
      "maxi\n",
      "matrix = [[8,2], [2,2]]\n",
      "r = []\n",
      "c = []\n",
      "find = 0\n",
      "maxi = 0\n",
      "for i in range(0, 2):\n",
      "    for j in range(0,2):\n",
      "        find += 1\n",
      "        if(find%2 != 0):\n",
      "            r.append(matrix[i][j])\n",
      "        else:\n",
      "            c.append(matrix[i][j])\n",
      "            \n",
      "for k in range(0, (len(r))*(len(c)),2):\n",
      "    if((r[k]+r[k+1]+c[k]+c[k+1])%2==0):\n",
      "        maxi = max(maxi, (r[k]+r[k+1]+c[k]+c[k+1]))\n",
      "maxi\n",
      "m1 = [3,7,15,76,20]\n",
      "int(m1[0])+m1[1]+m1[2]\n",
      "r = []\n",
      "c = []\n",
      "find = 0\n",
      "maxi = 0\n",
      "for i in range(len(m1)):\n",
      "        find += 1\n",
      "        if(find%2 != 0):\n",
      "            r.append(m1[i])\n",
      "        else:\n",
      "            c.append(m1[i])\n",
      "            \n",
      "for k in range(0, (len(r))*(len(c)),2):\n",
      "    if((r[k]+r[k+1]+c[k]+c[k+1])%2==0):\n",
      "        maxi = max(maxi, (r[k]+r[k+1]+c[k]+c[k+1]))\n",
      "\n",
      "maxi\n",
      "matrix = ['sam 123', 'uwer 234', 'gtye 345']\n",
      "m = [[]]\n",
      "for i in range(len(matrix)\n",
      "-----------------------------\n",
      "\n",
      "FIX = \"\"\"\n",
      "Add more test cases.\n",
      "\"\"\"\n",
      "\n",
      "def vowels_count(s):\n",
      "    \"\"\"Write a function vowels_count which takes a string representing\n",
      "    a word as input and returns the number of vowels in the string.\n",
      "    Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n",
      "    vowel, but only when it is at the end of the given word.\n",
      "\n",
      "    Example:\n",
      "    >>> vowels_count(\"abcde\")\n",
      "    2\n",
      "    >>> vowels_count(\"ACEDY\")\n",
      "    3\n",
      "    \"\"\"\n",
      "    total = 0\n",
      "    # we use total here because it makes the computation more intuitive:\n",
      "    # add up all the vowels\n",
      "    vowels = ['a', 'e', 'i', 'o', 'u']\n",
      "\n",
      "    # two possible ways to iterate through the letters\n",
      "    # 1. explicit loop\n",
      "    # 2. `for letter in input_string`\n",
      "    # I would choose 1 in this case.\n",
      "\n",
      "    # also, heuristics to pick which way to loop:\n",
      "    # - if you need to process every element and you don't care about indices,\n",
      "    #   then use for-in\n",
      "    # - if you need to access the strip()'ed representing of the string like\n",
      "    #   letter, use an explicit loop.\n",
      "    # - if you need to do something a certain number of times, without regard\n",
      "    #   to the elements inside the string, then use range() over the length\n",
      "\n",
      "    # here, we need to go through all the letters, and we really want to make\n",
      "    # sure we check every one of them. so, for-in is good for us\n",
      "\n",
      "    for letter in s.strip():\n",
      "        # the explicit loop uses indices. we will always use the i to get the\n",
      "        # letter from the string.\n",
      "\n",
      "        # note that we use .strip() so that if the word has leading or trailing\n",
      "        # whitespace, we also loop over them\n",
      "\n",
      "        # you may also have seen .strip used with .split()\n",
      "        # text.split().strip() will turn it into a list of strings, each of\n",
      "        # which is with leading and trailing whitespace removed.\n",
      "        # WHY NOT JUST USE text.split().strip() THOUGH??!\n",
      "        # the reason is that text.strip(' ') will remove whitespace *throughout*\n",
      "        # the entire string. text.split().strip() will not.\n",
      "\n",
      "        # usage through the \"word\": \"\" use case aside, note that we usually\n",
      "        # want to do text.strip() instead of removing leading or trailing\n",
      "        # whitespace manually.\n",
      "\n",
      "        # going back to the homework, we stick with how you wrote it:\n",
      "        # letter = s[i]\n",
      "\n",
      "        # another major \"footgun\" that this code fragment prevents\n",
      "        # is a string out-of-range access.\n",
      "        # note that we have set i to go from 0 to len(text), inclusive.\n",
      "        # the ith position for a string in Python is the ith character,\n",
      "        # exclusive of the newline. this means that for the string\n",
      "        # 'hello' (which has length 5), actually has 6 elements internally:\n",
      "        # h  e  l  l  o\\n\n",
      "        # if you try to index anything from 5 to 8, you get an error because\n",
      "        # then you are indexing into the strangeness that is trying to insert\n",
      "        # a character past the end of the string.\n",
      "        # if you think \"this is hooey,\" note that the reason is because strings\n",
      "        # are immutable.\n",
      "        # by trying to insert a character after the newline, even though the\n",
      "        # length is still only 5, the literal \\n is not in the string. that\n",
      "        # is, h e l l o\\n does not exist in the data structure.\n",
      "        # note that this is different from linked lists, where often, the\n",
      "        # last node is the one representing the end of the list.\n",
      "\n",
      "        # how could we change the loop counters to\n",
      "        # avoid these \"opportunities\" to cause runtime errors?\n",
      "        # using range(0,len(s)+1,1), by using -1 instead of 0.\n",
      "        # then, start = len(s)-1, stop = 0, step = -1.\n",
      "\n",
      "        # note that we could also do this with negative indices, but\n",
      "        # beware that it's error prone: negative indices are trickier.\n",
      "\n",
      "        # you may be asking, \"but we just talked about how to prevent\n",
      "        # an IndexError! why not have it go from 0 to len(s), inclusive?\"\n",
      "        # the con of that is that if the word is has 5 letters, we will also\n",
      "        # try to look at the 6th element, which does not exist.\n",
      "        # besides preventing an error, this forces us to let the ith element\n",
      "        # be the letter\n",
      "-----------------------------\n",
      "\n",
      "def is_multiply_prime(a):\n",
      "    \"\"\"Write a function that returns true if the given number is the multiplication of 3 prime numbers\n",
      "    and false otherwise.\n",
      "    Knowing that (a) is less then 100. \n",
      "    Example:\n",
      "    is_multiply_prime(30) == True\n",
      "    30 = 2 * 3 * 5\n",
      "    \"\"\"\n",
      "    #DETECTIF INPUT EST UNMULTIPLE DE 3 NOMBRES PREMIS\n",
      "    \"\"\"\n",
      "    FLAG=0\n",
      "    LIMIT = 1000\n",
      "    sieve = [i for i in range(LIMIT)]\n",
      "    sieve[1] = 0\n",
      "    for i in range(2, LIMIT):\n",
      "        if sieve[i] != 0:\n",
      "            j=i*i\n",
      "            while j < LIMIT:\n",
      "                sieve[j] = 0\n",
      "                j += i\n",
      "\n",
      "    premiers = [i for i in sieve if i != 0]\n",
      "    print premiers\n",
      "    [2, 3, 5, 7, 11 ...]\n",
      "    \"\"\"\n",
      "    if a > 0 and a<100:\n",
      "        flag=0\n",
      "        if a==1 or a==2 or a==3 or a==5 or a==7 or a==11 or a==13 or a==17 or a==19 or a==23 or a==29 or a==31 or a==37 or a==41 or a==43 or a==47 or a==49 or a==59 or a==61 or a==67 or a==71 or a==73 or a==79 or a==83 or a==89 or a==97:\n",
      "            flag=1\n",
      "        elif a%2==0: \n",
      "            for i in range(a/2+1):\n",
      "                if (a==(2*i)) or (a==(3*i)) or (a==(5*i)) or (a==(7*i)) or (a==(11*i)) or (a==(13*i)) or (a==(17*i)) or (a==(19*i)) or (a==(23*i)) or (a==(29*i)) or (a==(31*i)) or (a==(37*i)) or (a==(41*i)) or (a==(43*i)) or (a==(47*i)) or (a==(47*i)) or (a==(49*i)) or (a==(59*i)) or (a==(61*i)) or (a==(67*i)) or (a==(71*i)) or (a==(73*i)) or (a==(79*i)) or (a==(83*i)) or (a==(89*i)) or (a==(97*i)) or (a==(101*i)):\n",
      "                    flag=1\n",
      "                    break\n",
      "        elif a%3==0:\n",
      "            for i in range(a/3+1):\n",
      "                if (a==(3*i)) or (a==(3*i)) or (a==(5*i)) or (a==(7*i)) or (a==(11*i)) or (a==(13*i)) or (a==(17*i)) or (a==(19*i)) or (a==(23*i)) or (a==(29*i)) or (a==(31*i)) or (a==(37*i)) or (a==(41*i)) or (a==(43*i)) or (a==(47*i)) or (a==(47*i)) or (a==(49*i)) or (a==(59*i)) or (a==(61*i)) or (a==(67*i)) or (a==(71*i)) or (a==(73*i)) or (a==(79*i)) or (a==(83*i)) or (a==(89*i)) or (a==(97*i)) or (a==(101*i)):\n",
      "                    flag=1\n",
      "                    break\n",
      "        elif a%5==0:\n",
      "            for i in range(a/5+1):\n",
      "                if (a==(5*i)) or (a==(5*i)) or (a==(5*i)) or (a==(7*i)) or (a==(11*i)) or (a==(13*i)) or (a==(17*i)) or (a==(19*i)) or (a==(23*i)) or (a==(29\n",
      "-----------------------------\n",
      "\n",
      "def do_algebra(operator, operand):\n",
      "    \"\"\"\n",
      "    Given two lists operator, and operand. The first list has basic algebra operations, and \n",
      "    the second list is a list of integers. Use the two given lists to build the algebric \n",
      "    expression and return the evaluation of this expression.\n",
      "\n",
      "    The basic algebra operations:\n",
      "    Addition ( + ) \n",
      "    Subtraction ( - ) \n",
      "    Multiplication ( * ) \n",
      "    Floor division ( // ) \n",
      "    Exponentiation ( ** ) \n",
      "\n",
      "    Example:\n",
      "    operator['+', '*', '-']\n",
      "    array = [2, 3, 4, 5]\n",
      "    result = 2 + 3 * 4 - 5\n",
      "    => result = 9\n",
      "\n",
      "    Note:\n",
      "        The length of operator list is equal to the length of operand list minus one.\n",
      "        Operand is a list of of non-negative integers.\n",
      "        Operator list has at least one operator, and operand list has at least two operands.\n",
      "\n",
      "    \"\"\"\n",
      "\n",
      "    # Create list of possible errors\n",
      "    algorithm_errors = {\n",
      "                        'RangeError': \"Last operand is too large\", \n",
      "                        'TypeError': \"Operator function provided is not in algorithm\",\n",
      "                        'ValueError': \"Value given as operand is not a natural number\",\n",
      "                        'ZeroDivisionError': \"You're dividing by zero; you may wish one day to discuss this with God\",\n",
      "                        'RuntimeError': \"Operations still in progress; all algorithm types exhausted\"\n",
      "                        }\n",
      "\n",
      "    # For 'while' operation\n",
      "    i = 0 # Increment for operating iterations through 'operand'\n",
      "    operations = 0 # Start at 0; +1 for every operation\n",
      "    import math # For ceiling operation\n",
      "\n",
      "    # While we still have another operator, keep coding\n",
      "    while i < len(operator):\n",
      "\n",
      "        # Addition\n",
      "        if operator[i] == 'add':\n",
      "            operand.append(operand.pop(0) + operand.pop(0))\n",
      "            operations += 1\n",
      "            i += 1\n",
      "            continue\n",
      "\n",
      "        # Subtraction\n",
      "        if operator[i] == 'subtract':\n",
      "            operand.append(operand.pop(0) - operand.pop(0))\n",
      "            operations += 1\n",
      "            i += 1\n",
      "            continue\n",
      "\n",
      "        # Multiply\n",
      "        if operator[i] == 'multiply':\n",
      "            operand.append(operand.pop(0) * operand.pop(0))\n",
      "            operations += 1\n",
      "            i += 1\n",
      "            continue\n",
      "\n",
      "        # Floor division\n",
      "        if operator[i] == 'floor_divide':\n",
      "            try:\n",
      "                # If IntegerDivisionError happens, then extend operand list\n",
      "                operand.append(operand.pop(0) // operand.pop(0))\n",
      "                operations += 1\n",
      "                i += 1\n",
      "                continue\n",
      "\n",
      "            # See 'algorithm_errors' dict to know more\n",
      "            except ZeroDivisionError:\n",
      "                return algorithm_errors['ZeroDivisionError']\n",
      "            \n",
      "            except ValueError:\n",
      "                return algorithm_errors['ValueError']\n",
      "\n",
      "        # Divide\n",
      "        if operator[i] == 'divide':\n",
      "\n",
      "            first_num = operand.pop(0)\n",
      "            second_num = operand.pop(0)\n",
      "\n",
      "            try:\n",
      "                # If IntegerDivisionError happens, then extend operand list\n",
      "                operand.append(first_num / second_num)\n",
      "                # Update 'operations'\n",
      "                operations += 1\n",
      "                i += 1\n",
      "                continue\n",
      "\n",
      "            # See 'algorithm_errors' dict to know more\n",
      "            except ZeroDivisionError:\n",
      "                return algorithm_errors['ZeroDivisionError']\n",
      "            \n",
      "            except ValueError:\n",
      "                return algorithm_errors['ValueError']\n",
      "\n",
      "        # Exponentiation\n",
      "        # Handle negative exponentials\n",
      "        if operator[i] == 'exponent':\n",
      "\n",
      "            # Hope error handling works...\n",
      "            try:\n",
      "\n",
      "                # If IntegerDivisionError happens, then extend operand list\n",
      "                if isinstance(operand[0], int) and isinstance(operand[1], int) and isinstance(operand[1], int) != 0:\n",
      "                    operand.append(operand.pop(0) ** operand.pop(0))\n",
      "                    operations += 1\n",
      "                    i += 1\n",
      "                    continue\n",
      "\n",
      "                else:\n",
      "                    return algorithm_errors['RuntimeError']\n",
      "\n",
      "            # See 'algorithm_errors' dict to know more\n",
      "            # TODO: Close this!!!!!\n",
      "            except IndexError:\n",
      "                print('Tester is broken')\n",
      "                return algorithm_errors['RuntimeError']\n",
      "            \n",
      "            except ZeroDivisionError:\n",
      "                return algorithm_errors['ZeroDivisionError']\n",
      "            \n",
      "            except ValueError:\n",
      "                return algorithm_errors['ValueError']\n",
      "\n",
      "        # Ceiling division\n",
      "        elif operator[i] == 'ceil_divide':\n",
      "            try:                \n",
      "                c_floor = math.floor(operand.pop(0) / operand.pop(0))\n",
      "                if ((c_floor+1) - (c_floor)) == 0:\n",
      "                    operand.append(c_floor)\n",
      "                else:\n",
      "                    operand.append(c_floor+1)\n",
      "                # Update 'operations'\n",
      "                operations\n",
      "-----------------------------\n",
      "\n",
      "def do_algebra(operator, operand):\n",
      "    \"\"\"\n",
      "    Given two lists operator, and operand. The first list has basic algebra operations, and \n",
      "    the second list is a list of integers. Use the two given lists to build the algebric \n",
      "    expression and return the evaluation of this expression.\n",
      "\n",
      "    The basic algebra operations:\n",
      "    Addition ( + ) \n",
      "    Subtraction ( - ) \n",
      "    Multiplication ( * ) \n",
      "    Floor division ( // ) \n",
      "    Exponentiation ( ** ) \n",
      "\n",
      "    Example:\n",
      "    operator['+', '*', '-']\n",
      "    array = [2, 3, 4, 5]\n",
      "    result = 2 + 3 * 4 - 5\n",
      "    => result = 9\n",
      "\n",
      "    Note:\n",
      "        The length of operator list is equal to the length of operand list minus one.\n",
      "        Operand is a list of of non-negative integers.\n",
      "        Operator list has at least one operator, and operand list has at least two operands.\n",
      "\n",
      "    \"\"\"\n",
      "    result = 0\n",
      "    if operator[0] == \"+\":\n",
      "        result = operand[0] + operand[1]\n",
      "        if len(operator) > 1:\n",
      "            for i in range(len(operand)-1):\n",
      "                if operator[i] == \"+\":\n",
      "                    result += operand[i+2]\n",
      "                elif operator[i] == \"-\":\n",
      "                    result -= operand[i+2]\n",
      "                elif operator[i] == \"*\":\n",
      "                    result *= operand[i+2]\n",
      "                elif operator[i] == \"//\":\n",
      "                    result = result // operand[i+2]\n",
      "                elif operator[i] == \"**\":\n",
      "                    result = result ** operand[i+2]\n",
      "    elif operator[0] == \"-\":\n",
      "        result = operand[0] - operand[1]\n",
      "        if len(operator) > 1:\n",
      "            for i in range(len(operand)-1):\n",
      "                if operator[i] == \"+\":\n",
      "                    result += operand[i+2]\n",
      "                elif operator[i] == \"-\":\n",
      "                    result -= operand[i+2]\n",
      "                elif operator[i] == \"*\":\n",
      "                    result *= operand[i+2]\n",
      "                elif operator[i] == \"//\":\n",
      "                    result = result // operand[i+2]\n",
      "                elif operator[i] == \"**\":\n",
      "                    result = result ** operand[i+2]\n",
      "    elif operator[0] == \"*\":\n",
      "        result = operand[0] * operand[1]\n",
      "        if len(operator) > 1:\n",
      "            for i in range(len(operand)-1):\n",
      "                if operator[i] == \"+\":\n",
      "                    result += operand[i+2]\n",
      "                elif operator[i] == \"-\":\n",
      "                    result -= operand[i+2]\n",
      "                elif operator[i] == \"*\":\n",
      "                    result *= operand[i+2]\n",
      "                elif operator[i] == \"//\":\n",
      "                    result = result // operand[i+2]\n",
      "                elif operator[i] == \"**\":\n",
      "                    result = result ** operand[i+2]\n",
      "    elif operator[0] == \"//\":\n",
      "        result = int(operand[0] / operand[1])\n",
      "        if len(operator) > 1:\n",
      "            for i in range(len(operand)-1):\n",
      "                if operator[i] == \"+\":\n",
      "                    result += operand[i+2]\n",
      "                elif operator[i] == \"-\":\n",
      "                    result -= operand[i+2]\n",
      "                elif operator[i] == \"*\":\n",
      "                    result *= operand[i+2]\n",
      "                elif operator[i] == \"//\":\n",
      "                    result = result // operand[i+2]\n",
      "                elif operator[i] == \"**\":\n",
      "                    result = result ** operand[i+2]\n",
      "    elif operator[0] == \"**\":\n",
      "        result = operand[0] ** operand[1]\n",
      "        if len(operator) > 1:\n",
      "            for i in range(len(operand)-1):\n",
      "                if operator[i] == \"+\":\n",
      "                    result += operand[i+2]\n",
      "                elif operator[i] == \"-\":\n",
      "                    result -= operand[i+2]\n",
      "                elif operator[i] == \"*\":\n",
      "                    result *= operand[i+2]\n",
      "                elif operator[i] == \"//\":\n",
      "                    result = result // operand[i+2]\n",
      "                elif operator[i] == \"**\":\n",
      "                    result = result ** operand[i+2]\n",
      "    return (result) #, or return True if needed\n",
      "\n",
      "\"\"\" Hidden solutions for 1 to 34: \n",
      "    369\n",
      "    232\n",
      "    447\n",
      "    140\n",
      "    55\n",
      "    237\n",
      "    441\n",
      "    2,416\n",
      "    61\n",
      "    1,300\n",
      "    48.66..\n",
      "    2.0\n",
      "    152.4\n",
      "    33\n",
      "    5\n",
      "    2\n",
      "    16.0\n",
      "    8.8\n",
      "    3.0\n",
      "    18.0\n",
      "\n",
      "-----------------------------\n",
      "\n",
      "def do_algebra(operator, operand):\n",
      "    \"\"\"\n",
      "    Given two lists operator, and operand. The first list has basic algebra operations, and \n",
      "    the second list is a list of integers. Use the two given lists to build the algebric \n",
      "    expression and return the evaluation of this expression.\n",
      "\n",
      "    The basic algebra operations:\n",
      "    Addition ( + ) \n",
      "    Subtraction ( - ) \n",
      "    Multiplication ( * ) \n",
      "    Floor division ( // ) \n",
      "    Exponentiation ( ** ) \n",
      "\n",
      "    Example:\n",
      "    operator['+', '*', '-']\n",
      "    array = [2, 3, 4, 5]\n",
      "    result = 2 + 3 * 4 - 5\n",
      "    => result = 9\n",
      "\n",
      "    Note:\n",
      "        The length of operator list is equal to the length of operand list minus one.\n",
      "        Operand is a list of of non-negative integers.\n",
      "        Operator list has at least one operator, and operand list has at least two operands.\n",
      "\n",
      "    \"\"\"\n",
      "\n",
      "    # note: the sort algorithm is stable, hence it is possible to\n",
      "    # maintain the relative order of similar elements; allow to keep all exponents at the right\n",
      "    # since Python 3 did not introduced any other change in the floor division algorithm, \n",
      "    # it will behave the same way in Python 2 and in Python 3\n",
      "    # operator: *, //, +, **, -\n",
      "    # ordering: *, //, **, +, - (the order here matters!)\n",
      "    ranking2 = {'/': 1, '*': 2, '//': 2, '+': 1, '-': 1, 'exp': 3, '**': 4}\n",
      "    whereending = {}  # for brackets to know where to end the bracket in this string\n",
      "    prob = []  # biggest number from the problem, best to use the min value\n",
      "\n",
      "    # switch the place of numbers, so that the pre-translated signs will properly match the operands\n",
      "    array = [None]*(len(operator) + 1)\n",
      "    array[::2] = operand[::-1]\n",
      "    array[1::2] = operand[1::-1]\n",
      "\n",
      "    array = [c for l in array for c in l]  # flatten nested lists to a single list\n",
      "    array = [0] + array  # add the zero to avoid increase the complexity of the loop below\n",
      "\n",
      "    def where(number):\n",
      "        \"\"\"\n",
      "        Required to move the exponents beyond operators that only accept two inputs since\n",
      "        otherwise 5 // (4**2) would be divided instead of raised to power.\n",
      "        Hence we need to found the value first and return it's location in the string:\n",
      "        (5 // 4)**2 versus 5 // (4**2)\n",
      "\n",
      "        Also required for 2 // (2 + 3)**2 to find location of 2 to place bracket\n",
      "        \"\"\"\n",
      "        for i in range(len(operator)):\n",
      "            if number in array[2*i+1:2*i+3]:\n",
      "                if ranking2[operator[i]] == ranking2['**']:\n",
      "                    return 2*i+1, 2*i+3\n",
      "                else:\n",
      "                    return 2*i+1, 2*i+2\n",
      "        else:\n",
      "            return 0, len(operator)+1\n",
      "\n",
      "    # Python operator precedence works surprisingly(and (too) smartly) performs exponential first\n",
      "    #  when the exponent uses two operands rather than like the other advanced math languages\n",
      "    # http://mathinsight.org/binary_operators_python\n",
      "    # in Python 2: 4**(3 + 2), 4**(3 + 2) both will be = 4096\n",
      "    # in Python 3 only the first example behaves correctly\n",
      "    # also see https://www.cs.utexas.edu/users/EWD/transcriptions/EWD03xx/EWD316.5.html\n",
      "\n",
      "    for i in range(len(operator)):\n",
      "        # check if there any '**' operators present have 2 operands: 2** *(3-2)\n",
      "        if operator[i] == '**' and len(str(operand[i+1])) > 1:\n",
      "            v1, v2 = where(operand[i])  # if statements to return minimal values;\n",
      "            w1 = v1 - 1 if v1 > 0 else 0\n",
      "            w2 = v2 if v2 > 0 else len(operator)\n",
      "            whereending[w1] = w2\n",
      "        else:\n",
      "            whereending[int(i*2 + (operand[i] < 10))] = i*2+2  # put brackets if smaller than 10, not required otherwise\n",
      "\n",
      "    # build the string of the problem; add the initial 0, since we added the zero in the integers' array\n",
      "    prob += [stringify(array[0])[0]+'('+stringify(d)[0]+' '+operator[k-1]+' '+stringify(array[k+1])[0]+')'\n",
      "                 for k, d in enumerate(array, 1) if len(str(d)) > 1]\n",
      "\n",
      "    for i in range(len(operator)):  # check for postfix operators if needed +,-, and add\n",
      "        if ranking2[operator[i]] == ranking2['**']\n",
      "-----------------------------\n",
      "\n",
      "def anti_shuffle(s):\n",
      "    \"\"\"\n",
      "    Write a function that takes a string and returns an ordered version of it.\n",
      "    Ordered version of string, is a string where all words (separated by space)\n",
      "    are replaced by a new word where all the characters arranged in\n",
      "    ascending order based on ascii value.\n",
      "    Note: You should keep the order of words and blank spaces in the sentence.\n",
      "\n",
      "    For example:\n",
      "    anti_shuffle('Hi') returns 'Hi'\n",
      "    anti_shuffle('hello') returns 'ehllo'\n",
      "    anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n",
      "    \"\"\"\n",
      "\n",
      "    def string_to_list(string):\n",
      "        # define a function that takes a word and\n",
      "        # puts the letters and '' in a list.\n",
      "        letters_in_word = []\n",
      "        i = 0\n",
      "        # check if the word end is over, i.e we reached the last letter.\n",
      "        while i < len(string) - 1:\n",
      "            # check if the char is not a letter, then add it.\n",
      "            if not string[i].isalpha():\n",
      "                letters_in_word += [string[i]]\n",
      "                i += 1\n",
      "            else:\n",
      "                # accumulate all the letters together.\n",
      "                # in case the word is a one-letter long.\n",
      "                acc_words = ''\n",
      "                while i < len(string) - 1 and string[i].isalpha():\n",
      "                    acc_words += string[i]\n",
      "                    i += 1\n",
      "                # check if the word end is over, then we are at the last letter,\n",
      "                # we want to put it in the list as well.\n",
      "                if i == len(string) - 1 and string[i].isalpha():\n",
      "                    acc_words += string[i]\n",
      "                # sort the letter before the put them into the list.\n",
      "                letters_in_word += [sorted_string(acc_words)]\n",
      "        # check for the last letter in the word to insert it into the list.\n",
      "        if string[i].isalpha():\n",
      "            letters_in_word += [string[i]]\n",
      "        # check for the not-a-letter char in case it is at the end of the word.\n",
      "        if string[i] != ' ' and not string[i].isalpha():\n",
      "            letters_in_word += [string[i]]\n",
      "        # returns the list of letters and '' in the correct order.\n",
      "        return letters_in_word\n",
      "    # define a function that merge the letters back together in ascending order.\n",
      "\n",
      "    def sorted_string(list_of_letters):\n",
      "        # check if there only one letter in the word.\n",
      "        if len(list_of_letters) == 1:\n",
      "            return list_of_letters\n",
      "        # if there are two letters in the word.\n",
      "        elif len(list_of_letters) == 2:\n",
      "            return list_of_letters[0] + list_of_letters[1]\n",
      "        # if there are more than two letters in the word.\n",
      "        else:\n",
      "            # define a starting index to sort the string after.\n",
      "            mid_index = len(list_of_letters) // 2\n",
      "            # divide the list_of_letters into two lists.\n",
      "            left_list = list_of_letters[0:mid_index + 1:1]\n",
      "            right_list = list_of_letters[mid_index + 1::1]\n",
      "            # sort the left list.\n",
      "            if len(left_list) > 1:\n",
      "                sorted_left_list = sorted_string(left_list)\n",
      "            else:\n",
      "                sorted_left_list = left_list\n",
      "            # sort the right list.\n",
      "            if len(right_list) > 1:\n",
      "                sorted_right_list = sorted_string(right_list)\n",
      "            else:\n",
      "                sorted_right_list = right_list\n",
      "            # take the first char from the left list and insert it\n",
      "            # into the new ordered list.\n",
      "            new_string_letters = [sorted_left_list[0]]\n",
      "            # delete that char from the list.\n",
      "            del sorted_left_list[0]\n",
      "            # take the first char from the right list and insert it\n",
      "            # into the new ordered list.\n",
      "            new_string_letters += sorted_right_list[0]\n",
      "            # delete that char from the list.\n",
      "            del sorted_right_list[0]\n",
      "            # run on the highest-sorted list\n",
      "            # until one of the lists are not empty.\n",
      "            # the highest_sorted_list will always be the sortest list.\n",
      "            # since we delete a char from the list after we added it to the end\n",
      "            # of the ordered string, the sortest list will always be the first\n",
      "            # to empty and start sorting with the other list.\n",
      "            while len(sorted_left_list) != 0 and len(\n",
      "-----------------------------\n",
      "\n",
      "def anti_shuffle(s):\n",
      "    \"\"\"\n",
      "    Write a function that takes a string and returns an ordered version of it.\n",
      "    Ordered version of string, is a string where all words (separated by space)\n",
      "    are replaced by a new word where all the characters arranged in\n",
      "    ascending order based on ascii value.\n",
      "    Note: You should keep the order of words and blank spaces in the sentence.\n",
      "\n",
      "    For example:\n",
      "    anti_shuffle('Hi') returns 'Hi'\n",
      "    anti_shuffle('hello') returns 'ehllo'\n",
      "    anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n",
      "    \"\"\"\n",
      "\n",
      "    # strdeňuje, preskakuje prázdne miesta a predlžuje - A\n",
      "    # funkcia, ktorá rozloží na znaky, roztriedi podľa hodnoty ascii a\n",
      "    # texty dá späť do pôvodného tvara s nacapaným medzerami\n",
      "    # (spájne po elements, join). Strided pivot index by resolution.\n",
      "    def pivot_index(A, x, pivot_index_func=bisect.bisect_left):\n",
      "        pivot_index = pivot_index_func(A, x)\n",
      "        pivot_index = max(0, pivot_index - 1)\n",
      "        pivot = None\n",
      "        for i, a in enumerate(A[pivot_index:]):\n",
      "            if pivot is None or a != pivot:\n",
      "                _swap_at(A, pivot_index + i, pivot_index)\n",
      "                pivot = a\n",
      "        return pivot_index\n",
      "\n",
      "    _findB = {\n",
      "        \">=\": pivot_index,\n",
      "        \"<=\": lambda A, x: -pivot_index(C, -x, bisect.bisect_right) - 1,\n",
      "        \">\": lambda A, x: -pivot_index(C, -x, bisect.bisect_left) - 1,\n",
      "        \"<\": pivot_index,\n",
      "    }\n",
      "\n",
      "    def _qsort(lo, hi, flipped, f, start=0, wrong=False, method='>='):\n",
      "        \"\"\"\n",
      "        Make quick sort\n",
      "        :param lo: min value of partition to sort\n",
      "        :param hi: max value of partition to sort\n",
      "        :param flipped: when value should go left or right\n",
      "        :param f: function applied in filter(f, A)\n",
      "        :param start: The initial thing to find was the wrong edge.\n",
      "        For example: A[k] = f(k). Start is the minimum k such that\n",
      "        f(k) does not hold (i.e. f(start) = False). In this case\n",
      "        a current value starts at the left of that position, because\n",
      "        we already know the left side of it has elements for which\n",
      "        f is False, so we can ignore that\n",
      "        :param wrong: return answer with False on the wrong side of Bracket\n",
      "        (A[wrong] = true if wrong = 'left'; False otherwise)\n",
      "        :return: function handle if wrong=True or bool\n",
      "        \"\"\"\n",
      "        def rec(lo, hi, f, flipped, wrongSide, init_answer):\n",
      "            \"\"\"\n",
      "            Make recursive version of qsort\n",
      "            :param lo: min value of partition to sort\n",
      "            :param hi: max value of partition to sort\n",
      "            :param f: function applied in filter(f, A)\n",
      "            :param flipped: when value should go left or right\n",
      "            :param wrongSide: parameter when return answer is True\n",
      "                              and opposite\n",
      "            :param init_answer: the wrong position, k s.t f(k) = False\n",
      "            :return: bool\n",
      "            \"\"\"\n",
      "            nonlocal _findB\n",
      "            if hi - lo < 2:\n",
      "                return init_answer if wrongSide else None\n",
      "            mid = (lo + hi) // 2\n",
      "            new_f = lambda x: flipped ^ f(x, A[mid])\n",
      "            _ = _findB[method](A, mid, f=new_f)\n",
      "            left = rec(lo, _ + 1, f, flipped, 0, A[_])\n",
      "            right = rec(_, hi, f, flipped, 1, A[_])\n",
      "            if wrongSide:\n",
      "                return left if wrongSide == 0 else right\n",
      "            return\n",
      "\n",
      "        return rec(lo, hi, f, flipped, wrong, None)\n",
      "\n",
      "    def _quick_select(A, x, flipped=False, findBm=None):        \n",
      "        def new_f(k):\n",
      "            return x == A[k] if findBm is None else findBm(A, x, k)\n",
      "            \n",
      "        _ = _qsort(0, len(A), flipped, new_f, wrong=True, method='>=')\n",
      "        return _()\n",
      "-----------------------------\n",
      "\n",
      "def is_nested(string):\n",
      "    '''\n",
      "    Create a function that takes a string as input which contains only square brackets.\n",
      "    The function should return True if and only if there is a valid subsequence of brackets \n",
      "    where at least one bracket in the subsequence is nested.\n",
      "\n",
      "    is_nested('[[]]') ➞ True\n",
      "    is_nested('[]]]]]]][[[[[]') ➞ False\n",
      "    is_nested('[][]') ➞ False\n",
      "    is_nested('[]') ➞ False\n",
      "    is_nested('[[][]]') ➞ True\n",
      "    is_nested('[[]][[') ➞ True\n",
      "    '''\n",
      "    inside = 0\n",
      "    prev_match = None\n",
      "    for c in range(len(string)):\n",
      "        if string[c] == '[':\n",
      "            inside += 1\n",
      "        elif string[c] == ']':\n",
      "            inside -= 1\n",
      "            if string[c - 1] == '[':\n",
      "                prev_match = 'brace'\n",
      "            else:\n",
      "                prev_match = 'bracket'\n",
      "        if inside == 0 and prev_match == 'brace':\n",
      "            return True\n",
      "    return inside == 0\n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "    \n",
      "aa = \"!!!SAD!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!!\\n;Das!!2!ASD!ASD!ASD!ASD!ASD!ASD!ASD!ASD\\nasd!!!!!!ASD!!!!ASD!ASDsad!ASD!ASDdsf!ASD!ASDsad!ASD!SAD!SAD!SAD!!!SAD!!!SAD!SAD!SAD!SAD!SAD!SAD!SAD!!!!!ASD!ASD!!!ASDASD!!!!!!!!!!SA!!!D!!!!ASD!!!ASD!ASD!ASD!ASD!ASD!ASDsad!ASD!AS+32D!ASD!ASD!ASD!ASD!ASD!ASD!ASD!!!!as!ASD!ASD!ASD!ASD!ASD!ASD!ASD!!!!asd!ASDsad!ASD!ASD!ASD!ASD!ASD!ASD!+13ASD!-2ASD!ASD!ASDsad!!ASD!ASD!ASD!ASD!ASD!asd!ASD!!!!!+32aasd!!!!SAD!!!!SAD!!SAD!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!!SAD!!!SADDDSADS2!!!!SADsaddsad!!!SAD!!!SAD!!!SAD!!!SA!!!D!!!!ASD!!!ASD!ASD!ASD!ASD!ASD!ASD!!!!\n",
      "-----------------------------\n",
      "\n",
      "def words_string(s):\n",
      "    \"\"\"\n",
      "    You will be given a string of words separated by commas or spaces. Your task is\n",
      "    to split the string into words and return an array of the words.\n",
      "    \n",
      "    For example:\n",
      "    words_string(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n",
      "    words_string(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n",
      "    \"\"\"\n",
      "    return s.split(',') or s.split()\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"Hello my name is John\"), [\"Hello\", \"my\", \"name\", \"is\", \"John\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"Max, Milly, Molly and May\"), [\"Max\", \"Milly\", \"Molly\", \"and\", \"May\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"CodeWars can be addictive\"), [\"CodeWars\", \"can\", \"be\", \"addictive\"])\n",
      " \n",
      "\n",
      "words_string(\"CodeWars can be addictive\")\n",
      "type(words_string(\"CodeWars can be addictive\"))\n",
      " \n",
      "\n",
      "words_string(\"CodeWars can be addictive\").split(',')\n",
      "words_string(\"this is the second time for this lesson\").split(',')\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"first,do not Worry,things happen for a reason do not worry if things do not go as planned\"), [\"first\", \"do not Worry\", \"things happen for a reason do not worry if things do not go as planned\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"Life is good, life is better than your worst day and better than your best day\"), [\"Life\", \"is\", \"good\", \"life\", \"is\", \"better\", \"than\", \"your\", \"worst\", \"day\", \"and\", \"better\", \"than\", \"your\", \"best\", \"day\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"Happy Halloween! Happy Halloween!\"), [\"Happy\", \"Halloween!\", \"Happy\", \"Halloween!\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"you can achieve anything you want. Do not let anyone convince you otherwise.\"), [\"you\", \"can\", \"achieve\", \"anything\", \"you\", \"want.\", \"Do\", \"not\", \"let\", \"anyone\", \"convince\", \"you\", \"otherwise.\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"\"), [])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"   Just think of it  \"), [\"Just\", \"think\", \"of\", \"it\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"i try it several times before, but still not getting it right\"), [\"i\", \"try\", \"it\", \"several\", \"times\", \"before\", \"but\", \"still\", \"not\", \"getting\", \"it\", \"right\"])\n",
      "words_string(\"i try it several times before, but still not getting it right\").split()\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"i try it several times, before but still not getting it right\"), [\"i\", \"try\", \"it\", \"several\", \"times\", \"before\", \"but\", \"still\", \"not\", \"getting\", \"it\", \"right\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\" i   try , it  . . . . . . . . . . . . . . . . . . . . . . . . . several times before, but still not getting it right\"), [\"i\", \"try\", \"it\", \"several\", \"times\", \"before\", \"but\", \"still\", \"not\", \"getting\", \"it\", \"right\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"this is,  a test!\"), [\"this\", \"is\", \"a\", \"test!\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"I AM LoserSir!_YOU?\"), [\"I\", \"AM\", \"LoserSir!_YOU?\"])\n",
      "from nose.tools import assert_equals\n",
      "\n",
      "assert_equals(words_string(\"(1) (2) (3) how are you?\"),\n",
      "-----------------------------\n",
      "\n",
      "def move_one_ball(arr):\n",
      "    \"\"\"We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n",
      "    numbers in the array will be randomly ordered. Your task is to determine if\n",
      "    it is possible to get an array sorted in non-decreasing order by performing \n",
      "    the following operation on the given array:\n",
      "        You are allowed to perform right shift operation any number of times.\n",
      "    \n",
      "    One right shift operation means shifting all elements of the array by one\n",
      "    position in the right direction. The last element of the array will be moved to\n",
      "    the starting position in the array i.e. 0th index. \n",
      "\n",
      "    If it is possible to obtain the sorted array by performing the above operation\n",
      "    then return True else return False.\n",
      "    If the given array is empty then return True.\n",
      "\n",
      "    Note: The given list is guaranteed to have unique elements.\n",
      "\n",
      "    For Example:\n",
      "    \n",
      "    move_one_ball([3, 4, 5, 1, 2])==>True\n",
      "    Explanation: By performin 2 right shift operations, non-decreasing order can\n",
      "                 be achieved for the given array.\n",
      "    move_one_ball([3, 5, 4, 1, 2])==>False\n",
      "    Explanation:It is not possible to get non-decreasing order for the given\n",
      "                array by performing any number of right shift operations.\n",
      "                \n",
      "    \"\"\"\n",
      " \n",
      "    def go_left_or_take(n,nums):\n",
      "        #left is the number to the left of currently considered number.\n",
      "        #right is the number after \"nums[n]\" \n",
      "        left = nums[(n+len(nums)-1)%len(nums)] \n",
      "        right = nums[(n+1)%len(nums)]\n",
      "        if left > nums[n] and left > right:\n",
      "            # if the number to the left of nums[n] is larger than the value nums[n]\n",
      "            # and it is also the largest number among other array values\n",
      "            # then nums[n] should stop.\n",
      "            return False\n",
      "        \n",
      "        if right > nums[n] and right > left:\n",
      "            # if the number to the right of nums[n] is larger than the value nums[n]\n",
      "            # and it is also the largest number among other array values\n",
      "            # then nums[n] should go to nums[n+1] position.\n",
      "            storval = nums[n]\n",
      "            nums[n] = nums[(n+1)%len(nums)]\n",
      "            nums[(n+1)%len(nums)] = storval\n",
      "            \"\"\"Note that we introduce a two step move process so that each number\n",
      "            can only make one right shift per loop pass. This will prevent \n",
      "            unnecessary shifts.\n",
      "            \"\"\"\n",
      "            return True\n",
      "        \n",
      "        return True\n",
      "        \n",
      "    def check(nums):\n",
      "        \"\"\"\n",
      "        go_left_or_take(n,num) requires global within each loop.\n",
      "        global use should be carefully handled.\n",
      "        \"\"\"\n",
      "        global flag\n",
      "        \n",
      "        global loop\n",
      "        if nums[0] == min(nums):\n",
      "            # if the starting number is already the smallest one and the first\n",
      "            # loop is started and ended at storval, then the shifting process\n",
      "            # should stop.\n",
      "            return True\n",
      "    \n",
      "        n=0\n",
      "        \n",
      "        for n in range(len(nums)):\n",
      "            global storval\n",
      "            if storval == nums[n]:\n",
      "                flag += 1\n",
      "        if loop == 0:\n",
      "            loop += 1\n",
      "            global storval\n",
      "            storval = nums[n]\n",
      "        else:\n",
      "            \"\"\"if the first shift made the starting number the smallest one, then\n",
      "            the next loop should start at the spot where the ball stopped.\"\"\"\n",
      "            if nums[-1] <= nums[-2]:\n",
      "                storval = nums[-1]\n",
      "            else:\n",
      "                \"\"\"if the starting number changes, the ball evaluates its position only\n",
      "    when starts another loop.\"\"\"\n",
      "                if loop > 1:\n",
      "                    if flag == 0:\n",
      "                        loop = 0\n",
      "\n",
      "        if loop > 1:\n",
      "            if flag == 1:\n",
      "                loop = 0        \n",
      "        if flag > 1:\n",
      "            return False\n",
      "        for n in range(len(nums)):\n",
      "            global storval\n",
      "            if storval == nums[n]:\n",
      "                flag += 1\n",
      "        \n",
      "        if loop >= 1:\n",
      "            if go_left_or_take(n,nums) == False:\n",
      "                return False\n",
      "        \n",
      "        if loop == 0:\n",
      "            if nums[0] == min(nums):\n",
      "                return True\n",
      "            check(nums)\n",
      "        if loop > 1:\n",
      "            if flag == 1:\n",
      "                return True\n",
      "    loop = 0\n",
      "    if nums == []:\n",
      "        return True\n",
      "    if len(nums) == 1:\n",
      "        return True\n",
      "    else:\n",
      "        for n in range(len(nums)):\n",
      "            for j in range(len(nums)-1):\n",
      "                if nums[j] > nums[j+1]:\n",
      "                    return False\n",
      "        if len(nums) > 2:\n",
      "            flag = 0\n",
      "            if nums[0] != min(nums) and nums[0] != max(nums):\n",
      "                if check(nums) == True:\n",
      "                    return True\n",
      "        if len(nums) == 2:\n",
      "            if sum(nums) == sum(list(\n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "\n",
      "    def parseGrid(grid):\n",
      "        rows = len(grid)\n",
      "        columns = len(grid[0])\n",
      "        return rows, columns\n",
      "\n",
      "    def parseHeights(grid):\n",
      "        heights = []\n",
      "\n",
      "        for x in grid:\n",
      "            # for y in x:\n",
      "            heights.append(sum(x))\n",
      "        return heights.copy()\n",
      "\n",
      "    \"\"\"a loop from the row number of total - 1, to 0\n",
      "    at the row number start count from 0 to total - 1(inclusive of - 1)\"\"\"\n",
      "    \n",
      "    def heightsTo0(grid, row_num, bucket_capacity, this_h_a_r,  heights, rows, columns):\n",
      "        row_available = (this_h_a_r == 0)\n",
      "\n",
      "        while this_h_a_r > bucket_capacity:\n",
      "            this_h_a_r -= bucket_capacity\n",
      "            \n",
      "            this_transfer_heights = transferHeights(this_h_a_r, bucket_capacity, heights, rows, columns)\n",
      "            heights = this_transfer_heights.copy()\n",
      "            num_operations += 1\n",
      "       \n",
      "         # if this row len is the same as incoming row height then return nothing\n",
      "        if row_available == 1:\n",
      "            pass\n",
      "        else:\n",
      "            heights[row_num] = this_h_a_r\n",
      "            this_h_a_r = 0\n",
      "\n",
      "        return heights.copy(), num_operations\n",
      "\n",
      "    def heightsToN(grid, row_num, bucket_capacity, this_h_a_r,  heights, rows, columns):\n",
      "        row_available = (this_h_a_r == 0)\n",
      "\n",
      "        while this_h_a_r > bucket_capacity:\n",
      "            this_h_a_r -= bucket_capacity\n",
      "            \n",
      "            this_transfer_heights = transferHeights(this_h_a_r, bucket_capacity, heights, rows, columns)\n",
      "            heights = this_transfer_heights.copy()\n",
      "            num_operations += 1\n",
      "       \n",
      "         # if this row len is the same as incoming row height then return nothing\n",
      "        if row_available == 1:\n",
      "            pass\n",
      "        else:\n",
      "            heights[row_num] = this_h_a_r\n",
      "            this_h_a_r = 0\n",
      "\n",
      "        return heights.copy(), num_operations\n",
      "    # get transfer counts\n",
      "    def transferHeights(this_h_a_r, bucket_capacity, heights, rows, columns):\n",
      "        ## TODO\n",
      "        ## DEBUGGER\n",
      "        ## print('current index', current_i)\n",
      "\n",
      "        # above right\n",
      "        if indexes[0] == 0:\n",
      "            index_ar = (rows - 1, columns - 1)\n",
      "        else:\n",
      "            index_ar = (current_i[0] - 1, current_i[1] + 1)\n",
      "        print('ar', index_ar)\n",
      "        transfer_ar = ((heights[index_ar[0]][index_ar[1]] == 0) and (this_h_a_r > 0))\n",
      "        if transfer_ar:\n",
      "            print('TRUE', heights[index_ar[0]][index_ar[1]] == 0)\n",
      "            heights[index_ar[0]][index_ar[1]] += 1\n",
      "            this_h_a_r -= 1\n",
      "        else:\n",
      "            print('FALSE', heights[index_ar[0]][index_ar[1]] == 0)\n",
      "\n",
      "        this_current_element = heights[current_i[0]][current_i[1]]\n",
      "\n",
      "\n",
      "        # right\n",
      "        if indexes[1] == columns - 1:\n",
      "            index_r = (0, 0)\n",
      "        else:\n",
      "            print('CR RESET', current_i[1])\n",
      "            index_r = (current_i[0], current_i[1] + 1)\n",
      "        print('r', index_ar)\n",
      "        transfer_r = ((heights[index_r[0]][index_r[1]] == 0) and (this_h_a_r > 0))\n",
      "        if transfer_r:\n",
      "            print('TRUE', heights[index_r[0]][index_r[1]] == 0)\n",
      "           \n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "\n",
      "    N = len(grid)\n",
      "    M = len(grid[0])\n",
      "    V = [[[0]*(M+1) for _ in range(N+1)] for __ in range(N+1)]\n",
      "    mins = [[math.inf]*(M+1) for _ in range(N+1)]\n",
      "\n",
      "    class Pnt:\n",
      "        def __init__(self, x, y, v):\n",
      "            self.x = x\n",
      "            self.y = y\n",
      "            self.v = v\n",
      "    \n",
      "    def is_ok(V, P, i, j, k, c):\n",
      "        v = P[i][j]\n",
      "        ab = min(v, c) - V[i][j][k]\n",
      "        if j>0:\n",
      "            bc1 = V[i][j-1][k] - ab\n",
      "            if bc1<0 and v-ab+bc1>c:\n",
      "                return False\n",
      "            if j<M:\n",
      "                bc2 = V[i][j+1][k] - ab\n",
      "                if bc2<0 and v-ab+bc2>c:\n",
      "                    return False\n",
      "        return True\n",
      "    \n",
      "    def bfs():\n",
      "        Q = collections.deque()\n",
      "        used = [ [ [False]*(M+1) for _ in range(N+1) ] for __ in range(N+1) ]\n",
      "        P = [[0 if grid[i][j]==0 else math.inf for j in range(M+1)] for i in range(N+1)]\n",
      "        for i in range(1, N+1):\n",
      "            for j in range(1, M+1):\n",
      "                if grid[i-1][j-1]==1:\n",
      "                    P[i][j-1] = min(P[i][j-1], capacity)\n",
      "                    P[i][j] = min(P[i][j], capacity)\n",
      "        \n",
      "        for col in range(0, M+1):\n",
      "            for row in range(1, N+1):\n",
      "                \n",
      "                pnt = Pnt(row, col, capacity)\n",
      "                Q.append(pnt)\n",
      "                mins[row][col] = 0\n",
      "\n",
      "                while(Q):\n",
      "                    if pnt.v == 0 or used[row][col][pnt.v]:\n",
      "                        pnt = Q.popleft()\n",
      "                        if pnt.v == 0 or used[pnt.x][pnt.y][pnt.v]: continue\n",
      "                \n",
      "                    used[pnt.x][pnt.y][pnt.v] = True\n",
      "                    if pnt.x>0 and not used[pnt.x-1][pnt.y][pnt.v]:\n",
      "                        if is_ok(V, P, pnt.x-1, pnt.y, pnt.v, c) and V[pnt.x-1][pnt.y][pnt.v] < mins[pnt.x-1][pnt.y]:\n",
      "                            mins[pnt.x-1][pnt.y] = V[pnt.x-1][pnt.y][pnt.v]\n",
      "                            Q.append(Pnt(pnt.x-1, pnt.y, pnt.v))\n",
      "                    if pnt.x<N+1 and not used[pnt.x+1][pnt.y][pnt.v]:\n",
      "                        if is_ok(V, P, pnt.x+1, pnt.y, pnt.v, c) and V[pnt.x+1][pnt.y][pnt.v] < mins[pnt.x+1][pnt.y]:\n",
      "                            mins[pnt.x+1][pnt.y] = V[pnt.x+1][pnt.y][pnt.v]\n",
      "                            Q.append(Pnt(pnt.x+1, pnt.y, pnt.v))\n",
      "                    if pnt.y>0 and not used[pnt.x][pnt.y-1][pnt.v]:\n",
      "                        if is_ok(V, P, pnt.x\n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "\n",
      "    assert type(grid) == list\n",
      "\n",
      "    ROWS = len(grid)\n",
      "    COLS = len(grid[0]) if ROWS else int()\n",
      "\n",
      "    if ROWS * COLS == 0:\n",
      "        return int(0)\n",
      "\n",
      "    index_max_value = dict(list())\n",
      "\n",
      "    # roll_up\n",
      "    #   COL 0 COL 1\n",
      "    # ROW 0 3    4\n",
      "    # ROW 1 1    5\n",
      "    # ROW 2 0    -\n",
      "    for c in range(0, COLS):\n",
      "        v = int(0)\n",
      "        for r in range(0, ROWS):\n",
      "            v += int(grid[r][c])\n",
      "            grid[r][c] = v\n",
      "\n",
      "    # print(grid)\n",
      "    # roll_down\n",
      "    #   COL 0 COL 1\n",
      "    # ROW 0 0    2\n",
      "    # ROW 1 1    5\n",
      "    # ROW 2 3    3\n",
      "    for c in range(0, COLS):\n",
      "        def destroy_between(p1, p2):\n",
      "            for p in range(p1, p2):\n",
      "                common = index_max_value.get(p)\n",
      "                if not common:\n",
      "                    index_max_value[p] = set([c])\n",
      "                else:\n",
      "                    common.add(c)\n",
      "\n",
      "        s = int(0)\n",
      "        for r in range(ROWS-1, -1, -1):\n",
      "            v = int(grid[r][c])\n",
      "            grid[r][c] -= s\n",
      "            destroy_between(s, v)\n",
      "            s = grid[r][c]\n",
      "\n",
      "    def ROW(r, c):\n",
      "        return grid[r][c]\n",
      "\n",
      "    # ROW 1\n",
      "    # ROW 2\n",
      "    # ROW 3\n",
      "    # ROW 4\n",
      "    # ROW 5\n",
      "    # ROW 6\n",
      "    # ROW 7\n",
      "    # ROW 8 -\n",
      "    # ROW 9\n",
      "    \"\"\"\n",
      "    if index_max_value == {\n",
      "        # COL 0\n",
      "        0: [0],\n",
      "        1: [0], # <= This value is invalidated due to bucket capacity collision\n",
      "        4: [0],\n",
      "        7: [0, 1],\n",
      "        8: [0, 1, 2],\n",
      "        9: [0, 1, 2]\n",
      "        # COL 1\n",
      "    }\n",
      "\n",
      "    result would be 3 max rows since smallest value between them is half capacity.\n",
      "    [ROW 0, COL 0] -> [ROW 1, COL 0] = 6 units       | # 1\n",
      "    [ROW 1, COL 0] -> [ROW 5, COL 0] = 33 units      | # 1\n",
      "    [ROW 2, COL 1] -> [ROW 4, COL 1] = 5 units * 2   | # 2\n",
      "    \"\"\"\n",
      "    logger.debug(f'Grid: {grid}, capacity: {capacity}')\n",
      "    logger.debug(f'all concerned see: {index_max_value.items()}')\n",
      "\n",
      "    assert capacity > 0\n",
      "\n",
      "    best_index_v = -1\n",
      "    iterations   = -1\n",
      "\n",
      "    def take_in_consideration_bucket_capacity(index, rows):\n",
      "        \"\"\"\n",
      "        Take into consideration the bucket's capacity.\n",
      "        To lower the bucket from [ROW A] to [ROW B] the delta of these rows need to be\n",
      "        a minimum of [ceiling(0.5 * capacity)] to comply with bucket's fullness.\n",
      "        Thus, the minimum number of buckets to fill this row is: [2]\n",
      "            [0.5 * capacity] / [1 unit] = [ceiling(0.5 * capacity)] = [2]\n",
      "        And the wanted iterations number is: [ROW B - quantity_of_full_buckets]\n",
      "        \"\"\"\n",
      "        # get largest value and the rows beloning to it\n",
      "        max_value, items = max([(gr[1], gr[0]) for gr in rows])\n",
      "\n",
      "        nonlocal best_index_v\n",
      "        nonlocal iterations\n",
      "\n",
      "        # if delta is ceil(0,5 * capacity):\n",
      "        if ((max_value - index) == math.ceil(0.5 * capacity)):\n",
      "            iterations = grid\n",
      "            return\n",
      "\n",
      "        # if delta is grater than\n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "    rows, cols = len(grid), len(grid[0])\n",
      "    buckets_needed = 0\n",
      "    # Each row\n",
      "    for i in range(rows):\n",
      "        # Each column\n",
      "        for j in range(cols-1):\n",
      "            bucket_left = bucket_capacity\n",
      "            # DOWN and LEFT - no corner elements\n",
      "            if ((j != 0 or j != cols-1) or (i != 0 or i != rows-1)):\n",
      "                if (grid[i][j] == 1):\n",
      "                    grid[i][j] = 0\n",
      "                    buckets_needed += 1\n",
      "                    bucket_left = bucket_capacity-1\n",
      "                    if ((j-1 >= 0) and (grid[i][j-1] == 1)):\n",
      "                        if ((i+1 < rows) and (bucket_left > 0)):\n",
      "                            grid[i+1][j] = 0\n",
      "                            grid[i+1][j-1] = 0\n",
      "                            bucket_left -= 1\n",
      "                        if ((j-1 > 0) and (bucket_left > 0)):\n",
      "                            grid[i][j-2] = 0\n",
      "                            bucket_left -= 1\n",
      "                        if ((i-1 >= 0) and (bucket_left > 0)):\n",
      "                            grid[i-1][j] = 0\n",
      "                            grid[i-1][j-1] = 0\n",
      "                            bucket_left -= 1\n",
      "    return buckets_needed\n",
      "    \n",
      "    \n",
      "    \n",
      "\n",
      "print(\"\\nTests for find_max_repeat()\")\n",
      "assert find_max_repeat(\"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc\") == 3, \"test 1 False\"\n",
      "assert find_max_repeat(\"ab\") == 2, \"test 2 False\"\n",
      "assert find_max_repeat(\"aabbcc\") == 2, \"test 3 False\"\n",
      "assert find_max_repeat(\"aabbbcc\") == 3, \"test 4 False\"\n",
      "print(\"\\nTests for order_eggs()\")\n",
      "l1 = [[5,5], [1,1], [5,5], [5,5], [5,5], [5,5]]\n",
      "l2 = [[5,5], [5,5], [5,5], [5,5], [5,5], [5,5]]\n",
      "l3 = [[1,2], [2,3], [6,0], [1,2], [2,3]]\n",
      "l4 = [[1,2], [6,3], [3,0], [1,2], [2,1]]\n",
      "assert order_eggs(l1) == 2, \"test 5 False\"\n",
      "assert order_eggs(l2) == 1, \"test 6 False\"\n",
      "assert order_eggs(l3) == 2, \"test 7 False\"\n",
      "assert order_eggs(l4) == 4, \"test 8 False\"\n",
      "print(\"\")\n",
      "\n",
      "\n",
      "\n",
      "\"\"\"\n",
      "You have a row of rectangular wells. The depth of each well (depth from the top of the well) is recorded in a list.\n",
      "The weather is rainy and water forms puddles. \n",
      "Each puddle will form between two wells that are in the range [i-1 and i+1]. \n",
      "\n",
      "Compute the maximum height a puddle could reach for each element of the list.\n",
      "\n",
      "Example 1:\n",
      "    Input: [2, 3, 5, 4, 3]\n",
      "    Output: [2, 2, 3, 2, 2]\n",
      "\n",
      "    Explanation:\n",
      "        Let's look at each element in the list.\n",
      "        * 2. At index [0], the maximum height of a puddle is 2 (John).\n",
      "        * 3. At index [1], if John can work with Patrick, they will make a maximum height of 2 (Julia). \n",
      "                    A puddle stays only between wells with equal heights.\n",
      "        * 5. At index [2], the maximum height of a puddle is 3 (Lucy)\n",
      "        * 4. At index [3], the maximum height of a puddle is 2 (Mia).\n",
      "        * 3. At index [4], the maximum height of a puddle is 2 (Naun).\n",
      "\n",
      "    Time complexity: \n",
      "        O\n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "\n",
      "    # find a 'head' index to our grid ( x, y )\n",
      "    row_with_one = 0\n",
      "    col_with_one = 0\n",
      "\n",
      "    largest = -math.inf\n",
      "    sm = 0\n",
      "    row_index, = np.where(grid == 1)\n",
      "    if len(row_index) != 0:\n",
      "        for i in range(1, row_index[-1]+1):\n",
      "            sm += np.sum(grid[i])\n",
      "            if sm == largest:\n",
      "                largest = sm\n",
      "                row_with_one = i\n",
      "            else:\n",
      "                largest = np.amax([sm, largest])\n",
      "                if largest == sm:\n",
      "                    row_with_one = i\n",
      "            sm -= capacity\n",
      "            sm = 0 if sm < 0 else sm\n",
      "    row_index, col_index = np.where(grid[row_with_one] == 1)\n",
      "\n",
      "    # find last index of a grid. set up a window with a zero in a head\n",
      "\n",
      "    def get_window_index(arr, window_size):\n",
      "        hist = dict()\n",
      "        sm = 0\n",
      "        largest = -math.inf\n",
      "        for idx, num in enumerate(arr):\n",
      "            sm += num\n",
      "            hist.setdefault(sm, []).append(idx)\n",
      "            largest = np.amax([largest, sm])\n",
      "        for key, val in hist.items():\n",
      "            if len(val) > 1 and len(val) <= window_size:\n",
      "                first = val[0] if val[0] != val[-1] else val[1]-1\n",
      "                second = val[-1]\n",
      "                arr[first: second+1] = 0\n",
      "                return arr\n",
      "        largest_indexes = hist[largest]\n",
      "        first = largest_indexes[0] if largest_indexes[0] != largest_indexes[-1] else largest_indexes[1]-1\n",
      "        second = largest_indexes[-1]\n",
      "        arr[first: second+1] = 0\n",
      "        return arr\n",
      "\n",
      "    def get_largest_sum(arr, win, capacity):\n",
      "        sm = 0\n",
      "        largest = -math.inf\n",
      "        largest_indexes = []\n",
      "        indexes = []\n",
      "        for idx, num in enumerate(arr):\n",
      "            sm += num\n",
      "            if sm == capacity:\n",
      "                largest_indexes.append(idx)\n",
      "                largest_indexes.append(idx-1)\n",
      "                break\n",
      "            else:\n",
      "                if sm >= largest:\n",
      "                    largest = sm\n",
      "                    largest_indexes = indexes[:]\n",
      "                    largest_indexes.append(idx)\n",
      "                if sm < 0:\n",
      "                    sm = 0\n",
      "                    indexes = []\n",
      "                else:\n",
      "                    indexes.append(idx)\n",
      "            if sm > capacity: sm = capacity\n",
      "        if not largest_indexes:\n",
      "            return None\n",
      "        first = largest_indexes[0] if largest_indexes[0] != largest_indexes[-1]+1 else largest_indexes[1]\n",
      "        last = largest_indexes[-1]\n",
      "        if first == last:\n",
      "            return None\n",
      "        return [first, last]\n",
      "\n",
      "\n",
      "    fill_row_water = row_index[-1] - row_index[0] + 1\n",
      "    fill_col_water = get_window_index(col_with_one, row_index[-1]-1)\n",
      "    longest_sum = get_largest_sum(col_with_one, fill_col_water, capacity)\n",
      "    visited = True if grid[row_with_one][-1] == 1 else False\n",
      "    while not visited:\n",
      "        row_index, col_index = np.where(grid[row_with_one] == 1)\n",
      "        fill_col_water = get_window_index(grid[:, col_index[-1]], col_index[-1])\n",
      "        if fill_col_water is not None:\n",
      "            break\n",
      "        fill_row_water = get_largest_sum(grid[row_with_one], row_index[-1]-1, capacity)\n",
      "        if fill_row_water is not None:\n",
      "            break\n",
      "    return np.ceil((fill_row_\n",
      "-----------------------------\n",
      "\n",
      "def max_fill(grid, capacity):\n",
      "    import math\n",
      "    \"\"\"\n",
      "    You are given a rectangular grid of wells. Each row represents a single well,\n",
      "    and each 1 in a row represents a single unit of water.\n",
      "    Each well has a corresponding bucket that can be used to extract water from it, \n",
      "    and all buckets have the same capacity.\n",
      "    Your task is to use the buckets to empty the wells.\n",
      "    Output the number of times you need to lower the buckets.\n",
      "\n",
      "    Example 1:\n",
      "        Input: \n",
      "            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n",
      "            bucket_capacity : 1\n",
      "        Output: 6\n",
      "\n",
      "    Example 2:\n",
      "        Input: \n",
      "            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n",
      "            bucket_capacity : 2\n",
      "        Output: 5\n",
      "    \n",
      "    Example 3:\n",
      "        Input: \n",
      "            grid : [[0,0,0], [0,0,0]]\n",
      "            bucket_capacity : 5\n",
      "        Output: 0\n",
      "\n",
      "    Constraints:\n",
      "        * all wells have the same length\n",
      "        * 1 <= grid.length <= 10^2\n",
      "        * 1 <= grid[:,1].length <= 10^2\n",
      "        * grid[i][j] -> 0 | 1\n",
      "        * 1 <= capacity <= 10\n",
      "    \"\"\"\n",
      "    num_rows = len(grid)\n",
      "    num_cols = len(grid[0])\n",
      "\n",
      "    def wells_needs_water(grid, row_idx):\n",
      "        \"\"\"Calculate the total number of water needed on a particular row based on a grid and row index.\"\"\"\n",
      "        return list(filter(lambda x: not x, grid[row_idx])).count(0)\n",
      "\n",
      "    def wells_with_water(grid, row_idx, water_needed_for_this_row):\n",
      "        \"\"\"Add water for a particular row.\"\"\"\n",
      "        # keep an array of index of wells which has water\n",
      "        col_idxes_w_water = []\n",
      "        \n",
      "        # reverse traverse this row\n",
      "        for col_idx in range(num_cols - 1, -1, -1):\n",
      "            # check if there's still wells which need water\n",
      "            if water_needed_for_this_row > 0:\n",
      "                # if current well needs water, put water in the well\n",
      "                if not grid[row_idx][col_idx]:\n",
      "                    grid[row_idx][col_idx] = 1\n",
      "                    water_needed_for_this_row -= 1\n",
      "\n",
      "                    # append index of water filled well to the array\n",
      "                    col_idxes_w_water.append(col_idx)\n",
      "\n",
      "                # if current well doesn't need water, we don't need to put water\n",
      "                else:\n",
      "                    continue\n",
      "            else:\n",
      "                break\n",
      "\n",
      "        return [grid, col_idxes_w_water]\n",
      "\n",
      "    def pour_water_to_buckets(grid, row_idx, buckets_for_this_row):\n",
      "        \"\"\"Pour water from previous row to this row.\"\"\"\n",
      "        # reverse traverse this row by 2\n",
      "        # skip if current well is empty\n",
      "        # if there's water on current well, \n",
      "        # check if bucket capacity can take the rest of it\n",
      "        #     if yes put the water in the bucket\n",
      "        #     else pour the rest to the next well\n",
      "        #     start count pour operation\n",
      "        #     continue traversal\n",
      "        # if there's no water on current well, \n",
      "        #     check if bucket has water, if no, do nothing\n",
      "        #     check if bucket doesn't exceed bucket capacity\n",
      "        #     if yes put the water in the well\n",
      "        #     else pour the rest to the next well\n",
      "        #     start count pour operation\n",
      "        #     continue traversal\n",
      "        col_idx = len(buckets_for_this_row) - 1\n",
      "\n",
      "        while (col_idx >= 0):\n",
      "            cur_bucket_capacity = buckets_for_this_row[col_idx]\n",
      "\n",
      "            if (col_idx < len(grid[row_idx])):\n",
      "                cur_well_has_water = grid[row_idx][col_idx]\n",
      "            \n",
      "            # put all water from the buckets to the well (if possible)\n",
      "            if cur_well_has_water and water_in_well == 0:\n",
      "                water_in_well = min(cur_bucket_capacity, capacity)\n",
      "            \n",
      "            # put rest from previous well to the well (if possible)\n",
      "            elif cur_well_has_water and water_in_well < 0:\n",
      "                water_in_well = min((cur_well_has_water + capacity - cur_bucket_capacity), capacity)\n",
      "\n",
      "            # put all water from the well to the buckets (if possible)\n",
      "            elif cur_well_has_water and water_in_well > 0:\n",
      "                water_in_well = min((cur_well_has_water - capacity + cur_bucket_capacity), capacity)\n",
      "\n",
      "            # pour the water back in the well to the bucket if the bucket is not full\n",
      "            if (cur_bucket_capacity < capacity):\n",
      "                total_pour += 1\n",
      "            \n",
      "            col_idx -= 2\n",
      "\n",
      "        return total_pour\n",
      "\n",
      "    total_water_needed = sum([wells_needs_water(grid, row_idx) for row_idx in range(num_rows)])\n",
      "    total_pour = 0\n",
      "    water_in_well = num_cols\n",
      "\n",
      "    row_idx = 0\n",
      "   \n",
      "-----------------------------\n",
      "\n",
      "def fix_spaces(text):\n",
      "    \"\"\"\n",
      "    Given a string text, replace all spaces in it with underscores, \n",
      "    and if a string has more than 2 consecutive spaces, \n",
      "    then replace all consecutive spaces with - \n",
      "    \n",
      "    fix_spaces(\"Example\") == \"Example\"\n",
      "    fix_spaces(\"Example 1\") == \"Example_1\"\n",
      "    fix_spaces(\" Example 2\") == \"_Example_2\"\n",
      "    fix_spaces(\" Example   3\") == \"_Example-3\"\n",
      "    \"\"\"\n",
      "    \n",
      "    text = text.replace(' ','_')\n",
      "    text = text.replace('__','_')\n",
      "    text = text.replace('__','_')\n",
      "    return text.replace('_','-').strip('_').strip()\n",
      "fix_spaces(\"Example   3\")\n",
      "\n",
      "clean_names = [fix_spaces(x) for x in tree_df['spc_common'].values]\n",
      "tree_df['clean_names'] = clean_names\n",
      "tree_df\n",
      "clean_names\n",
      " \n",
      " \n",
      "zip_filepath = '../data_raw/tree_census/2016_Street_Tree_Census_-_Tree_Data.zip'\n",
      "zf = zipfile.ZipFile(zip_filepath)\n",
      "\n",
      "fixed_strings = [' '] # as per the email that was sent with the data\n",
      "for name in zf.namelist():\n",
      "    if name.endswith('.csv') and name.split('/')[-2] not in fixed_strings:\n",
      "        fname_rn = name.replace(\"/\", \"_\")\n",
      "        logging.info(\"replacing {} with {}\".format(name,fname_rn))\n",
      "        zf.extract(name,path='../data_raw/with_all_data')\n",
      "        os.remove(os.path.join('../data_raw/with_all_data',name))\n",
      "\n",
      " \n",
      " \n",
      "zf.extract(\"/2016/92nd-St_aggregated.csv\",\"../data_raw/with_agg\")\n",
      "\n",
      "\n",
      "[x for x in zf.namelist() if \"2016_Street_Tree_Census\" in x]\n",
      "to_exclude_names = ['/2016/2016_Street_Tree_Census_-_Tree_Data.csv','/2016/2016_Street_Tree_Census_-_Tree_Data.zip',\\\n",
      "                    '/2016_Street_Tree_Census_-_Tree_Data.zip','/2016_Street_Tree_Census_-_Tree_Data.csv',\\\n",
      "                    '2016_Street_Tree_Census_-_Map_Lots.zip',\"/2016.zip\",\"/\"]\n",
      "[x for x in zf.namelist() if \"2016_Street_Tree_Census\" in x]\n",
      "list_files = [x for x in zf.namelist() if \"Street_Tree_Census\" in x and \".zip\" not in x and \".csv\" in x]\n",
      "\n",
      "list_files\n",
      "list_files.remove(\"/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Tree_Data.zip\")\n",
      "list_files.remove(\"/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Tree_Data.csv\")\n",
      "list_files.remove(\"/2016/2016.csv\")\n",
      "list_files.remove(\"/2016/2016.zip\")\n",
      "\n",
      "\n",
      "\n",
      "list_files\n",
      "[\n",
      "'/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.shp\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.shx\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.dbf\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.prj\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.shp.xml\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Map_Lots/Map_Lots.kml\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_Tree_Species.csv\"',\n",
      " '/2016/2016_Street_Tree_Census_-_Tree_Data/2016_Street_Tree_Census_-_\n",
      "-----------------------------\n",
      "\n",
      "def hex_key(num):\n",
      "    \"\"\"You have been tasked to write a function that receives \n",
      "    a hexadecimal number as a string and counts the number of hexadecimal \n",
      "    digits that are primes (prime number, or a prime, is a natural number \n",
      "    greater than 1 that is not a product of two smaller natural numbers).\n",
      "    Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n",
      "    Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n",
      "    So you have to determine a number of the following digits: 2, 3, 5, 7, \n",
      "    B (=decimal 11), D (=decimal 13).\n",
      "    Note: you may assume the input is always correct or empty string, \n",
      "    and symbols A,B,C,D,E,F are always uppercase.\n",
      "    Examples:\n",
      "    For num = \"AB\" the output should be 1.\n",
      "    For num = \"1077E\" the output should be 2.\n",
      "    For num = \"ABED1A33\" the output should be 4.\n",
      "    For num = \"123456789ABCDEF0\" the output should be 6.\n",
      "    For num = \"2020\" the output should be 2.\n",
      "    \"\"\"\n",
      "    digits = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, \n",
      "              '7': 0, '8': 0, '9': 1, 'A': 0, 'B': 1, 'C': 0, 'D': 1,\n",
      "              'E': 0, 'F': 0}\n",
      "\n",
      "    ls = []\n",
      "    for i, c in enumerate(num):\n",
      "        if i < len(num) - 1:\n",
      "            k = int(c + num[i+1], 16)\n",
      "            ls.append(k)\n",
      "            if k >= 10:\n",
      "                break \n",
      "        else:\n",
      "            ls.append(int(c, 16))\n",
      "\n",
      "    return len(list(k for k in ls if k in digits.keys() and digits[str(k)]))\n",
      "\n",
      "\n",
      "assert hex_key('') == 0, 'Assertion error'\n",
      "assert hex_key('0') == 0, 'Assertion error'\n",
      "assert hex_key('D0') == 0, 'Assertion error'\n",
      "assert hex_key('DC0') == 0, 'Assertion error'\n",
      "assert hex_key('D0c') == 0, 'Assertion error'\n",
      "assert hex_key('cD0') == 0, 'Assertion error'\n",
      "assert hex_key('0D') == 0, 'Assertion error'\n",
      "assert hex_key('D00') == 0, 'Assertion error'\n",
      "assert hex_key('D03') == 1, 'Assertion error'\n",
      "assert hex_key('D05') == 1, 'Assertion error'\n",
      "assert hex_key('D07') == 1, 'Assertion error'\n",
      "assert hex_key('D003') == 1, 'Assertion error'\n",
      "assert hex_key('D005') == 1, 'Assertion error'\n",
      "assert hex_key('D007') == 1, 'Assertion error'\n",
      "assert hex_key('3D00') == 0, 'Assertion error'\n",
      "assert hex_key('D3300') == 0, 'Assertion error'\n",
      "assert hex_key('D311') == 0, 'Assertion error'\n",
      "assert hex_key('D55') == 0, 'Assertion error'\n",
      "assert hex_key('D777') == 0, 'Assertion error'\n",
      "assert hex_key('D009') == 0, 'Assertion error'\n",
      "assert hex_key('D339') == 0, 'Assertion error'\n",
      "assert hex_key('D55A') == 0, 'Assertion error'\n",
      "assert hex_key('D777C') == 0, 'Assertion error'\n",
      "assert hex_key('D009F') == 0, 'Assertion error'\n",
      "assert hex_key('2B33F') == 1, 'Assertion error'\n",
      "assert hex_key('2233F') == 1, 'Assertion error'\n",
      "assert hex_key('4B33F') == 1, 'Assertion error'\n",
      "assert hex_key('6B33F') == 1, 'Assertion error'\n",
      "assert hex_key('DB33F') == 1, 'Assertion error'\n",
      "assert hex_key('2D33F') == 1, 'Assertion error'\n",
      "assert hex_key('A3A1F') == 1, 'Assertion error'\n",
      "assert hex_key('2333F') == 1, 'Assertion error'\n",
      "assert hex_key('2D33G') == 0, 'Assertion error'\n",
      "assert hex_key('G333F') == 0, 'Assertion error'\n",
      "assert hex_key('2DB3G') == 0, 'Assertion error'\n",
      "assert hex_key('HG7') == 0, 'Assertion error'\n",
      "assert hex_key('A3AA1F') == 1, 'Assertion error'\n",
      "assert hex_key('C21A33') == 2, 'Assertion error'\n",
      "assert hex_key('DDC1A33') == 2, 'Assertion error'\n",
      "assert hex_key('DED1A33') == 3, 'Ass\n",
      "-----------------------------\n",
      "\n",
      "def hex_key(num):\n",
      "    \"\"\"You have been tasked to write a function that receives \n",
      "    a hexadecimal number as a string and counts the number of hexadecimal \n",
      "    digits that are primes (prime number, or a prime, is a natural number \n",
      "    greater than 1 that is not a product of two smaller natural numbers).\n",
      "    Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n",
      "    Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n",
      "    So you have to determine a number of the following digits: 2, 3, 5, 7, \n",
      "    B (=decimal 11), D (=decimal 13).\n",
      "    Note: you may assume the input is always correct or empty string, \n",
      "    and symbols A,B,C,D,E,F are always uppercase.\n",
      "    Examples:\n",
      "    For num = \"AB\" the output should be 1.\n",
      "    For num = \"1077E\" the output should be 2.\n",
      "    For num = \"ABED1A33\" the output should be 4.\n",
      "    For num = \"123456789ABCDEF0\" the output should be 6.\n",
      "    For num = \"2020\" the output should be 2.\n",
      "    \"\"\"\n",
      "    num = num.split(\" \")\n",
      "    count = 0\n",
      "    for i in num:\n",
      "        if i[0] in (\"3\", \"5\", \"7\", \"2\", \"B\", \"D\") and i[1] == \"\":\n",
      "            count+=1\n",
      "        if len(i)>1 and re.search(r\"^[A-Z0-9]+$\", i):\n",
      "            count+=1\n",
      "    return count\n",
      "\n",
      "\n",
      "    \n",
      "\n",
      "    \n",
      "test = \"AB E7V 3F2S ABBBBBBBB DCBAD18483FFFE8ECE1DE1B1DE1DA1DE9CA3DE8B83DE8567DE81ACDC79FFE696BEC814E\", \"1 1 1 1 1 2 0 1 1 0 1 1 0 2 0 1 1 2 0 1 1 2 1 1 0 2 0 2 1 2 0 2 1 2 1 1 0 2 1 2 0 2 1 3 0 2 0 2 1 2 0 2 1 2 1 2 0 2 0 3 1 2 1 1 0 2 0 2 1 2 1 4 0 2 0 2 1 2 1 2 0 2 1 2 0 2 0 2 1 2 1 1 0 2 1\"\n",
      "print(hex_key(test))\n",
      "\n",
      "'''\n",
      "On January 1st, a group of people \n",
      "comes together to start a project \n",
      "that will last a whole year. In this \n",
      "project, the people that are part of \n",
      "it meet together weekly, on the same day of the week. \n",
      "During one of those meetings, when exactly t minutes have \n",
      "passed, they decide to change the day they meet on to the \n",
      "one that follows the current day of the week. \n",
      "Therefore, in one year of the project, \n",
      "the number of times the day in which \n",
      "they meet changes will be\n",
      " equal to the number of times t minutes \n",
      "have passed in that year. Assume that the year \n",
      "starts in a Tuesday.\n",
      "Given the total number of minutes (total), \n",
      "your task is to return the number of times the \n",
      "day of the weekly meeting changed \n",
      "(again, always starting on a Tuesday).\n",
      "The answer should be an integer no larger than 1000000.\n",
      "For total = 5000, the output should be \n",
      "changeTheDay(total) = 3\n",
      "500 = 60 * 3 + 40 = 60 * (7 + 1) + 40 = 480 + 40 = 520 = 60 * 8\n",
      "1000 = 60 * 16\n",
      "2000 = 60 * 33\n",
      "3000 = 60 * 50\n",
      "4000 = 60 * 65\n",
      "5000 = 60 * 78\n",
      "2000 = 60 * 15 = 60 * (2 x 7 + 1) = 840 + 60 = 900 = 60 x 15\n",
      "3000 = 60 * 25 = 60 * (3 x 7 + 1) = 1680 + 60 = 1740 = 60 x 29\n",
      "4000 = 60 * 33 = 60 * (4 x 7 + 1) = 2520 + 60 = 2580 = 60 x 43\n",
      "5000 = 60 * 41 = 60 * (5 x 7 + 1) = 3360 + 60 = 3420 = 60 x 57\n",
      "\n",
      "For total = 91999, the output should be changeTheDay(total) = 83\n",
      "91999 = 1999 * 45 + 7 = 1999 * (6 x 7 + 7) = 8994 + 1999 = 10993 = 1999 * 5 \n",
      "+ 10 = 1999 * (7 x 7 + 5) = 14186 + 1999 = 16185 = 1999 * 8 + 6 = 1999 * (9 x 7 + 6) \n",
      "19980 = 1999 * 10 + 2 = 1999 * (14 x 7 + 2) = 27856 + 1999 = 29855 = 1999 * 14 + \n",
      "10 = 1999 * (20 x 7 + 10) = 41440 + 1999 = 43439 = 1999 * 22 + 5 = 1999 * (31 x 7 \n",
      "+ 5) = 61973 + 1999 = 63972 = 1999 * 32 + 7 = 1999 * (45 x 7 + 7) = 89954 + 1999 = \n",
      "91953 = 1999 * 56 + 4 = 1999 * (80 x 7 + 4) = 159928 + 1999 = 161927 = 1999 * 88 + \n",
      "1 = 1999 * (127 x 7 + 1) = 259563 + 1999 = 261562 = 1999 * 127 + 5 = 1999 * (182 x \n",
      "7 + 5) = 389422 + 1999 = 3914\n",
      "-----------------------------\n"
     ]
    }
   ],
   "source": [
    "# Finds the prompts with finish reason \"length\"\n",
    "\n",
    "df = pd.read_csv(\"lots_humaneval_prog.csv\")\n",
    "\n",
    "x = df[df[\"Finish Reason\"] == \"length\"]\n",
    "\n",
    "for i,j  in x.iterrows():\n",
    "    print(j[\"Generated Program\"])\n",
    "    print(\"-----------------------------\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>count</th>\n",
       "      <th>unique</th>\n",
       "      <th>top</th>\n",
       "      <th>freq</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Prompt id</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>130</td>\n",
       "      <td>130</td>\n",
       "      <td>from typing import List\\n\\n\\ndef separate_pare...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>124</td>\n",
       "      <td>124</td>\n",
       "      <td>\\n\\ndef truncate_number(number: float) -&gt; floa...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>126</td>\n",
       "      <td>126</td>\n",
       "      <td>from typing import List\\n\\n\\ndef below_zero(op...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>150</td>\n",
       "      <td>150</td>\n",
       "      <td>from typing import List\\n\\n\\ndef intersperse(n...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>111</td>\n",
       "      <td>111</td>\n",
       "      <td>from typing import List\\n\\n\\ndef filter_by_sub...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>156</th>\n",
       "      <td>135</td>\n",
       "      <td>135</td>\n",
       "      <td>\\ndef int_to_mini_roman(number):\\n    \"\"\"\\n   ...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>158</th>\n",
       "      <td>139</td>\n",
       "      <td>139</td>\n",
       "      <td>\\ndef find_max(words):\\n    \"\"\"Write a functio...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>159</th>\n",
       "      <td>140</td>\n",
       "      <td>140</td>\n",
       "      <td>\\ndef eat(number, need, remaining):\\n    \"\"\"\\n...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>160</th>\n",
       "      <td>144</td>\n",
       "      <td>144</td>\n",
       "      <td>\\ndef do_algebra(operator, operand):\\n    \"\"\"\\...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>162</th>\n",
       "      <td>148</td>\n",
       "      <td>148</td>\n",
       "      <td>\\ndef string_to_md5(text):\\n    \"\"\"\\n    Given...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>100 rows × 4 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "          count unique                                                top freq\n",
       "Prompt id                                                                     \n",
       "1           130    130  from typing import List\\n\\n\\ndef separate_pare...    1\n",
       "2           124    124  \\n\\ndef truncate_number(number: float) -> floa...    1\n",
       "3           126    126  from typing import List\\n\\n\\ndef below_zero(op...    1\n",
       "5           150    150  from typing import List\\n\\n\\ndef intersperse(n...    1\n",
       "7           111    111  from typing import List\\n\\n\\ndef filter_by_sub...    1\n",
       "...         ...    ...                                                ...  ...\n",
       "156         135    135  \\ndef int_to_mini_roman(number):\\n    \"\"\"\\n   ...    1\n",
       "158         139    139  \\ndef find_max(words):\\n    \"\"\"Write a functio...    1\n",
       "159         140    140  \\ndef eat(number, need, remaining):\\n    \"\"\"\\n...    1\n",
       "160         144    144  \\ndef do_algebra(operator, operand):\\n    \"\"\"\\...    1\n",
       "162         148    148  \\ndef string_to_md5(text):\\n    \"\"\"\\n    Given...    1\n",
       "\n",
       "[100 rows x 4 columns]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Gets # of unique stats\n",
    "df = pd.read_csv('lots_humaneval_prog_uniq.csv')\n",
    "\n",
    "d = df.groupby(by=[\"Prompt id\"])[\"Formatted Generated Program\"].describe()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.9 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
