在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 怎樣遍歷生成所有的可能組合?

怎樣遍歷生成所有的可能組合?

有5道不定項(xiàng)選擇題目,每題有A,B,C,D四個選項(xiàng),至少有一個是對的,怎樣生成這5道題目所有的回答可能?
(A,B,C,D,A)、(A、B、C、D、B).......(AB,ABCD,AB,B,C)

回答
編輯回答
孤慣

上班偷偷寫的, 用了兩次回溯,第一個get_str利用回溯找到所有單個問題的答案可能的選項(xiàng),第二個回溯get_answer直接找出所有答案。寫的不好多擔(dān)待。

li = ['a', 'b', 'c', 'd']


def get_str(str_list, length, index):
    ans = []
    if len(str_list) == length:
        return ''.join(str_list)

    for i in range(index, 4):
        str_list.append(li[i])
        temp = get_str(str_list, length, i+1)
        str_list.pop(-1)
        if isinstance(temp, str):
            ans.append(temp)
        else:
            ans.extend(temp)
    return ans


def get_answer(all_str, ans_list, length):
    # ans = []
    if len(ans_list) == length:
        print(ans_list)
        return

    for str_ in all_str:
        ans_list.append(str_)
        get_answer(all_str, ans_list, length)
        ans_list.pop(-1)


all_str = []
for i in range(1, 5):
    all_str.extend(get_str([], i, 0))


get_answer(all_str, [], 5)

2017年12月8日 22:59
編輯回答
空痕

你參考一下這個

里面我也有回答,手機(jī)不方便,這里就不重復(fù)復(fù)制了。

2017年2月5日 02:58
編輯回答
失心人
import itertools

a = ('a','b','c','d')
ans = []

for i in range(1, len(a)):
    ans += list(itertools.combinations(a,i))
2018年5月12日 22:55