zoukankan      html  css  js  c++  java
  • 函数式编程->reduce


    """
    # 需求:把list里面的数字加起来
    num_l = [1, 2, 3, 4, 5, 100]
    res = 0
    for num in num_l:
    res += num
    # print(res)

    # 定义函数
    num_l = [1, 2, 3, 4, 5, 100]
    def reduce_test(array):
    res = 0
    for num in array:
    res += num
    return(res)
    print(reduce_test(num_l))
    # 逻辑仍然是写死了,所有的值乘起来呢?
    """

    # 另一种升级
    num_l = [1, 2, 3, 4, 5, 100]
    def multi(m,n):
    return m * n
    def reduce_test(func, array, init=None):
    # res = 1 这么写又写死了.
    if init is None:
    res = array.pop(0)
    else:
    res = init
    for i in array:
    res = func(res, i)
    return res
    print(reduce_test(multi, num_l))
    print(reduce_test(lambda m,n:m*n, num_l))
    print(reduce_test(multi, num_l, 100))

    # 升级:reduce, 功能:把一个完整的序列进行处理,最终得到一个值.
    from functools import reduce
    num_l = [1, 2, 3, 4, 5, 100]
    print(reduce(lambda m,n:m*n, num_l))
  • 相关阅读:
    hdu 4403 枚举
    hdu 4405概率dp
    lightoj 1036 dp
    lightoj 1033 区间dp
    lightoj 1032 二进制的dp
    hdu 4293 dp求最大权值不重合区间
    poj 2449 第k短路
    hdu 4284 状态压缩
    hdu4281 区间dp
    poj 2288 tsp经典问题
  • 原文地址:https://www.cnblogs.com/Windows-phone/p/9729986.html
Copyright © 2011-2022 走看看