Skip to content

Instantly share code, notes, and snippets.

@jerinisready
Last active March 17, 2021 14:09
Show Gist options
  • Save jerinisready/6450a63ddfec374c0306d1d71007cfa5 to your computer and use it in GitHub Desktop.
Save jerinisready/6450a63ddfec374c0306d1d71007cfa5 to your computer and use it in GitHub Desktop.
Bit Wise Combinations of items in dictionary! If you have a set of objects, and want to access as a list of their combinations, use this simple snippet which uses bitwise and operator in python!
def get_status(code: int):
"""
This function will return a list of items
"""
_status_set = {
1: 'Alice',
2: 'Bob',
4: 'Charlie',
8: 'David',
16: 'Eve',
32: 'Frank',
64: 'Grace',
128: 'Heidi',
256: 'Ivan',
}
statuses = []
next_greatest_factor = max(list(_status_set.keys()))
"""
''' *** VALIDATION IF Input expects to be string*** '''
# if not code.isdigit() or int(code) >= next_greatest_factor * 2:
# return code # raise NotACode("This is not a valid key!")
# code = int(code)
"""
while next_greatest_factor:
if code & next_greatest_factor: # finding if number is a factor using "Bitwise AND Operator"
statuses.append(
_status_set[next_greatest_factor]
) # if so; add corresponding value to the list to be returned!
next_greatest_factor //= 2 # get next factor
# statuses.reverse() # [].reverse() to get in order~!
return statuses
if __name__ == "__main__" :
stat_code = 240 # 128 + 64 + 32 + 16
print(get_status(stat_code))
# >>> ['Eve', 'Frank', 'Grace', 'Heidi']
stat_code = 120 # 64 + 32 + 16 + 8
print(get_status(stat_code))
# >>> ['David', 'Eve', 'Frank', 'Grace',]
stat_code = 75 # 64 + 8 + 2 + 1
print(get_status(stat_code))
# >>> ['Alice', 'Bob', 'David', 'Grace']
stat_code = 3 # 2 + 1
print(get_status(stat_code))
# >>> ['Alice', 'Bob']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment