【Kata Daily 190923】Odder Than the Rest(找出奇数)
题目:
Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located.
This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output -1
.
Examples:
odd_one([2,4,6,7,10]) # => 3
odd_one([2,16,98,10,13,78]) # => 4
odd_one([4,-8,98,-12,-7,90,100]) # => 4
odd_one([2,4,6,8]) # => -1
题目大意:给定一个list,找出唯一的那个奇数的位置
解法:
def odd_one(arr): # Code here for x in arr: if x%2: return arr.index(x) return -1
看一下另外的解法:
def odd_one(arr): for i in range(len(arr)): if arr[i] % 2 != 0: return i return -1
知识点:
1、获取list的索引,可以使用index的方法,也可以使用arr[i]通过获取i的值来获取
2、判断是否为奇数偶数时,可以使用if x%2来判断或者和0进行相不相等来判断