Python中可以表示架子上项目的矩阵

时间:2018-08-08 20:20:14

标签: python matrix data-structures

我的问题很简单。 Python中是否有一个图书馆,该图书馆的数据结构可以代表货架上的物品?本质上,它将需要是一个矩阵,其中每行的长度相同,但每行中的项目长度可以不同。

这是一个视觉表示:

Diagram

3 个答案:

答案 0 :(得分:1)

这应该告诉您货架上是否有两个货架物品重叠(某种意义上是一个物品在另一个物品之上或之下)。...假设您知道货架物品在索引中的位置。

class Item(list):
    pass

shelves = [
    [Item([1, 2,        3,        4]) ,Item([5,          6 ])],
    [Item([7, 8]),Item([9]),Item([10,        11]), Item([12])]
]

# shelf items are indexed by two indices, shelf and item
def shelf_items_overlap(shelves, shelf1, item1, shelf2, item2):
    item1_real_index = sum(map(len, shelves[shelf1][:item1]))
    item2_real_index = sum(map(len, shelves[shelf2][:item2]))
    return range_overlaps(
         item2_real_index, item2_real_index + len(shelves[shelf2][item2]),
         item1_real_index, item1_real_index + len(shelves[shelf1][item1])
    )

def range_overlaps(x11,x12,x21,x22):
    ''' return if (x11, x12) overlaps (x21, x22) '''
    return x21<=x12<=x22 or x21<=x11<=x22 or x11<=x21<=x12 or x11<=x22<=x12

print(shelf_items_overlap(shelves, 0, 1, 1, 0), shelf_items_overlap(shelves, 0, 1, 1, 2)) 

答案 1 :(得分:1)

我认为您的问题应该比数组更好地使用类。我知道这也许不是您要查找的答案,但这是项目和shelf_rows的类实现的快速代码,可让您获取其在架子中的信息。

class Item ():
    # Init the item class with a lenght 
    def __init__(self, length, name = 'Item'):
        self.name = name
        self.length = length
    # Allow us to use the len method on item to get the length
    def __len__(self):
        return self.length
    # Show us a clear print of the Item
    def __repr__(self):
        return '%r of length (%r)' % (self.name,self.length)

class ShelfRow ():
    #Make a ShelfRow of a fixed length
    def __init__ (self, length):
        self.length = length
        self.space_left = length
        self.items = []
    #Use append like if it was a list
    def append (self,Item):
        if Item.length > self.space_left:
            return 'This should throw an error because the length is too long for the space left'
        else:
            self.items.append (Item)
            self.space_left = self.space_left - Item.length
    # Use the __getitem__ special method to get the position of an item
    def __getitem__(self,position):
        return self.items[position]
    #Print the content of items
    def __repr__(self):
        return '%r' % self.items

# Make three items
item_a = Item(4, 'Big Box')
item_b = Item(2, 'Medium Box')
item_c = Item(2, 'Medium Box')
item_d = Item(8, 'Super Big Box')

#Make a shelfRow
shelf_row1 = ShelfRow(8)
shelf_row2 = ShelfRow(8)

#Populate shelfs
shelf_row1.append(item_a)
shelf_row1.append(item_b)
shelf_row1.append(item_c)
shelf_row2.append(item_d)

#Make a shelf, it could be an object too (it should probably)
shelf = [shelf_row1,shelf_row2]

#Print what is in every shelf_row
for shelf_row in shelf:
    print(shelf_row)

另一个答案可能是最接近您想要的答案,但是我觉得也许您可以通过做一些抽象的事情来解决您的问题。

无论如何,我希望这是有用的。

答案 2 :(得分:0)

我不知道任何模块,但这似乎是传统的“使此数据结构”类型的问题。因此,这是您可以使用的基础,它看起来与其他问题类似,但这应该可以满足您的需求。它几乎是一种使用页面分配中使用的想法作为您的问题的实现,因为您需要框架包含一定数量的固定大小的页面。可以使用更好的算法(或添加过程)对其进行优化,但我忘记了我使用的算法,也不想实现更复杂的东西。

class Item:
    def set_width(self, width):
        self.width = width

    def get_width(self):
        return self.width

    def __init__(self, width=0):
        self.width = width

class Shelf:
    def add_item(self, item):
        if item.get_width() > self.max_width:
            print("Item will not fit in the shelf.")
            return False

        row = 0
        while (row < len(self.rows)):
            if (self.get_row_tot(row) + item.get_width()) <= self.max_width:
                self.rows[row].append(item)
                return True
            row += 1

        # Stop here, we want to prevent addition of a shelf
        if max_height != -1 and row >= max_height:
            print("Item will not fit in the shelf.")
            return False

        self.rows.append([item])
        return True

    def get_row_tot(self, row):
        tot = 0
        for i in self.rows[row]:
            tot += i.get_width()
        return tot


    def remove_item(self, row, item):
        if row < len(self.rows):
            self.rows[row].remove(item)
            return True
        else:
            print("Row does not exist")
            return False

    def __init__(self, max_width, max_height=-1):
        """
        max_height = -1 means no height limit
        """
        self.max_width = max_width
        self.max_height = max_height
        self.rows = []
        self.head = 0


a = Shelf(3)
b = Item(1)
c = Item(1)
d = Item(2)
e = Item(2)

a.add_item(b)
a.add_item(c)
a.add_item(d)
a.remove_item(0, c)
a.remove_item(2, e)
a.add_item(e)

就像我说的那样,可以对其进行优化,并且可以进行一些补充,例如交换,设置,搜索,排序等方法。您还可以将Item修改为正在使用的对象。