Enumerating all 3-tuples
Ben Bacarisse
ben.usenet at bsb.me.uk
Sat Mar 10 15:06:20 EST 2018
bartc <bc at freeuk.com> writes:
> [repost as original seems to have gone to email; my newsreader has
> somehow acquired a 'Reply' button where 'Followup' normally goes.]
[I thought it was intended but my reply bounced.]
> On 10/03/2018 14:23, Ben Bacarisse wrote:
>> Ben Bacarisse <ben.usenet at bsb.me.uk> writes:
>
>> Off topic: I knocked up this Haskell version as a proof-of-concept:
>>
>> import Data.List
>>
>> pn n l = pn' n (map (:[]) l)
>> where pn' n lists | n == 1 = lists
>> | otherwise = diag (pn' (n-1) lists) lists
>> diag l1 l2 = zipWith (++) (concat (inits l1))
>> (concat (map reverse (inits l2)))
>>
<snip>
> What's the output? (And what's the input; how do you invoke pn, if
> that's how it's done?)
You pass a number and a list which should probably be infinite like
[1..]. You'd better take only a few of the resulting elements then:
*Main> let triples = pn 3 [1..]
*Main> take 20 triples
[[1,1,1],[1,1,2],[1,2,1],[1,1,3],[1,2,2],[2,1,1],[1,1,4],[1,2,3],[2,1,2],[1,3,1],[1,1,5],[1,2,4],[2,1,3],[1,3,2],[2,2,1],[1,1,6],[1,2,5],[2,1,4],[1,3,3],[2,2,2]]
or you can index the list to look at particular elements:
*Main> triples !! 10000000
[70,6,1628]
but, as I've said, the order of the results is not the usual one (except
for pairs).
--
Ben.
More information about the Python-list
mailing list