Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.93 KB | None | 0 0
  1. # Daily Programmer #90
  2. # ---------------------
  3. # A nonstandard black-and-white image format defining the image as a series of
  4. # commands to a "person" with a stamp who can move on a grid stamping black
  5. # pixels.
  6.  
  7. def parse(text):
  8.     """
  9.    Make text ready for executing.
  10.  
  11.    Returns each "token" separated by a single space.
  12.    """
  13.     outputText = []
  14.     valid_characters = ['p','n','s','w','e']
  15.     lastCharWasDigit = False
  16.  
  17.     for char in text:
  18.         char = char.lower()
  19.         if char in valid_characters:
  20.             outputText.append("%s " % char)
  21.             lastCharWasDigit = False
  22.         elif char.isspace():
  23.             if lastCharWasDigit:
  24.                 outputText.append(" ")
  25.             lastCharWasDigit = False
  26.         elif char.isdigit():
  27.             outputText.append("%s" % char)
  28.             lastCharWasDigit = True
  29.         else:
  30.             raise ValueError("Invalid character: '%s'" % char)
  31.     return "".join(outputText)
  32.  
  33. def execute(text):
  34.     """
  35.    Execute 'text'.
  36.    Returns (pixels, width, height)
  37.    """
  38.     text = parse(text).split(' ')
  39.  
  40.     print("Tokenization:")
  41.     print(text)
  42.  
  43.     # Obtain the width and height
  44.     (w,h) = (0,0)
  45.     try:
  46.         w = int(text[0])
  47.         h = int(text[1])
  48.     except ValueError:
  49.         raise ValueError("Expected width and height as first tokens in text.")
  50.  
  51.     grid = [0 for i in range(w*h)]
  52.     currentIndex = 0
  53.     directionToIndexChange = {'n':-h, 's':h, 'w':-1, 'e':1}
  54.  
  55.     for token in text[2:]:
  56.         if token == 'p':
  57.             grid[currentIndex] = 1
  58.         elif token == '':
  59.             # End!
  60.             break
  61.         else:
  62.             currentIndex += directionToIndexChange[token]
  63.             if currentIndex < 0 or currentIndex >= len(grid):
  64.                 print("Execution failed, out of bounds.")
  65.  
  66.     return (grid, w, h)
  67.  
  68. def grid_to_ascii(grid, width, height):
  69.     text = []
  70.     for row in range(height):
  71.         for col in range(width):
  72.             index = (row*height)+col
  73.             if grid[index]:
  74.                 text.append('#')
  75.             else:
  76.                 text.append(' ')
  77.         text.append('\n')
  78.     return "".join(text)
  79.  
  80. if __name__ == '__main__':
  81.     import sys
  82.     if len(sys.argv) <= 1:
  83.         print("Arguments: file [file2 ... fileN] or <NO_FILE> <TEXT>")
  84.         sys.exit(1)
  85.  
  86.     executeArgv = False
  87.     if sys.argv[1] == "<NO_FILE>":
  88.         executeArgv = True
  89.  
  90.     if executeArgv:
  91.         text = " ".join(sys.argv[2:])
  92.         result = execute(text)
  93.  
  94.         print("Output Data:")
  95.         print(result)
  96.  
  97.         print("Rasterization:")
  98.         print(grid_to_ascii(*result))
  99.         sys.exit(0)
  100.  
  101.     for file in [open(filename) for filename in sys.argv[1:]]:
  102.         text = file.read()
  103.         file.close()
  104.         result = execute(text)
  105.  
  106.         print("Output Data:")
  107.         print(result)
  108.  
  109.         print("Rasterization:")
  110.         print(grid_to_ascii(*result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement