-3

This is my code for copying data from the old stack to the new stack then enqueue them to the queue

for word in dictionary:
            if len(word) == len(lastWord):  #Make sure same len
                if (oneLetterDiff(word, dequeuedStack.peek())) == True and (word in dequeuedStack._data) == False: #One letter difference
                    s = MyStack()
                    print 'before %s' % dequeuedStack._data
                    s.copyFrom(dequeuedStack) #Copy stack over
                    s.push(word) #Add new word
                    print 'after %s' % s._data
                    q.enqueue(s) #Enqueue the stack
                    print 'after copying %s' % dequeuedStack._data
                    print word

This is the code for copying the list

def copyFrom(self, aStack):
    self._data = aStack._data

And this is to append it to the queue

def enqueue(self, value):
    self._data.append(value)

However, dequeuedStack._data was changed without me calling any methods to modify it

This is an example of the output

['stone', 'atone']
before ['stone', 'atone']
after ['stone', 'atone', 'alone']
after copying ['stone', 'atone', 'alone']
alone
before ['stone', 'atone', 'alone']
after ['stone', 'atone', 'alone', 'clone']
after copying ['stone', 'atone', 'alone', 'clone']
clone
leongwq
  • 191
  • 1
  • 12
  • 5
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Chris_Rands Jan 18 '18 at 10:18

2 Answers2

2

Dictionaries in Python are references. This means that when you do self._data = aStack._data, you're actually making both dictionaries the same reference, instead of actually making a new dictionary and copying values to it.

To deep copy, try the following:

import copy

...

def copyFrom(self, aStack):
    self._data = copy.deepcopy(aStack)
  • 3
    If I'm allowed to be picky, the statement "Dictionaries in Python are passed by reference" is wrong. Everything in Python is "passed by value", it just happens to be that this value is a reference to an object. See [this](https://stackoverflow.com/questions/534375/passing-values-in-python) – DeepSpace Jan 18 '18 at 10:27
  • 1
    @DeepSpace sure, that's fair. I'll update the answer. Thank you! – Pedro von Hertwig Batista Jan 18 '18 at 10:32
0

Changed my method for copying to list to self._data = aStack._data[:] and it works

leongwq
  • 191
  • 1
  • 12