Finding permutations of lists using sublists

I was looking at this website about recursion. Where I found this example of using recursion to find the permutations of a list of people:

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."

However it keeps return 0 and I have no idea why, any ideas? And how exactly are the substrings working in this case? Don't they just splice the individual items in the list? What purpose would that have?

Answers


All you need to change is

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

Because, when people is [], it returns an empty list. So, if people has only one element, the fill_seats(everyone_else) will return [], so possible will also return []. The same is returned through the chain and finally returned back.

With that change, the output becomes

['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.

Need Your Help

Import symfony images, don' t have access to httpd.conf - Symfony 1.4

php symfony1

When i want import this from Symfony library on local server I usually do this:

Datagridview virtual model combobox

c# datagridview combobox

how can you dynamically add items to a combobox using the datagridview virtual mode?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.