In [1]:
%qtconsole
In [2]:
%pylab inline
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 [17]:
def swap(a, i, j):
if i >= len(a) | j >= len(a) :
print "wrong input!"
temp = a[i]
a[i] = a[j]
a[j] = temp
#input target vector(list) and i, modified list to < target[i], = target[i], > target[i]
def dutch_nation_flag(target, i):
pivot = target[i]
small = 0
equal = 0
large = len(target) - 1
while (equal <= large):
if(target[equal] == pivot):
equal += 1
elif (target[equal] < pivot):
swap(target, equal, small)
equal += 1
small += 1
else:
swap(target, equal, large)
large = large - 1
In [20]:
#test case:
a = [1,2,2,3,3,4,2,1,4,5,6,4,3,1,4,2,1]
i = 3
print a[3]
dutch_nation_flag(a, i)
a
Out[20]: