Source code for lego_recursion
"""A recursive solution to the lego problem from Homework #4. This
solution performs mix and match, but does not check for two different
ways to satisfy the 4x2 lego substitution.
"""
def read_legos(fname):
"""Util function to read legos from a file. Assumes each line
contains a lego type, comma, number of that lego type.
"""
legos = []
for line in open(fname):
m = line.strip().split(",")
lego = m[0].strip()
cnt = int(m[1])
legos.extend( [lego]*cnt )
return legos
def subs(lego):
"""Returns a substitution for a lego as a list of legos, by finding
the largest possible pieces that taken together make up the input lego.
"""
if lego == '1x1':
return [] ## No substitution exists.
elif lego == '2x1':
return ['1x1']*2
elif lego == '2x2':
return ['2x1']*2
elif lego == '4x2':
return ['4x1']*2
elif lego == '4x1':
return ['2x1']*2
[docs]def replacement(lego, legolist):
"""Find replacement legos recursively. For the replacement,
all the substitutions should be satisfiable. The function
returns:
list of substituted legos, list of remaining legos
if a substitition is found. Otherwise, it returns None.
"""
if lego in legolist:
remaining = legolist[:]
remaining.remove(lego)
return [ lego ], remaining ##Searched lego is found, return success
else:
subslegos = subs(lego)
if len(subslegos) == 0:
return None ## No more substitutions, return failure
##Substitutions exist, search for each one separately
##Modify the lego list alog the way.
lego1 = subslegos[0]
lego2 = subslegos[1]
result1 = replacement(lego1, legolist)
## If no substitution for the first piece, report failure
if result1 == None:
return None
result2 = replacement(lego2, result1[1])
## If no substitution for the first piece, report failure
if result2 == None:
return None
##If we came here, both pieces have substitutions, report their
##combination
return result1[0] + result2[0], result2[1]
if __name__ == "__main__":
mylegos = read_legos("mylegos.txt")
reqlegos = read_legos("legosrequired.txt")
foundlegos = []
missinglegos = []
for lego in reqlegos:
result = replacement(lego, mylegos)
if result == None: # No substitutions were found.
missinglegos.append(lego)
else: ##A substitution was found.
match = result[0]
remaining_legos = result[1]
foundlegos.append( [lego, match] )
mylegos = remaining_legos
print "My remaining legos", mylegos
print "Required legos", reqlegos
print "Still missing legos", missinglegos
print
print "Found legos:"
for item in foundlegos:
print item