Skip to content

Commit b0649fb

Browse files
committed
EPI: parity and swap bits (py)
1 parent edc34c1 commit b0649fb

File tree

3 files changed

+26
-6
lines changed

3 files changed

+26
-6
lines changed

elements-of-programming-interviews/problem_mapping.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ problem_mapping = {
2424
"total": 10000
2525
},
2626
"Python: parity.py": {
27-
"passed": 0,
27+
"passed": 10000,
2828
"total": 10000
2929
}
3030
},
@@ -38,7 +38,7 @@ problem_mapping = {
3838
"total": 10001
3939
},
4040
"Python: swap_bits.py": {
41-
"passed": 0,
41+
"passed": 10001,
4242
"total": 10001
4343
}
4444
},

elements-of-programming-interviews/python/parity.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22

33

44
def parity(x: int) -> int:
5-
# TODO - you fill in here.
6-
return 0
5+
parity = False
6+
while (x):
7+
if (x & 1):
8+
parity = not parity
9+
x >>= 1
10+
return parity
711

812

913
if __name__ == '__main__':

elements-of-programming-interviews/python/swap_bits.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,25 @@
11
from test_framework import generic_test
22

33

4+
def swap_bits_strings(x, i, j):
5+
"""
6+
Different strategy; complicated binary operations can be hard to read
7+
and reason about, but python makes it easy to convert an integer to a list of bits,
8+
which we can then manipulate and recombine to an integer.
9+
"""
10+
bits = list(bin(x)[2:].zfill(64)[::-1])
11+
swapped = [val for val in bits]
12+
swapped[i] = bits[j]
13+
swapped[j] = bits[i]
14+
return int("".join(swapped[::-1]), 2)
15+
16+
417
def swap_bits(x, i, j):
5-
# TODO - you fill in here.
6-
return 0
18+
# Check if bits are different; if so, flip them both.
19+
if ((x >> i) & 1) != ((x >> j) & 1):
20+
mask = (1 << i) | (1 << j)
21+
x ^= mask
22+
return x
723

824

925
if __name__ == '__main__':

0 commit comments

Comments
 (0)