第 1 1 章 数 据 集 合
1 # stats.py
2 from math import sqrt
3
4 def getNumbers():
5 nums = [] # start with an empty list
6 # sentinel loop to get numbers
7 xStr = input("Enter a number (<Enter> to quit) >> ")
8 while xStr != "":
9 x = float(xStr)
10 nums.append(x) # add this value to the list
11 xStr = input("Enter a number (<Enter> to quit) >> ")
12 return nums
13
14 def mean(nums):
15 total = 0.0
16 for num in nums:
17 total = total + num
18 return total / len(nums)
19
20 def stdDev(nums, xbar):
21 sumDevSq = 0.0
22 for num in nums:
23 dev = num -xbar
24 sumDevSq = sumDevSq + dev * dev
25 return sqrt(sumDevSq/len(nums)-1)
26
27 def median(nums):
28 nums.sort()
29 size = len(nums)
30 midPos = size // 2
31 if size % 2 == 0:
32 med = (nums[midPos] + nums[midPos-1]) / 2.0
33 else:
34 med = nums[midPos]
35 return med
36
37 def main():
38 print("This program computes mean, median, and standard deviation.")
39
40 data = getNumbers()
41 xbar = mean(data)
42 std = stdDev(data, xbar)
43 med = median(data)
44
45 print("\nThe mean is", xbar)
46 print("The standard deviation is", std)
47 print("The median is", med)
48
49 if __name__ == '__main__':main()
1 # gpasort.py
2 # A program to sort student sinformation into GPA order.
3
4 from gpa import Student, makeStudent
5
6 def readStudents(filename):
7 infile = open(filename, 'r')
8 students = []
9 for line in infile:
10 students.append(makeStudent(line))
11 infile.close()
12 return students
13
14 def writeStudents(students, filename):
15 outfile = open(filename, 'w')
16 for s in students:
17 print("{0}\t{1}\t{2}".
18 format(s.getName(), s.getHours(), s.getQPoints()),
19 file=outfile)
20 outfile.close()
21
22 def main():
23 print("This program sorts student grade information by GPA")
24 filename = input("Enter the name of the data file: ")
25 data = readStudents(filename)
26 data.sort(key=Student.gpa)
27 filename = input("Enter a name for the output file: ")
28 writeStudents(data, filename)
29 print("The data has been written to", filename)
30
31
32 if __init__ == '__main__':
33 main()
1 # dieview2.py
2 from graphics import *
3 class DieView:
4 """ DieView is a widget that displays a graphical
5 representation of a standard six-sided die."""
6
7 def __init__(self, win, center, size):
8 """Create a view of a die, e.g.:
9 d1 = GDie(myWin, Point(40,50), 20)
10 creates a die centered at (40,50) having sides
11 of length 20."""
12
13 # first define some standard values
14 self.win = win
15 self.background = "white" # color of die face
16 self.foreground = "black" # color of the pips
17 self.psize = 0.1 * size # radius of each pip
18 hsize = size / 2.0 # half of size
19 offset = 0.6 * hsize # distance from center to outer pips
20
21 # create a square for the face
22 cx, cy = center.getX(), center.getY()
23 p1 = Point(cx-hsize, cy-hsize)
24 p2 = Point(cx+hsize, cy+hsize)
25 rect = Rectangle(p1,p2)
26 rect.draw(win)
27 rect.setFill(self.background)
28 # Create 7 circles for standard pip locations
29 self.pips = [ self.__makePip(cx-offset, cy-offset),
30 self.__makePip(cx-offset, cy),
31 self.__makePip(cx-offset, cy+offset),
32 self.__makePip(cx, cy),
33 self.__makePip(cx+offset, cy-offset),
34 self.__makePip(cx+offset, cy),
35 self.__makePip(cx+offset, cy+offset) ]
36
37 # Create a table for which pips are on for each value
38 self.onTable = [ [], [3], [2,4], [2,3,4],
39 [0,2,4,6], [0,2,3,4,6], [0,1,2,4,5,6] ]
40
41 self.setValue(1)
42 def __makePip(self, x, y):
43 """Internal helper method to draw a pip at (x,y)"""
44 pip = Circle(Point(x,y), self.psize)
45 pip.setFill(self.background)
46 pip.setOutline(self.background)
47 pip.draw(self.win)
48 return pip
49
50 def setValue(self, Value):
51 """Set this die to display value."""
52 # Turn all the pips off
53 for pip in self.pips:
54 pip.setFill(self.background)
55
56 # Turn the appropriate pips back on
57 for i in self.onTable[value]:
58 self.pips[i].setFill(self.foreground)
59
1 # calc.pyw --A four function calculator using Python arithmetic.
2 # Illustrates use of objects and lists to build a simple GUI.
3
4 from graphics import *
5 from button import Button
6
7 class Calculator:
8 # This class implements a simple calculator GUI
9
10 def __init__(self):
11 # create the window for the calculator
12 win = GraphWin("calculator")
13 win.setCoords(0,0,6,7)
14 win.setBackground("slategray")
15 self.win = win
16 # Now create the widgets
17 self.__createButtons()
18 self.__createDisplay()
19
20 def __createButtons(self):
21 # create list of buttons
22 # start with all the standard sized buttons
23 # bSpecs gives center coords and label of buttons
24 bSpecs = [(2,1,'0'), (3,1,'.'),
25 (1,2,'1'), (2,2,'2'), (3,2,'3'), (4,2,'+'), (5,2,'-'),
26 (1,3,'4'), (2,3,'5'), (3,3,'6'), (4,3,'*'), (5,3,'/'),
27 (1,4,'7'), (2,4,'8'), (3,4,'9'), (4,4,'<-'), (5,4,'C')]
28 self.buttons = []
29 for (cx,cy,label) in bSpecs:
30 self.buttons.append(Button(self.win, Point(cx,cy), .75, .75, label))
31 #create the larger = button
32 self.buttons.append(Button(self.win, Point(4.5,1), 1.75, .75, "="))
33
34 # activate all buttons
35 for b in self.buttons:
36 b.activate()
37
38 def __createDisplay(self):
39 bg = Rectangle(Point(.5,5,5), Point(5.5,6.5))
40 bg.setFill('white')
41 bg.draw(self.win)
42 text = Text(Point(3,6), "")
43 text.draw(self.win)
44 text.setFace("courier")
45 text.setStyle("bold")
46 text.setSize(16)
47 self.display = text
48
49 def getButton(self):
50 # Waits for a button to be clicked and returns the label of
51 # the button that was clicked.
52 while True:
53 p = self.win.getMouse()
54 for b in self.buttons:
55 if b.clicked(p):
56 return b.getLabel() # method exit
57
58 def processButton(self, key):
59 # Updates the display of the calculator for press of this key
60 text = self.display.getText()
61 if key == 'C':
62 self.display.setText("")
63 elif key =='<-' :
64 # Backspace,slice off the last character.
65 self.display.setText(text[:-1])
66 elif key == '=':
67 # Evaluate the expresssion and display the result.
68 # the try...except mechanism "catches" errors in the
69 # formula being evaluated.
70 try:
71 result = eval(text)
72 except:
73 result = 'ERROR'
74 self.display.setText(str(result))
75 else:
76 # Normal key press, append it to the end of the display
77 self.display.setText(text+key)
78
79 def run(self):
80 # Infinite event loop to process button clicks.
81 while True:
82 key = self.getButton()
83 self.processButton(key)
84
85 # This runs the program.
86 if __name__ == '__main__':
87 # First create a calculator object
88 theCalc = Calculator()
89 # Now call the calculator's run method.
90 theCalc.run()
Traceback (most recent call last):
File "/home/yhm/Study/python/20221205/calc.py", line 88, in <module>
theCalc = Calculator()
File "/home/yhm/Study/python/20221205/calc.py", line 17, in __init__
self.__createButtons()
File "/home/yhm/Study/python/20221205/calc.py", line 36, in __createButtons
b.activate()
TypeError: 'bool' object is not callable
1 def byFreq(pair):
2 return pair[1]
3
4 def main():
5 print("This program analyzes word frequency in a file")
6 print("and prints a report on the n most frequent words.\n")
7
8 # get the sequence of words from the file
9 fname = input("File to analyze: ")
10 text = open(fname, 'r').read()
11 text = text.lower()
12 for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
13 text = text.replace(ch, ' ')
14 words = text.split()
15
16 # construct a dictionary of word counts
17 counts = {}
18 for w in words:
19 counts[w] = counts.get(w,0) + 1
20
21 # output analysis of n most frequent words.
22 n = eval(input("Output analysis of how many words? "))
23 items = list(counts.items())
24 items.sort()
25 items.sort(key=byFreq, reverse=True)
26 for i in range(n):
27 word, count = items[i]
28 print("{0:<15}{1:>5}".format(word, count))
29
30 if __name__ == '__main__':main()
11.8小结
11.9练习