0

How to implement the following function foo

foo(2*i for i in [1, 3, 5])  # returning something like [(1, 2), (3, 6), (5, 10)]

I didn't know it is possible before I see the document of a third-party module.

The x in the above link is just a special dict called tupledict. The following case is also legal.

model.addConstrs(i >= 0 for i in [4,3,2,0])
Out[32]: 
{4: <gurobi.Constr *Awaiting Model Update*>,
 3: <gurobi.Constr *Awaiting Model Update*>,
 2: <gurobi.Constr *Awaiting Model Update*>,
 0: <gurobi.Constr *Awaiting Model Update*>}
12
  • 1
    It's not possible. The generator just returns the results, it's not possible to determine how it calculated them.
    – Barmar
    Commented Jul 27, 2022 at 6:34
  • what is the question ? How to write the foo method ? How to build the list you show in comment ?
    – azro
    Commented Jul 27, 2022 at 6:34
  • @azro He wants the foo() function to somehow get the x values so it can combine them with the generated values.
    – Barmar
    Commented Jul 27, 2022 at 6:34
  • 1
    The example you link to works very differently. In the example, x would be a special object which implements a lot of magic __dunder__ methods for specific operators. It cannot work when x is just a plain integer.
    – deceze
    Commented Jul 27, 2022 at 6:36
  • 1
    It says it right there on the page: if x is a Gurobi variable It doesn't work with ordinary variables.
    – Barmar
    Commented Jul 27, 2022 at 6:37

1 Answer 1

1
def foo(g):
    res = []
    for val in g:
        indexes = [v for k, v in g.gi_frame.f_locals.items() if k != '.0']

        res.append(indexes+[val])
    return res

Something like that.

gi_frame and f_locals are documented so they are safe to use maybe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.