Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Data Structures and Algorithms with Python
< Prev   CONTENTS   Next >

1.13 The Accumulator Pattern

To use the different command classes that we have just defined, our program will read the variable length records from the file as it did before using the loop and a half pattern that we have already seen. Patterns of programming, sometimes called idioms, are important in Computer Science. Once we have learned an idiom we can apply it over and over in our programs. This is useful to us because as we solve problems its nice to say, “Oh, yes, I can solve this problem using that idiom”. Having idioms at our fingertips frees our minds to deal with the tougher problems we encounter while programming.

One important pattern in programming is the Accumulator Pattern. This pattern is used in nearly every program we write. When using this pattern you initialize an accumulator before a loop and then inside the loop you add to the accumulator. For instance, the code in Sect. 1.13.1 uses the accumulator pattern to construct the list of squares from 1 to 10.

1.13.1 List of Squares

1 # initialize the accumulator, in this case a list

2 accumulator = []

3

4 # write some kind of for loop or while loop

5 for i in range(1,11):

6 # add to the accumulator, in this case add to the list

7 accumulator = accumulator + [i ** 2]

To complete our graphics program, we'll use the loop and a half pattern to read the records from a file and the accumulator pattern to add a command object to our PyList container for each record we find in the file. The code is given in Sect. 1.13.2.

1.13.2 A Graphics Program

1 import turtle

2

3 # Command classes would be inserted here but are left out because they

4 # were defined earlier in the chapter.

5

6 # This is our PyList class. It holds a list of our graphics

7 # commands.

8

9 class PyList:

10 def init (self):

11 self.items = []

12

13 def append(self,item):

14 self.items = self.items + [item]

15

16 # if we want to iterate over this sequence, we define the special method

17 # called iter (self). Without this we'll get "builtins.TypeError:

18 # 'PyList' object is not iterable" if we try to write

19 # for cmd in seq:

20 # where seq is one of these sequences. The yield below will yield an

21 # element of the sequence and will suspend the execution of the for

22 # loop in the method below until the next element is needed. The ability

23 # to yield each element of the sequence as needed is called "lazy" evaluation

24 # and is very powerful. It means that we only need to provide access to as

25 # many of elements of the sequence as are necessary and no more.

26 def iter (self):

27 for c in self.items:

28 yield c

29

30 def main():

31 filename = input("Please enter drawing filename: ")

32

33 t = turtle.Turtle()

34 screen = t.getscreen()

35 file = open(filename, "r")

36

37 # Create a PyList to hold the graphics commands that are

38 # read from the file.

39 graphicsCommands = PyList()

40

41 command = file.readline().strip()

42

43 while command != "":

44

45 # Now we must read the rest of the record and then process it. Because

46 # records are variable length, we'll use an if-elif to determine which

47 # type of record it is and then we'll read and process the record.

48 # In this program, processing the record means creating a command object

49 # using one of the classes above and then adding that object to our

50 # graphicsCommands PyList object.

51

52 if command == "goto":

53 x = float(file.readline())

54 y = float(file.readline())

55 width = float(file.readline())

56 color = file.readline().strip()

57 cmd = GoToCommand(x,y,width,color)

58

59 elif command == "circle":

60 radius = float(file.readline())

61 width = float(file.readline())

62 color = file.readline().strip()

63 cmd = CircleCommand(radius,width,color)

64

65 elif command == "beginfill":

66 color = file.readline().strip()

67 cmd = BeginFillCommand(color)

68

69 elif command == "endfill":

70 cmd = EndFillCommand()

71

72 elif command == "penup":

73 cmd = PenUpCommand()

74

75 elif command == "pendown":

76 cmd = PenDownCommand()

77 else:

78 # raising an exception will terminate the program immediately

79 # which is what we want to happen if we encounter an unknown

80 # command. The RuntimeError exception is a common exception

81 # to raise. The string will be printed when the exception is

82 # printed.

83 raise RuntimeError("Unknown Command: " + command)

84

85 # Finish processing the record by adding the command to the sequence.

86 graphicsCommands.append(cmd)

87

88 # Read one more line to set up for the next time through the loop.

89 command = file.readline().strip()

90

91 # This code iterates through the commands to do the drawing and

92 # demonstrates the use of the iter(self) method in the

93 # PyList class above.

94 for cmd in graphicsCommands:

95 cmd.draw(t)

96

97 file.close()

98 t.ht()

99 screen.exitonclick()

100 print("Program Execution Completed.")

101

102 if name == " main ":

103 main()

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel