0

I'm rewriting a piece of Python code for C and I'm stuck at a moment where the author used zip function. Please consider the following:

def coords(step_size):
    for dz in (-step_size / 2, step_size / 2):
        for dx, dy in zip((-step_size / 2, step_size / 2, step_size / 2, -step_size / 2),
                          (step_size / 2, step_size / 2, -step_size / 2, -step_size / 2)):
            yield dx, dy, dz

This function is called in a loop like so:

for dx, dy, dz in coords(step_size):
    ....

If my understanding is correct, zip creates a tulpa iterator object by combining passed values and this function simply calculates the values for dx, dy,dz, but I'm struggling to figure out what exactly happens here and how could I adapt it for C. Would appreciate your help greatly!

Thanks

Artur
  • 41
  • 6

2 Answers2

3

Your code creates the eight vertices of an axis-aligned cube in a specific order. In C, a more or less faithful rendering of the Python code could look like this:

struct point {
    double x, y, z;
};

double s = 1.0;
const double zz[2] = {-s / 2, s / 2};
const double xx[4] = {-s / 2, s / 2, s / 2, -s / 2};  // zipped list, left
const double yy[4] = {s / 2, s / 2, -s / 2, -s / 2};  // zipped list, right

struct point p[8];
unsigned n = 0;

for (unsigned i = 0; i < 2; i++) {
    for (unsigned j = 0; j < 4; j++) {
        p[n].x = xx[j];
        p[n].y = yy[j];
        p[n].z = zz[i];
        
        n++;
    }
}

C doesn't have generators, so his code just fills an array. Zip might look like a good way to achieve this in Python, but Python isn't C, so don't bother to write your own zip. A more typical rendering of your code in C might look like this:

struct point p[8] = {
    {-s / 2,  s / 2, -s / 2},
    { s / 2,  s / 2, -s / 2},
    { s / 2, -s / 2, -s / 2},
    {-s / 2, -s / 2, -s / 2},
    {-s / 2,  s / 2,  s / 2},
    { s / 2,  s / 2,  s / 2},
    { s / 2, -s / 2,  s / 2},
    {-s / 2, -s / 2,  s / 2}
};
M Oehm
  • 28,726
  • 3
  • 31
  • 42
0

By way of explanation, zip() returns a new list that is created from the input lists. The new list contains tuples where the n-th tuple contains each of the n-th elements of the input lists.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268