0

Find the same value in two lists, e.g:

 A = [4,7,1,9]
 B = [5,8,7,2,4] 

Below is my code, but I can't find what's wrong:

def samevalue(self, A, B):
    A = [4,7,1,9]
    B = [5,8,7,2,4]
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                return A[i]
            else:
                return ValueError("there is no same value")
Booboo
  • 38,656
  • 3
  • 37
  • 60
Tata Fu
  • 3
  • 2
  • Can you format the code so I can have a better look at it? – NduJay Oct 25 '19 at 12:07
  • I have put an answer for you. If it is helpful you can press the tick under the arrows by the answer to accept it. Hope it helps and welcome to stackoverflow. – NduJay Oct 25 '19 at 12:12
  • @Tata Fu, can you provide the exact output you want? Do you want the first match or the intersection of the lists? – hsin1.att214 Oct 25 '19 at 12:48
  • 1
    Your function takes parameters `A` and `B` yet you ignore them and assign values to them. Why? Also, you define a parameter `self`, which is normally done when the function is a method belonging to a class definition. It serves no purpose here. – Booboo Oct 25 '19 at 12:50
  • Possible duplicate of [First common element from two lists](https://stackoverflow.com/questions/16118621/first-common-element-from-two-lists) – benvc Oct 25 '19 at 14:49

7 Answers7

2

You need to return ValueError after you have checked all the combinations and hence, the return statement should be outside of the for-loops.

def samevalue(self, A, B):
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                return A[i]
    return ValueError("there is no same value")
hsin1.att214
  • 118
  • 4
0

It should work perfectly with this. Make sure you return ValueError if there are no same values.

def samevalue(self, A, B):
    A = [4,7,1,9]
    B = [5,8,7,2,4]
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                return A[i]
    return ValueError("there is no same value")

You could try this too

A = [4, 7, 1, 9]
B = [5, 8, 7, 2, 4]
for n in A:
    if n in B:
        print(n)
Booboo
  • 38,656
  • 3
  • 37
  • 60
NduJay
  • 760
  • 1
  • 10
  • 23
0
def samevalue(self, A, B):
    raiseerror = True
    A = [4,7,1,9]
    B = [5,8,7,2,4]
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                yield A[i]
                raiseerror = False
    if raiseerror:
        return ValueError("there is no same value")

will be better, as it return all same value. For improve:

A = [4, 7, 1, 9]
B = [5, 8, 7, 2, 4]
raise_error = True
for n in A:
    if n in B:
        print(n)
        raise_error = False
assert (not raise_error)

okie
  • 847
  • 6
  • 18
  • Neither "solution" does what the OP wants: The first solution does not return a value because it is a generator function (the OP presumably only wanted to return one value) and the second solution raises an `AssertionError` rather than a `ValueError`. – Booboo Oct 25 '19 at 12:58
0

The problem with your code is that you are returning from the else condition from inside the loops. So, the code will return a ValueError for the first mismatch, which is not what you want to do. Instead, you should let the loops finish so that you can be sure that you have checked each and every items in both the list. And if the loops have finished and no values are returned, this means that there were no matching values, which is when you raise and Error.

def samevalue():
    A = [4,7,1,9]
    B = [5,8,7,2,4]
    for a in A:
        for b in B:
            if a == b:
                return a

    return ValueError("there is no same value")
0

Your function takes parameters A and B yet you ignore them and assign values to them. Why? Also, you define a parameter self, which is normally done when the function is a method belonging to a class definition. It serves no purpose here.

As been pointed out, you need to move return ValueError("there is no same value") out of the loop and execute it only after you have tested all values in A against all values in B:

def samevalue(A, B):
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                return A[i]
    return ValueError("there is no same value")

print(samevalue([4,7,1,9], [5,8,7,2,4]))

Prints:

4

Or (more efficient):

def samevalue(A, B):
    for a in A:
        if a in B:
            return a
    return ValueError("there is no same value")

Or (most efficient for large lists):

def samevalue(A, B):
    seta = set(A)
    setb = set(B)
    setc = seta & setb
    if not setc:
        return ValueError("there is no same value")
    return setc.pop()
Booboo
  • 38,656
  • 3
  • 37
  • 60
0
#!/bin/python

#maybe you want this.
def samevalue_v1(A, B):
    C = []
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                C.append(A[i])
            else:
                continue
    return C

#and maybe a little performance improvements after the list sorted.
def samevalue_v2(A, B):
    C = []
    A = sorted(A)
    B = sorted(B)
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] == B[j]:
                C.append(A[i])
            else:
                continue
    return C

#and maybe this is a better solution.
def samevalue_v3(A, B):
    C = []
    A = sorted(A)
    B = sorted(B)
    i = j = 0
    while i<len(A) and j<len(B):
        if A[i] < B[j]:
            i += 1
        elif A[i] > B[j]:
            j += 1
        else:
            C.append(A[i])
            i += 1
            j += 1
    return C

A = [4, 7, 1, 9]
B = [5, 8, 7, 2, 4]
print(samevalue_v1(A, B))
print(samevalue_v2(A, B))
print(samevalue_v3(A, B))
meyao
  • 1
  • 2
0

first why not iterate over each element on your lists? usin for item in list

but you can make simple, using filter function to find into the list and get you want:

A = [4,7,1,9]
B = [5,8,7,2,4]

in_both = list(filter(lambda a: a in B, A))

it works for me.

juancarlos
  • 593
  • 3
  • 9