-1

Im trying to write a function where it accepts the various arrays and adds the total of the odd numbers. Then if the total is correct it returns "TEST PASSED" but i cannot complete the code. the code is:

def odd_ones(array):
  total = 0
  for i in range(0,len(array)-1):
    if array[i] % 2 != 0:
      total += array[i]
      print(total)
    else:
      print("no odd numbers detected")



def test_odd_ones():
  print("Odd Ones Unit Test...")
  print("")
  if odd_ones([1,2,3,4,5,6,7,8,9]) == 25:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([3,3,1,1,5,5]) == 18:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([2,4,6,10,20]) == 0:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([]) == "Empty Array":
    print("TEST PASSED")
  else:
    print("TEST FAIL

1 Answers1

1

Here you should use range(0, len(array)) because range iterates upto n-1. You should return total from the function so that it can be used while calling the function.

def odd_ones(array):
  if len(array) == 0:
    return "Empty Array"
  total = 0
  for i in range(0,len(array)):
    if array[i] % 2 != 0:
      total += array[i]
  return total


def test_odd_ones():
  print("Odd Ones Unit Test...")
  print("")
  if odd_ones([1,2,3,4,5,6,7,8,9]) == 25:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([3,3,1,1,5,5]) == 18:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([2,4,6,10,20]) == 0:
    print("TEST PASSED")
  else:
    print("TEST FAILED")
  if odd_ones([]) == "Empty Array":
    print("TEST PASSED")
  else:
    print("TEST FAILED")
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25