Suppose I have the following numpy
array:
arr = numpy.array([[1, 7], [2, 0], [2, 1], [2, 3], [3, 4], [3, 5], [5, 6]])
Suppose I choose a specific key, in this case 2
. Then I would like the sorting to be the following:
arr_sorted = [[2, 0], [2, 1], [2, 3], [1, 7], [3, 4], [3, 5], [5, 6]]
The idea is first start with all the elements with key as 2, and then go to the entries whose keys were the values of the previous key.
Starting with 2, the entries are [2, 0], [2, 1], [2, 3]
. The next keys after 2 will therefore be 0, 1, 3. There are no entries with 0 as key. There is one entry with 1 as the key: [1, 7]
. There are two entries with 3 as the key: [3, 4], [3, 5]
. The next unprocessed key is 7
, but it has no entries. Same goes for 4. There is a single entry with 5 as the key: [5, 6]
. 6 has no entries.
Is there any numpy
or dictionary
tricks to achieve this?
My nearest attempt is the following:
def bfs_finder(d, start):
queue = deque([start])
seen = [start]
results = []
while queue:
_vertices = queue.popleft()
current = [i for i, a in enumerate(d) if len([x for x in a if x in _vertices])==1 and i not in seen]
curr1 = [a[1] for i, a in enumerate(d) if len([x for x in a if x in _vertices]) == 1 and i not in seen]
if len(current)>0:
results.extend(curr1)
queue.extend(curr1)
seen.extend(current)
return results
But, I am actually getting an error of current = [i for i, a in enumerate(d) if len([x for x in a if x in _vertices])==1 and i not in seen]
TypeError: argument of type 'int' is not iterable
. Any suggestions on how to fix this error, as well as if there are any good improvements would be highly appreciated.