-1

I'm trying to create a list-like ADT that holds instances of another ADT. I've been using "None" in other cases but I don't have any use for "None" checks in this so I'm trying not to use that.

myList = [MyAdt()] * 10

So basically it's creating this instance and multiplying that one 10 times. Any ideas as to how I can tweak so it creates new instances?

** I'll give you the ADTs if you want but I don't think they're relevant. **

WeirdGuy
  • 13
  • 9
  • You want a list of ten instances of `MyAdt` class? – DjaouadNM Mar 10 '19 at 16:40
  • Yeah, but then I loose the O(1) time complexity. Thanks for the pointer thou, I'll have that as a backup! – WeirdGuy Mar 10 '19 at 16:41
  • You tweak it by *not* doing list multiplication. See https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – jonrsharpe Mar 10 '19 at 16:42
  • 1
    `[MyAdt()] * 10` isn't O(1) to begin with; it's still O(*n*), because you have to populate a list with 10 references; the fact that they are references to the same object is irrelevant. – chepner Mar 10 '19 at 16:48
  • Thanks for the pointers, I just figured list.append is O(1) while my "10" was better explained as "n" all along. Guess I'll just blame it on sleep deprivation to make myself feel better. ;) – WeirdGuy Mar 10 '19 at 17:05

3 Answers3

0

Creating a list of 10 instances of MyAdt rather than 10 variables pointing to one instance can be done using:

myList = [MyAdt() for i in range(10)]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

You want something like

my_list = [MyAdt() for _ in range(10)]

to create 10 distinct instances of MyAdt() for my_list.


As an aside, your original code was still O(n), despite reusing the same reference for each element of the list. The fact that it is written using a single * operation doesn't change that; in this case, * itself is not an O(1) operation. Its operands are list and an int, making it a completely different function than the one evaluated when both operands are numeric types.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

I don't know what O(1) means to you, but if it means the same as it does for me it means constant compared to the number of ADTs instances you want to build. If that's correct then that's just impossible. By definition your "complexity" is in Theta(n).

Now how to instantiate properly is another question, but here is one possible answer:

class MyAdt:
  count = 0
  def __init__(self):
    self.a = MyAdt.count
    MyAdt.count += 1
  def __repr__(self):
    return str(self.a)

lists_size = 10

myList = [MyAdt()] * lists_size
print(myList)

myList = [MyAdt() for _ in range(lists_size)]
print(myList)

Which prints:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]  # 10 refs to the same instance
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 10 distinct instances

Note that the 1st item of the second list prints "1" because it's the second instance we create, not the first.

cglacet
  • 8,873
  • 4
  • 45
  • 60