-4

I don't understand how to re-use a list.

Here's the code:

brackets = ["(",")"]
char  = "abcdefghijklmnopqrstuvwyxz"
chars = list(char)
nums = ["0","1","2","3","4","5","6","7","8","9"]
newstrlist = []
memoryinbracket = []


def unpack(str):   
i = 0 
liststr = list(str)

while "(" in liststr:
    index = liststr.index("(")
    counter = 1
    i = index + 1
    while i <= len(liststr):
        item = liststr[i]
        if liststr[i] == ")":
            counter = counter - 1
            if counter > 0:
                memoryinbracket.append(item)
            else:
                break
        elif item == "(":
            memoryinbracket.append(item)
            counter = counter + 1
        else :
            memoryinbracket.append(item)
        i = i+1

    unpack(memoryinbracket)
    inbracket = newstrlist
    e = index
    if liststr[i+1] in nums:
        nr = int(liststr[i+1])
        newl = ''.join(inbracket)
        ch = (newl)*(nr-1)
        inbracket.append(ch)
        liststr.pop(i+1)
    while e<=i:
        liststr.pop(index)
        e = e+1
    liststr.insert(index,inbracket)
    **del newstrlist[:] ??????

newstrlist = []**
for i in range (len(liststr)):
    if liststr[i] in chars:
        newstrlist.append(liststr[i])
    if liststr[i] in nums:
        if liststr[i-1] in chars:
            if len(liststr)>i+1 and liststr[i+1] in nums:
                nr = int(liststr[i]+liststr[i+1])
                ch = liststr[i-1]*(nr-1)
                newstrlist.append(ch)
            elif liststr[i] == "0":
                newstrlist.remove(liststr[i-1])
            else:
                nr = int(liststr[i])
                ch = liststr[i-1]*(nr-1)
                newstrlist.append(ch)        

    i = i+1
i = 0    



def test_unpacks():         
unpack("a5(c3b)2ew")
unpack("a3bc2")
unpack("a10bc2")
unpack("a(bc)2d")
unpack("a(bc)d")
unpack("(a2)2")
unpack("a(b2c)d") 

test_unpacks()

I need to newstrlist to be cleared at some point, but inbracket not to change after newstrlist is re-used.

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
user3836013
  • 5
  • 1
  • 2
  • 4

2 Answers2

1

You should write

inbracket = list(newstrlist);

for the assignment, otherwise your lists will be pointers to the same actual element, and modifying newstrlist will modify inbracket.

0

Look to https://stackoverflow.com/a/850831/47351

Copy from answer of Koba:

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []
Community
  • 1
  • 1
RvdK
  • 19,580
  • 4
  • 64
  • 107