0

This is the code I am working with in C. It seems like a simple swap for variables.

#define ELEM_SWAP(a,b) { register double t=(a);(a)=(b);(b)=t; }

But I have seen it called like so

ELEM_SWAP(array[x], array[y]). 

I am trying to emulate this macro in Python 3 using numpy arrays. The closest equivalent I have to this is this function but it seems like the C code swaps variables and the Python swaps the items inside the list.

def elem_swap(mylist, x, y):
    mylist[x], mylist[y] = mylist[y], mylist[x]
    return mylist
  • 1
    Can you add example input and both expected output and actual output for elem_swap? – steviestickman Jul 16 '20 at 23:56
  • _it seems like the C code swaps variables_ how are `array[x], array[y]` variables? Aren't they elements of array in C too? – Ehsan Jul 16 '20 at 23:58
  • 1
    Swapping in array can be different from swapping in lists. Depending on the array shape, the fact that an indexed item may be a view can cause unexpected results. With arrays list indexing may be better: `arr[[i,j] = arr[[j, i]]`, – hpaulj Jul 17 '20 at 00:03
  • @steviestickman If given array [1,2,3], passing elem_swap(array[0], array[2]) should make it [3,2,1], or at least that is what I believe it is doing. This is legacy code that I am looking at and this is what I am assuming what it does in context of how I have seen it being used. – GrainsAndRice Jul 17 '20 at 00:50
  • @Ehsan They are, i just meant in the context of the parameters. t=(a);(a)=(b);(b)=t; seemed as if it swapped variables and seeing it called on array elements directly confused me. – GrainsAndRice Jul 17 '20 at 00:50
  • @GrainsAndRice I am no C expert, but doesn't that swap contents of variables as well? – Ehsan Jul 17 '20 at 00:56
  • 1
    Does https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python answer your question? Python does not have macros and you would never use a function to swap variables, since you can directly do it in the code and because the function call only interferes with the technique. – Karl Knechtel Jul 17 '20 at 01:30

1 Answers1

3

C #define is a text processing directive. It simply replaces text

So, this code:

ELEM_SWAP(array[x], array[y]) 

is replaced by this one:

{ register double t=(array[x]);(array[x])=(array[y]);(array[y])=t; }

which will swap variable contents. If you tried something like ELEM_SWAP(1, 1) it will fail.

There is no way to translate this macro in python code with its full capabilities. But if we need to have a similar one for lists; then your function is good enough. Except that I would remove the return part unless you really need it ((keep in mind that you are returning the same list, not a copy of it))

def elem_swap(mylist, x, y):
    mylist[x], mylist[y] = mylist[y], mylist[x]

This will be used like:

lst = [1.0, 2.3, 4.6, 3.9]
elem_swap(lst, 1, 2)
Shadi Naif
  • 184
  • 9