Python for Everyone

4.6 Write a program to prompt the user for hours and rate per hour using 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 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. Do not name your variable sum or use the sum() function.

def computepay(h, r):
    if h<=40:
        p=h*r
    else:
        p=40*r+(h-40)*r*1.5
    return p
hour=input("Enter Hours:")
rate=input("Enter Rate:")
h=float(hour)
r=float(rate)
p=computepay(h, r)
print(p)

Loops and Iteration
Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers
Break Statement
The break statement ends the current loop and jumps to the statement immediately following the loop
Definite Loops
Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.
for i in [5,4,3,2,1] :
print(i)

To count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop.

a=0
    print('Before', a)
    for thing in [9, 41, 23, 32]:
          a=a+1
          print(a, thing)
     print('After', a)

To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum wach time through the loop

a=0
    print('Before', a)
    for thing in [9, 41, 23, 32]:
          a=a+thing
          print(a, thing)
     print('After', a)

Search Using a Boolean Variable
If we want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for

found=False
    print('Before', found)
    for value in [9, 41, 23, 32]:
         if value == 23:
             found = True
         print(found, value)
    print('After', found)

Using None to find the smallest number

smallest=None
    print('Before')
    for value in [9, 41, 23, 32]:
          if smallest is None:
             smallest=value
          elif value < smallest:
             smallest=value
          print (smallest, value)
    print('After', smallest)

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 7, 2, bob, 10, and 4 and match the output below.

smallest=None

largest=None

while True:
    num=input("Enter a number: ")
    if num == "Done":
        break
    else:
        try:
           n=int(num)
        except:
           print("Invalid input")
           continue #back to the top statement

    if largest is None:
        largest=n
        smallest=n
    else:
        if largestif smallest>n:
            smallest=n
print("Maximum:",largest)
print("Minimum:",smallest)

Len Function
Using a while statement and an iteration variable, and the len function, we can construct a loop to look at each of the letters in a string individually.

fruit = 'banana'
index = 0
while index < len(fruit):
        letter = fruit[index]
        print(index, letter)
        index = index + 1
fruit = 'banana'
for letter in banana:
     print(letter)

Slicing Strings
The second number is one beyond the end of the slice “up to but not including”

s = 'Monty Python'
print(s[0:4])
Mont
print(s[6:20])
Python
print(s[:])
Monty Python

Search and Replace

greet = 'Hello Bob'
nstr = greet.replace('o', 'x')
print(nstr)
Hellx Bxb

Stripping Whitespace
lstrip() and rstrip() remove whitespace at the left or right
strip() removes both beginning and ending whitespace
greet = ’ Hello Bob ’
greet.strip()

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";
a = text.find('0')
b = text[a : ]
c = float(b)
print(c)
fhand = open('mbox-short.txt')
inp = fhand.read()  #Read the Whole File
for line in fland:    #Search Through a File
     line = line.rstrip()
     if line.startswith('From: '):
          print(line) 
 for line in fhand:  #using in to select
       line = line.rstrip()
       if not '@uct.az.za' in line:
              continue
       print(line)

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.

# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
fw = fh.read()
fw = fw.rstrip()
print (fw.upper())

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. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/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 = input("Enter file name: ")
fh = open(fname)
count = 0
s = 0
ave = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    fp = line.find(' ')
    fv = line[fp : ]
    num = fv.strip()
    num = num.strip()
    num = float(num)
    s = s + num
    count = count + 1

ave = s / count
print("Average spam confidence:", ave)

Chapter 8 Lists
Strings are immutable: we cannot change the contents of a string
Lists are mutable: we can change an element of a list using the index operator

lotto = [2,9,0,3]
lotto[2] = 28
print(lotto)
[2,9,28,3]

The range function returns a list of numbers that range from zero to one less than the parameter

print(range(4))
[0, 1, 2, 3]

Building a list from scratch
we can create an empty list and then add elements using the append method

stuff = list()
stuff.append('book')
stuff.append(99)
print(stuff)
['book', 99]
friends = ['Jason', 'Daisy']   #a list can be sorted
friends.sort()
print(friends)
['Daisy', 'Jason']

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 the split() method. 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.

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
words = list()
for line in fh:
    words = line.split()
    for word in words:
        if lst.count(word) == 0:
            lst.append(word)
lst.sort()
print(lst)

8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with ‘From ’ like the following line:

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

You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.

Hint: make sure not to include the lines that start with ‘From:’.

fname = input("Enter file name: ")
fh = open(fname)
count = 0
for line in fh:
    if line.startswith('From: '):
        words = line.split()
        print(words[1])
        count = count + 1
print("There were", count, "lines in the file with From as the first word")
han = open('mbox-short.txt')
for line in han:
     line = line.rstrip()
     wds = line.split()
     # guardian in a compound statement
     if len(wds) < 3 or wds[0] != 'From' :
         continue
     print(wds[2])

The get method for dictionaries
The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get()
if name in counts:
x = counts[name]
else:
x = 0
equal to:
x = counts.get(name, 0)
You can get a list of keys, values, or items from a dictionary
jjj = {‘chuck’ : 1, ‘fred’ : 42, ‘jan’ : 100}
print(list(jjj))
print(jjj.keys())
print(jjj.values())
print(jjj,items())

for aaa,bbb in jjj.items():
print(aaa, bbb) #two iteration variables

Find the biggest count and corresponding word

name = input('Enter file')
handle = open(name)
counts = dict()
for line in handle:
      words = line.split()
      for word in words:
            counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word, count in counts.items():
      if bigcount is None or count > bigcount:
           bigword = word
           bigcount =count
 print(bigword, bigcount)

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 = input("Enter file:")
handle = open(name)
counts = dict()
for line in handle:
    if line.startswith('From:'):
       words = line.split()
       words = words[1]
#print(words)
       counts[words] = counts.get(words, 0) + 1

bigword = None
bigcount = -1
for key,count in counts.items():
    #print(key, count)
    if count > bigcount:
        bigcount = count
        bigword = key
print(bigword, bigcount)

Tuple: index, count
tuple is immutable
We prefer tuple over list when we are making temporary variables
The 10 most common words

fhand = open('remeo.txt')
counts = dict()
for line in fhand:
      words =  line.split()
      for word in words:
            counts[word] = counts.get(word, 0) + 1
lst = list()
for key, val in counts.items():
      newtup = (val, key)
      lst.append(newtup)
lst = sorted(lst, reverse=True)
for val, key in lst[ :10]:
     print(key, val)

Even shorter version
c = {‘a’: 10, ‘b’: 1, ‘c’: 22}
print(sorted([(v,k) for k,v in c.items()]))
[(1, ‘b’), (10, ‘a’), (22, ‘c’)]

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 [email protected] 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.

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
    if line.startswith('From '):
       words =  line.split()
       words = words[5]
       #print(words)
       nums = words.split(':')
       #print(nums)
       nums = nums[0]
       #print(nums)
       counts[nums] = counts.get(nums, 0) + 1
#print(counts)
lst = list()
for hour, count in counts.items():
    newtup = (hour, count)
    lst.append(newtup)
lst = sorted(lst)
for hour, count in lst[:]:
    print(hour, count)

你可能感兴趣的:(python)