# -*-coding:utf-8-*- # Python2.7 __author__ = 'LL_YING' # 找出一组数中只出现一次的元素。注:其它元素都出现过两次。 class Solution(): def singleNumber(self, A): ''' :param A:a list of integer :return:integer ''' return reduce(lambda x,y:x^y, A) print Solution().singleNumber((1,2,3,4,3,2,1)) ''' 数组中只出现一次的元素其余的都出现过两次,使用XOR(异或)就很好解决。 XOR:相同为0,不同为1,这样将数组中的相同的数字异或之后,剩余的数字 就是那个单个的数字。异或运算之间可以互相交换,所以异或的顺序与结果无 关。 Python的reduce()方法: reduce(function, iterable[, initializer])第一个参数为调用的函数,参 数二为迭代对象,第三个为可选参数,初始值。函数的作用是参数iterable中的 item顺序迭代调用function。 例: def add(x,y): return x + y >>> reduce(add, range(1, 11)) 55 >>> reduce(add, range(1, 11), 20) 75 Python中实现异或为:^ 由上面的知识很容易可以解决这个看似复杂的问题。 再学习reduce时候遇见几个和reduce类似的方法: 1、filter(function, iterable) 对iterable中的item依次执行function(item),将执行结果为True的返回。类型 取决于iterable的类型,如果为string或者元组,则返回相同,此外都为列表。如 果function为None,则iterable的所有item都为False,删除所有元素。 例: >>> def f(x): return x % 2 != 0 and x % 3 != 0 >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] >>> def f(x): return x != 'a' >>> filter(f, "abcdef") 'bcdef 2、map(function, iterable, ...) iterable中的item依次执行function(item),返回结果为列表。支持多个iterable, 需要function具有相应数量的参数支持。 例: >>> def cube(x): return x*x*x >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] >>> def add(x, y): return x+y >>> map(add, range(8), range(8)) [0, 2, 4, 6, 8, 10, 12, 14] '''