[Python] Python equivalent of Mathematica's Sow/Reap

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose in Mathematica I define the following function:

    f[list_] := Map[Prime[Sow[#]] &, list];


    which outputs a list of prime numbers, such that if the input list has n at position i, then the output list will contain the nth prime number at position i. For example,

    In[2]:= f[{1, 3, 4}]

    Out[2]= {2, 5, 7}


    Now, if for some reason (debugging, etc...) I want to check what values are being fed into the Prime function. Because of the Sow command in the function, I can do

    In[3] := Reap[f[{1, 3, 4}]]

    Out[3] := {{2, 5, 7}, {{1, 3, 4}}}


    For more details on Sow/Reap, see the Wolfram Documentation. My question is, is there a natural Python equivalent of Mathematica's Sow and Reap functionality? In particular, is there a way to do this kind of thing without explicitly returning extra things from the python function you want to do it to, writing a second python function that is almost the same but returns something extra, or using global variables?

    Continue reading...

Compartilhe esta Página