[Python-ideas] Haskell envy
Steven D'Aprano
steve at pearwood.info
Mon Apr 23 18:52:16 CEST 2012
Nestor wrote:
[...]
> But then somebody else submitted this Haskell solution:
>
> import Data.List
> f :: (Ord a,Num a) => [a] -> Bool
> f lst = (\y -> elem y $ map sum $ subsequences $ [ x | x <- lst, x /=
> y ]) $ maximum lst
>
>
> I wonder if we should add a subsequences function to itertools or make
> the "r" parameter of combinations optional to return all combinations
> up to len(iterable).
You really don't do your idea any favours by painting it as "Haskell envy".
I have mixed ideas on this. On the one hand, subsequences is a natural
function to include along with permutations and combinations in any
combinatorics tool set. As you point out, Haskell has it. So does Mathematica,
under the name "subsets".
But on the other hand, itertools is arguably not the right place for it. If we
add subsequences, will people then ask for partitions and derangements next?
Where will it end? At some point the line needs to be drawn, with some
functions declared "too specialised" for the general itertools module.
(Perhaps there should be a separate combinatorics module.)
And on the third hand, what you want is a simple two-liner, easy enough to
write in place:
from itertools import chain, combinations
allcombs = chain(*(combinations(data, i) for i in range(len(data)+1)))
which is close to what your code used. However, the discoverability of this
solution is essentially zero (if you don't know how to do this, it's hard to
find out), and it is hardly as self-documenting as
from itertools import subsequences
allcombs = subsequences(data)
Overall, I would vote +0.5 on a subsequences function.
--
Steven
More information about the Python-ideas
mailing list