zoukankan      html  css  js  c++  java
  • [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)
    

    备注:部分内容参考这个博客,仅供学习交流使用,侵删。

  • 相关阅读:
    泰勒综合
    滤波器、窗等的系数为什么是对称的?
    l'alphabet en francais
    弄清for循环的本质
    js中的闭包
    js中用正则表达式
    java Calendar
    Android实现XML解析技术
    junit4 详解
    redhat vi 命令
  • 原文地址:https://www.cnblogs.com/zjx-pku/p/13174177.html
Copyright © 2011-2022 走看看