I have the following code:
class MyClass:
def __init__(self):
self.w = 2
self.h = 2
self.table = []
def add_item(self, x, y, string_value):
table0 = self.table
if x >= self.w:
self.w = x + 1
if y >= self.h:
self.h = y + 1
self.table = [['foo' for h in range(self.h)] for w in range(self.w)]
for i in range(0, len(table0)):
for j in range(0, len(table0[i])):
self.table[i][j] = table0[i][j]
self.table[x][y] = string_value
def main():
c = MyClass()
c.add_item(7, 0, 'May')
c.add_item(0, 5, 'June')
c.add_item(2, 3, 'January')
if __name__ == "__main__":
main()
This code takes the coordinates from the user to add a cell with a specific value to the table. To do so, if the coordinates are greater than the current table's dimension, then table's dimension will be updated accordingly. I have two questions:
- There is a nested loop in the add_item function to copy the previous content into the updated table. In terms of time complexity, isn't there a more efficient way to do that?
- Each time when the table is updated, the previous content is still in the memory without being assigned to any variable, so how do I get rid of it? I know there is Garbage Collector interface in python, but I never used it before, if this is the correct way, how do I use it?
Thanks.