Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- [object_id] = object
- object
- {
- id,
- parents,
- children
- }
- [4] -> [7] ->
- [1] -> [2] -> [3] -> [6]
- [5] ->
- '''
- class InputData:
- def __init__(self, unique_id, parents, children):
- self.id = unique_id
- self.parents = parents
- self.children = children
- self.visited = False
- # Gera mapa de entrada e também o ID do objeto inicial.
- def getMappedInput(data_input):
- mapped_input, initial_object_id = {}, -1
- for i in data_input:
- mapped_input[i.id] = i
- if not i.parents:
- initial_object_id = i.id
- return mapped_input, initial_object_id
- # Retorna mapa com novo objeto inserido.
- def addNewObject(mapped_input, input):
- if input.id in mapped_input:
- return
- mapped_input[input.id] = input
- return mapped_input
- # Retorna mapa com objeto removido.
- def removeObject(mapped_input, input):
- mapped_input.pop(input.id, None)
- return mapped_input
- def iterateThroughMap(mapped_input, id_now):
- # Pega o objeto correspodente ao ID atual.
- map_object = mapped_input[id_now]
- # Para evitar que um objeto seja processado duas vezes. Se não tiver problema basta remover esta linha.
- if map_object.visited:
- return
- print(map_object.id)
- map_object.visited = True
- # Pega os objetos seguintes (filhos) ao atual.
- next_objects = map_object.children
- # Se não tiver filho interrompe a varredura por este ramo.
- if not next_objects:
- return
- # Chama, recursivamente, a função nos filhos do objeto atual.
- # Se os filhos devem ser processados concorrentemente USE threading ou multiprocessing neste escopo.
- # Na aplicação atual vai ser processada toda a geração seguinte ao filho atual para depois o próximo ser processado.
- for i in next_objects:
- # No caso os filhos são armazenados, no set de entrada, já diretamente como IDs. Caso eles sejam objetos você usaria aqui i.id.
- iterateThroughMap(mapped_input, i)
- input_data_tuple = (
- # InputData(ID, pais, filhos)
- InputData(1, None, (2,)),
- InputData(6, (5, 7), None),
- InputData(3, (2,), (4, 5)),
- InputData(7, (4,), (6,)),
- InputData(4, (3,), (7,)),
- InputData(2, (1,), (3,)),
- InputData(5, (3,), (6,)),
- )
- input_data_map, first_id = getMappedInput(input_data_tuple)
- iterateThroughMap(input_data_map, first_id)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement