-1

I have two list: array1 = [1, 0, -1, 0, 0, 1,1, -1, 0, 1] array2 = [0, 1, -1] I want to return another list based on how the second list is sorted for example the output of the two lists above would be

[0, 0, 0, 0, 1, 1, 1, 1, -1, -1] 

this is what I currently have however only [0,0,0,0] print can anyone tell me what im doing wrong:

def patternSort(arr1, arr2):
    counter = 0
    i = 0
    arr3 = []
    while i < len(arr1):
        if arr1[i] == arr2[counter]:
            arr3.append(arr1[i])
            
        i += 1
    print(arr3)


array1 = [1, 0, -1, 0, 0, 1,1, -1, 0, 1]
array2 = [0, 1, -1] 

patternSort(array1, array2)
sadboy99
  • 45
  • 1
  • 6
  • 1
    So you want to count the number of 0's and output that many 0's. Then count the 1's and output that many 1's. Then count the -1's and output that many -1s. For my first step, I'd call `collections.Counter(array1)`, and then iterate through `array2` to generate the output. – Frank Yellin Nov 12 '21 at 02:30

1 Answers1

1

If array2 is relatively short and you're not worried about the time complexity of searching it, this can be accomplished succinctly by using a custom comparison key with the existing sorted builtin:

>>> sorted(array1, key=array2.index)
[0, 0, 0, 0, 1, 1, 1, 1, -1, -1]

Note that this performs a linear search of array2 for every comparison during sorting. If you need something more performant, you can resolve the comparison keys ahead of time and store them in a dictionary:

order_map = {k: order for order, k in enumerate(array2)}
sorted(array1, key=order_map.get)  # [0, 0, 0, 0, 1, 1, 1, 1, -1, -1]
Brian61354270
  • 8,690
  • 4
  • 21
  • 43