Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created February 6, 2012 06:04
Show Gist options
  • Save daGrevis/1750086 to your computer and use it in GitHub Desktop.
Save daGrevis/1750086 to your computer and use it in GitHub Desktop.
PyQuick: String #1
# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
if count < 10:
return 'Number of donuts: ' + str(count)
else:
return 'Number of donuts: many'
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) < 2:
return ''
else:
start = s[:2]
end = s[-2:]
return start + end
# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
first = s[0:1]
s = s.replace(first, '*')
s = s.replace('*', first, 1)
return s
# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
new_a = b[:2] + a[2:]
new_b = a[:2] + b[2:]
return new_a + ' ' + new_b
@daGrevis
Copy link
Author

daGrevis commented Feb 6, 2012

Looking for neater ways to do the same. :]

@HaydenRU
Copy link

Look at my take :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment