def func(*input) → dict:
‘’’
假设一个灯组有ABC一共3盏灯,每盏灯的状态只有ON/OFF两种状态。假设A、C灯亮,则输出字典{‘A’: 1, ‘B’: 0, ‘C’: 1},其中1表示ON开,0表示OFF关。
请编写一个函数func,接收灯组的字母作为参数(支持任意个),返回该灯组的所有开关状态的组合字典(不限顺序)。
示例:
输入:"A",输出:{0: {'A': 0}, 1: {'A': 1}}
输入:"A", "B",输出:{0: {'A': 0, 'B': 0}, 1: {'A': 0, 'B': 1}, 2: {'A': 1, 'B': 0}, 3: {'A': 1, 'B': 1}}
:param input:
:return:
'''
# 考虑输入的字母不同
# 用递归.没有实现
# if len(input) == 0:
# return {}
# if len(input) == 1:
# data = input[0]
# return {0: {f'{data}': 0}, 1: {f'{data}': 1}}
# elif len(input) == 2:
# dataA = input[0]
# dataB = input[1]
# return {0: {f'{dataA}': 0, f'{dataB}': 0}, 1: {f'{dataA}': 0, f'{dataB}': 1}, 2: {f'{dataA}': 1, f'{dataB}': 0}, 3: {f'{dataA}': 1, f'{dataB}': 1}}
# else:
# dataA = input[0]
# dataB= input[1:]
# func(dataA, dataB)
# 利用数字
input_len = len(input)
max_num = pow(2, input_len)
index = 0
result_dict = {}
num_list = []
for i in range(0, pow(2, input_len)):
num_list.append(i)
for i in range(0, len(num_list)):
bin_num = bin(num_list[i])
bin_num = bin_num[2:]
bin_str = str(bin_num)
cur_index = 0
cur_dict = {}
for j in range(0 ,input_len):
bin_len = len(bin_num)
if j < bin_len:
cur_dict[input[j]] = int(bin_num[bin_len-j-1])
else:
cur_dict[input[j]] = 0
result_dict[i] = cur_dict
return result_dict
def test_func():
assert func(“A”) == {0: {‘A’: 0}, 1: {‘A’: 1}}
# assert func(“A”, “B”) == {0: {‘A’: 0, ‘B’: 0}, 1: {‘A’: 0, ‘B’: 1}, 2: {‘A’: 1, ‘B’: 0}, 3: {‘A’: 1, ‘B’: 1}}
assert func(“A”, “B”, “C”) == {0: {‘A’: 0, ‘B’: 0, ‘C’: 0}, 1: {‘A’: 1, ‘B’: 0, ‘C’: 0}, 2: {‘A’: 0, ‘B’: 1, ‘C’: 0}, 3: {‘A’: 1, ‘B’: 1, ‘C’: 0}, 4: {‘A’: 0, ‘B’: 0, ‘C’: 1}, 5: {‘A’: 1, ‘B’: 0, ‘C’: 1}, 6: {‘A’: 0, ‘B’: 1, ‘C’: 1}, 7: {‘A’: 1, ‘B’: 1, ‘C’: 1}}