CSC111 String Exercise Solutions
--Thiebaut 15:08, 9 April 2009 (UTC)
Solution program for the exercises on strings and list we did in class on 4/7/09. Warning: the functions are not robust and might crash if fed wrong information!!!
# solution program for class exercises on strings
# and lists
# D. Thiebaut
movie1 = "8.9 Pulp Fiction (1994)"
movie2 = "8.3 Singin' in the Rain (1952)"
def splitMovie( movie ):
# takes a movie line and splits it into 3 components
spaceIndex = movie.find( '\t' ) #look for tab
score = float( movie[ : spaceIndex].strip() )
parenIndex = movie.find( '(' )
parenIndex2 = movie.find( ')' )
year = int( movie[ parenIndex+1: parenIndex2 ] )
title = movie[ spaceIndex+1 : parenIndex ]
title = title.strip()
return score, title, year
def checkAlphabet( line ):
# report all the characters of the alphabet that are not
# in line
lowerLine = line.lower()
for ch in "abcdefghijklmnopqrstuvwxyz":
# if ch is already in line, go to next char
if ch in lowerLine:
continue
# otherwise, print it
print ch, "is not in", line
def splitMovie2( movie ):
# split the line into words
words = movie.split()
score = float( words[0] )
year = int( words[-1][1:-1] ) # remove parentheses
title = ' '.join( words[ 1: -1 ] ) #from second word to one before last
return score, title, year
def findUniqueWords( line ):
# given a string of characters, breaks it into individual words and
# prints the list of words that are repeated.
# Warning: this function does not remove punctuation marks...
words = line.split()
words.sort()
repeatedWords = []
for i in range( 1, len( words ) ):
if words[i]==words[i-1]:
if words[i] not in repeatedWords:
repeatedWords.append( words[i] )
print "\n\nWords repeated in", line
for word in repeatedWords:
print word
def main():
# test splitMovie function
print splitMovie( movie1 )
print splitMovie( movie2 )
# test checkAlphabet function
checkAlphabet( "the quick red fox jumped over the dog" )
# check second version of splitting movie line
print splitMovie2( movie1 )
print splitMovie2( movie2 )
# test findUniqueWords
findUniqueWords( "the quick fox and the red dog, and the cat" )
text = """OVER the last week, the fashion groupies
have stood for hours to get a piece of Topshop,
sometimes in the rain, sometimes as curious tourists
took their pictures in their L train get-ups.
They may have suspected they were being manipulated,
since the store, which opened at 478 Broadway on
April 2, did not appear all that crowded. Still,
they waited, and waited, and then they bought such
items of this very moment as pink leopard-print
dresses no bigger than a house cat, black leggings
with fringe along the sides and sunglasses with
lenses shaped like lips."""
findUniqueWords( text )
main()