0

Alright, so I have a small issue:

def common(a,b,c):
    a.sort()
    b.sort()
    c.sort()
    i = 0
    j = 0
    k = 0
    common=False
    while i<len(a) and j<len(b):
        if a[i] == b[j]:
            if b[j] == c[k]:
                return True
            else:
                k = k+1
                continue
        else:
            if i == len(a):
                j = j+1
            else:
                i = i+1
    return common
a=[3, 1, 5, 10]
b=[4, 2, 6, 1]
c=[5, 3, 1, 7]
print common(a,b,c)

Basically, it has to tell me if there are common elements in the lists. With 1 it works, but if I replace the 1's with 8's, it doesn't work anymore.

nsnro
  • 5
  • 2

3 Answers3

2

Your 'j' never increase, 1 is working because after sort it is the 1st element and doesn't need j to be increased.

My suggestion is convert your lists to sets and check the common elements using intersection(&)

def common(a,b,c):
    common = set(a) & set(b) & set(c)
    return True if common else False


a=[3, 8, 5, 10]
b=[4, 2, 6, 8]
c=[5, 3, 8, 7]
print common(a,b,c)
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

Your current algorithm only works if the smallest value in the b list is common to the other lists. If there's a different common value, you'll never find it, because you'll increment i until it is len(a), then quit.

I think you need to change your logic so that you increment the index of the list that points at the smallest value. If a[i] is less than b[j], you need to increment i. If c[k] is less still, you should increment it instead.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

What you've programmed is not doing at all what you expect, so you need to rethink your logic. If you look at your loop, you first check if a[0] matches b[0]. Nope, so add to i. Then you compare a[1] to b[0], nope and so on. If nothing matches b[0], you exit the loop without ever checking the other elements of b. It works with 1's in your lists because after you sort, those happen to be in the first position in all three lists.

In any case, this is pretty clunky. There's a much easier way of doing this via set intersection. See this related question.

Community
  • 1
  • 1
alaferg
  • 233
  • 2
  • 10