输出N个数字的所有排列
作者:互联网
1. 什么是排列
比如0、1、2的全部排列是(0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0)。
2. Python 代码
def confict(stored, new): if new in stored: return True return False def arrange(n, stored=()): for i in range(n): if not confict(stored, i): if len(stored) == n - 1: yield (i,) else: for result in arrange(n, stored + (i,)): yield (i,) + result
3. n = 4 时,输出结果:
if __name__ == "__main__": i = 1 for k in arrange(4): print("{:2d}: ".format(i), end="") print(k) i += 1 """output: 1: (0, 1, 2, 3) 2: (0, 1, 3, 2) 3: (0, 2, 1, 3) 4: (0, 2, 3, 1) 5: (0, 3, 1, 2) 6: (0, 3, 2, 1) 7: (1, 0, 2, 3) 8: (1, 0, 3, 2) 9: (1, 2, 0, 3) 10: (1, 2, 3, 0) 11: (1, 3, 0, 2) 12: (1, 3, 2, 0) 13: (2, 0, 1, 3) 14: (2, 0, 3, 1) 15: (2, 1, 0, 3) 16: (2, 1, 3, 0) 17: (2, 3, 0, 1) 18: (2, 3, 1, 0) 19: (3, 0, 1, 2) 20: (3, 0, 2, 1) 21: (3, 1, 0, 2) 22: (3, 1, 2, 0) 23: (3, 2, 0, 1) 24: (3, 2, 1, 0) """
标签:__,输出,排列,数字,stored,result,print,new,arrange 来源: https://www.cnblogs.com/2noy/p/10702016.html