0% found this document useful (0 votes)
127 views6 pages

Py4Inf Solutions

The document contains Python code snippets for various programming exercises. The first code snippet prompts the user to enter a score between 0 and 1, checks if it is in range, and prints the corresponding grade. The second snippet repeatedly prompts the user for numbers, tracks the minimum and maximum numbers entered, and prints them out once "done" is entered. The third snippet summarizes the overall task of analyzing text files containing spam confidence data and calculating statistics.

Uploaded by

JAI PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views6 pages

Py4Inf Solutions

The document contains Python code snippets for various programming exercises. The first code snippet prompts the user to enter a score between 0 and 1, checks if it is in range, and prints the corresponding grade. The second snippet repeatedly prompts the user for numbers, tracks the minimum and maximum numbers entered, and prints them out once "done" is entered. The third snippet summarizes the overall task of analyzing text files containing spam confidence data and calculating statistics.

Uploaded by

JAI PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 6

Solutions for SI502

--- 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out
of range print an error. If the score is between 0.0 and 1.0, print a grade.

grade = raw_input("Enter score:")


try:
grade= float(grade)
if grade >1 or grade <0:
print "Bad Score"
if grade<=1 and grade >=0.9:
print "A"
if grade<0.9 and grade >=0.8:
print "B"
if grade<0.8 and grade >=0.7:
print "C"
if grade<0.7 and grade >=0.6:
print "D"
else:
print "F"

--- 5.2 Write a program that repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the maximum and minimum of the numbers. If
the user enters anything other than a number, detect their mistake using try and
except and print an error message and skip to the next number.

minn = maxn = None


while True:
num = raw_input("Enter number: ")
if num == "done":
break
try:
num = float(num)
if minn is None:
minn = maxn = num
minn = min(minn, num)
maxn = max(maxn, num)
except:
print "This is not a valid input"
print "Max: %f" % maxn
print "Min: %f" % minn

--- 6.5 Take the following Python code that stores a string:

str = 'X-DSPAM-Confidence: 0.8475'


Use find and string slicing to extract the portion of the string after the colon
character and then use the float function to convert the extracted string into a
floating point number.

st = "X-DSPAM-Confidence: 0.8475"
# colon = st.find(":")
# length = len(st)
# substring = st[colon + 1 : length]
substring = st.split(":")[1]
number = float(substring)
print "Number: ", number

--- 7.1 Write a program to read through a file and print the contents of the file (line
by line) all in upper case.

fname = raw_input("Enter a file name: ")


try:
ffile = open(fname)
for line in ffile:
print line.upper()
except:
print "This file was not found"

--- 7.2 Write a program to prompt for a file name, and then read through the file.
When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the
line to extract the floating point number on the line. Count these lines and the
compute the total of the spam confidence values from these lines. When you reach
the end of the file, print out the average spam confidence.

fname = raw_input("Enter a file name: ")


try:
ffile = open(fname)
ssum = 0
nline = 0
for nline, line in enumerate(ffile):
if line.strip().startswith("X-DSPAM-Confidence:"):
colon = line.find(":")
slash = line.find("\\")
current_av = line[colon+1:slash]
ssum = ssum + float(current_av)
print "Average Spam confidence: ", ssum/nline
except:
print "This file was not found"
--- 8.4 Download a copy of the file from www.py4inf.com/code/romeo.txt then write
a program to open the file romeo.txt and read it line by line. For each line, split the
line into a list of words using the split function. For each word, check to see if the
word is already in a list. If the word is not in the list, add it to the list. When the
program completes, sort and print the resulting words in alphabetical order.

fhand = open("romeo.txt")
words =[]
for line in fhand:
llist = line.lower().split(" ")
for word in llist:
print word
word= word.strip()
if word not in words:
words.append(word)
print sorted(words)

--- Program Output

Enter file: romeo.txt


['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is',
'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window','with',
'yonder']

--- 8.5 Write a program to read through the mail box data and when you find line
that starts with “From”, you will split the line into words using the split function.
We are interested in who sent the message which is the second word on the From
line.

From [email protected] Sat Jan 5 09:14:16 2008

You will parse the From line and print out the second word for each From line and
then you will also count the number of From (not From:) lines and print out a count
at the end.

fhand= open("mbox-short.txt")
lines = 0
for line in fhand:
if line.startswith("From "):
lines+=1

print "There are",lines,"lines in the file with From as the first word"
--- 9.3 Write a program to read through a mail log, and build a histogram using a
dictionary to count how many messages have come from each email ad- dress and
print the dictionary.

--- Output

Enter file name: mbox-short.txt


{'[email protected]': 1, '[email protected]': 3,
'[email protected]': 5, '[email protected]': 1, '[email protected]': 2,
'[email protected]': 3, '[email protected]': 4, '[email protected]': 1,
'[email protected]': 4, '[email protected]': 2, '[email protected]': 1}

fname = raw_input('Enter file name: ')


fhand = open(fname)
c = dict()
for line in fhand:
if not line.startswith('From ') : continue
pieces = line.split()
email = pieces[1]
c[email] = c.get(email,0) + 1

print c

--- 9.4 Add code to the above program to figure out who has the most messages in
the file. After all the data has been read and the dictionary has been created, look
through the dictionary using a maximum loop to find who has the most messages
and print how many messages the person has.

--- Output

Enter a file name: mbox-short.txt


[email protected] 5

Enter a file name: mbox.txt


[email protected] 195

fname = raw_input('Enter file name: ')


fhand = open(fname)
c = dict()
for line in fhand:
if not line.startswith('From ') : continue
pieces = line.split()
email = pieces[1]
c[email] = c.get(email,0) + 1
bigc = None
bige = None
for word in c:
value = c[word]
if bigc == None or value > bigc:
bigw = word
bigc = value

print bigw, bigc

--- 10.2 This program counts the distribution of the hour of the day for each of the
messages. You can pull the hour from the “From” line by finding the time string
and then splitting that string into parts using the colon character. Once you have
accumulated the counts for each hour, print out the counts, one per line, sorted by
hour as shown below.

-- Output

Enter a file name: mbox-short.txt


04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

fname = raw_input('Enter file name: ')


fhand = open(fname)
c = dict()
for line in fhand:
if not line.startswith('From ') : continue
pieces = line.split()
time = pieces[5]
parts = time.split(':')
hour = parts[0]
c[hour] = c.get(hour,0) + 1

lst = list()
for key in c:
value = c[key]
lst.append( (value, key) )

lst.sort()

for value, key in lst:


print key, value

You might also like