Solutions for String exercises

String1.py

  1# Copyright 2010 Google Inc.
  2# Licensed under the Apache License, Version 2.0
  3# http://www.apache.org/licenses/LICENSE-2.0
  4# ggg
  5
  6# Basic string exercises
  7# Fill in the code for the functions below. main() is already set up
  8# to call the functions with a few different inputs,
  9# printing 'OK' when each function is correct.
 10# The starter code for each function includes a 'return'
 11# which is just a placeholder for your code.
 12# It's ok if you do not complete all the functions, and there
 13# are some additional functions to try in string2.py.
 14
 15
 16# A. donuts
 17# Given an int count of a number of donuts, return a string
 18# of the form 'Number of donuts: <count>', where <count> is the number
 19# passed in. However, if the count is 10 or more, then use the word 'many'
 20# instead of the actual count.
 21# So donuts(5) returns 'Number of donuts: 5'
 22# and donuts(23) returns 'Number of donuts: many'
 23def donuts(count):
 24    output = 'Number of donuts: '
 25    if count >= 10:
 26        output += 'many' 
 27    else:
 28        output += str(count)
 29    return output
 30
 31
 32# B. both_ends
 33# Given a string s, return a string made of the first 2
 34# and the last 2 chars of the original string,
 35# so 'spring' yields 'spng'. However, if the string length
 36# is less than 2, return instead the empty string.
 37def both_ends(s):
 38    output = ''
 39    if len(s) < 2:
 40        pass
 41    else:
 42        output = s[0:2] + s[-2:]
 43    return output
 44
 45
 46# C. fix_start
 47# Given a string s, return a string
 48# where all occurences of its first char have
 49# been changed to '*', except do not change
 50# the first char itself.
 51# e.g. 'babble' yields 'ba**le'
 52# Assume that the string is length 1 or more.
 53# Hint: s.replace(stra, strb) returns a version of string s
 54# where all instances of stra have been replaced by strb.
 55def fix_start(s):
 56  # get the first letter
 57  firts = s[0]
 58  # replace all occorences in the rest of the string
 59  s = s.replace(firts, '*')
 60  # reset first letter to original
 61  s = firts + s[1:]
 62  return s
 63
 64
 65# D. MixUp
 66# Given strings a and b, return a single string with a and b separated
 67# by a space '<a> <b>', except swap the first 2 chars of each string.
 68# e.g.
 69#   'mix', pod' -> 'pox mid'
 70#   'dog', 'dinner' -> 'dig donner'
 71# Assume a and b are length 2 or more.
 72def mix_up(a, b):
 73  # get first 2 letters of a and b
 74  afirst = a[:2]
 75  bfirst = b[:2]
 76  # get remains og a and b
 77  alast = a[2:]
 78  blast = b[2:]
 79  # concatenate a and b
 80  ab = f'{bfirst}{alast} {afirst}{blast}'
 81  return ab
 82
 83  # solution google
 84  a_swapped = b[:2] + a[2:]
 85  b_swapped = a[:2] + b[2:]
 86  #return a_swapped + ' ' + b_swapped
 87
 88  # 3 solution
 89  # return b[:2] + a[2:] + ' ' + a[:2] + b[2:]
 90
 91
 92# Provided simple test() function used in main() to print
 93# what each function returns vs. what it's supposed to return.
 94def test(got, expected):
 95  if got == expected:
 96    prefix = ' OK '
 97  else:
 98    prefix = '  X '
 99  print (f'{prefix} got: {got} expected: {expected}')
100
101
102# Provided main() calls the above functions with interesting inputs,
103# using test() to check if each result is correct or not.
104def main():
105  print ('donuts')
106  # Each line calls donuts, compares its result to the expected for that call.
107  test(donuts(4), 'Number of donuts: 4')
108  test(donuts(9), 'Number of donuts: 9')
109  test(donuts(10), 'Number of donuts: many')
110  test(donuts(99), 'Number of donuts: many')
111
112  print()
113  print ('both_ends')
114  test(both_ends('spring'), 'spng')
115  test(both_ends('Hello'), 'Helo')
116  test(both_ends('a'), '')
117  test(both_ends('xyz'), 'xyyz')
118
119  
120  print()
121  print ('fix_start')
122  test(fix_start('babble'), 'ba**le')
123  test(fix_start('aardvark'), 'a*rdv*rk')
124  test(fix_start('google'), 'goo*le')
125  test(fix_start('donut'), 'donut')
126
127  print()
128  print ('mix_up')
129  test(mix_up('mix', 'pod'), 'pox mid')
130  test(mix_up('dog', 'dinner'), 'dig donner')
131  test(mix_up('gnash', 'sport'), 'spash gnort')
132  test(mix_up('pezzy', 'firm'), 'fizzy perm')
133
134
135# Standard boilerplate to call the main() function.
136if __name__ == '__main__':
137  main()

