I want to write a function permutations(route, cities). It should take a list (cities), append every possible permutations of the cities to the route list, and print each permutation in route on a new line. Every permutation must start with the first city, i.e. "Boston".
I am using recursion for this implementation, but can't get it to work.
def permutations(route, cities):
def recurs(cities_temp):
if len(cities_temp) == 0:
return []
elif len(cities_temp) == 1:
return [cities_temp]
else:
route_temp = []
for i in range(len(cities_temp)):
x = cities_temp[i] #x is item i in the input list
y = cities_temp[:i] + cities_temp[1+i:] #y is the remaining (everything but item i)
for j in recurs(y):
route_temp.append([x] + j)
return route_temp
route = recurs(cities)
print(' '.join([city_names[i] for i in route]))
city_names = ["Boston", "Seattle", "Chicago", "Dallas"]
permutations([0], list(range(1, len(city_names)))) #calling the permutations function
Can you all please take a look at it and let me know what I am doing wrong?
routeargument topermutations? It seems redundant.TypeError: list indices must be integers or slices, not list, though.if len(cities_temp) == 0: return [] elif len(cities_temp) == 1: return [cities_temp]should instead beif len(cities_temp) <= 1: return [cities_temp].route = ...to... in route]))and replacing it withprint(' '.join(city_names[i] for routes in recurs(cities) for i in route + routes))should "work", for a given definition of "work".list(range(1, len(city_names)))and not directlycity_names? Also note thatrange(1, len(city_names))has one fewer element thancity_names. You probably want eitherrange(len(city_names))orrange(1, len(city_names)+1).