In [5]:
%qtconsole
In [16]:
#What is Parity?
#Parity is defined as the even/odd number of bit 1 in the representation of binary.
#e.g. parity(10) is 0, since the number of 1 bits in 10 is 2(even)
def parity(num):
result = 0
while (num):
result ^= 1 #Important: += is increment
num &= (num -1) #do not forget to renew
return result
In [22]:
#test case:
test = 10
print bin(test), parity(test)
In [23]:
#Note:
#x & (x - 1): clear least significant bit
#x & ~(x - 1): keep the lowest set bit
#x ^ (x >> 1): What the hell is this? (Gray code)!!
In [18]:
#Python does not constrain the bits length of a object, but in C++ does.
#Check the data type to use before write the code.
def swap(num, i, j):
if num & 1 << i != num & 1 << j :
num ^= (1 << i | 1 << j) #num^= 1<<i: flip the i bit value
return num
In [20]:
#Test case:
test = 10
i = 4
j = 3
print bin(test), bin(swap(test, i, j))
In [10]:
#In python you can do what ever you want, but in cpp can not.
#Take care
def revers_bits(target):
result = 0
while(target): #for 64 bits use i in range(64):
result = result << 1
result |= target & 1
target = target >> 1
return result
In [11]:
#test case
test = 10
print bin(test), bin(revers_bits(test))
暂时不会
In [25]:
#use list data type as input
#return a list of list
from math import log
def power_set(target):
result = []
for i in range(2 ** len(target)):
temp = []
while(i):
id = i & ~(i - 1) #get last sig bit
s = target[int(log(id, 2))] #get tie item correspond to id
temp.append(s)
i &= i - 1 #clear last bit
result.append(temp)
print temp
return result
In [26]:
#test case
test = [0,1,2,3,4]
result = power_set(test)
len(result)
Out[26]:
暂时不会
In [ ]:
In [26]:
In [ ]: