Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Exercise 8.1 Write a function called chop that takes a list and modifies it, removing the first
- and last elements, and returns None.
- Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
- '''
- def chop():
- list1=[1,2,3,4,5,6,7,8]
- list1.pop(0)
- list1.pop(len(list1)-1)
- return None
- def middle():
- list2=[1,2,3,4,5,6,7,8]
- list2.pop(0)
- list2.pop(len(list2)-1)
- return list2
- '''
- Exercise 8.3 Rewrite the guardian code in the above example without two if statements.
- Instead use a compound logical expression using the and logical operator with a single
- if statement.
- '''
- fhand = open('mbox-short.txt')
- count = 0
- for line in fhand:
- words = line.split()
- # print 'Debug:', words
- if len(words) == 0 or words[0] != 'From': continue
- print words[2]
- '''
- Exercise 8.4 Download a copy of the file from www.py4inf.com/code/romeo.txt
- 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.
- '''
- fhand = open('romeo.txt')
- for line in fhand:
- words=line.split()
- print words
- '''
- Exercise 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 stephen.marquard@uct.ac.za 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('mail.txt')
- count=0
- for line in fhand:
- words=line.split()
- if words[0]=='From':
- count=count+1
- print words[1]
- elif words[0]!='From':
- continue
- print 'there are ',count,'lines that start with From'
- '''
- Exercise 8.6 Rewrite the program that prompts the user for a list of numbers and prints out
- the maximum and minimum of the numbers at the end when the user enters “done”. Write the
- program to store the numbers the user enters in a list and use the max() and min() fuctions to
- compute the maximum and minimum numbers after the loop completes.
- '''
- a=raw_input('Enter a number:')
- list=[]
- while(a!='done'):
- list.append(a)
- a=raw_input('Enter a number:')
- print list
- print max(list)
- print min(list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement