Kata Daily 190923Odder Than the Rest(找出奇数)
Posted bcaixl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kata Daily 190923Odder 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进行相不相等来判断
以上是关于Kata Daily 190923Odder Than the Rest(找出奇数)的主要内容,如果未能解决你的问题,请参考以下文章
Kata Daily 190917Numericals of a String(字符出现的次数)
Kata Daily 191012Find numbers which are divisible by given number