Advertisement
Guest User

rg123

a guest
Jul 29th, 2009
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. # List representing the given puzzle:
  2. # Number of letters in each row from top to bottom...
  3. positions = [1,2,3,4,3,2,3,4,3,2,1]
  4.  
  5. def get_num_paths(positions):
  6.     # Start with a list consisting of a 1 for every letter in the
  7.     # top row.  These are totals paths so far at top row...
  8.     totals = [1 for x in xrange(positions[0])]
  9.     # Now for every other row...
  10.     for i in range(1, len(positions)):
  11.         L = len(totals)
  12.         # If current row is wider than previous row by 1...
  13.         if positions[i] == L + 1:
  14.             new_totals = [totals[0]]  # New leftmost total is previous
  15.                                       # leftmost total.
  16.             if L > 1:
  17.                 # Calculate new totals in the middle by adding together
  18.                 # previous adjacent totals and add them to the new list...
  19.                 new_totals.extend([sum(totals[x : x + 2])
  20.                                    for x in xrange(L - 1)])
  21.             new_totals.append(totals[-1])  # New rightmost total is previous
  22.                                            # rightmost total.
  23.             totals = new_totals
  24.         # Else if current row is narrower than previous row by 1...
  25.         elif positions[i] == L - 1:
  26.             # All new totals can be handled in this case by adding together
  27.             # previous adjacent totals...
  28.             new_totals = [sum(totals[x : x + 2])
  29.                           for x in xrange(L - 1)]
  30.             totals = new_totals
  31.         # Else it isn't a puzzle this function solves...
  32.         else:
  33.             return "Invalid structure."
  34.     return sum(totals)  # Sum of final path totals is the result.
  35.  
  36. print get_num_paths(positions)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement