Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Daily Programmer #90
- # ---------------------
- # A nonstandard black-and-white image format defining the image as a series of
- # commands to a "person" with a stamp who can move on a grid stamping black
- # pixels.
- def parse(text):
- """
- Make text ready for executing.
- Returns each "token" separated by a single space.
- """
- outputText = []
- valid_characters = ['p','n','s','w','e']
- lastCharWasDigit = False
- for char in text:
- char = char.lower()
- if char in valid_characters:
- outputText.append("%s " % char)
- lastCharWasDigit = False
- elif char.isspace():
- if lastCharWasDigit:
- outputText.append(" ")
- lastCharWasDigit = False
- elif char.isdigit():
- outputText.append("%s" % char)
- lastCharWasDigit = True
- else:
- raise ValueError("Invalid character: '%s'" % char)
- return "".join(outputText)
- def execute(text):
- """
- Execute 'text'.
- Returns (pixels, width, height)
- """
- text = parse(text).split(' ')
- print("Tokenization:")
- print(text)
- # Obtain the width and height
- (w,h) = (0,0)
- try:
- w = int(text[0])
- h = int(text[1])
- except ValueError:
- raise ValueError("Expected width and height as first tokens in text.")
- grid = [0 for i in range(w*h)]
- currentIndex = 0
- directionToIndexChange = {'n':-h, 's':h, 'w':-1, 'e':1}
- for token in text[2:]:
- if token == 'p':
- grid[currentIndex] = 1
- elif token == '':
- # End!
- break
- else:
- currentIndex += directionToIndexChange[token]
- if currentIndex < 0 or currentIndex >= len(grid):
- print("Execution failed, out of bounds.")
- return (grid, w, h)
- def grid_to_ascii(grid, width, height):
- text = []
- for row in range(height):
- for col in range(width):
- index = (row*height)+col
- if grid[index]:
- text.append('#')
- else:
- text.append(' ')
- text.append('\n')
- return "".join(text)
- if __name__ == '__main__':
- import sys
- if len(sys.argv) <= 1:
- print("Arguments: file [file2 ... fileN] or <NO_FILE> <TEXT>")
- sys.exit(1)
- executeArgv = False
- if sys.argv[1] == "<NO_FILE>":
- executeArgv = True
- if executeArgv:
- text = " ".join(sys.argv[2:])
- result = execute(text)
- print("Output Data:")
- print(result)
- print("Rasterization:")
- print(grid_to_ascii(*result))
- sys.exit(0)
- for file in [open(filename) for filename in sys.argv[1:]]:
- text = file.read()
- file.close()
- result = execute(text)
- print("Output Data:")
- print(result)
- print("Rasterization:")
- print(grid_to_ascii(*result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement