



#
# Sort large text files in a minimum amount of memory
#
import argparse
import os





class    __lowerCAmelCase					:
				__lowerCamelCase					=							'''block_{0}.dat'''




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       filename
									_lowerCAmelCase         =       []




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.BLOCK_FILENAME_FORMAT.format(_snake_case						)
									with open(_snake_case		,							"""w"""						) as file:
														file.write(_snake_case						)
									self.block_filenames.append(_snake_case						)




				def 				snake_case  (				self						):



									"""simple docstring"""





									return self.block_filenames




				def 				snake_case  (				self		,							_snake_case		,							_snake_case=None						):



									"""simple docstring"""





									_lowerCAmelCase         =       0
									with open(self.filename						) as file:
														while True:
																			_lowerCAmelCase         =       file.readlines(_snake_case						)

																			if lines == []:
																								break

																			if sort_key is None:
																								lines.sort()
																			else:
																								lines.sort(key=_snake_case						)

																			self.write_block("""""".join(_snake_case						)		,							_snake_case						)
																			i += 1




				def 				snake_case  (				self						):



									"""simple docstring"""





									map(os.remove		,							self.block_filenames						)





class    __lowerCAmelCase					:




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       -1
									_lowerCAmelCase         =       None

									for i in range(len(_snake_case						)						):
														if min_str is None or choices[i] < min_str:
																			_lowerCAmelCase         =       i

									return min_index





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       files
									_lowerCAmelCase         =       set()
									_lowerCAmelCase         =       len(_snake_case						)
									_lowerCAmelCase         =       {i: None for i in range(self.num_buffers						)}




				def 				snake_case  (				self						):



									"""simple docstring"""





									return {
									    i: self.buffers[i] for i in range(self.num_buffers						) if i not in self.empty
									}




				def 				snake_case  (				self						):



									"""simple docstring"""





									for i in range(self.num_buffers						):
														if self.buffers[i] is None and i not in self.empty:
																			_lowerCAmelCase         =       self.files[i].readline()

																			if self.buffers[i] == "":
																								self.empty.add(_snake_case						)
																								self.files[i].close()

									if len(self.empty						) == self.num_buffers:
														return False

									return True




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.buffers[index]
									_lowerCAmelCase         =       None

									return value





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       merge_strategy




				def 				snake_case  (				self		,							_snake_case		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       FilesArray(self.get_file_handles(_snake_case		,							_snake_case						)						)
									with open(_snake_case		,							"""w"""		,							_snake_case						) as outfile:
														while buffers.refresh():
																			_lowerCAmelCase         =       self.merge_strategy.select(buffers.get_dict()						)
																			outfile.write(buffers.unshift(_snake_case						)						)




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       {}

									for i in range(len(_snake_case						)						):
														_lowerCAmelCase         =       open(filenames[i]		,							"""r"""		,							_snake_case						)  # noqa: UP015

									return files





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       block_size




				def 				snake_case  (				self		,							_snake_case		,							_snake_case=None						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.get_number_blocks(_snake_case		,							self.block_size						)
									_lowerCAmelCase         =       FileSplitter(_snake_case						)
									splitter.split(self.block_size		,							_snake_case						)

									_lowerCAmelCase         =       FileMerger(NWayMerge()						)
									_lowerCAmelCase         =       self.block_size / (num_blocks + 1)
									merger.merge(splitter.get_block_filenames()		,							filename + """.out"""		,							_snake_case						)

									splitter.cleanup()




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									return (os.stat(_snake_case						).st_size / block_size) + 1


def 						_UpperCAmelCase							( snake_case     ):





					"""simple docstring"""

					if string[-1].lower() == "k":
										return int(string[:-1]     ) * 10_24
					elif string[-1].lower() == "m":
										return int(string[:-1]     ) * 10_24 * 10_24
					elif string[-1].lower() == "g":
										return int(string[:-1]     ) * 10_24 * 10_24 * 10_24
					else:
										return int(snake_case     )


def 						_UpperCAmelCase							( ):





					"""simple docstring"""

					_lowerCAmelCase         =       argparse.ArgumentParser()
					parser.add_argument(
					    """-m"""      ,		"""--mem"""      ,		help="""amount of memory to use for sorting"""      ,		default="""100M"""     )
					parser.add_argument(
					    """filename"""      ,		metavar="""<filename>"""      ,		nargs=1      ,		help="""name of file to sort"""     )
					_lowerCAmelCase         =       parser.parse_args()

					_lowerCAmelCase         =       ExternalSort(parse_memory(args.mem     )     )
					sorter.sort(args.filename[0]     )


if __name__ == "__main__":
	main()








from __future__ import annotations





def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase				):
					"""simple docstring"""






					assert (
					    c % greatest_common_divisor(_UpperCAmelCase       ,			_UpperCAmelCase				) == 0
					)  # greatest_common_divisor(a,b) function implemented below
					((lowercase)   ,      (lowercase)   ,      (lowercase))						   =       extended_gcd(_UpperCAmelCase       ,			_UpperCAmelCase				)  # extended_gcd(a,b) function implemented below
					lowercase						   =       c / d
					return (r * x, r * y)





def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase = 2				):
					"""simple docstring"""






					((lowercase)   ,      (lowercase))						   =       diophantine(_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase				)  # Initial value
					lowercase						   =       greatest_common_divisor(_UpperCAmelCase       ,			_UpperCAmelCase				)
					lowercase						   =       a // d
					lowercase						   =       b // d

					for i in range(_UpperCAmelCase				):
										lowercase						   =       xa + i * q
										lowercase						   =       ya - i * p
										print(_UpperCAmelCase       ,			_UpperCAmelCase				)





def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase				):
					"""simple docstring"""






					if a < b:
										lowercase   ,      lowercase						   =       b, a

					while a % b != 0:
										lowercase   ,      lowercase						   =       b, a % b

					return b





def 		__snake_case						(    _UpperCAmelCase       ,			_UpperCAmelCase				):
					"""simple docstring"""






					assert a >= 0 and b >= 0

					if b == 0:
										lowercase   ,      lowercase   ,      lowercase						   =       a, 1, 0
					else:
										((lowercase)   ,      (lowercase)   ,      (lowercase))						   =       extended_gcd(_UpperCAmelCase       ,			a % b				)
										lowercase						   =       q
										lowercase						   =       p - q * (a // b)

					assert a % d == 0 and b % d == 0
					assert d == a * x + b * y

					return (d, x, y)


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

		testmod(name='''diophantine''', verbose=True)
		testmod(name='''diophantine_all_soln''', verbose=True)
		testmod(name='''extended_gcd''', verbose=True)
		testmod(name='''greatest_common_divisor''', verbose=True)






