<p>这是我的字典解决方案,<br/>
与矩阵表示法相比,使用room<a href="https://en.wikipedia.org/wiki/Sparse_matrix" rel="nofollow noreferrer">matrix is sparse</a>时效率更高,因为空单元格不会被保存。<br/>
但是,我已经将房间表示封装在一个对象中,因此可以更改表示,同时保持有用的方法完好无损。<br/></p>
<br/>
<pre><code>import re
input = \
"""
<2,2>
sugar 0,1
spoons 1,1
"""
class Room:
def __init__(self, height, width):
self.height = height
self.width = width
self.items = dict()
def add_item(self, item_type, x_position, y_position):
if x_position > self.height or y_position > self.width:
raise Exception(f'Invalid position ({x_position},{y_position}) for matrix size [{self.height},{self.width}]')
self.items[(x_position, y_position)] = item_type
def __str__(self):
BLANK_NAME = 'Blank'
SPACES_BETWEEN_CELLS = 2
str = ''
for y_position in range(self.width):
for x_position in range(self.height):
item_type = self.items.get((x_position, y_position), BLANK_NAME)
str += SPACES_BETWEEN_CELLS * ' ' + item_type.capitalize()
str += '\n'
return str
def parse_numbers_from_string(str, seperators=''):
return [int(s) for s in re.split(seperators, str) if s.isdigit()]
def parse_lines_from_string(str):
lines = str.split('\n')
return [x for x in lines if x]
def parse(input, seperators='\<|\>| |,'):
lines = parse_lines_from_string(input)
height, width = parse_numbers_from_string(lines[0], seperators)
room = Room(height, width)
for line_number in range(1, len(lines)):
item_type = lines[line_number].split()[0]
x_position, y_position = parse_numbers_from_string(lines[line_number], seperators)
room.add_item(item_type, x_position, y_position)
return room
if '__main__' == __name__:
room = parse(input)
print(room)
</code></pre>