Back to General discussions forum
I'm using Python to solve problem 27#, bubble sort. My variable original_data changes despite seemingly not being modified by the code. Here's how it looks like:
with open("data.txt", "r") as f:
data = f.read().split() #take input data from the file
length = int(data.pop(0))
print("input data is: ",data)
print()
swaps_count = 0
finished = False
while finished == False:
original_data = data #make a copy of input data for later comparison
print("original data is: ",original_data)
result = ""
for n in range(length):
a,b = data[:2]
if len(data) == 2:
result += min(data) + " "
result += max(data) + " "
break
elif int(a) < int(b):
result += a + " "
data = data[1:]
else:
swaps_count += 1
result += b + " "
data[1] = a
data = data[1:]
result = result.split()
print("the result is: ",result)
if result == original_data: #if sorting is complete
finished = True #break out of while loop
print("finished!")
break
else: #if sorting is not finished
print("old data is: ",original_data)
data = result #start over
print("new data is: ",data)
both data and original_data are the same at the start: ['3', '1', '4', '1', '5', '9', '2', '6']. When I run the code and compare the result of the sorting loop with original_data to determine if the sorting is finished, original_data suddenly looks different: ['3', '3', '4', '1', '5', '9', '2', '6'], and I have no idea why.
Edit: I edited the code a bit so it doesn't run forever, but the original problem with a variable changing for no reason still exists.
Be warned, the while loop doesn't work properly because of the problem, it will run forever.
I fixed the original formatting but I can't delete this comment.
original_data changes despite seemingly not being modified by the code
I think it's because original_data
and data
point to the same array in memory. To avoid it, you have to clone data
.
You must be right. I tested it with this:
a = [1,2,3]
b = a
b.append(4)
print(a)
and appending b changes a. I thought it would be a copy and not reference to previous variable. I had that topic in my udemy course but it was long time ago. I will use that info to fix it.
Thx
A handy shortcut in Python is that, for lists, a = b
sets a
to point at b
, while a = b[:]
sets a
as a copy of b
.
I think I prefer .copy(), as then you can easily see what it does, when [:] looks obscure.