Funciones
4.6 Write a program to prompt the user for hours and rate per hour using raw_input to
compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40
hours. Put the logic to do the computation of time-and-a-half in a function
called computepay() and use the function to do the computation. The function should
return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay
should be 498.75). You should use raw_input to read a string and float() to convert the
string to a number. Do not worry about error checking the user input unless you want to -
you can assume the user types numbers properly.
def computepay(h,r):
p = 40 * r
if h > 40 :
p = p + ( r * 1.5 ) * ( h % 40 )
return p
try:
inp = raw_input("Enter hours: ")
hours = float(inp)
inp = raw_input("Enter rate per hour: ")
rate = float(inp)
except:
print "Enter a number"
quit()
p = computepay(hours,rate)
print p
498.75
Bucles
5.2 Write a program that repeatedly prompts a user for integer numbers until the user
enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If
the user enters anything other than a valid number catch it with a try/except and put out an
appropriate message and ignore the number. Enter the numbers from the book for problem
5.1 and Match the desired output as shown.
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try:
int_num = int(num)
if largest is None:
largest = int_num
elif int_num > largest :
largest = int_num
if smallest is None:
smallest = int_num
elif smallest > int_num :
smallest = int_num
except :
print "Invalid input"
continue
print "Maximum", largest
print "Minimum", smallest
Invalid input Maximum is 7 Minimum is 4
Cadenas
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the
end of the line below. Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475";
pos_ini = text.find("0")
pos_end = len(text)
number = text[pos_ini:pos_end]
print float(number)
0.8475
Ficheros
7.1 Write a program that prompts for a file name, then opens that file and reads through the
file, and print the contents of the file in upper case. Use the file words.txt to produce the
output below.
You can download the sample data at http://www.pythonlearn.com/code/words.txt
# Use words.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
print line.upper().rstrip()
7.2 Write a program that prompts for a file name, then opens that file and reads through the
file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute
the average of those values and produce an output as shown below.
You can download the sample data at http://www.pythonlearn.com/code/mbox-
short.txt when you are testing below enter mbox-short.txt as the file name.
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
counter = 0
calc = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
else:
index = line.find(":")
value = float(line[index+1:len(line)].strip())
counter = counter + 1
calc += value
print "Average spam confidence:",calc/counter
Average spam confidence: 0.750718518519
Listas
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of
words using thesplit() function. The program should build a list of words. For each word on
each line check to see if the word is already in the list and if not append it to the list. When
the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.pythonlearn.com/code/romeo.txt
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
newList = line.split()
for word in newList:
if word not in lst:
lst.append(word)
lst.sort()
print lst
['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']
Diccionarios
9.4 Write a program to read through the mbox-short.txt and figure out who has the sent
the greatest number of mail messages. The program looks for 'From ' lines and takes the
second word of those lines as the person who sent the mail. The program creates a Python
dictionary that maps the sender's mail address to a count of the number of times they
appear in the file. After the dictionary is produced, the program reads through the dictionary
using a maximum loop to find the most prolific committer.
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
line = line.rstrip()
if line.startswith("From"):
newList = line.split()
if newList[0] != "From:":
counts[newList[1]] = counts.get(newList[1],0) + 1
bigcount = None
bigsender = None
for key,value in counts.items():
if bigcount is None or value > bigcount:
bigcount = value
bigsender = key
print bigsender, bigcount
cwen@iupui.edu 5
Tuplas
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by
hour of the day for each of the messages. You can pull the hour out from the 'From ' line by
finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour
as shown below. Note that the autograder does not have support for the sorted() function.
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
04 3 06 1 07 1 09 2 10 3 11 6 14 1 15 2 16 4 17 2 18 1 19 1