Python习题:给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。(比如:给出 [1,2,2,1,3,4,3],返回 4)

方法一:使用列表的count()方法取出单独的数

1 def find_single(num_list):
2     for n in num_list:
3         if num_list.count(n) == 1:
4             return n
5 
6 print(find_single([1,2,2,1,3,4,3]))

方法二:使用异或方法,简单快速

1 def find_single(num_list):
2     EOR = 0
3     for n in num_list:
4         EOR =EOR^n
5     return EOR
6 
7 print(find_single([1,2,2,1,3,4,3]))

猜你喜欢

转载自www.cnblogs.com/felixqiang/p/10312042.html
今日推荐