Python 我们怎样才能找到n位数的排列?

Python 我们怎样才能找到n位数的排列?,python,list,function,loops,recursion,Python,List,Function,Loops,Recursion,我使用python中的列表和循环编写了4位数字的排列 a =list(input("enter a four digit number:")) n=[] for i in range (0,4): for j in range (0,4): if(j!=i): for k in range(0,4): if(k!=i and k!=j): for w in range (0,4

我使用python中的列表和循环编写了4位数字的排列

a =list(input("enter a four digit number:"))
n=[]
for i in range (0,4):
    for j in range (0,4):
        if(j!=i):
            for k in range(0,4):
                if(k!=i and k!=j):
                    for w in range (0,4):
                        if(w!=i and w!=j and w!=k):
                            n.append(a[i]+""+a[j]+""+a[k]+""+a[w])


print(n)

如果输入是1234,则输出将是所有1234的排列,即24个排列。有人能帮我做n位数的排列吗?我更希望看到一个pythonic解决方案。

对于循环中的条件,如果使用条件递归, 根据数字的长度,应该有动态的for循环数 因此,采用循环递归方法。 数字串接在l变量中 当数字集合中有重复的数字时,该方法可以使它们区分开来

#n digit number as input converted into list
f=list(input("enter any number:"))
#dynamic array for dynamic for loop inside recursion 
a=[0 for k in range(len(f))]

c=[]#list which is to be used for append for digits
ans=[]# result in which the 
# recursion for if loop inside for loop
#1st argument is fixed inside the loop
#2nd argument will be decreasing
def conditn(k,m):
    if(m==0):
        return 1
    if(m==1):
        if(a[k]!=a[0]):
            return 1
    if(a[k]!=a[m-1] and conditn(k,m-1)):
        return 1
#recursion for for loop
#1st argument y is the length of the number
#2nd argument is for initialization for the varible to be used in for loop
#3rd argument is passing the list c
def loop(y, n,c):


    if  n<y-1:
        #recursion until just befor the last for loop
        for a[n] in range(y):
            if(conditn(n,n)):

                loop(y, n + 1,c)


    else:
    # last for loop
        if(n==y-1):
            for a[n] in range(y):
            #last recursion of condition
                if(conditn(n,n)):
                #concatinating the individual number
                    concat=""
                    for i in range(y):
                        concat+=f[a[i]]+""
                    c.append(concat)

#returning the list of result for n digit number
    return c 
#printing the list of numbers after method call which has recursion within
#set is used used to convert any of the iterable to the
#distinct element and sorted sequence of iterable elements, 
for j in (set(loop(len(f),0,c))):
    print(j)
#n作为输入的数字转换为列表
f=列表(输入(“输入任何数字”))
#用于递归内部动态for循环的动态数组
a=[0表示范围内的k(len(f))]
c=[]#用于追加数字的列表
ans=[]#结果
#if循环内部for循环的递归
#第一个参数在循环中是固定的
#第二个参数将减少
def条件(k,m):
如果(m==0):
返回1
如果(m==1):
如果(a[k]!=a[0]):
返回1
如果(a[k]!=a[m-1]和条件(k,m-1)):
返回1
#循环递归
#第一个参数y是数字的长度
#第二个参数用于初始化for循环中要使用的变量
#第三个参数正在传递列表c
def回路(y、n、c):
如果n置换[1..n]

导入itertools
N=4#选择一个数字进行排列[1..N]
打印(列表(itertools.permutations(范围(1,N+1)))
现在,如果要排列任意列表:

导入itertools
样本=[1,5,6,2,1]
打印(列表(itertools.排列(示例)))

就python而言,您的代码很好。对于任何问题,我也更愿意使用python,python提供了健壮且较少的行数。这是否回答了您的问题?