pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

Python pastebin - collaborative debugging tool View Help


Posted by rg123 on Wed 29 Jul 17:01
report abuse | download | new post

  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)

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with @@


Remember me so that I can delete my post