使用子列表查找列表的排列

时间:2014-02-25 05:20:57

标签: python substring

我在看this 关于递归的网站。我在这里找到了使用递归来查找人员列表的排列的示例:

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 个答案:

答案 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.

答案 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']