本文介绍了你什么时候使用reduce()而不是sum()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习函数式编程,并在尝试计算我的测验平均分数时想出了这个例子。



我想出的例子是:

 分数= [90,91,92,94,95,96,97,99,100] 

def add(num1,num2):
'''返回参数的总和'''
返回num1 + num2

导入操作符

timeit reduce(add,scores)/ len(scores)# - > 1000000循环,最好3:每循环799ns

timeit sum(分数)/ len(分数)# - > 1000000循环,最好3:每个循环207纳秒

timeit reduce(operator.add,scores)/ len(scores)# - > 1000000个循环,最好的3:每个循环485 ns

在上面的例子中,一个更高阶的函数几乎慢了4倍。所以我的问题是,什么时候使用高阶函数是个好时机,因为清楚的是上面的例子不是?

解决方案

reduce()任意操作在数据列表上,而不是当你已经有一个大量优化的库函数,它不仅在小列表上胜过 reduce(),而且还有大幅在更大的表现上胜过它。

reduce()让您可以灵活地创建任意但是这种灵活性是以牺牲一些性能开销为代价的,特别是在大多数基本功能结构被认为略超出主流的语言中。

Python是功能性因为它具有一流的功能,但它主要不是功能性语言。它为循环提供了大量的迭代器,并且具有各种语言特性,使得显式循环易于编写,但并不关注递归定义的列表操作(尽管它确实允许它们在有限的程度上 - 缺乏TCO可以避免我直接用Python解释我的Erlang或Guile代码,但是确实可以让我灵活地执行诸如)。


I began learning functional programming recently, and came up with this example when attempting to calculate my quiz average for a class.

The example I came up with is:

scores = [90, 91, 92, 94, 95, 96, 97, 99, 100]

def add(num1, num2):
    '''returns the sum of the parameters'''
    return num1 + num2

import operator

timeit reduce(add, scores) / len(scores)  #--> 1000000 loops, best of 3: 799 ns per loop

timeit sum(scores) / len(scores)  #--> 1000000 loops, best of 3: 207 ns per loop

timeit reduce(operator.add, scores) / len(scores) #--> 1000000 loops, best of 3: 485 ns per loop

It would seem that in the example above, using an higher order function is almost 4 times slower.

So my questions is, when would be a good time to use an higher-order function, because clearly the example above it is not?

解决方案

reduce() makes sense when you require an arbitrary operation over a list of data, not when you already have a heavily optimized library function that will not only outperform reduce() on small lists, but drastically outperform it on larger ones.

reduce() gives you the flexibility to create arbitrary folds, but that flexibility comes at the cost of some performance overhead, especially in a language where most basic functional constructs are considered slightly outside the mainstream.

Python is "functional" in that it has first-class functions, but it is not primarily a functional language. It provides a lush supply of iterators for use in loops and has all sorts of language features that make explicit loops easy to write, but is not focused around recursively defined list operations (though it does permit them to a limited degree -- lack of TCO prevents me from, say, paraphrasing my Erlang or Guile code directly in Python, but does give me the flexibility to do things like benchmark competing approaches that adhere to similar interfaces).

这篇关于你什么时候使用reduce()而不是sum()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:12