views:

67

answers:

2

I am almost finished with a task someone gave me that at first involved easy use of the product() function from itertools. However, the person asked that it should also do something a bit different like:

li =

[[1, 2, 3],
[4, 5, 6]]

A regular product() would give something like: [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4] ...

What it should do is:

Do a regular product(), then, add the next item from the first element in the list and so on. A complete set of example would be:

[[1, 4, 2]
[1, 4, 3],
[1, 5, 2],
[1, 5, 3],
[2, 4, 3],
[2, 5, 3],
[2, 6, 3]]

How should I use itertools in this circumstance?

EDIT:

It might help if I explain the goal of the program: The user will enter, for example, a 5 row by 6 column list of numbers.
A normal product() will result in a 5-number combination. The person wants a 6-number combination. Where will this "6th" number come from? It would come from his choice of which row he wants.

+1  A: 

I wondering what is the magical computations you performing, but it look's like that's your formula:

k = int(raw_input('From What row items should be appeared again at the end?'))
res = [l for l in product(*(li+[li[k]])) if l[k]<l[len(li)] ]
Odomontois
Yes. This is the idea. For this particular line of code and to get the result I want as I asked in the question, yes it works.But what if I want any x rows by x+1 cols?
chiurox
Ohhh, I finally got the idea. That's very neat, didn't think of it this way. Just do a product() of a list with a subset of its own list!I'm hoping this would give all combinations needed.
chiurox
Hahaha, 'magical computations.' To be completely honest, I don't know what the person wants with this. I just took it as a chance to learn some python (never used it before) and get back in touch with some programming.Now that I think about it, it is a really trivial thing. Thanks a lot though.
chiurox
+1  A: 

Generalized for more than two sublist (map function would be the other alternative)

from pprint import pprint
for li in ([[1, 2, 3],
            [4, 5, 6]],

           [[1,  2,  3,  4],
            [5,  6,  7,  8],
            [9, 10, 11, 12]]
           ):
    triples= []
    prevlist=li[0]
    for nextlist in li[1:]:
        for spacing in range(1,len(prevlist)):
            triples.extend([[first,other,second]
                            for first,second in zip(prevlist,prevlist[spacing:])
                            for other in nextlist])

    pprint(sorted(triples))
Tony Veijalainen
This works for the specification I set in the question.What if I want a 5 rows by 6 cols? or any x rows by x+1 cols?
chiurox