给定两个 lists/vectors,其中一个是另一个的子集,我怎样才能以最有效的方式对齐它们?
Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible?
给定两个 lists/vectors,其中一个是另一个的子集,我怎样才能以最有效的方式对齐它们?对于上下文,我正在对矩阵进行切片(在 C++ 中),我还需要对标签进行切片。由于这些列表将是标签,因此它们在列表中应被视为唯一。
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))
由于list1
中的值是唯一的,只需获取list2
的第一项的索引即可获得第一个元组值,为第二个添加len(list2)-1
:
def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
a = list1.index(list2[0])
return (a, a+len(list2)-1)
示例:
>>> doAlignment([7, 3, 4, 6, 9], [3, 4, 6, 9])
(1, 4)
给定两个 lists/vectors,其中一个是另一个的子集,我怎样才能以最有效的方式对齐它们?对于上下文,我正在对矩阵进行切片(在 C++ 中),我还需要对标签进行切片。由于这些列表将是标签,因此它们在列表中应被视为唯一。
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))
由于list1
中的值是唯一的,只需获取list2
的第一项的索引即可获得第一个元组值,为第二个添加len(list2)-1
:
def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
a = list1.index(list2[0])
return (a, a+len(list2)-1)
示例:
>>> doAlignment([7, 3, 4, 6, 9], [3, 4, 6, 9])
(1, 4)