im working on a python script that takes an array and rotates it, but i've been having the same problem. This is the code:
def parse(string):
string += " "
a = 0
arr = []
arrI = 0
for i in range(1, len(string)):
if string[i] == " ":
arr.append("")
for j in range(a, i):
arr[len(arr) - 1] += string[j]
a = i
return(arr)
a = parse(input())
N = int(a[0])
K = int(a[1])
array = parse(input())
temp = array
array[0] = temp[N - 1]
for i in range(1, N - 1):
array[i] = temp[i - 1]
print(array)
Keep in mind that N is the amount of integers in the array and I haven't used K yet, so ignore it. For the inputs I do N = 5 and array = 1, 2, 3, 4, 5. I expect to get 5 1 2 3 4 but instead get 5 5 5 5 5. I eventually found out that temp was changing even when I never told it to. When I add prints,
print(temp)
array[0] = temp[N - 1]
print(temp)
I am surprised to find that the two prints had different answers, even when I never told temp to change, just array.
I made a temp because if I changed one part of array, I can't use it later. Then, I tried a second layer, where
temp1 = answer
temp = temp1
and in the for loop at the endtemp = temp1
Same answer. Next, I thought maybe I could make a separate variable containing the number I want, so it can not be traced back to temp.So, instead of array[i] = temp[i - 1]
, I did
item = temp[i - 1]
array[i] = item
Nothing changes. Also, I'm not asking for how to rotate an array, im asking how to fix this problem. Thank you.