马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一隻太平洋睡鯊 于 2022-8-23 15:54 编辑
題目:
X=’abcd’ , 請輸出如下的各種組合 C14 , C24 ,C34,C44
{a},{b},{c},{d}, {a,b},{a,c},{a,d},{b,c},{b,d},{c,d}, {a,b,c},{a,b,d},{a,c,d},{b,c,d}, {a,b,c,d}
我的答案(用迴圈):
- listresult = []
- X='abcd'
- for i in X:
- setemp = {i}
- listresult.append(setemp)
- for n in X:
- for m in listresult:
- setemp = m.copy()
- setemp.update([n])
- if setemp not in listresult:
- listresult.append(setemp)
- print(listresult)
复制代码
輸出:
- [{'a'},
- {'b'},
- {'c'},
- {'d'},
- {'a', 'b'},
- {'a', 'c'},
- {'a', 'd'},
- {'b', 'c'},
- {'b', 'd'},
- {'a', 'b', 'c'},
- {'a', 'b', 'd'},
- {'c', 'd'},
- {'a', 'c', 'd'},
- {'b', 'c', 'd'},
- {'a', 'b', 'c', 'd'}]
复制代码
我的問題是,這個題目應該能用Recursion(遞迴/遞歸)達成?
我試了幾個思路,都不太對
希望有人能給個思路
- def f(s):
- result = [s]
- for i in s:
- x = s.replace(i,'',1)
- if x:
- result += f(x)
- return sorted(set(result), key=lambda x:[len(x), x])
复制代码
|