将厨房用品矩阵转换为ascii转换

2024-05-23 19:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我被问到了这个面试问题

在游戏中,我们必须将厨房物品的矩阵渲染成实际的图形。要做到这一点,你必须 给出表格中厨房物品的矩阵信息-

<height, width of room>
<item_type> <x position> <y position>

比如说

<2,2>
sugar 0,1
spoons 1,1

这相当于01时的糖和11时的1勺糖

生成ASCII转换糖(空白为空方块)

Blank Blank 
Sugar Spoon

假设没有内存溢出,则对arbit输入执行此操作

我对内容进行了循环,编写了for循环,但我的代码有错误。最好的方法是什么?创建一个字典或大小为NxN的文件,并在其上循环,然后放入空格或条目


Tags: of信息图形游戏typeposition矩阵item
3条回答

试试这个

t="""<2,2>
sugar 0,1
spoons 1,1"""

l = t.split('\n')

h, w = l[0].strip('>').strip('<').split(',')
kitchen = [['Blank']*int(w) for i in range(int(h))]

for line in l[1:]:
    item, location = line.split(' ')
    i, j = location.split(',')
    kitchen[int(j)][int(i)] = item
print(kitchen)

我认为这个问题没有具体的答案。但也许像这样的事情会很好:

In [10]: def get_board_size(): 
    ...:     return map(int, input().strip('<>').split(',')) 
    ...: 

In [11]: def arrange(w, h): 
    ...:     board = [['Blank' for _ in range(w)] for _ in range(h)] 
    ...:     while (inp := input()) != 'q': 
    ...:         text, coordinates = inp.split() 
    ...:         x, y = map(int, coordinates.split(',')) 
    ...:         board[x][y] = text 
    ...:     return board 
    ...: 

In [12]: def main(): 
    ...:     w, h = get_board_size() 
    ...:     board = arrange(w, h) 
    ...:     print('\n       Result       ') 
    ...:     for row in board: 
    ...:         print(' '.join(row)) 
    ...:         print() 
    ...: 

In [13]: main()
<2,2>
Sugar 0,1
Spoon 1,1
q

       Result       
Blank Sugar

Blank Spoon

这是我的字典解决方案,
与矩阵表示法相比,使用roommatrix is sparse时效率更高,因为空单元格不会被保存。
但是,我已经将房间表示封装在一个对象中,因此可以更改表示,同时保持有用的方法完好无损。


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)

相关问题 更多 >