Advanced Exercises

These are taken from codingbat.com.

Strings Strings Strings

Given a string and a non-negative int n, return a larger string that is n copies of the original string.

from test import testEqual

def string_times(str, n):
  # Write your code here
  return "Your answer goes here"


# These tests will all pass when your code is right 
testEqual(string_times('Hi', 2), 'HiHi')
testEqual(string_times('Hi', 3), 'HiHiHi')
testEqual(string_times('Hi', 1), 'Hi')
testEqual(string_times('Hi', 0), '')
testEqual(string_times('Hi', 5), 'HiHiHiHiHi')
testEqual(string_times('Oh Boy!', 2), 'Oh Boy!Oh Boy!')
testEqual(string_times('x', 4), 'xxxx')
testEqual(string_times('', 4), '')
testEqual(string_times('code', 2), 'codecode')
testEqual(string_times('code', 3), 'codecodecode')

Front of strings

Given a string and a non-negative int n, we’ll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;

from test import testEqual

def front_times(str, n):
  # Write your code here
  return "Your answer goes here"


# These tests will all pass when your code is right 
testEqual(front_times('Chocolate', 2), 'ChoCho')
testEqual(front_times('Chocolate', 3), 'ChoChoCho')
testEqual(front_times('Abc', 3), 'AbcAbcAbc')
testEqual(front_times('Ab', 4), 'AbAbAbAb')
testEqual(front_times('A', 4), 'AAAA')
testEqual(front_times('', 4), '')	    
testEqual(front_times('Abc', 0), '')

Every other

Given a string, return a new string made of every other char starting with the first, so “Hello” yields “Hlo”.

string_bits(‘Hello’) → ‘Hlo’ string_bits(‘Hi’) → ‘H’ string_bits(‘Heeololeo’) → ‘Hello’

from test import testEqual

def string_bits(str):
  # Write your code here
  return "Your answer goes here"

testEqual(string_bits("Hello"),"Hlo")
testEqual(string_bits('Hi'),'H')	    
testEqual(string_bits('Heeololeo'),'Hello')
testEqual(string_bits('HiHiHi'),'HHH')
testEqual(string_bits(''),'')
testEqual(string_bits('Greetings'),'Getns')    
testEqual(string_bits('Chocoate'),'Coot')
testEqual(string_bits('pi'),'p')
testEqual(string_bits('Hello Kitten'),'HloKte')
testEqual(string_bits('hxaxpxpxy'),'happy')