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

Check to see if two lists have the same value at the same index, if so return the index. If not return -1

So basically I am trying to compare two lists to see if they hold the same value at the same index at any point. If they do I return the index, if they do not, I return -1.
`

Dlist = [17,13,10,6,2]
Ilist = [5,9,10,15,18]
def seqsearch(DS,IS):
    
    for i in range(len(DS)-1):
        found = False
        if DS[i] == IS[i]:
            answer = i
            found = True
            if found == True:
                print(f"Yes! Found at index =", answer)
            else:
                return print("No!\n-1")


print(seqsearch(Dlist,Ilist))

`

When I had first done this as a test I was having no issues however adding in the text has made it more difficult and my main issue is with the if else statement. I seem to be able to only get one message to work, either yes or no, not both based on the case.

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

>Solution :

You could loop over both lists like so:

Dlist = [17, 13, 10, 6, 2]
Ilist = [5, 9, 10, 15, 18]


def seqsearch(DS, IS):

    for index_1, element_1 in enumerate(DS):
        for index_2, element_2 in enumerate(IS):

            if (element_1 == element_2) and (index_1 == index_2):
                print(f"Yes! Found at index ={index_1}")
                return index_1
    print("No!")
    return -1


print(seqsearch(Dlist, Ilist))

However, there are more improvements you can make. zip() indeed is a better option, but slightly more complicated to understand.

Also, please note that return is not the same as print. You were not returning -1; you were printing it.

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