輸出N個數字的所有排列
阿新 • • 發佈:2019-04-13
lse n) 輸出結果 return () format orm 排列 ont
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)"""
輸出N個數字的所有排列