时间:2022-06-07 09:20:14 | 栏目:Python代码 | 点击:次
def full_sort(seq: list): ''' author: 浅若清风cyf date: 2022/03/17 全排列算法(递归) :param seq: 原始序列 :return: ''' results = [] if len(seq) == 1: return seq elif len(seq) == 2: # 递归返回终点 return [[seq[0], seq[1]], [seq[1], seq[0]]] else: for i in seq: sub_seq = seq.copy() # list类型为引用传递,此处需要使用copy()创建一个副本,避免修改原始list sub_seq.remove(i) tmp_result = full_sort(sub_seq) # 获取子列表的全排列 for t in tmp_result: results.append([i] + t) return results
if __name__ == '__main__': res = full_sort([1, 2, 3, 4]) n = 0 for i in res: print(i, end=' ') n += 1 if n % 5 == 0: n = n % 5 print('')
res = full_sort(['Apple', 'XiaoMi', 'HuaWei', 'OPPO']) n = 0 for i in res: print(i, end=' ') n += 1 if n % 5 == 0: n = n % 5 print('')