




'''simple docstring'''


lowerCAmelCase_      :  str				     =  range(2, 20 + 1)
lowerCAmelCase_      :  str				     =  [10**k for k in range(ks[-1] + 1)]
lowerCAmelCase_      :  dict[int, dict[int, list[list[int]]]]				     =  {}



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					Dict ,    UpperCamelCase__    :					Dict ,    UpperCamelCase__    :					Optional[Any] ,    UpperCamelCase__    :					Union[str, Any]				):




     """simple docstring"""


     a_     :							List[Any]     						=  sum(a_i[j] for j in range(UpperCamelCase__ ,    len(UpperCamelCase__				)				)				)
     a_     :							str     						=  sum(a_i[j] * base[j] for j in range(min(len(UpperCamelCase__				) ,    UpperCamelCase__				)				)				)

     a_						,     a_     :							Optional[int]     						=  0, 0
     a_     :							int     						=  n - i

     a_     :							List[Any]     						=  memo.get(UpperCamelCase__				)

     if sub_memo is not None:
          a_     :							Optional[Any]     						=  sub_memo.get(UpperCamelCase__				)

          if jumps is not None and len(UpperCamelCase__				) > 0:
               # find and make the largest jump without going over
               a_     :							Any     						=  -1
               for _k in range(len(UpperCamelCase__				) - 1 ,    -1 ,    -1				):
                    if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                         a_     :							Optional[int]     						=  _k
                         break

               if max_jump >= 0:
                    a_						,     a_						,     a_     :							Tuple     						=  jumps[max_jump]
                    # since the difference between jumps is cached, add c
                    a_     :							int     						=  diff + c
                    for j in range(min(UpperCamelCase__ ,    len(UpperCamelCase__				)				)				):
                         a_						,     a_     :							Dict     						=  divmod(UpperCamelCase__ ,    10				)
                    if new_c > 0:
                         add(UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__				)

          else:
               a_     :							str     						=  []
     else:
          a_     :							Dict     						=  {c: []}
          a_     :							int     						=  sub_memo

     if dn >= max_dn or c + diff >= base[k]:
          return diff, dn

     if k > ks[0]:
          while True:
               # keep doing smaller jumps
               a_						,     a_     :							Any     						=  next_term(UpperCamelCase__ ,    k - 1 ,    i + dn ,    UpperCamelCase__				)
               diff += _diff
               dn += terms_jumped

               if dn >= max_dn or c + diff >= base[k]:
                    break
     else:
          # would be too small a jump, just compute sequential terms instead
          a_						,     a_     :							Optional[Any]     						=  compute(UpperCamelCase__ ,    UpperCamelCase__ ,    i + dn ,    UpperCamelCase__				)
          diff += _diff
          dn += terms_jumped

     a_     :							Optional[Any]     						=  sub_memo[c]

     # keep jumps sorted by # of terms skipped
     a_     :							List[str]     						=  0
     while j < len(UpperCamelCase__				):
          if jumps[j][1] > dn:
               break
          j += 1

     # cache the jump for this value digitsum(b) and c
     sub_memo[c].insert(UpperCamelCase__ ,    (diff, dn, k)				)
     return (diff, dn)



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					List[Any] ,    UpperCamelCase__    :					Dict ,    UpperCamelCase__    :					Optional[int] ,    UpperCamelCase__    :					Any				):




     """simple docstring"""


     if i >= n:
          return 0, i
     if k > len(UpperCamelCase__				):
          a_i.extend([0 for _ in range(k - len(UpperCamelCase__				)				)]				)

     # note: a_i -> b * 10^k + c
     # ds_b -> digitsum(b)
     # ds_c -> digitsum(c)
     a_     :							int     						=  i
     a_						,     a_						,     a_     :							Dict     						=  0, 0, 0
     for j in range(len(UpperCamelCase__				)				):
          if j >= k:
               ds_b += a_i[j]
          else:
               ds_c += a_i[j]

     while i < n:
          i += 1
          a_     :							List[str]     						=  ds_c + ds_b
          diff += addend
          a_     :							str     						=  0
          for j in range(UpperCamelCase__				):
               a_     :							str     						=  a_i[j] + addend
               a_						,     a_     :							Dict     						=  divmod(UpperCamelCase__ ,    10				)

               ds_c += a_i[j]

          if addend > 0:
               break

     if addend > 0:
          add(UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__				)
     return diff, i - start_i



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					Union[str, Any] ,    UpperCamelCase__    :					str ,    UpperCamelCase__    :					List[str]				):




     """simple docstring"""


     for j in range(UpperCamelCase__ ,    len(UpperCamelCase__				)				):
          a_     :							Any     						=  digits[j] + addend
          if s >= 10:
               a_						,     a_     :							List[str]     						=  divmod(UpperCamelCase__ ,    10				)
               a_     :							str     						=  addend // 10 + quotient
          else:
               a_     :							Dict     						=  s
               a_     :							Optional[Any]     						=  addend // 10

          if addend == 0:
               break

     while addend > 0:
          a_						,     a_     :							Any     						=  divmod(UpperCamelCase__ ,    10				)
          digits.append(UpperCamelCase__				)



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					int = 10**15				):




     """simple docstring"""


     a_     :							List[str]     						=  [1]
     a_     :							Optional[int]     						=  1
     a_     :							Union[str, Any]     						=  0
     while True:
          a_						,     a_     :							List[str]     						=  next_term(UpperCamelCase__ ,    20 ,    i + dn ,    UpperCamelCase__				)
          dn += terms_jumped
          if dn == n - i:
               break

     a_     :							str     						=  0
     for j in range(len(UpperCamelCase__				)				):
          a_n += digits[j] * 10**j
     return a_n


