Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created February 6, 2012 13:28
Show Gist options
  • Save daGrevis/1752026 to your computer and use it in GitHub Desktop.
Save daGrevis/1752026 to your computer and use it in GitHub Desktop.
PyQuick: String #2
# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
if len(s) < 3:
return s
elif s[-3:] == 'ing':
return s + 'ly'
else:
return s + 'ing'
# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
first_found = s.find('not')
second_found = s.find('bad')
if first_found == -1 or second_found == -1:
return s
else:
if second_found > first_found:
return s[:first_found] + 'good' + s[second_found + 3:]
else:
return s
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
a_len = len(a)
a_res = int(a_len / 2)
if a_len % 2:
a_res = a_res + 1
a_front = a[:a_res]
a_back = a[a_res:]
b_len = len(b)
b_res = int(b_len / 2)
if b_len % 2:
b_res = b_res + 1
b_front = b[:b_res]
b_back = b[b_res:]
return a_front + b_front + a_back + b_back
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment