New to Python - Want code review of simple combination routine
Michael Bauers
MichaelB at firstlogic.com
Wed May 22 12:21:13 EDT 2002
I am posting a routine I wrote to return a list of combinations. The input
to 'combination' is a list, and 'n' which represents the number of elements
to take in combination. If you forgot your math, [1,2,3] with n=2 should
give [[1,2], [1,3], [2,3]]
Because I am new to Python, I am not sure I wrote this the most efficient
way. I would appreciate feedback on this code. This would help me know
whether I am understanding how to code in Python correctly.
The algorithm works like this:
left list right list
[] [1,2,3]
call combination2()
[1] [2,3] - move 1 to left list
call combination 2
[1,2] [3] - move 2 to left list, add [1,2] to result list
[1] [3] - Remove 2 from left list
[1,3] [] - Move 3 to left list, add [1,3] to result list
- return from recursive call to combination2()
[1] [2,3] - after call, same as before
[2] [3] - Remove 1 from left list, move 2 from right list to left
list
call combination 2
[2,3] [] - move 3 to left list, add [2,3] to result list
********************** Python code ***********************
import copy
def combinations(list, n):
if n > len(list):
return []
comb_list = []
r = combinations2([], list, n, comb_list)
return comb_list
def combinations2(l_list, r_list, n, result_list):
if (len(r_list) == 0 or n == 0):
return copy.copy(l_list)
else:
temp_l_list = copy.copy(l_list)
temp_r_list = copy.copy(r_list)
for i in r_list:
temp_r_list.remove(i)
temp_l_list.append(i)
if n == 1:
result_list.append(copy.copy(temp_l_list))
else:
combinations2(temp_l_list, temp_r_list, n - 1,
result_list)
temp_l_list.remove(i)
More information about the Python-list
mailing list