Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Equivalent to Javascript index assignment

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading