编写了一段代码,如果至少有一个整数是偶数则返回 true,否则返回 false

时间:2021-05-01 20:11:41

标签: python

完整问题:编写一个函数 all,它同样以整数列表 l 作为参数。如果这些整数中至少有一个是偶数,它应该返回 True,否则返回 False。如果 l 为空,则返回值通常为 False。您的函数不应以任何方式修改列表参数。

我已经编写了代码,但它一直未能通过以下测试。不确定我哪里出错了,因为它适用于其他测试。
测试:

def test_ranges100(self):
        # All (except 1; all True)
        for n in range(2,101):
          arg = list(range(1, n+1))
          with self.assertUnmodified(arg):
            self.assertTrue(any(arg))

    # Odds (all False)
    for n in range(1, 101, 2):
      arg = list(range(1, n+1, 2))
      with self.assertUnmodified(arg):
        self.assertFalse(any(arg))

def test_simple(self):
    arg = [-5, -1, 10, 0, 1, 100]
    with self.assertUnmodified(arg):
      self.assertTrue(any(arg))
    arg = [-5, -1, 1, 101]
    with self.assertUnmodified(arg):
      self.assertFalse(any(arg))
    arg = [-10, 10, 0, -10, 10]
    with self.assertUnmodified(arg):
      self.assertTrue(any(arg))

这是我目前编写的代码:

def any(l):
  for i in l:
    if (i % 2 == 0):
      return True 
    else: 
      return False 

有人知道为什么我的代码无法通过上述测试吗?

2 个答案:

答案 0 :(得分:0)

您的代码只需要简单的修改:

def any(l):
  for i in l:
    if (i % 2 == 0):
      return True 
  return False

删除 else: 和取消缩进 return False 意味着:

  1. 当列表以奇数开头时,for 循环将继续查找偶数。
  2. 如果列表仅包含奇数,该函数将仅在末尾return False
  3. 当列表不包含任何元素时,该函数将return False

答案 1 :(得分:0)

听起来好像可以这样解决:

def exists_with_an_even(numbers):
    return any(x % 2 == 0 for x in numbers)

exists_with_an_even([1, 2, 3])
True

exists_with_an_even([])
False

exists_with_an_even([1, 3])
False

exists_with_an_even([5, -2, 1, 5, 7])
True
相关问题