我需要找到两个字符串之间的交集。断言:
assert intersect("test", "tes") == list("tes"), "Assertion 1"
assert intersect("test", "ta") == list("t"), "Assertion 2"
assert intersect("foo", "fo") == list("fo"), "Assertion 3"
assert intersect("foobar", "foo") == list("foo"), "Assertion 4"
Run Code Online (Sandbox Code Playgroud)
我尝试了该intersect
函数的不同实现。intersect
将收到 2 个str
参数,w
并且w2
列表理解。迭代并查找第二个字符串中出现的情况。
return [l for l in w if l in w2]
Run Code Online (Sandbox Code Playgroud)
断言 1 和 2失败,因为多个t inw
与一个t in匹配w2
设置交叉点。
return list(set(w).intersection(w2)
return list(set(w) & set(w2))
Run Code Online (Sandbox Code Playgroud)
断言 3 和 4失败,因为集合是 acollection of …