[Snark] [Python] Memoize for the sick speedups

Anand Sundaram submissions at badcode.rocks
Tue Mar 12 14:19:36 UTC 2019


== License ==

This train wreck of a program was written by Anand Sundaram
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. (CC-BY-SA)

== diamond.sh ==

#!/bin/bash

letter=$1
python3 ./diamond.py "$letter"

== diamond.py ==

# Memoize for the sick speedups
A = 65 # Explicit is better than impl
charToRow = {}

class Diamond_Square_Row:
    def __init__(self, letter, row, num_rows):
        self.letter = letter
        self.row = row
        self.num_rows = num_rows
        self.columns = (DiamondSquareRow_charCoal(letter, col, num_rows) for col in range(num_rows))
    def __str__(self):
        s = ''.join([str(cell) for cell in self.columns])
        self.__init__(self.letter, self.row + self.num_rows, self.num_rows)
        return s

# Separate side effects
def with_lookup(op):
    def lookUp(*vals, **key_Vals):
        op(    *vals, **key_Vals)
        letter = key_Vals['letter']
        return charToRow.get(letter, chr(letter))
    return lookUp

import sys

class DiamondSquareRow_charCoal:
    def __init__(self, letter, column, num_cols):
        self.letter=letter
        self.blank = abs(column- ( (num_cols -1)/ 2)) != letter - A

    def __str__(self):
        return chr(self.letter) if not self.blank else " "

def main():
    diamond = DiamondSquare(sys.argv[1])
    print(str(diamond))

# from __future__ import braces

class DiamondSquare:
    def __init__(self, letter): #{
        letters = []
        for x in range(A,ord(letter) +1):
            letters.append(x)
            # if not A<=chr(x) <= 'z':
            if not 65 <= x<=122:
                break # Forces crash and exits program with helpful error at this line
        else: 
            self.letters = letters

        self.letters.extend(letters[:-1][::-1])
        self.num_rows = len(letters)
        self.rows = ( self.get_row(row, letter= l) for (row, l) in enumerate(self.letters ))
    #}

    @with_lookup
    def get_row(self, row, **vals): #{
        letter = vals['letter']
        if row not in range(self.num_rows):
            return
        else:
            row = Diamond_Square_Row(letter, row, len(self.letters))
            charToRow[letter] = row
    #}

    def __str__(self): #{
        return '\n'.join((str(row) for row in self.rows))
    #}

if (__name__ == '__main__'): #{
    main()
#}


More information about the Snark mailing list