在列出123的排列列表时出现builtin_function错误

时间:2013-11-20 22:40:05

标签: python algorithm

我想制作123排列的排序列表,但我不能使用python的模块。当我运行此代码时,我收到消息:

'builtin_function_or_method' object has no attribute 'sort' (line 22)

n = int(input())

elements = str(input())

elements = elements.split

def factor(elements, i , n):

    if i == n - 1:
        return(elements)
    else:
        for j in range(i, n):
            elements[i], elements[j] = elements[j], elements[i]
            factor(elements, i + 1)
            elements[i], elements[j] = elements[j], elements[i]

list = []

list = factor(elements, 0, n)

list = list.sort

while True :
    if list == [] : break
    else:
        print(list[0])
        list.pop([0])

1 个答案:

答案 0 :(得分:3)

这是一个问题:

elements = elements.split

我认为你的意思是:

elements = elements.split() # you forgot the parentheses!

这是另一个类似的问题:

list = list.sort # you forgot the parentheses, and the function call is wrong

我认为你在寻找这个:

list = sorted(list)

或者这个:

list.sort() # no assignment here, it's an in-place sort

另外,建议一句:调用变量list是一个坏主意,它与内置类型和函数名称冲突。最后一句话:你想要做的事情已经在标准模块中实现了,试试看:

import itertools as it
list(it.permutations([1, 2, 3])) # see? told you `list` was a function!
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]