【问题标题】:Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible?给定两个列表/向量,其中一个是另一个的子集,我怎样才能以最有效的方式对齐它们?
【发布时间】:2021-11-24 05:42:51
【问题描述】:

给定两个列表/向量,其中一个是另一个的子集,我怎样才能以最有效的方式对齐它们?对于上下文,我正在对矩阵进行切片(在 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))
        

【问题讨论】:

    标签: python list algorithm vector alignment


    【解决方案1】:

    由于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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多