Lesson 2 of 2
Bits and small math
Every integer is a row of bits, and a few operators work on all its bits at once: XOR cancels pairs, and `x & (x - 1)` removes the lowest 1. A little arithmetic does the rest: a sum formula finds a missing number, `%` keeps big numbers small, and Euclid's rule finds a gcd.
Write a number in binary and read one back, using place values,
% 2and// 2Predict
&,|,^,<<and>>on small numbers, bit by bitUse XOR to cancel pairs and find the value without a twin in O(1) extra space
Count 1 bits with
x & (x - 1), and fill the counts for 0 to n from smaller countsFind a missing number from the expected total, keep big numbers small with
%, and compute a gcd with Euclid's rule
A nightly job writes two log records for every run: one when the run starts, one when it ends. Both carry the run's id. Tonight one run crashed and never wrote its end record. The ids from all the records, in no particular order, are [4, 1, 6, 1, 4]. Which run crashed?
A dict of counts finds it: count each id and look for a count of 1. That works, and it costs memory for every id. This lesson finds it with one integer of memory, using an operator you may never have typed: XOR.
The greedy walks in the previous lesson kept their notebook (the values a walk writes down as it goes) to one or two numbers by choosing well. This lesson keeps the notebook that small with bits and a little arithmetic. To see why XOR works, we first look at numbers the way the computer stores them, as rows of 0s and 1s.
Numbers as bits
How does a computer write 13? In base 10, the digits of 472 are worth hundreds, tens and ones. In base 2, called binary, each digit is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. Each digit is a bit, and it is either 0 or 1. 13 is 8 + 4 + 1, so in binary it is 1101: a 1 in the 8s place, a 1 in the 4s place, a 0 in the 2s place and a 1 in the 1s place.
In module 1 you peeled the digits off 472 with % 10 (the last digit) and // 10 (drop the last digit). Binary works the same way with 2: n % 2 is the last bit, and n // 2 drops it. Before you step, guess the bits this loop finds for 13, in the order it finds them.
n = 13bits = ""while n > 0:bits = str(n % 2) + bitsn = n // 2print(bits)print(bin(13))
(nothing printed yet)The bits come out last one first, which is why each new one goes on the front. The loop is a walk like any other, with the four answers this course gives every algorithm (the promise is what stays true after every pass):
bin(n) writes n in binary for you, with 0b in front, and the prefix works the other way too: 0b1101 typed in your code is the number 13. To read binary back, add the place values where the bits are 1: 1101 is 8 + 4 + 1 = 13.
The binary number 10110 is which number in decimal? From the right, its five places are worth 1, 2, 4, 8 and 16.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Operators that work bit by bit
What can you do with two rows of bits? Python has operators that line up the bits of two numbers and combine them one column at a time. Each column is worked out from the two bits in that column alone. & (AND) gives 1 only where both bits are 1. | (OR) gives 1 where either bit is 1. ^ (XOR, short for "exclusive or") gives 1 where the bits differ, so a pair of 1s gives 0. In Python, ^ is not a power: 2 ^ 3 is 1, and the power is 2 ** 3.
| bit of a | bit of b | and | or | xor |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Two more operators move bits instead of combining them. x << 1 shifts every bit one place left, which doubles x. x >> 1 shifts every bit one place right and drops the last one, the same as x // 2. And x & 1 keeps only the last bit, because 1 has a single 1 bit, at the end. So x & 1 is the same as x % 2: 1 for odd numbers, 0 for even.
The instrument below lines up 12 and 10 as rows of 8 bits, a on top and b under it, with the place values above them and the result row at the bottom. Each bit is a button that flips it, and the Operation buttons switch between &, |, ^ and the two shifts. It opens on 12 & 10. Before you look at the result row, use the table: which places have a 1 in both numbers?
So far: a number is a row of bits; &, | and ^ combine two rows column by column; << and >> slide one row. x & 1 and x >> 1 are the bit versions of % 2 and // 2.
6 is 110 and 5 is 101 in binary. Type exactly what this prints.
a = 6
b = 5
print(a & b, a | b, a ^ b)
print(a << 1, a >> 1)
For practice, Reverse the 32 bits uses four of these operators: & 1 reads the last bit, >> 1 drops it, and << 1 with | adds it to the end of the answer.
XOR cancels pairs
Back to the crashed run: how can one integer find the id without a twin? XOR has three properties that, together, do it:
x ^ xis 0. Every bit meets an equal bit, and equal bits give 0.x ^ 0isx. A 0 bit never changes the bit it meets.- Order does not matter.
a ^ bequalsb ^ a, and(a ^ b) ^ cequalsa ^ (b ^ c). Each column is worked out on its own, and it ends as 1 exactly when it saw an odd number of 1s.
So the XOR of all the ids can be regrouped as if each id sat next to its twin: (4 ^ 4) ^ (1 ^ 1) ^ 6. Each pair is 0, and 6 survives. The notebook is one integer, result, starting at 0. result ^= x is shorthand for result = result ^ x, the same way += works. The print line uses format(x, "03b"), which writes a number in binary with 3 digits, padded with zeros. Guess before you step: what is result after the third id, before any pair has closed?
ids = [4, 1, 6, 1, 4]result = 0for x in ids:result ^= xprint(format(x, "03b"), format(result, "03b"))print(result)
(nothing printed yet)A dict of counts needs O(n) extra space, one key per distinct id. XOR keeps only the combined bits, and that is enough, because every pair cancels.
The promise speaks of values seen an odd number of times. Check it on a list where one value appears three times.
Start result at 0 and do result ^= x for every x in [7, 2, 7, 2, 7]. Here 2 appears twice and 7 appears three times. What is result at the end?
Choose one answer, then check.
Now write it as a function. The tests add the edge cases: one item, a single value of 0, and negative numbers.
One integer did the work of a dict. A list of one item works because 0 ^ x is x. A single value of 0 works because every pair cancels and result stays 0. Negative numbers work because x ^ x is 0 for every integer, negative or not.
Counting the 1 bits
How many 1s does 44 have? Written out, 44 is 32 + 8 + 4, which is 101100: three 1s. A loop could check all six bits with x & 1 and x >> 1. A faster loop jumps from one 1 to the next, using one fact: x & (x - 1) is x with its lowest 1 bit turned off. (The lowest 1 bit is the rightmost 1. Many problems call a 1 bit a set bit.)
Why: subtracting 1 borrows from the lowest 1. In decimal, 500 − 1 is 499: the lowest digit that is not 0 drops by one, and every 0 to its right becomes the largest digit, 9. In binary the largest digit is 1, so 44 − 1 turns 101100 into 101011. The lowest 1 becomes 0, every 0 below it becomes 1, and the bits above it do not change. Then & keeps only the 1s both numbers share. Everything above survives, the lowest 1 is gone, and the bits below were 0 in x, so they stay 0.
The instrument shows 44 and 43 lined up with & chosen. Before you read the result row, work out 44 & 43 from 101100 and 101011.
A power of two (1, 2, 4, 8 and so on) has exactly one 1 bit, so removing it leaves 0. That gives a one-line test for powers of two. Turn away 0 first: it has no 1 bits at all, so 0 & (0 - 1) is 0 too. The usual guard, x <= 0, also turns away negative numbers, and no power of two is negative.
Put the lines in order to build is_power_of_two(x), which returns True when x is 1, 2, 4, 8 and so on, and False otherwise, including for 0 and negative numbers. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
if x < 0:return (x & (x + 1)) == 0if x <= 0:def is_power_of_two(x):return (x & (x - 1)) == 0return False
Counting the 1s is the same move in a loop: turn off the lowest 1 until nothing is left, and count the turns. Guess first: how many times does the loop body run for 44?
x = 44count = 0while x > 0:x = x & (x - 1)count += 1print(count)
(nothing printed yet)This loop is the practice problem Count the 1 bits. Here, combine it with XOR: the number of places where two numbers differ is the number of 1s in their XOR. That count is called the Hamming distance.
Write hamming_distance(x, y), which returns the number of bit positions where x and y differ. 1 is 001 and 4 is 100, so they differ in two places. Both numbers are 0 or more. Then press Watch it run to see the notebook change.
raise NotImplementedError, then press Run tests. Each check says what it expects.Now count the 1s of every number from 0 to n. Running the loop on each number works. The faster idea reuses work: the bits of i are the bits of i >> 1 with one more bit on the end, and that last bit is i & 1. 13 is 1101; 13 >> 1 is 6, which is 110; and 13 & 1 is 1. So the count for 13 is the count for 6, plus 1. If you fill the counts in increasing order, the count for i >> 1 is always ready, because i >> 1 is smaller than i for every i of 1 or more. Here are 0 to 7. Cover the last column and fill it yourself, reading each count from the row that i >> 1 names:
| i | binary | i >> 1 | i & 1 | count |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0, the start |
| 1 | 1 | 0 | 1 | 0 + 1 = 1 |
| 2 | 10 | 1 | 0 | 1 + 0 = 1 |
| 3 | 11 | 1 | 1 | 1 + 1 = 2 |
| 4 | 100 | 2 | 0 | 1 + 0 = 1 |
| 5 | 101 | 2 | 1 | 1 + 1 = 2 |
| 6 | 110 | 3 | 0 | 2 + 0 = 2 |
| 7 | 111 | 3 | 1 | 2 + 1 = 3 |
Row 7 reads row 3, which reads row 1, which reads row 0. Every row reads a row above it, already filled. Now write it.
Each count is one lookup and one addition, so the whole list is O(n): the table idea from module 12, where each cell is built from a smaller cell already filled.
Recap: x & (x - 1) turns off the lowest 1. Repeat it to count 1s in one pass per 1 bit; apply it once to test for a power of two. To count every number up to n, reuse the count of i >> 1.
The missing number: what the total should be
A loader expects sensor ids 1 to 5, and one never arrives: [3, 1, 5, 2]. You know what the total should be before you read a single id. 1 + 2 + 3 + 4 + 5 = 15, the ids that arrived add up to 11, and the missing id is 15 − 11 = 4.
The sum 1 + 2 + ... + n is n(n + 1) / 2. To see why, write the numbers forward, and backward underneath. For n = 5:
| forward | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| backward | 5 | 4 | 3 | 2 | 1 |
| column sum | 6 | 6 | 6 | 6 | 6 |
Every column adds to n + 1, and there are n columns, so the two rows hold n(n + 1) and one row holds half of that. For n = 5: 5 × 6 = 30, and half is 15. In code, use // so the result stays an int: n(n + 1) is always even, because one of two neighboring numbers is even, so // divides it exactly. Guess before you step: which values does actual take?
ids = [3, 1, 5, 2]n = len(ids) + 1expected = n * (n + 1) // 2actual = 0for x in ids:actual += xprint(expected - actual)
(nothing printed yet)A list holds every whole number from 0 to 20 except one. Its items add up to 197. Which number is missing?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Python integers do not overflow. Many languages store an integer in a fixed number of bits. A 32-bit integer, such as Java's int, holds at most 2,147,483,647 (231 − 1), and a result past that overflows: it comes out wrong. The full total for n = 100,000 is 5,000,050,000, more than twice that limit. Python integers grow as needed:
print(2 ** 31 - 1) # 2147483647, the 32-bit limit
print(100_000 * 100_001 // 2) # 5000050000, still exact
print(2 ** 64) # 18446744073709551616, all 20 digits
When a total could pass 32 bits, say out loud that Python's integers grow, and name the fix in a fixed-size language: a 64-bit type, or the XOR version below.
The problem is the same idea with the range 0 to n. Notice what changes.
The range starts at 0, so n is len(nums) itself, and 0 adds nothing to the full total. Neither end needs special code: when 0 is missing the two totals are equal, and when n is missing the gap is n.
The XOR version keeps every number small. XOR together every number from 0 to n and every number in the list. Each value in the list meets its twin from the range and cancels, and only the missing value is left. On [3, 0, 1], n is 3, and 0 ^ 1 ^ 2 ^ 3 ^ 3 ^ 0 ^ 1 is 2. Every number involved is at most n, and XOR never makes a number with more bits than its inputs have, so it cannot overflow in any language. The problem's solution writes it out.
Remainders and the greatest common divisor
What is % good for, beyond odd and even? % gives the remainder, and two uses come up again and again. The first is wrapping around. In a ring of 5 seats numbered 0 to 4, walking 7 seats from seat 0 lands on seat 7 % 5, which is 2. Python's % always gives a result from 0 to 4 here, even for a negative step: -1 % 5 is 4, one seat behind seat 0.
The second is keeping big numbers small. When a problem says "return the answer modulo 109 + 7" (modulo means the remainder after dividing by it), take % MOD after each addition or multiplication, with MOD = 10**9 + 7. The final remainder is the same as if you took it once at the end. Python would not overflow, but a huge number makes every operation slower.
Predict this small version, with 7 in place of 109 + 7.
The loop multiplies 5, 6 and 4, but keeps only the remainder after dividing by 7 at each step. Type exactly what it prints.
MOD = 7
total = 1
for x in [5, 6, 4]:
total = total * x % MOD
print(total)
print(5 * 6 * 4 % MOD, -1 % MOD)
Euclid's rule
The greatest common divisor, gcd(a, b), is the largest number that divides both a and b with no remainder. The divisors of 18 are 1, 2, 3, 6, 9 and 18. Of those, 1, 2, 3 and 6 also divide 48, so gcd(48, 18) is 6. Problems use it to put a fraction in lowest terms: 18/48 is 3/8 after dividing top and bottom by 6.
Listing divisors is slow. Euclid's rule is fast: gcd(a, b) equals gcd(b, a % b). The two pairs have exactly the same common divisors. With 48 and 18, 48 % 18 is 12, which is 48 − 2 × 18. Any number that divides 48 and 18 also divides 48 − 2 × 18 = 12, and any number that divides 18 and 12 also divides 2 × 18 + 12 = 48. Each step swaps in a smaller pair. When the second number reaches 0, the first one is the answer, because every number divides 0, so gcd(a, 0) is a. Guess the pairs before you step.
def gcd(a, b):while b > 0:a, b = b, a % breturn a
(nothing printed yet)In Python, math.gcd(48, 18) returns 6. Know the call, and be ready to write the loop.
On paper, run Euclid's rule on gcd(84, 36). Write each pair (a, b), then the next pair (b, a % b), until b is 0. Reveal one step at a time to check.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Last, say it the way you would in the room.
An interviewer asks you to find the one value without a twin in a list where every other value appears twice. You describe a dict of counts, and they ask: "Can you do it without the extra memory?" Write what you would say: the dict version and its cost, then the XOR version with its walk, notebook, promise and cost.
Saved in this browser as you type.