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

Pick position of a list based on the position of another list in Python

Im a Python beginner and also new to Stackoverflow cant seem to find a solution to this problem and I have been looking around in weeks. It’s an assignment and we cant use inbuild Python functions.

I want to find the position of an item in list A and choose the same position from list B. The item in list A should not be equal to zero. Once done, I have to add the corresponding value in B.
Eg:

A = [0,0,1,1]
B = [25,9,8,3]

A should result in position 2,3
B therefore equals to 8,3
8+3 = 11

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

Below is what I have tried so far

binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
    if binary[position] !=0:
        position = position+1
        print(position)

>Solution :

I think you got it. From your code, simply register the positions in the separate list that you created and then sum it up

binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
    if binary[position] !=0:
        output_decimal.append(decimal[position])
# to add everything
print(sum(output_decimal))

Output gives you: 16+8 = 24

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