I am working on a counter in Python3 for devices in the field. It tries to contact the device and returns the total number that are online and offline.
def count_online(mac_list):
online = 0
offline = 0
for mac in mac_list:
is_online = poll_device(mac) # ask the device if it is online, return bool
if is_online:
online += 1
else:
offline += 1
return online, offline
I have seen "Branchless method to convert false/true to -1/+1?" as well as "Why "If" is Sloowww", however I need a count of both the online and offline devices. I also appreciate that in Python, trying to go branchless is arguably a bit pointless as it's not a low level language like C. On the other hand, the Hopper Necklace reminds us not to waste our microseconds, so is there a more efficient way to write this? Would a branchless approach decrease run time?
You can use the fact that
isinstance(True, int)and use pure mathematical operations with one go on your input iterator (which doesn't have to be a list):