【问题标题】:How to find first matching between arrays and format it如何找到数组之间的第一个匹配项并对其进行格式化
【发布时间】:2018-11-01 12:40:26
【问题描述】:

我有基本清单

['hello', 'how', 'you', 'doing', 'today']

我想将其他列表与它进行比较。

如果是这样的列表

['one', 'two', 'three', 'hello', 'how', 'you', 'doing', 'today']

算法应该返回

['hello', 'how', 'you', 'doing', 'today'] 

实际上只是在给定列表中找到基本列表

给定的列表也可以是这样的

['one', 'two', 'three', 'how', 'you', 'doing', 'today']

所以我们可以在这个例子中看到缺少单词 hello 所以第一个匹配是在基本列表的位置 1 上。在这种情况下,返回列表应该是这样的

['*', 'how', 'you', 'doing', 'today']

第一次匹配后会发生什么并不重要

所以再一次 示例 1

basic = ['hello', 'how', 'you', 'doing', 'today']
given = ['one', 'two', 'three', 'hello', 'how', 'you', 'doing', 'today']
output = ['hello', 'how', 'you', 'doing', 'today']

示例 2

basic = ['hello', 'how', 'you', 'doing', 'today']
given = ['how', 'you', 'doing', 'man']
output = ['*', 'how', 'you', 'doing', 'man']

示例 3

basic = ['hello', 'how', 'you', 'doing', 'today']
given = ['one', 'two', 'you', 'doing', 'man', 'yeaaaap']
output = ['*', '*', 'you', 'doing', 'man', 'yeaaaap']

我的函数是这样的

def findFirstMatch(basic, given):
    for index, item in enumerate(basic):
        for i, el in enumerate(given):
            if basic[index].lower() == given[i].lower():
                return given[i:]

所以现在我在这里只是在第一次匹配之前删除元素。如果第一次匹配在 1 个位置,它可以正常工作,但在 示例 2 中它将无法正常工作。

【问题讨论】:

  • 好的,请根据您对这项任务的研究,展示您尝试过的方法,并解释为什么它没有按预期工作

标签: python algorithm search


【解决方案1】:

我无法理解这个问题:我假设您想要实现的是以下算法:

def match(basic, given):
    out = []

    # 1. go through list 'basic'
    # until you find the item in 'given'
    # append '*' to the output list for item you
    # do not find

    first_match = None
    for item in basic:
        if not item in given:
            out.append("*")
        else:
            first_match = item
            break
    if not first_match:
        return out

    # 2. now that we have found a match,
    # simply append the rest of 'given'

    index = given.index(first_match)
    out.extend(given[index:])

    return out

测试一下:

match(['hello', 'how', 'you', 'doing', 'today'], ['one', 'two', 'three', 'hello', 'how', 'you', 'doing', 'today'])

# ['hello', 'how', 'you', 'doing', 'today']

match(['hello', 'how', 'you', 'doing', 'today'], ['how', 'you', 'doing', 'man'])

# ['*', 'how', 'you', 'doing', 'man']

match(['hello', 'how', 'you', 'doing', 'today'], ['one', 'two', 'you', 'doing', 'man', 'yeaaaap'])

# ['*', '*', 'you', 'doing', 'man', 'yeaaaap']

复制你的例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2013-05-07
    • 1970-01-01
    • 2022-07-13
    • 2012-06-20
    相关资源
    最近更新 更多