File tree Expand file tree Collapse file tree 3 files changed +26
-6
lines changed
elements-of-programming-interviews Expand file tree Collapse file tree 3 files changed +26
-6
lines changed Original file line number Diff line number Diff 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 } ,
Original file line number Diff line number Diff line change 22
33
44def 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
913if __name__ == '__main__' :
Original file line number Diff line number Diff line change 11from 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+
417def 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
925if __name__ == '__main__' :
You can’t perform that action at this time.
0 commit comments