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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010082526/article/details/84953450

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

哈哈,通过

别人的:

【1】def find_uniq(arr): a, b = set(arr) return a if arr.count(a) == 1 else b

【2】def find_uniq(arr): s = set(arr) for e in s: if arr.count(e) == 1: return e

【3】def find_uniq(arr): a = sorted(arr) return a[0] if a[0] != a[1] else a[-1]

【4】from collections import Counter

       def find_uniq(arr): return next(k for k,v in Counter(arr).items() if v == 1)

【5】def find_uniq(a): return Counter(a).most_common()[-1][0]

猜你喜欢

转载自blog.csdn.net/u010082526/article/details/84953450