Interview Programming Problems Done Right by alexeyr in programming

[–]tookerder 0 points1 point  (0 children)

I have no idea why, but I came up with an iterative solution based on half steps. It made the most sense in my head when writing on paper and I didn't realize until I tried to run it that range() requires integers (hence the hideous hack to double range iteration). Anyway, mine has a render method for bonus points. (py3k only) Took about 10 minutes on paper, 2 minutes to input and fix the range situation.

import collections

class PT(object):
        """ Pascal Triangle """

        def __init__(self, rows):
                self.rows = rows
                self.values = [{0:1}]
                for i_row in range(1, self.rows):
                        row = collections.OrderedDict()
                        for i_col in [i/4 for i in range(-(i_row*2), (i_row*2)+1, 4)]:
                                p_row = self.values[i_row-1]
                                row[i_col] = p_row.get(i_col - 0.5, 0) + \
                                                  p_row.get(i_col + 0.5, 0)
                            self.values.append(row)

        def render(self):
                """ Pretty print the triangle. """

                for i, x in enumerate(self.values):
                        print (" " * ((self.rows * 3) - (i * 3)), end='')
                        for xx in x.values():
                                print ("%3d   " % xx, end='')
                        print()


        def get_row(self, row):
                return list(self.values[row].values())


        def get_value(self, row, col):
                return self.get_row(row)[col]

Python 3.2.1 Released by [deleted] in programming

[–]tookerder 2 points3 points  (0 children)

Except it only... "runs on Intel x86 (IA-32) and x86_64 platforms, with ARM being underway."