codewars练习(2)Find the unique number(逻辑问题)

There is an array with some numbers. All numbers are equal except for one. Try to find it!

findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55

def find_uniq(arr):
    # your code here
    a=[]
    b=[]
    j=1
    n=arr[0]
    for index,val in enumerate(arr):
      if index==0:
        a.append(val)
      if val in a:
        j+=1
        continue
      else:
        b.append(val)
    if j==1:
      n=a[0]
    else:
      n=b[0]
    return n   # n: unique integer in the array 

测试通过:

test.describe("Basic Tests")
test.assert_equals(find_uniq([ 1, 1, 1, 2, 1, 1 ]), 2)
test.assert_equals(find_uniq([ 0, 0, 0.55, 0, 0 ]), 0.55)
test.assert_equals(find_uniq([ 3, 10, 3, 3, 3 ]), 10)

提交以后报错

 Value = 1

1 should equal 0

在python环境下试了下

    find_uniq([0, 1,1,1,1])

输出的结果是1

原来是变量j初始化的问题,初始化j=1,   

  if index==0:
        a.append(val)
      if val in a:
        j+=1
        continue

这里,j就变成2了

这样输出的就是b[0]了

所以,修改为j=0

哈哈,通过

codewars练习(2)Find the unique number(逻辑问题)