'Warlus Operator conversion
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.
Solution 1:[1]
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
Solution 2:[2]
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))
Solution 3:[3]
Looking at the documentation, it should become
EXTENTS_OF_SUBRANGES.append((bound, bound + extent_size))
bound = bound + extent_size
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | deceze |
| Solution 2 | |
| Solution 3 |
