该程序是:请输入3位数字:635排列为:635、653、365、356、563、536

发布于 2025-01-24 07:12:37 字数 549 浏览 2 评论 0原文

def permutation_generate(lst):
    if len(lst)== 0:
        return []
    
    if len(lst)==1:
        return [1]
    
    l =[]
    for i in range(len(lst)):
        m = lst[i]
        
        remLst= lst[:i]+ lst[i+1:]
        for p in permutation_generate(remLst):
            l.append([m]+p)
        return l
    
data= list(input("Please enter a 3 digits number:\n"))
print("The permutations are:")
for p in permutation_generate(data):
    print(*p,sep='', end="")
    

#TypeError:只能列表列表(而不是“ int”) #错误的解决方案是什么?

def permutation_generate(lst):
    if len(lst)== 0:
        return []
    
    if len(lst)==1:
        return [1]
    
    l =[]
    for i in range(len(lst)):
        m = lst[i]
        
        remLst= lst[:i]+ lst[i+1:]
        for p in permutation_generate(remLst):
            l.append([m]+p)
        return l
    
data= list(input("Please enter a 3 digits number:\n"))
print("The permutations are:")
for p in permutation_generate(data):
    print(*p,sep='', end="")
    

#TypeError: can only concatenate list (not "int") to list
#What is the solution of the error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎会甘心 2025-01-31 07:12:37

在第13行,您的函数repernaint_generate(remlst)返回列表[1]
然后,您开始在循环的中迭代它。因此p是1 type int
这就是为什么在第14行上您会遇到错误的错误[m]+int无法正常工作的原因。 [M]+[P]将起作用。

为了您的任务,请查看Python标准库的Itertools模块

On line 13 your function permutation_generate(remLst) returns a list [1]
and you start iterating over it in a for loop. So p is 1 of type int
thats why on line 14 you get the error trying to concatenate [m]+int won't work. [m]+[p] would work.

And for your task take a look at itertools module of python standard library

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文