Python Data Structures: Pocket Primer by Oswald Campesato

Python Data Structures: Pocket Primer by Oswald Campesato

Author:Oswald Campesato
Language: eng
Format: epub
Publisher: Mercury Learning and Information


TASK: CHECK FOR ADJACENT SET BITS IN A BINARY NUMBER

Listing 3.29 displays the contents of check_adjacent_bits.py that illustrates how to solve this task.

LISTING 3.29: check_adjacent_bits.py

# true if adjacent bits are set in num: def check(num): return num & (num << 1) arr1 = [15, 16, 17, 50, 67, 99] for num in arr1: print("Decimal: ",num) print("Binary: ",bin(num)) if check(num): print("Adjacent pair of set bits found") else: print("No adjacent pair of set bits found") print("---------------
")

Listing 3.29 defines the Python function check() that returns the result of the logical “and” of the parameter n with the value (n<<1), which does detect the presence of adjacent bits that are set equal to 1. Now launch the code in Listing 3.29 and you will see the following output:

15 in binary = 0b1111 Adjacent pair of set bits found ----------------- 16 in binary = 0b10000 No adjacent pair of set bits found ----------------- 17 in binary = 0b10001 No adjacent pair of set bits found ----------------- 50 in binary = 0b110010 Adjacent pair of set bits found ----------------- 67 in binary = 0b1000011 Adjacent pair of set bits found ----------------- 99 in binary = 0b1100011 Adjacent pair of set bits found -----------------



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.