Home > front end >  When asked to write function for multiple of 3, why do i keep getting errors?
When asked to write function for multiple of 3, why do i keep getting errors?

Time:02-01

When I'm asked to write in my function a code to count the characters of a code but only if its a multiple of three, i keep getting stuck and i've tried so many times to figure it out but to no avail! This was the question: ...verifies that its length is a multiple of 3, and returns the number of codons in that string...

I tried this:

def countCodons(DNA):
  count = 0
  for num in DNA:
    if len(num) % 3 == 0:
      count  = 1
      return len(DNA)
    else:
      return False
assert countCodons("CATGGG") == 2
assert countCodons("CAATGGG") == False

But I keep getting an error. When i just put in "countCodons" I keep getting False.

CodePudding user response:

You are making this too complicated. The function needs to do two things:

  1. determine if the length of the input string is a multiple of 3
  2. if so, return the length of the input string divided by 3

You were right in assuming that you can use ... % 3 == 0 somehow but you were not applying it correctly. You don't need a for loop, which iterates over the individual characters in the string. Just apply it on the length of the string directly.

Regarding 2., even if you had managed to count the characters in the input string, you forgot to divide by 3.

Here's a straightforward solution:

def countCodons(DNA):
    if len(DNA) % 3 == 0:  # length is a multiple of 3
        return len(DNA) // 3
    else:
        return False

Note that // is used to return an integer result, rather than a floating-point result.

Alternatively you could use the divmod function which combines the integer division with remainder in one step:

def countCodons(DNA):
    count, remainder = divmod(len(DNA), 3)
    if remainder == 0:
        return count
    else:
        return False

CodePudding user response:

This assertion fails because the return statement is within the loop and only returns the length of the input string, not the count of codons. So, it will always return the length of the input string, even if there are no codons in the input string.

assert countCodons("CAATGGG") == False

This assertion succeeds because the first element in the input string is not a multiple of 3, so the function returns False.

To fix this issue, the return statement should be outside the loop and return the count of codons. Here's the corrected code:

def countCodons(DNA):
  count = 0
  for num in DNA:
    if len(num) % 3 == 0:
      count  = 1
  return count if count > 0 else False

This code will now correctly return the count of codons in the input string.

  • Related