2014-02-25 43 views
0

我正在查看关于递归的网站​​ 。当我发现使用递归找人名单的排列的这个例子:使用子列表查找列表排列

def fill_seats(people): 
    # Return a list of ways to fill len(people) seats with the people 
    # named in the sequence people. 
    if len(people) == 0: 
     return [] 
    else: 
     possible = [] 
     for i in range(len(people)): 
     this_person = people[i] 
     everyone_else = people[:i] + people[i+1:] 
     for seating_arrangement in fill_seats(everyone_else): 
      possible = possible + [[this_person] + seating_arrangement] 
     return possible 

our_class = ["Biella", "Gwen", "Katie", "Seth", "Will"] 

for arrangement in fill_seats(our_class): 
    print arrangement 

print len(fill_seats(our_class)), "total possible arrangements." 

但是它使返回0,我不知道为什么,任何想法?在这种情况下子串是如何工作的?难道他们不仅仅将单个项目拼接在一起?那有什么目的?

回答

2

所有你需要改变的是

if len(people) == 1: 
    return [people] 

因为,当people[],它返回一个空列表。所以,如果人们只有一个元素,fill_seats(everyone_else)将返回[],所以可能还会返回[]。同样的东西通过链条返回并最终返回。

随着这种变化,输出变为

['Biella', 'Gwen', 'Katie', 'Seth', 'Will'] 
['Biella', 'Gwen', 'Katie', 'Will', 'Seth'] 
['Biella', 'Gwen', 'Seth', 'Katie', 'Will'] 
... 
... 
... 
['Will', 'Seth', 'Gwen', 'Katie', 'Biella'] 
['Will', 'Seth', 'Katie', 'Biella', 'Gwen'] 
['Will', 'Seth', 'Katie', 'Gwen', 'Biella'] 
120 total possible arrangements. 
+0

不会返回一个列表的列表? –

+0

@AaronHall它将返回一个字符串列表,但是该字符串列表在'[[this_person] + seating_arrangement]'中连接。所以,那应该没问题。 – thefourtheye

+0

如果人是一个字符串,它的len可能会> 1,对不对? –

1

要回答你的问题有关的切片,这些都不是子,他们的子列表。 例如,如果people是以下列表:

people = ['Adam', 'Betsy', 'Charlie', 'David'] 

我们开始通过在人各项指标迭代。因此,我们的第一次迭代将分配

>>> this_person = people[0] 
>>> this_person 
'Adam' 

然后everyone_else是:

>>> people[:0] 
[] 
>>> people[1:] 
['Betsy', 'Charlie', 'David'] 
>>> everyone_else = people[:0] + people[1:] 
>>> everyone_else 
['Betsy', 'Charlie', 'David'] 

基本上,你重建列表中留出当前指数i,则用较小的列表递归。

i = 1,它看起来像这样:

>>> this_person = people[1] 
'Betsy' 
>>> people[:1] 
['Adam'] 
>>> people[2:] 
['Charlie', 'David'] 
>>> everyone_else = people[:1] + people[2:] 
>>> everyone_else 
['Adam', 'Charlie', 'David'] 
+0

噢好吧,所以'[:]'sytax只是一个切片机?我认为这只是我的错误。谢谢 – Amon

+0

另外,有'人[:0]'有什么意义?为什么不只是'人们[1:]'?将它们加在一起似乎是多余的 – Amon

+1

@Amon这是'people [:0]'返回空列表时的特殊情况。看我的编辑 – jayelm