How to Achieve Full Arrangement of Given Digits in Python


The example tells us how to generate all permutations of the given three digits with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def swap(i,j):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp
a = [int(input("please input your first num:")),int(input("please input your second num:")),
     int(input("please input your third num:")),int(input("please input your last num:"))]


def CalAll(first, num):
    if first == num - 1:  # return when reach the end
        return
    for i in range(first, num):
        if i != first:  # remove duplicates
            swap(i, first)
            if a[0]!=0:
                print(a[0],a[1],a[2])
        CalAll(first + 1, num)  # recursion
        swap(i, first)

print('All possible arrangements of your inputs:')
CalAll(0, len(a))

Output:

please input the first num: 0
please input the second num: 1
please input the third num: 2
please input the fourth num: 3

All possible arrangements of your inputs:
1 0 2
1 0 3
1 2 0
1 2 3
1 3 2
1 3 0
2 1 0
2 1 3
2 0 1
2 0 3
2 3 0
2 3 1
3 1 2
3 1 0
3 2 1
3 2 0
3 0 2
3 0 1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments