def set_to_num(x):
list_zeros = [0 for x in range(0,max(x)+1)]
location_set = [max(x)-i for i in x]
for j in location_set:
list_zeros[j] = 1
list_out = [str(i) for i in list_zeros]
to_num = str(''.join(list_out))
str_l = '0b'+to_num
out_num = int(str_l, 2)
return out_num
def num_to_set(x):
name = [int(v) for v in(bin(x))[2:]]
location = 0
find = 1
location_set = set()
for i in range(name.count(find)):
location += name[location:].index(find)
location_set.add(location)
location += 1
location_set = [len(name)-1-i for i in location_set]
location_set = sorted(location_set)
print(type(location_set))
print(location_set)
a = 0b100011010 # [1, 3, 4, 8]
b = 0b100010010 # [1, 4, 8]
list_a = [1, 3, 4, 8]
num_to_set(a) # [1, 3, 4, 8]
result = set_to_num(list_a)
i = 5
# 集合之间的操作:
# a | (1 << i) -> 把i插入到集合中
insert_i = a | (1 << i)
num_to_set(insert_i)
# [1, 3, 4, 5, 8]
print('After insert_i, insert_i is :',bin(insert_i))
# After insert_i, insert_i is : 0b100111010
# a & ~(1<< i)-> 把i从集合中删除
i = 4
remove_i = a & ~(1<< i)
num_to_set(remove_i)
# [1, 3, 8]
print('After remove_i, remove_i is :',bin(remove_i))
# After remove_i, remove_i is : 0b100001010
# a & (1<< i) -> 判断i是否属于该集合 (零不属于, 非零属于)
i = 6
assert_i = a & (1<< i)
num_to_set(assert_i)
# []
print('After assert_i, assert_i is :',bin(assert_i))
# After assert_i, assert_i is : 0b0
# a 交 b
c = a & b
num_to_set(c)
# [1, 4, 8]
print('After a & b, a & b is :',bin(c))
# After a & b, a & b is : 0b100010010