码迷,mamicode.com
首页 > 其他好文 > 详细

【Kata Daily 190923】Odder Than the Rest(找出奇数)

时间:2019-09-23 18:30:14      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:class   index   相等   def   oca   dde   inpu   style   tput   

题目:

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 190923】Odder Than the Rest(找出奇数)

标签:class   index   相等   def   oca   dde   inpu   style   tput   

原文地址:https://www.cnblogs.com/bcaixl/p/11573614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!