I am trying to permute an array based on values from another array. A = [5, 6, 7, 8] P = [1, 3 ,2, 0] Should return [6, 8, 7, 5]
I have the below code written in python. I wanted to see if this is an acceptable approach to this problem or if there are better ways to solve this problem
def permute(A, P):
for i in range(len(P)):
if i != P[i]:
if int(P[P[i]]) >= 0:
if A[i]>0:
A[i], P[i]=A[P[i]], -A[i]
else:
A[i], P[i] = A[P[i]], f"{A[i]}"
else:
if isinstance(P[P[i]],int):
A[i], P[i] = -P[P[i]], -A[i]
else:
A[i], P[i] = int(P[P[i]]), f"{A[i]}"
return(A)
I store the original value from A as a negative value in P so i can retrieve it back by changing the sign. However I am doing a string convert if the value in the original array is negative to keep a track of when the values are negative vs when i store them as negative in P.
This code works but looking for ideas on if this can be done in a much cleaner way
[A[i] for i in P ]would be a bit easier.