[1].Array.diff
Description
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
- It should remove all values from list a, which are present in list b,such as
array_diff([1,2],[1]) == [2]
- If a value is present in b, all of its occurrences must be removed from the other: such as
array_diff([1,2,2,2,3],[2]) == [1,3]
Solution
my code
def array_diff(a, b):
for num in b:
while num in a:
a.remove(num)
return a
others' code
def array_diff(a, b):
return [x for x in a if x not in b]
def array_diff(a, b):
return [x for x in a if x not in set(b)]
def array_diff(a, b):
#your code here
return filter(lambda i: i not in b, a)
Conclusion
-
set()
具有去重功能 -
列表推导式
-
list
&dict
&set
的时间复杂度
-
filter(function,iterable)
用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用list()
来转换
fliter使用示例
#过滤出列表中的奇数
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
#过滤出1~100内的平方数
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)
备注:部分内容参考这个博客,仅供学习交流使用,侵删。