0

Original code in JS:

// applying crossover
for (let i = cxpoint1; i < cxpoint2; i++) {
  let temp1 = ind1[i]
  let temp2 = ind2[i]

  ind1[i]         = temp2
  ind1[p1[temp2]] = temp1

  ind2[i]         = temp1
  ind2[p2[temp1]] = temp2

  return [ind1, ind2]

New to JS and wondering what is happening on this line:

ind1[p1[temp2]] = temp1

Trying to understand so I can make an equivalent function in Python.

I understand the assignment, however obviously in Python you cannot use double brackets as shown on the line above. If someone could tell me the concept, I should be able to apply it to my situation.

Thanks in advance.

4
  • 3
    why you cannot use double brackets in python? if you have that temp2 = 1 p1 = [2,3,4] and you do ind1[p1[temp2]] = temp1 this will be equivalent of doing ind1[p1[1]] = temp1 which will be equivalent of doing ind1[3] = temp1 Commented Jul 1, 2022 at 15:12
  • What python code have you tried? What results did you get? Commented Jul 1, 2022 at 15:13
  • on that line you are just taking index from p1 array and updfdating that index value to temp1 Commented Jul 1, 2022 at 15:14
  • Hi mountainwater, questions like "what does this code do?" are not really within scope of this site. To get an answer for your question, provide a minimal example in JS that shows the desired behavior, and what you've tried in python that isn't working. Commented Jul 1, 2022 at 15:16

2 Answers 2

1

To fully understand the code one would need to know how the arrays p1 and p2 look like, but I assume they are integer-arrays. You select an integer from that array in the inner statement that then is the index for the outer statement.

It works exactly the same in python:

ind1 = [1, 2, 3, 4, 5]
p1 = [3, 1, 2]
print(ind1[p1[0]])
# -> 4

In this example the inner statement resolves to 3 (first element in the p1-list) and the outer statement then resolves to 4 (fourth element in the ind1-list.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, understood the concept now with this simple example. Thanks for your time and patience.
1

There's nothing magical going on here.

ind1[p1[temp2]]

p1[temp2] resolves to some value, let's call it a. So the expression then becomes ind1[a].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.