|
Second Summer 2006 |
So here are some programs we will develop:
message = raw_input("Give me the word: ")
dictionary = {}
for e in message:
if dictionary.has_key(e):
dictionary[e] = dictionary[e] + 1
else :
dictionary[e] = 1
print "I have built the dictionary:"
for e in dictionary.keys():
print "Letter " + e + " occurs " + str(dictionary[e])
letter = raw_input("Give me the letter: ")
if dictionary.has_key(letter):
print "Letter " + letter + " occurs " + str(dictionary[letter]) + " times in " + message
else:
print "Letter " + letter + " does not occur in " + message
print "Again:"
count = 0
for e in message:
if letter == e:
count = count + 1
print countHere's how this program works:
The next program finds the longest line in a file:Give me the word: stupendous I have built the dictionary: Letter p occurs 1 Letter s occurs 2 Letter u occurs 2 Letter t occurs 1 Letter d occurs 1 Letter e occurs 1 Letter o occurs 1 Letter n occurs 1 Give me the letter: u Letter u occurs 2 times in stupendous Again: 2 >>>
Here's how it looks:
def tokens(line):
tokens = line.split()
return len(tokens)
def nonspace(line):
tokens = line.split()
sum = 0
for token in tokens:
sum = sum + len(token)
return sum
file = open("C:/Documents and Settings/dgerman/Desktop/rem.txt", "r")
bob = ""
jim = ""
tom = ""
for line in file:
if len(line) > len(bob):
bob = line
if tokens(line) > tokens(jim):
jim = line
if nonspace(line) > nonspace(tom):
tom = line
file.close()
print bob
print jim
print tom
I've watched the stars fall silent from your eyes
All the sights that I have seen
I can't believe that I believed I wished
T h a t y o u c o u l d s e e
There's a new planet in the solar system
There is nothing up my sleeve
I'm pushing an elephant up the stairs
I'm tossing up punch lines that were never there
Over my shoulder a piano falls
Crashing to the ground
then the lines printed will be no. 1, 4 and 8 (not in that order).