Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • AB Check in Python
    I'm writing the code for the "AB Check" Challenge, and I'm wondering why this won't work:
    def ABCheck(str): 
      for i in range(len(str)):
        if str[i] == "a" and str[i + 3] == "b":
          return "true"
      return "false"
    
    print ABCheck(raw_input())
    
    Thanks in advance!
    KnightOfNi asked this question on 11/8/14 | python
    Answers
  • +
  • 1
  • -
  • First of all, you have a fault in checking the distance between letters 'a' and 'b'. You actually check the third letter from letter 'a' instead the fourth. Secondly, you only check if a letter is 'a' and the other one 'b', where you should also check if the first letter is 'b' and the other one 'a'. Finally, you should take serious caution when dealing with arrays like this: str[ i + 3 ] since that +3 addition can point 'outside' the array. For example, if u have a string str="abc" and 'i' equals 2, then the code str[i+3] would actually become str[5] and now you can clearly see that you're gonna have an error.
    def ABCheck(str): 
      for i in range(len(str)):
        try:
          if str[i] == "a" and str[i + 4] == "b":
            return "true"
          elif str[i] == "b" and str[i + 4] == "a":
            return "true"
        except:
          return "false"
      return "false"
    
    print ABCheck(raw_input())
  • +
  • 0
  • -
  • The following is my code. When I test it locally, every single test case passes without problems. But none of those test cases work inside Coder Byte. Is it a compiler issue?
    import math
    
    class AB:
        def __init__(self):
            self.array = []
            self.outcome = False
        def ABCheck(self, str):
            a_index = []
            b_index = []
            str = str.lower()
            self.array = list(str)
            for i in range(len(self.array)):
                if self.array[i] == 'a':
                    a_index.append(self.array.index('a'))
                    self.array[i] = '0'
                if self.array[i] == 'b':
                    b_index.append(self.array.index('b'))
                    self.array[i] = '0'
            
            for i in a_index:
                for j in b_index:
                    if math.fabs(i - j) == 4:
                        self.outcome = True
                        break
                    else:
                        continue
            
            return self.outcome
            
    obj = AB()
    print obj.ABCheck(raw_input())
    
  • +
  • 0
  • -
  • This code would fail on all three of the following inputs, each for a different reason. Bug 1: "a123b" Bug 2: "b123a" Bug 3: "a123" I know that doesn't answer your question, but perhaps by analyzing those inputs, you can answer your own question.
    Login to write an answer