B.Joelene
B.Joelene

Reputation: 133

Checking the same elements in a list : python

Hey there i'm so new in coding and i want make program comparing two lists elements and returning the same elements in them. so far i writed this code but i'm having problem with algoritm because it is set operation and i can't find actual same elements with intersection function.

in my code i want to look for each string and finding similarity of them. what i've tried to do is :

    input="AGA"
    input1="ACA"
    input=input_a
    if len(input1) == len(input):
        i = 0
        while i < len(input1):
            j = 0
            while j < len(input_a):
                input_length = list(input_a)
                if input1[i] != input_a[j]:
                    if input1[i] in input_a:
                        print "1st %s" % input_length
                        print "2nd %s" % set(input1)
                        intersection = set(DNA_input_length).intersection(set(input1))
                        print intersection
                        total = len(intersection)
                        print (float(total) / float(
                            len(input1))) * 100, "is the similarity percentage"
                        break

                    DNA_input_length.remove(input_a[i])
                j = j + 1
            break

what is wrong with my code is actually the intersection part i guess and i want to see as common elements which are included each list for input and input1 = A,A (2 A's both) however, i get just one A.. How can i improve this code to evaluating common elements which is Two A not one. I really need your help..

Upvotes: 0

Views: 56

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114038

I would define similarity as the the hamming distance between the words (which I think is what you want

word1 = "AGA"
word2 = "ACAT"
score = sum(a==b for a,b in zip(word1,word2)) + abs(len(word1)-len(word2))

Upvotes: 2

Felk
Felk

Reputation: 8224

If you just need to find the intersecting elements of 2 flat lists, do:

a = "AGA"
b = "ACA"
c = set(a) & set(b)
print(c)
> {'A'}

Upvotes: 0

Related Questions