i'm lost in list manipulation

Greg Ewing (using news.cis.dfn.de) wmwd2zz02 at sneakemail.com
Thu Mar 4 04:47:00 CET 2004


Here's an alternative solution using recursion:

def di(prefix, suffix, result):
   head = suffix[0]
   tail = suffix[1:]
   prefix2 = prefix + [head]
   if not tail:
     result.append(prefix2)
   else:
     di(prefix2, tail, result)
     di(prefix2 + ['-'], tail, result)

def insert_dashes(items):
   result = []
   di([], items, result)
   return result

print insert_dashes(['a'])
print insert_dashes(['a', 'b'])
print insert_dashes(['a', 'b', 'c', 'd'])

cosc353% python insdash.py
[['a']]
[['a', 'b'], ['a', '-', 'b']]
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', '-', 'd'], ['a', 'b', '-', 'c', 'd'], 
['a', 'b', '-', 'c', '-', 'd'], ['a', '-', 'b', 'c', 'd'], ['a', '-', 'b', 'c', 
'-', 'd'], ['a', '-', 'b', '-', 'c', 'd'], ['a', '-', 'b', '-', 'c', '-', 'd']]


-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list