Warlus Operator conversion

53 Views Asked by At

I have a piece of code involving walrus operator. I am trying to convert it to normal python code. But I am not sure if it is happening correctly or not.

# code with warlus
NUM_ELEMS = cpu_count()
NUM_CORES = len(list_of_data)

fair_core_worload = NUM_ELEMS // NUM_CORES
cores_with_1_more = NUM_ELEMS % NUM_CORES

EXTENTS_OF_SUBRANGES = []
bound = 0

for i, extent_size in enumerate(
    [fair_core_worload + 1 for _ in range(cores_with_1_more)]
    + [fair_core_worload for _ in range(NUM_CORES - cores_with_1_more)]
):
    
    EXTENTS_OF_SUBRANGES.append((bound, bound := bound + extent_size))

According to my understanding, it should be working with this code.

for i, extent_size in enumerate(
    [fair_core_worload + 1 for _ in range(cores_with_1_more)]
    + [fair_core_worload for _ in range(NUM_CORES - cores_with_1_more)]
):
    bound = extent_size
    bound_extended = bound + extent_size
    EXTENTS_OF_SUBRANGES.append((bound, bound_extended))

I do not have python3.8 to test the walrus code.

3

There are 3 best solutions below

5
On BEST ANSWER
EXTENTS_OF_SUBRANGES.append((bound, bound := bound + extent_size))

can be destructured into:

temp = bound + extent_size
EXTENTS_OF_SUBRANGES.append((bound, temp))
bound = temp
3
On

Looking at the documentation, it should become

EXTENTS_OF_SUBRANGES.append((bound, bound + extent_size))
bound = bound + extent_size 
0
On

bound is getting updated in each iteration by extent_size, so you need to keep track of the previous bound value:

for i, extent_size in enumerate(
    [fair_core_worload + 1 for _ in range(cores_with_1_more)]
    + [fair_core_worload for _ in range(NUM_CORES - cores_with_1_more)]
):
    prev_bound = bound
    bound += extent_size
    EXTENTS_OF_SUBRANGES.append((prev_bound, bound))