简体   繁体   中英

Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible?

Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible? For context, I'm slicing a matrix (in C++) and I need to also slice the labels. Since these lists will be labels they should be considered unique within the list.

import unittest
from typing import List, Tuple 

def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
    pass

#The elements in the lists are labels, so they should be unique - i.e. we won't 
# ever have [5, 5, 6, 7, 8].

class AlignTests(unittest.TestCase):
    
    def test1(self):
        v1 = [1, 2, 3, 4, 5, 6]
        v2 = [1, 2]
        first, last = doAlignment(v1, v2)
        self.assertEqual((0, 1), (first, last))
        
    def test2(self):
        v1 = [1, 2, 3, 4, 5, 6]
        v2 = [2, 3, 4]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 3), (first, last))

    def test3(self):
        v1 = [7, 3, 4, 6, 9]
        v2 = [3, 4, 6]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 3), (first, last))
        
    def test4(self):
        v1 = [7, 3, 4, 6, 9]
        v2 = [3, 4, 6, 9]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 4), (first, last))
        

As the values in list1 are unique, just get the index of the first item of list2 to get the the first tuple value, add len(list2)-1 for the second:

def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
    a = list1.index(list2[0])
    return (a, a+len(list2)-1)

example:

>>> doAlignment([7, 3, 4, 6, 9], [3, 4, 6, 9])
(1, 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM