Find the odd int
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
Example
test.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)
test.assert_equals(find_it([1,1,2,-2,5,2,4,4,-1,-2,5]), -1);
test.assert_equals(find_it([20,1,1,2,2,3,3,5,5,4,20,4,5]), 5);
test.assert_equals(find_it([10]), 10);
test.assert_equals(find_it([1,1,1,1,1,1,10,1,1,1,1]), 10);
test.assert_equals(find_it([5,4,3,2,1,5,4,3,2,10,10]), 1);
Algorithm analysis
输入:有序数组
输出:数组中出现次数为奇数的对应的数
算法中对数据元素的操作主要是计数,然后加个奇数条件判断。初步考虑用循环遍历返回。那个值取值来自于有序数组,那是个列表。可迭代的对象都可用用生成表达式。
Algorithm details
- 对第一个数据元素在有序序列中出现次数进计数并判断是否为奇数;
- 是则结束算法,输出这个元素;
- 否则进入1,直至结束输出当下元素。
Code
def find_it(seq):
for i in seq:
if seq.count(i) % 2 != 0:#求余为0,即为偶数;这里是不等于,所以为奇数。
#计数函数obj.count(sub(对象的子集), start=索引1,ending=索引2),
#函数功能是返回对象子集出现的次数,索引1为开始的索引位置,索引2为结束的索引位置
return i
or
def find_it(seq):
return [i for i in seq if seq.count(i)%2 != 0][0]#列表生成式:
#[i(新生成的函数表达式,这里是本身所以取i) for i in 序列名][返回新列表索引]
#返回生成列表索引位置对应的值
Thanks for reading
题目来源:www.codewars.com