2017年2月13日 星期一

【Python】Codility in Python : Lesson 2 - Arrays【OddOccurrencesInArray】

Arrays 練習題的第一題題目是【OddOccurrencesInArray】
Task : Find value that occurs in odd number of elements.

方法一:使用 XOR 的簡易方式

def solutionByXOR(A):
  result = 0
  for number in (A):
    result ^= number
  return result

方法二:使用 groupby 的簡易方式

def solutionByGroup(A):
  for k, v in groupby(sorted(A)):
    if(len(list(v)) == 1):
      return k
  return 0

方法三:使用排序後兩兩比較的檢查方式

def solutionByLoop(A):
  if(len(A) == 1):
    return A[0]
  else:
    sortedList = sorted(A)
    count = len(sortedList) - 1
    for i in range(0, count, 2):
      if sortedList[i] != sortedList[i+1]:
        return sortedList[i]
    return sortedList[count]

完整練習題 source code 請參閱:github

沒有留言:

張貼留言