if __name__ == "__main__":
 print(f"{solution() = }")






'''simple docstring'''


import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


lowerCAmelCase_      :  Any				     =  datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
 import pyspark







@dataclass
class      SCREAMING_SNAKE_CASE    (						datasets.BuilderConfig				):
      __magic_name__  :       Optional[datasets.Features]   							=					None



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					"pyspark.sql.DataFrame" ,    UpperCamelCase__    :					List[int] ,    ):




     """simple docstring"""


     import pyspark

     def generate_fn():
          a_     :							Any     						=  df.select("""*""" ,    pyspark.sql.functions.spark_partition_id().alias("""part_id"""				)				)
          for partition_id in partition_order:
               a_     :							int     						=  df_with_partition_id.select("""*"""				).where(F"part_id = {partition_id}"				).drop("""part_id"""				)
               a_     :							str     						=  partition_df.collect()
               a_     :							List[str]     						=  0
               for row in rows:
                    yield F"{partition_id}_{row_id}", row.asDict()
                    row_id += 1

     return generate_fn







class      SCREAMING_SNAKE_CASE    (						_BaseExamplesIterable				):






      def __init__( self   :  Dict						,						lowercase__   :  "pyspark.sql.DataFrame"						,						lowercase__   :  Optional[int]=None						,						):


           '''simple docstring'''

           a_     :							Tuple     						=  df
           a_     :							Dict     						=  partition_order or range(self.df.rdd.getNumPartitions()       )
           a_     :							Dict     						=  _generate_iterable_examples(self.df						,						self.partition_order       )






      def __iter__( self   :  Optional[Any]       ):


           '''simple docstring'''

           yield from self.generate_examples_fn()






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  np.random.Generator       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  list(range(self.df.rdd.getNumPartitions()       )       )
           generator.shuffle(lowercase__       )
           return SparkExamplesIterable(self.df						,						partition_order=lowercase__       )






      def 							lowercase_						( self   :  Any						,						lowercase__   :  int						,						lowercase__   :  int       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.split_shard_indices_by_worker(lowercase__						,						lowercase__       )
           return SparkExamplesIterable(self.df						,						partition_order=lowercase__       )






      @property
      def 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           return len(self.partition_order       )







class      SCREAMING_SNAKE_CASE    (						datasets.DatasetBuilder				):
      __magic_name__  :       Optional[int]   							=					SparkConfig






      def __init__( self   :  Optional[Any]						,						lowercase__   :  "pyspark.sql.DataFrame"						,						lowercase__   :  str = None						,						lowercase__   :  str = None						,						**lowercase__   :  Dict						,						):


           '''simple docstring'''

           import pyspark

           a_     :							Dict     						=  pyspark.sql.SparkSession.builder.getOrCreate()
           a_     :							List[str]     						=  df
           a_     :							List[str]     						=  working_dir

           super().__init__(
               cache_dir=lowercase__						,						config_name=str(self.df.semanticHash()       )						,						**lowercase__						,						)






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           def create_cache_and_write_probe(lowercase__   :  Any       ):
                # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
                # already exist.
                os.makedirs(self._cache_dir						,						exist_ok=lowercase__       )
                a_     :							List[Any]     						=  os.path.join(self._cache_dir						,						"""fs_test""" + uuid.uuida().hex       )
                # Opening the file in append mode will create a new file unless it already exists, in which case it will not
                # change the file contents.
                open(lowercase__						,						"""a"""       )
                return [probe_file]

           if self._spark.conf.get("""spark.master"""						,						""""""       ).startswith("""local"""       ):
                return

           # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
           # accessible to the driver.
           # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
           if self._cache_dir:
                a_     :							str     						=  (
                    self._spark.sparkContext.parallelize(range(1       )						,						1       ).mapPartitions(lowercase__       ).collect()
                )
                if os.path.isfile(probe[0]       ):
                     return

           raise ValueError(
               """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir"""       )






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           return datasets.DatasetInfo(features=self.config.features       )






      def 							lowercase_						( self   :  Tuple						,						lowercase__   :  datasets.download.download_manager.DownloadManager       ):


           '''simple docstring'''

           return [datasets.SplitGenerator(name=datasets.Split.TRAIN       )]






      def 							lowercase_						( self   :  Any						,						lowercase__   :  int       ):


           '''simple docstring'''

           import pyspark

           def get_arrow_batch_size(lowercase__   :  List[Any]       ):
                for batch in it:
                     yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]}       )

           a_     :							Union[str, Any]     						=  self.df.count()
           a_     :							List[str]     						=  df_num_rows if df_num_rows <= 100 else 100
           # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
           a_     :							str     						=  (
               self.df.limit(lowercase__       )
               .repartition(1       )
               .mapInArrow(lowercase__						,						"""batch_bytes: long"""       )
               .agg(pyspark.sql.functions.sum("""batch_bytes"""       ).alias("""sample_bytes"""       )       )
               .collect()[0]
               .sample_bytes
               / sample_num_rows
           )
           a_     :							List[str]     						=  approx_bytes_per_row * df_num_rows
           if approx_total_size > max_shard_size:
                # Make sure there is at least one row per partition.
                a_     :							List[str]     						=  min(lowercase__						,						int(approx_total_size / max_shard_size       )       )
                a_     :							Union[str, Any]     						=  self.df.repartition(lowercase__       )






      def 							lowercase_						( self   :  Optional[Any]						,						lowercase__   :  str						,						lowercase__   :  str						,						lowercase__   :  int						,						):


           '''simple docstring'''

           import pyspark

           a_     :							str     						=  ParquetWriter if file_format == """parquet""" else ArrowWriter
           a_     :							int     						=  os.path.join(self._working_dir						,						os.path.basename(lowercase__       )       ) if self._working_dir else fpath
           a_     :							Optional[int]     						=  file_format == """parquet"""

           # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
           # pickling the SparkContext.
           a_     :							int     						=  self.config.features
           a_     :							List[str]     						=  self._writer_batch_size
           a_     :							str     						=  self._fs.storage_options

           def write_arrow(lowercase__   :  Optional[Any]       ):
                # Within the same SparkContext, no two task attempts will share the same attempt ID.
                a_     :							int     						=  pyspark.TaskContext().taskAttemptId()
                a_     :							List[str]     						=  next(lowercase__						,						lowercase__       )
                if first_batch is None:
                     # Some partitions might not receive any data.
                     return pa.RecordBatch.from_arrays(
                         [[task_id], [0], [0]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)
                a_     :							List[str]     						=  0
                a_     :							Union[str, Any]     						=  writer_class(
                    features=lowercase__						,						path=working_fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						writer_batch_size=lowercase__						,						storage_options=lowercase__						,						embed_local_files=lowercase__						,						)
                a_     :							List[str]     						=  pa.Table.from_batches([first_batch]       )
                writer.write_table(lowercase__       )
                for batch in it:
                     if max_shard_size is not None and writer._num_bytes >= max_shard_size:
                          a_						,     a_     :							Optional[Any]     						=  writer.finalize()
                          writer.close()
                          yield pa.RecordBatch.from_arrays(
                              [[task_id], [num_examples], [num_bytes]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)
                          shard_id += 1
                          a_     :							Any     						=  writer_class(
                              features=writer._features						,						path=working_fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						writer_batch_size=lowercase__						,						storage_options=lowercase__						,						embed_local_files=lowercase__						,						)
                     a_     :							str     						=  pa.Table.from_batches([batch]       )
                     writer.write_table(lowercase__       )

                if writer._num_bytes > 0:
                     a_						,     a_     :							Any     						=  writer.finalize()
                     writer.close()
                     yield pa.RecordBatch.from_arrays(
                         [[task_id], [num_examples], [num_bytes]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)

                if working_fpath != fpath:
                     for file in os.listdir(os.path.dirname(lowercase__       )       ):
                          a_     :							str     						=  os.path.join(os.path.dirname(lowercase__       )						,						os.path.basename(lowercase__       )       )
                          shutil.move(lowercase__						,						lowercase__       )

           a_     :							Any     						=  (
               self.df.mapInArrow(lowercase__						,						"""task_id: long, num_examples: long, num_bytes: long"""       )
               .groupBy("""task_id"""       )
               .agg(
                   pyspark.sql.functions.sum("""num_examples"""       ).alias("""total_num_examples"""       )						,						pyspark.sql.functions.sum("""num_bytes"""       ).alias("""total_num_bytes"""       )						,						pyspark.sql.functions.count("""num_bytes"""       ).alias("""num_shards"""       )						,						pyspark.sql.functions.collect_list("""num_examples"""       ).alias("""shard_lengths"""       )						,						)
               .collect()
           )
           for row in stats:
                yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  "datasets.SplitGenerator"						,						lowercase__   :  str = "arrow"						,						lowercase__   :  Optional[Union[str, int]] = None						,						lowercase__   :  Optional[int] = None						,						**lowercase__   :  Optional[int]						,						):


           '''simple docstring'''

           self._validate_cache_dir()

           a_     :							Dict     						=  convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE       )
           self._repartition_df_if_needed(lowercase__       )
           a_     :							Any     						=  not is_remote_filesystem(self._fs       )
           a_     :							str     						=  os.path.join if is_local else posixpath.join

           a_     :							Optional[Any]     						=  """-TTTTT-SSSSS-of-NNNNN"""
           a_     :							int     						=  F"{self.name}-{split_generator.name}{SUFFIX}.{file_format}"
           a_     :							Optional[Any]     						=  path_join(self._output_dir						,						lowercase__       )

           a_     :							Dict     						=  0
           a_     :							Optional[Any]     						=  0
           a_     :							Dict     						=  0
           a_     :							List[str]     						=  []
           a_     :							Dict     						=  []

           for task_id, content in self._prepare_split_single(lowercase__						,						lowercase__						,						lowercase__       ):
                (
                    (
                    a_
                )						,     (
                    a_
                )						,     (
                    a_
                )						,     (
                    a_
                )						,     
                )     :							Tuple     						=  content
                if num_bytes > 0:
                     total_num_examples += num_examples
                     total_num_bytes += num_bytes
                     total_shards += num_shards
                     task_id_and_num_shards.append((task_id, num_shards)       )
                     all_shard_lengths.extend(lowercase__       )

           a_     :							List[Any]     						=  total_num_examples
           a_     :							int     						=  total_num_bytes

           # should rename everything at the end
           logger.debug(F"Renaming {total_shards} shards."       )
           if total_shards > 1:
                a_     :							Dict     						=  all_shard_lengths

                # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
                # pickling error due to pickling the SparkContext.
                a_     :							List[str]     						=  self._fs

                # use the -SSSSS-of-NNNNN pattern
                def _rename_shard(
                    lowercase__   :  int						,						lowercase__   :  int						,						lowercase__   :  int						,						):
                     rename(
                         lowercase__						,						fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						fpath.replace("""TTTTT-SSSSS"""						,						F"{global_shard_id:05d}"       ).replace("""NNNNN"""						,						F"{total_shards:05d}"       )						,						)

                a_     :							int     						=  []
                a_     :							List[str]     						=  0
                for i in range(len(lowercase__       )       ):
                     a_						,     a_     :							List[str]     						=  task_id_and_num_shards[i]
                     for shard_id in range(lowercase__       ):
                          args.append([task_id, shard_id, global_shard_id]       )
                          global_shard_id += 1
                self._spark.sparkContext.parallelize(lowercase__						,						len(lowercase__       )       ).map(lambda lowercase__       : _rename_shard(*lowercase__       )       ).collect()
           else:
                # don't use any pattern
                a_     :							int     						=  0
                a_     :							Any     						=  task_id_and_num_shards[0][0]
                self._rename(
                    fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						fpath.replace(lowercase__						,						""""""       )						,						)






      def 							lowercase_						( self   :  Tuple						,						lowercase__   :  "datasets.SplitGenerator"						,						):


           '''simple docstring'''

           return SparkExamplesIterable(self.df       )
