Coding Bat: Python. String-2

All solutions were successfully tested on 18 April 2013.

double_char:

def double_char(str):
  result = ''
  for char in str:
    result += char * 2
  return result

count_hi:

def count_hi(str):
  count = 0
  for i in range(len(str)-1):
    if str[i:i+2] == 'hi':
      count += 1
  return count

cat_dog:

def cat_dog(str):
  count_cat = 0
  count_dog = 0
  for i in range(len(str)-2):
    if str[i:i+3] == 'dog':
      count_dog += 1
    if str[i:i+3] == 'cat':
      count_cat += 1
  
  return count_cat == count_dog

count_code:

def count_code(str):
  count = 0
  for i in range(0, len(str)-3):
    if str[i:i+2] == 'co' and str[i+3] == 'e':
      count += 1
  return count

end_other:

def end_other(a, b):
  a = a.lower()
  b = b.lower()
  #return (b.endswith(a) or a.endswith(b))
  return a[-(len(b)):] == b or a == b[-(len(a)):] 

Either way is fine.

xyz_there:

def xyz_there(str):
  for i in range(len(str)):
    if str[i] != '.' and str[i+1:i+4] == 'xyz':
      return True
  if str[0:3] == 'xyz':
    return True
  return False

26 thoughts on “Coding Bat: Python. String-2

  1. Philip

    For ‘cat_dog’, would you criticize this solution:

    def cat_dog(str):
    if str.count('cat') == str.count('dog'):
    return True
    else:
    return False

    Reply
    1. Gregor Ulm Post author

      The Java String class does not have a method named count(), so your code wouldn’t work. However, assuming such a method exists, and does what you intend it to do, you could simply write “return str.count(‘cat’) == str.count(‘dog’)”.

      Reply
      1. Philip

        Hmm, well I replied to your Python solutions–not the Java ones. Rather, my question centers around the usefulness of using Python’s built-in list methods, as opposed to writing something more ‘verbose’. After perusing your blog articles it seems that you have opinions about most things computer science-related, so I thought I would ask what you thought.

        Reply
        1. Gregor Ulm Post author

          Please excuse the oversight. Yes, the String class in Python does have a method named count. In the real world you would normally use that method instead of rolling your own. However, the point of the Coding Bat exercises is to teach you basic programming skills, i.e. programmatic thinking, which is why Nick Parlante didn’t include the count() method in his overview of strings in Python.

          Reply
  2. Adelani

    def count_hi(str):
    count = 0
    for i in range(len(str)): #I didn’t use “len(str)-1” here.
    if str[i:i+2] == ‘hi’:
    count += 1
    return count

    Hi Gregor, I just had a quick question the code i just posted above also works for the count “hi” function. However, I noticed that you used len(str) -1. Can you please explain why the -1 would matter? I just want to have a clear understanding.

    Reply
    1. Gregor Ulm Post author

      Have a look at the subsequent if-statements, and think about how they relate to the variable i being iterated in the for-loop.

      Reply
  3. MakuZo

    I know it’s an old topic, but last exercise could be shortened to that:
    def xyz_there(str):
    return str.count(‘xyz’) > str.count(‘.xyz’)

    Reply
    1. Python007

      Can you please explain in case value of both xyz and .xyz is 1, as in string “.xyzxyz” then why does it still return True?

      Reply
  4. logan

    Hey guys, I sometimes understand why this is the case, but in other situations..I don’t. When it comes to seeing if a string starts with a certain sequence of letters, I understand why it is done. But for the example count_hi and cat dog, I would appreciate some help!

    why is it that you do
    for i in range(len(str) – 2): or (-1) in the other case?

    I know we are looking for the string ‘hi’, so why subtract one from the string? Is it because the last index is omitted in the range(len), so we only need to subtract 1 to get to -2?

    Same with the -2 for cat dog, is this the same reason? -2 off of a string with the last character already omitted is -3 (the len of string cat or dog)?

    Thanks!

    Reply
  5. Jack G

    def xyz_there(str):
    if ‘.xyz’ in str:
    str = str.replace(‘.xyz’, “”)
    if ‘xyz’ in str:
    return True
    return False

    This is a better solution than the one you gave for `xyz_there`

    Reply
    1. John Kershaw

      Very nice – but you don’t need to test for .xyz before replacing.

      def xyz_there(s):
      return ‘xyz’ in s.replace(‘.xyz’, ”)

      Reply
  6. S.Sathish Kumar

    I think, this will solve it quickly.

    return True if str.count(“xyz”) – str.count(“.xyz”) else False

    Reply
  7. Leo Liang

    def xyz_there(str):
    # Affix character ‘a’ in front of str
    str = “a” + str
    # The algorithm below (enclosed in the for loop) handles all cases
    # except when “xyz” is the beginning pf str.
    # So my thinking is, if I add another valid character in front so that this
    # leading “xyz” is counted, then I avoid writing another if statement

    for i in range(len(str) – 3):
    if str[i] != ‘.’ and str[i + 1 : i + 4] == ‘xyz’:
    return True
    return False

    Reply
  8. Azgar

    Please can someone elaborate as to why the solution for xyz_there: does not give the out of range error?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.