String2.py

  1
  2# Copyright 2010 Google Inc.
  3# Licensed under the Apache License, Version 2.0
  4# http://www.apache.org/licenses/LICENSE-2.0
  5
  6# Additional basic string exercises
  7
  8# D. verbing
  9# Given a string, if its length is at least 3,
 10# add 'ing' to its end.
 11# Unless it already ends in 'ing', in which case
 12# add 'ly' instead.
 13# If the string length is less than 3, leave it unchanged.
 14# Return the resulting string.
 15def verbing(s):
 16  if len(s) >= 3 and s[-3:] != 'ing':
 17    s = s + 'ing'
 18  elif len(s) >= 3:
 19    s = s + 'ly'
 20  return  s
 21
 22
 23# E. not_bad
 24# Given a string, find the first appearance of the
 25# substring 'not' and 'bad'. If the 'bad' follows
 26# the 'not', replace the whole 'not'...'bad' substring
 27# with 'good'.
 28# Return the resulting string.
 29# So 'This dinner is not that bad!' yields:
 30# This dinner is good!
 31def not_bad(s):
 32
 33  # find not and bad
 34  n = s.find('not')
 35  b = s.find('bad')
 36  # check if not and bad in string and in the right order
 37  if n < b and n != -1:
 38    # slice the 'not' ... 'bad' string
 39    substr = s[n : b+3]
 40    # replace and return the new string
 41    return s.replace(substr, 'good', 1)
 42  
 43  return s
 44  
 45
 46
 47# F. front_back
 48# Consider dividing a string into two halves.
 49# If the length is even, the front and back halves are the same length.
 50# If the length is odd, we'll say that the extra char goes in the front half.
 51# e.g. 'abcde', the front half is 'abc', the back half 'de'.
 52# Given 2 strings, a and b, return a string of the form
 53#  a-front + b-front + a-back + b-back
 54def front_back(a, b):
 55  a_mid = 0
 56  b_mid = 0
 57  if len(a) % 2 == 0:
 58    a_mid = int(len(a)/2)
 59  else:
 60    a_mid = int(len(a)/2) + 1
 61
 62  if len(b) % 2 == 0:
 63    b_mid = int(len(b)/2)
 64  else:
 65    b_mid = int(len(b)/2) + 1
 66
 67  return  a[:a_mid] + b[:b_mid] + a[a_mid:] + b[b_mid:]
 68
 69
 70# Simple provided test() function used in main() to print
 71# what each function returns vs. what it's supposed to return.
 72def test(got, expected):
 73  if got == expected:
 74    prefix = ' OK '
 75  else:
 76    prefix = '  X '
 77  print (prefix + ' got: ' + got + ' expected: ' + expected)
 78
 79
 80# main() calls the above functions with interesting inputs,
 81# using the above test() to check if the result is correct or not.
 82def main():
 83  print ('verbing')
 84  test(verbing('hail'), 'hailing')
 85  test(verbing('swiming'), 'swimingly')
 86  test(verbing('do'), 'do')
 87
 88  print()
 89  print ('not_bad')
 90  test(not_bad('This movie is not so bad'), 'This movie is good')
 91  test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
 92  test(not_bad('This tea is not hot'), 'This tea is not hot')
 93  test(not_bad("It's bad yet not"), "It's bad yet not")
 94
 95  print()
 96  print ('front_back')
 97  test(front_back('abcd', 'xy'), 'abxcdy')
 98  test(front_back('abcde', 'xyz'), 'abcxydez')
 99  test(front_back('Kitten', 'Donut'), 'KitDontenut')
100
101if __name__ == '__main__':
102  main()