rg123
By: a guest | Jul 29th, 2009 | Syntax:
Python | Size: 1.66 KB | Hits: 44 | Expires: Never
# List representing the given puzzle:
# Number of letters in each row from top to bottom...
positions = [1,2,3,4,3,2,3,4,3,2,1]
def get_num_paths(positions):
# Start with a list consisting of a 1 for every letter in the
# top row. These are totals paths so far at top row...
totals = [1 for x in xrange(positions[0])]
# Now for every other row...
for i in range(1, len(positions)):
L = len(totals)
# If current row is wider than previous row by 1...
if positions[i] == L + 1:
new_totals = [totals[0]] # New leftmost total is previous
# leftmost total.
if L > 1:
# Calculate new totals in the middle by adding together
# previous adjacent totals and add them to the new list...
new_totals.extend([sum(totals[x : x + 2])
for x in xrange(L - 1)])
new_totals.append(totals[-1]) # New rightmost total is previous
# rightmost total.
totals = new_totals
# Else if current row is narrower than previous row by 1...
elif positions[i] == L - 1:
# All new totals can be handled in this case by adding together
# previous adjacent totals...
new_totals = [sum(totals[x : x + 2])
for x in xrange(L - 1)]
totals = new_totals
# Else it isn't a puzzle this function solves...
else:
return "Invalid structure."
return sum(totals) # Sum of final path totals is the result.
print get_num_paths(positions)