K-way merge: обновление из одного списка в многомерный массив (python) - PullRequest
0 голосов
/ 17 сентября 2018

Я довольно новичок в python и у меня есть учебное задание, которое нас попросили выполнить в университете. Любая помощь будет оценена.

В настоящее время мы изучаем K-way merging, и приведенный нами пример кода Python (ниже) основан на одном списке, например [1, 2, 3, 4, 5, 6]. Меня попросили применить этот код Python к многомерному массиву или списку списков, и я пытаюсь понять, какие части нужно изменить.

Это код:

import sys

# Find the smallest record
def find_min(records):    
  """ 
  Find the smallest record
  Arguments
  records -- the input record set

  Return:
  result -- the smallest record's index
  """
  m = records[0]
  index = 0
  for i in range(len(records)):
      if(records[i] < m):  
      index = i
      m = records[i]
  return index
############################

 def k_way_merge(record_sets):
  """ 
  K-way merging algorithm

  Arguments:
  record_sets -- the set of mulitple sorted sub-record sets

  Return:
  result -- the sorted and merged record set
  """

  # indexes will keep the indexes of sorted records in the given buffers
  indexes = []
  for x in record_sets:
      indexes.append(0) # initialisation with 0

  # final result will be stored in this variable
  result = []  

  while(True):
       merged_result = [] # the merging unit (i.e. # of the given buffers)

       # This loop gets the current position of every buffer
       for i in range(len(record_sets)):
           if(indexes[i] >= len(record_sets[i])):
             merged_result.append(sys.maxsize)
           else:
             merged_result.append(record_sets[i][indexes[i]])  

       # find the smallest record 
       smallest = find_min(merged_result)

       # if we only have sys.maxsize on the tuple, 
       # we reached the end of every record set
       if(merged_result[smallest] == sys.maxsize):
          break

       # This record is the next on the merged list
       result.append(record_sets[smallest][indexes[smallest]])
       indexes[smallest] +=1

  return result

Если честно, я даже не знаю, с чего начать, чтобы изменить его - поэтому вместо единого списка, входящего в аргумент 'record_sets', это сложный многомерный массив. Например [[1, 2, 3, 4, 5, 6, 7], [3, 4, 5, 6, 7, 8, 9], [a, b, c, d, e]]. Я хотел бы иметь возможность сортировать каждый список по одному значениям в каждом списке (скажем, индекс = 3). Даже если есть более простой способ сделать это, к сожалению, я должен придерживаться метода слияния k-way.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...