-1

有点卡在这里编码挑战!我正在编写一个函数,它接受两个参数(字符串、查询)并打印每个查询字符串在输入字符串中出现的次数。我想我已经很接近解决这个问题了,但是我的函数目前对查询字符串之前/之后带有空格的查询字符串不敏感。

版本 1(对包含空格的查询字符串不敏感):

strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']

def matchingStrings(strings, queries):
    for i in range(len(queries)):]
        n_matches = strings.count(queries[i])
        print(n_matches)

matchingStrings(strings,queries)

电流输出:

1
0
0

版本 2(尝试保留引号):

def matchingStrings(strings, queries):
    for i in range(len(queries)):
        query_to_match = '\'%s\'' % queries[i]
        n_matches = strings.count(query_to_match)
        print(n_matches)


matchingStrings(strings,queries)

电流输出:

0
0
0

预期输出:

2
1
0
4

2 回答 2

1

这将通过使用正则表达式来工作,尽管它遍历两个列表时速度较慢:

def matching_strings(strings, queries):
    for query in queries:
        count = 0
        for string in strings:
            if re.match(query.strip(), string):
                count += 1
        print(count)

在您的输入上运行该函数将提供所需的输出!这通过检查查询字符串是否匹配(不带空格.strip())来工作。

这是我的输出:

>>> strings = ['ab', ' ab', 'abc']
>>> queries = ['ab', ' abc', ' bc']
>>> matching_strings(strings, queries)
2
1
0
于 2022-01-11T09:00:25.670 回答
1

所以这个解决方案接近正确的答案,但有一些事情正在发生。首先,要将所有查询与所有字符串进行比较,我们需要两个 for 循环。这是帮助可视化正在发生的事情的伪代码:

  1. 对于查询中的每个查询:开始计数以计算字符串中有多少单词与当前查询匹配。将为每个查询重置。
  2. 对于我们想要与当前查询比较的每个单词:我们不关心空格,因此我们将从查询和字符串中删除它。
  3. 如果剥离后单词和查询相同:
  4. 在柜台上加一个。
  5. 在浏览完所有单词后,打印计数,其中包含有多少单词与当前查询匹配。
  6. 继续下一个查询。

如果您想查看它,这里是 python。

strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']

def matchingStrings(strings, queries):
    for query in queries:
        count = 0 
        # need to iterate through ALL strings. 
        for string in strings:
            if query.strip() == string.strip():
               count += 1
        print(count)

matchingStrings(strings, queries)

输出:

2
1
0
于 2022-01-11T09:25:01.463 回答