Python Programming: An Introduction To Computer Science

Size: px
Start display at page:

Download "Python Programming: An Introduction To Computer Science"

Transcription

1 Pytho Programmig: A Itroductio To Computer Sciece Chapter 10 Defiig Classes Pytho Programmig, 2/e 1

2 Objectives To appreciate how defiig ew classes ca provide structure for a complex program. To be able to read ad write Pytho class defiitios. To uderstad the cocept of ecapsulatio ad how it cotributes to buildig modular ad maitaiable programs. Pytho Programmig, 2/e 2

3 Objectives To be able to write programs ivolvig simple class defiitios. To be able to write iteractive graphics programs ivolvig ovel (programmer desiged) widgets. Pytho Programmig, 2/e 3

4 Quick Review of Objects I the last three chapters we ve developed techiques for structurig the computatios of the program. We ll ow take a look at techiques for structurig the data that our programs use. So far, our programs have made use of objects created from pre-defied class such as Circle. I this chapter we ll lear how to write our ow classes to create ovel objects. Pytho Programmig, 2/e 4

5 Quick Review of Objects I chapter five a object was defied as a active data type that kows stuff ad ca do stuff. More precisely, a object cosists of: 1. A collectio of related iformatio. 2. A set of operatios to maipulate that iformatio. Pytho Programmig, 2/e 5

6 Quick Review of Objects The iformatio is stored iside the object i istace variables. The operatios, called methods, are fuctios that live iside the object. Collectively, the istace variables ad methods are called the attributes of a object. Pytho Programmig, 2/e 6

7 Quick Review of Objects A Circle object will have istace variables such as ceter, which remembers the ceter poit of the circle, ad radius, which stores the legth of the circle s radius. The draw method examies the ceter ad radius to decide which pixels i a widow should be colored. Pytho Programmig, 2/e 7

8 Quick Review of Objects The move method will chage the value of ceter to reflect the ew positio of the circle. All objects are said to be a istace of some class. The class of a object determies which attributes the object will have. A class is a descriptio of what its istaces will kow ad do. Pytho Programmig, 2/e 8

9 Quick Review of Objects New objects are created from a class by ivokig a costructor. You ca thik of the class itself as a sort of factory for stampig out ew istaces. Cosider makig a ew circle object: mycircle = Circle(Poit(0,0),20) Circle, the ame of the class, is used to ivoke the costructor. Pytho Programmig, 2/e 9

10 Quick Review of Objects mycircle = Circle(Poit(0,0), 20) This statemet creates a ew Circle istace ad stores a referece to it i the variable mycircle. The parameters to the costructor are used to iitialize some of the istace variables (ceter ad radius) iside mycircle. Pytho Programmig, 2/e 10

11 Quick Review of Objects mycircle = Circle(Poit(0,0), 20) Oce the istace has bee created, it ca be maipulated by callig o its methods: mycircle.draw(wi) mycircle.move(dx,dy) Pytho Programmig, 2/e 11

12 Caoball Program Specificatio Let s try to write a program that simulates the flight of a caoball or other projectile. We re iterested i how far the caoball will travel whe fired at various lauch agles ad iitial velocities. Pytho Programmig, 2/e 12

13 Caoball Program Specificatio The iput to the program will be the lauch agle (i degrees), the iitial velocity (i meters per secod), ad the iitial height (i meters) of the caoball. The output will be the distace that the projectile travels before strikig the groud (i meters). Pytho Programmig, 2/e 13

14 Caoball Program Specificatio The acceleratio of gravity ear the earth s surface is roughly 9.8 m/s/s. If a object is throw straight up at 20 m/s, after oe secod it will be travelig upwards at 10.2 m/s. After aother secod, its speed will be.4 m/s. Shortly after that the object will start comig back dow to earth. Pytho Programmig, 2/e 14

15 Caoball Program Specificatio Usig calculus, we could derive a formula that gives the positio of the caoball at ay momet of its flight. However, we ll solve this problem with simulatio, a little geometry, ad the fact that the distace a object travels i a certai amout of time is equal to its rate times the amout of time (d = rt). Pytho Programmig, 2/e 15

16 Desigig the Program Give the ature of the problem, it s obvious we eed to cosider the flight of the caoball i two dimesios: it s height ad the distace it travels. Let s thik of the positio of the caoball as the poit (x, y) where x is the distace from the startig poit ad y is the height above the groud. Pytho Programmig, 2/e 16

17 Desigig the Program Suppose the ball starts at positio (0,0), ad we wat to check its positio every teth of a secod. I that time iterval it will have moved some distace upward (positive y) ad some distace forward (positive x). The exact distace will be determied by the velocity i that directio. Pytho Programmig, 2/e 17

18 Desigig the Program Sice we are igorig wid resistace, x will remai costat through the flight. However, y will chage over time due to gravity. The y velocity will start out positive ad the become egative as the ball starts to fall. Pytho Programmig, 2/e 18

19 Desigig the Program Iput the simulatio parameters: agle, velocity, height, iterval. Calculate the iitial positio of the caoball: xpos, ypos Calculate the iitial velocities of the caoball: xvel, yvel While the caoball is still flyig: Update the values of xpos, ypos, ad yvel for iterval secods further ito the flight Output the distace traveled as xpos Pytho Programmig, 2/e 19

20 Desigig the Program Usig step-wise refiemet: def mai(): agle = eval(iput("eter the lauch agle (i degrees): ")) vel = eval(iput("eter the iitial velocity (i meters/sec): ")) h0 = eval(iput("eter the iitial height (i meters): ")) time = eval(iput("eter the time iterval betwee positio calculatios: ")) Calculatig the iitial positio for the caoball is also easy. It s at distace 0 ad height h0! xpos = 0 ypos = h0 Pytho Programmig, 2/e 20

21 Desigig the Program If we kow the magitude of the velocity ad the agle theta, we ca calculate yvel=velocity*si(theta)ad xvel=velocity*cos(theta). Pytho Programmig, 2/e 21

22 Desigig the Program Our iput agle is i degrees, ad the Pytho math library uses radias, so theta = (p*agle)/180. theta = (agle * pi)/180.0 xvel = vel * cos(theta) yvel = vel * si(theta) I the mai loop, we wat to keep updatig the positio of the ball util it reaches the groud: while ypos >= 0.0: We used >= 0 so the loop will start if the ball starts out o the groud. Pytho Programmig, 2/e 22

23 Desigig the Program Each time through the loop we wat to update the state of the caoball to move it time secods farther. Sice we assume there is o wid resistace, xvel remais costat. Say a ball is travelig at 30 m/s ad is 50 m from the firig poit. I oe secod it will be meters away. If the time icremet is.1 secod it will be *.1 = 53 meters. xpos = xpos + time * xvel Pytho Programmig, 2/e 23

24 Desigig the Program Workig with yvel is slightly more complicated sice gravity causes the y- velocity to chage over time. Each secod, yvel must decrease by 9.8 m/s, the acceleratio due to gravity. I 0.1 secods the velocity will be 0.1(9.8) =.98 m/s. yvel1 = yvel * time Pytho Programmig, 2/e 24

25 Desigig the Programs To calculate how far the caoball travels over the iterval, we eed to calculate its average vertical velocity over the iterval. Sice the velocity due to gravity is costat, it is simply the average of the startig ad edig velocities times the legth of the iterval: ypos = ypos + time * (yvel + yvel1)/2.0 Pytho Programmig, 2/e 25

26 Desigig Programs # cball1.py # Simulatio of the flight of a cao ball (or other projectile) # This versio is ot modularized. from math import pi, si, cos def mai(): agle = eval(iput("eter the lauch agle (i degrees): ")) vel = eval(iput("eter the iitial velocity (i meters/sec): ")) h0 = eval(iput("eter the iitial height (i meters): ")) time = eval(iput("eter the time iterval betwee positio calculatios: ")) mai() radias = (agle * pi)/180.0 xpos = 0 ypos = h0 xvel = vel * cos(radias) yvel = vel * si(radias) while ypos >= 0: xpos = xpos + time * xvel yvel1 = yvel * time ypos = ypos + time * (yvel + yvel1)/2.0 yvel = yvel1 prit("\distace traveled: {0:0.1f} meters.".format(xpos) Pytho Programmig, 2/e 26

27 Modularizig the Program Durig program developmet, we employed step-wise refiemet (ad top-dow desig), but did ot divide the program ito fuctios. While this program is fairly short, it is complex due to the umber of variables. Pytho Programmig, 2/e 27

28 Modularizig the Program def mai(): agle, vel, h0, time = getiputs() xpos, ypos = 0, h0 xvel, yvel = getxycompoets(vel, agle) while ypos >= 0: xpos, ypos, yvel = updatecaoball(time, xpos, ypos, xvel, yvel) prit("\distace traveled: {0:0.1f} meters.".format(xpos) It should be obvious what each of these helper fuctios does based o their ame ad the origial program code. Pytho Programmig, 2/e 28

29 Modularizig the Program This versio of the program is more cocise! The umber of variables has bee reduced from 10 to 8, sice theta ad yvel1 are local to getxycompoets ad updatecaoball, respectively. This may be simpler, but keepig track of the caoball still requires four pieces of iformatio, three of which chage from momet to momet! Pytho Programmig, 2/e 29

30 Modularizig the Program All four variables, plus time, are eeded to compute the ew values of the three that chage. This gives us a fuctio with five parameters ad three retur values. Yuck! There must be a better way! Pytho Programmig, 2/e 30

31 Modularizig the Program There is a sigle real-world caoball object, but it requires four pieces of iformatio: xpos, ypos, xvel,x ad yvel. Suppose there was a Projectile class that uderstood the physics of objects like caoballs. A algorithm usig this approach would create ad update a object stored i a sigle variable. Pytho Programmig, 2/e 31

32 Modularizig the Program Usig our object-based approach: def mai(): agle, vel, h0, time = getiputs() cball = Projectile(agle, vel, h0) while cball.gety() >= 0: cball.update(time) prit("\distace traveled: {0:0.1f} meters.".format(cball.getx())) mai() To make this work we eed a Projectile class that implemets the methods update, getx, ad gety. Pytho Programmig, 2/e 32

33 Example: Multi-Sided Dice A ormal die (sigular of dice) is a cube with six faces, each with a umber from oe to six. Some games use special dice with a differet umber of sides. Let s desig a geeric class MSDie to model multi-sided dice. Pytho Programmig, 2/e 33

34 Example: Multi-Sided Dice Each MSDie object will kow two thigs: How may sides it has. It s curret value Whe a ew MSDie is created, we specify, the umber of sides it will have. Pytho Programmig, 2/e 34

35 Example: Multi-Sided Dice We have three methods that we ca use to operate o the die: roll set the die to a radom value betwee 1 ad, iclusive. setvalue set the die to a specific value (i.e. cheat) getvalue see what the curret value is. Pytho Programmig, 2/e 35

36 Example: Multi-Sided Dice >>> die1 = MSDie(6) >>> die1.getvalue() 1 >>> die1.roll() >>> die1.getvalue() 5 >>> die2 = MSDie(13) >>> die2.getvalue() 1 >>> die2.roll() >>> die2.getvalue() 9 >>> die2.setvalue(8) >>> die2.getvalue() 8 Pytho Programmig, 2/e 36

37 Example: Multi-Sided Dice Usig our object-orieted vocabulary, we create a die by ivokig the MSDie costructor ad providig the umber of sides as a parameter. Our die objects will keep track of this umber iterally as a istace variable. Aother istace variable is used to keep the curret value of the die. We iitially set the value of the die to be 1 because that value is valid for ay die. That value ca be chaged by the roll ad setroll methods, ad retured by the getvalue method. Pytho Programmig, 2/e 37

38 Example: Multi-Sided Dice # msdie.py # Class defiitio for a -sided die. from radom import radrage class MSDie: def iit (self, sides): self.sides = sides self.value = 1 def roll(self): self.value = radrage(1, self.sides+1) def getvalue(self): retur self.value def setvalue(self, value): self.value = value Pytho Programmig, 2/e 38

39 Example: Multi-Sided Dice Class defiitios have the form class <class-ame>: <method-defiitios> Methods look a lot like fuctios! Placig the fuctio iside a class makes it a method of the class, rather tha a stad-aloe fuctio. The first parameter of a method is always amed self, which is a referece to the object o which the method is actig. Pytho Programmig, 2/e 39

40 Example: Multi-Sided Dice Suppose we have a mai fuctio that executes die1.setvalue(8). Just as i fuctio calls, Pytho executes the followig four-step sequece: mai suspeds at the poit of the method applicatio. Pytho locates the appropriate method defiitio iside the class of the object to which the method is beig applied. Here, cotrol is trasferred to the setvalue method i the MSDie class, sice die1 is a istace of MSDie. Pytho Programmig, 2/e 40

41 Example: Multi-Sided Dice The formal parameters of the method get assiged the values supplied by the actual parameters of the call. I the case of a method call, the first formal parameter refers to the object: self = die1 value = 8 The body of the method is executed. Pytho Programmig, 2/e 41

42 Example: Multi-Sided Dice Cotrol returs to the poit just after where the method was called. I this case, it is immediately followig die1.setvalue(8). Methods are called with oe parameter, but the method defiitio itself icludes the self parameter as well as the actual parameter. Pytho Programmig, 2/e 42

43 Example: Multi-Sided Dice The self parameter is a bookkeepig detail. We ca refer to the first formal parameter as the self parameter ad other parameters as ormal parameters. So, we could say setvalue uses oe ormal parameter. Pytho Programmig, 2/e 43

44 Example: Multi-Sided Dice Pytho Programmig, 2/e 44

45 Example: Multi-Sided Dice Objects cotai their ow data. Istace variables provide storage locatios iside of a object. Istace variables are accessed by ame usig our dot otatio: <object>.<istace-var> Lookig at setvalue, we see self.value refers to the istace variable value iside the object. Each MSDie object has its ow value. Pytho Programmig, 2/e 45

46 Example: Multi-Sided Dice Certai methods have special meaig. These methods have ames that start ad ed with two _ s. iit is the object cotructor. Pytho calls this method to iitialize a ew MSDie. iit provides iitial values for the istace variables of a object. Pytho Programmig, 2/e 46

47 Example: Multi-Sided Dice Outside the class, the costructor is referred to by the class ame: die1 = MSDie(6) Whe this statemet is executed, a ew MSDie object is created ad iit is executed o that object. The et result is that die1.sides is set to 6 ad die1.value is set to 1. Pytho Programmig, 2/e 47

48 Example: Multi-Sided Dice Istace variables ca remember the state of a particular object, ad this iformatio ca be passed aroud the program as part of the object. This is differet tha local fuctio variables, whose values disappear whe the fuctio termiates. Pytho Programmig, 2/e 48

49 Example: The Projectile Class This class will eed a costructor to iitialize istace variables, a update method to chage the state of the projectile, ad getx ad gety methods that ca report the curret positio. I the mai program, a caoball ca be created from the iitial agle, velocity, ad height: cball = Projectile(agle, vel, h0) Pytho Programmig, 2/e 49

50 Example: The Projectile Class The Projectile class must have a iit method that will use these values to iitialize the istace variables of cball. These values will be calculated usig the same formulas as before. Pytho Programmig, 2/e 50

51 Example: The Projectile Class class Projectile: def iit (self, agle, velocity, height): self.xpos = 0.0 self.ypos = height theta = pi * agle / self.xvel = velocity * cos(theta) self.yvel = velocity * si(theta) We ve created four istace variables (self.???). Sice the value of theta is ot eeded later, it is a ormal fuctio variable. Pytho Programmig, 2/e 51

52 Example: The Projectile Class The methods to access the X ad Y positio are straightforward. def gety(self): retur self.ypos def getx(self): retur self.xpos Pytho Programmig, 2/e 52

53 Example: The Projectile Class The last method is update, where we ll take the time iterval ad calculate the update X ad Y values. def update(self, time): self.xpos = self.xpos + time * self.xvel yvel1 = self.yvel * time self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 self.yvel = yvel1 yvel1 is a temporary variable. Pytho Programmig, 2/e 53

54 Data Processig with Class A class is useful for modelig a real-world object with complex behavior. Aother commo use for objects is to group together a set of iformatio that describes a perso or thig. Eg., a compay eeds to keep track of iformatio about employees (a Employee class with iformatio such as employee s ame, social security umber, address, salary, etc.) Pytho Programmig, 2/e 54

55 Data Processig with Class Groupig iformatio like this is ofte called a record. Let s try a simple data processig example! A typical uiversity measures courses i terms of credit hours, ad grade poit averages are calculated o a 4 poit scale where a A is 4 poits, a B is three, etc. Pytho Programmig, 2/e 55

56 Data Processig with Class Grade poit averages are geerally computed usig quality poits. If a class is worth 3 credit hours ad the studet gets a A, the he or she ears 3(4) = 12 quality poits. To calculate the GPA, we divide the total quality poits by the umber of credit hours completed. Pytho Programmig, 2/e 56

57 Data Processig with Class Suppose we have a data file that cotais studet grade iformatio. Each lie of the file cosists of a studet s ame, credit-hours, ad quality poits. Adams, Hery Comptewell, Susa DibbleBit, Dey Joes, Jim Smith, Frak Pytho Programmig, 2/e 57

58 Data Processig with Class Our job is to write a program that reads this file to fid the studet with the best GPA ad prit out their ame, credithours, ad GPA. The place to start? Creatig a Studet class! We ca use a Studet object to store this iformatio as istace variables. Pytho Programmig, 2/e 58

59 Data Processig with Class class Studet: def iit (self, ame, hours, qpoits): self.ame = ame self.hours = float(hours) self.qpoits = float(qpoits) The values for hours are coverted to float to hadle parameters that may be floats, its, or strigs. To create a studet record: astudet = Studet( Adams, Hery, 127, 228) The coolest thig is that we ca store all the iformatio about a studet i a sigle variable! Pytho Programmig, 2/e 59

60 Data Processig with Class We eed to be able to access this iformatio, so we eed to defie a set of accessor methods. def getname(self): retur self.ame def gethours(self): retur self.hours def getqpoits(self): retur self.qpoits def gpa(self): retur self.qpoits/self.hours For example, to prit a studet s ame you could write: prit astudet.getname() Pytho Programmig, 2/e 60

61 Data Processig with Class How ca we use these tools to fid the studet with the best GPA? We ca use a algorithm similar to fidig the max of umbers! We could look through the list oe by oe, keepig track of the best studet see so far! Pytho Programmig, 2/e 61

62 Data Processig with Class Get the file ame from the user Ope the file for readig Set best to be the first studet For each studet s i the file if s.gpa() > best.gpa set best to s Prit out iformatio about best Pytho Programmig, 2/e 62

63 Data Processig with Class # gpa.py # Program to fid studet with highest GPA class Studet: def iit (self, ame, hours, qpoits): self.ame = ame self.hours = float(hours) self.qpoits = float(qpoits) def getname(self): retur self.ame def gethours(self): retur self.hours def mai(): fileame = iput("eter ame the grade file: ") ifile = ope(fileame, 'r') best = makestudet(ifile.readlie()) for lie i ifile: s = makestudet(lie) if s.gpa() > best.gpa(): best = s ifile.close() prit("the best studet is:", best.getname()) prit ("hours:", best.gethours()) prit("gpa:", best.gpa()) if ame == ' mai ': mai() def getqpoits(self): retur self.qpoits def gpa(self): retur self.qpoits/self.hours def makestudet(ifostr): ame, hours, qpoits = ifostr.split("\t") retur Studet(ame, hours, qpoits) Pytho Programmig, 2/e 63

64 Ecapsulatig Useful Abstractios Defiig ew classes (like Projectile ad Studet) ca be a good way to modularize a program. Oce some useful objects are idetified, the implemetatio details of the algorithm ca be moved ito a suitable class defiitio. Pytho Programmig, 2/e 64

65 Ecapsulatig Useful Abstractios The mai program oly has to worry about what objects ca do, ot about how they are implemeted. I computer sciece, this separatio of cocers is kow as ecapsulatio. The implemetatio details of a object are ecapsulated i the class defiitio, which isulates the rest of the program from havig to deal with them. Pytho Programmig, 2/e 65

66 Ecapsulatig Useful Abstractios Oe of the mai reasos to use objects is to hide the iteral complexities of the objects from the programs that use them. From outside the class, all iteractio with a object ca be doe usig the iterface provided by its methods. Pytho Programmig, 2/e 66

67 Ecapsulatig Useful Abstractios Oe advatage of this approach is that it allows us to update ad improve classes idepedetly without worryig about breakig other parts of the program, provided that the iterface provided by the methods does ot chage. Pytho Programmig, 2/e 67

68 Puttig Classes i Modules Sometimes we may program a class that could useful i may other programs. If you might be reusig the code agai, put it ito its ow module file with documetatio to describe how the class ca be used so that you wo t have to try to figure it out i the future from lookig at the code! Pytho Programmig, 2/e 68

69 Module Documetatio You are already familiar with # to idicate commets explaiig what s goig o i a Pytho file. Pytho also has a special kid of commetig covetio called the docstrig. You ca isert a plai strig literal as the first lie of a module, class, or fuctio to documet that compoet. Pytho Programmig, 2/e 69

70 Module Documetatio Why use a docstrig? Ordiary commets are igored by Pytho Docstrigs are accessible i a special attribute called doc. Most Pytho library modules have extesive docstrigs. For example, if you ca t remember how to use radom: >>> import radom >>> prit radom.radom. doc radom() -> x i the iterval [0, 1). Pytho Programmig, 2/e 70

71 Module Documetatio Docstrigs are also used by the Pytho olie help system ad by a utility called PyDoc that automatically builds documetatio for Pytho modules. You could get the same iformatio like this: >>> import radom >>> help(radom.radom) Help o built-i fuctio radom: radom(...) radom() -> x i the iterval [0, 1). Pytho Programmig, 2/e 71

72 Module Documetatio To see the documetatio for a etire module, try typig help(module_ame)! The followig code for the projectile class has docstrigs. Pytho Programmig, 2/e 72

73 Module Documetatio # projectile.py """projectile.py Provides a simple class for modelig the flight of projectiles.""" from math import pi, si, cos class Projectile: """Simulates the flight of simple projectiles ear the earth's surface, igorig wid resistace. Trackig is doe i two dimesios, height (y) ad distace (x).""" def iit (self, agle, velocity, height): """Create a projectile with give lauch agle, iitial velocity ad height.""" self.xpos = 0.0 self.ypos = height theta = pi * agle / self.xvel = velocity * cos(theta) self.yvel = velocity * si(theta) Pytho Programmig, 2/e 73

74 Module Documetatio def update(self, time): """Update the state of this projectile to move it time secods farther ito its flight""" self.xpos = self.xpos + time * self.xvel yvel1 = self.yvel * time self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 self.yvel = yvel1 def gety(self): "Returs the y positio (height) of this projectile." retur self.ypos def getx(self): "Returs the x positio (distace) of this projectile." retur self.xpos Pytho Programmig, 2/e 74

75 Workig with Multiple Modules Our mai program ca import from the projectile module i order to solve the origial problem! # cball4.py # Simulatio of the flight of a cao ball (or other projectile) # This versio uses a separate projectile module file from projectile import Projectile def getiputs(): a = eval(iput("eter the lauch agle (i degrees): ")) v = eval(iput("eter the iitial velocity (i meters/sec): ")) h = eval(iput("eter the iitial height (i meters): ")) t = eval(iput("eter the time iterval betwee positio calculatios: ")) retur a,v,h,t def mai(): agle, vel, h0, time = getiputs() cball = Projectile(agle, vel, h0) while cball.gety() >= 0: cball.update(time) prit("\distace traveled: {0:0.1f} meters.".format(cball.getx()) Pytho Programmig, 2/e 75

76 Workig with Multiple Modules If you are testig a multi-module Pytho program, you eed to be aware that reloadig a module may ot behave as you expect. Whe Pytho first imports a give module, it creates a module object that cotais all the thigs defied i the module (a amespace). If a module imports successfully (o sytax errors), subsequet imports do ot reload the module. Eve if the source code for the module has bee chaged, re-importig it ito a iteractive sessio will ot load the updated versio. Pytho Programmig, 2/e 76

77 Workig with Multiple Modules The easiest way start a ew iteractive sessio for testig wheever ay of the modules ivolved i your testig are modified. This way you re guarateed to get a more recet import of all the modules you re usig. Pytho Programmig, 2/e 77

78 Widgets Oe very commo use of objects is i the desig of graphical user iterfaces (GUIs). Back i chapter 5 we talked about GUIs beig composed of visual iterface objects kow as widgets. The Etry object defied i our graphics library is oe example of a widget. Pytho Programmig, 2/e 78

79 Example Program: Dice Roller Let s build a couple useful widgets! Cosider a program that rolls a pair of six-sided dice. The program will display the dice graphically ad provide two buttos, oe for rollig the dice ad oe for quittig the program. Pytho Programmig, 2/e 79

80 Example Program: Dice Roller There are two kids of widgets: buttos ad dice. The two buttos will be examples of the Butto class, while the dice images will be provided by dieview. Pytho Programmig, 2/e 80

81 Buildig Buttos Most moder GUIs have buttos with 3- dimesioal look ad feel. Our simple graphics package does ot have the machiery to produce buttos that appear to depress as they are clicked. All we ca do is report back where the mouse was clicked after the click has bee completed. Pytho Programmig, 2/e 81

82 Buildig Buttos Our buttos will be rectagular regios i a graphics widow where user clicks ca ifluece the behavior of the ruig applicatio. We eed a way to determie whether a butto has bee clicked. It would be ice to be able to activate ad deactivate (gray-out) idividual buttos. Pytho Programmig, 2/e 82

83 Buildig Buttos Costructor Create a butto i a widow. We will specify the widow, locatio/size of the butto, ad the label o the butto. Activate Set the state of the butto to active. Deactivate Set the state of the butto to iactive. Pytho Programmig, 2/e 83

84 Buildig Buttos Clicked Idicate if the butto was clicked. If the butto is active, this method will determie if the poit clicked is iside the butto regio. The poit will have to be set as a parameter to the method. getlabel Returs the label strig of a butto. This is provided so that we ca idetify a particular butto. Pytho Programmig, 2/e 84

85 Buildig Buttos To support these operatios, our buttos will eed a umber of istace variables. For example, buttos are draw as a rectagle with some text cetered o it. Ivokig the activate ad deactivate methods will chage the appearace of the buttos. Pytho Programmig, 2/e 85

86 Buildig Buttos Savig the Rectagle ad Text objects as istace variables meas we will be able to cotrol the width of the outlie ad color of the label. Let s try writig these methods ad build up a list of possible istace variables! Oce we have the list, we ca write the costructor to iitialize them. Pytho Programmig, 2/e 86

87 Buildig Buttos I activate, we ca sigal a butto is active by makig its outlie thicker ad makig the label text black. def activate(self): "Sets this butto to 'active'. " self.label.setfill('black') self.rect.setwidth(2) self.active = True Remember, self refers to the butto object. Our costructor will have to iitialize self.label as a appropriate Text object ad self.rect as a rectagle object. Self.active also has a Boolea istace variable to remember whether or ot the butto is curretly iactive. Pytho Programmig, 2/e 87

88 Buildig Buttos The code for deactivate is very similar: def deactivate(self): "Sets this butto to 'iactive'." self.label.setfill('darkgrey') self.rect.setwidth(1) self.active = 0 Pytho Programmig, 2/e 88

89 Buildig Buttos Let s work o the clicked method. The graphics package has the getmouse method to see if ad where the mouse has bee clicked. If a applicatio eeds to get a butto click, it will have to first call getmouse ad the see which butto, if ay, the poit is iside of. Pytho Programmig, 2/e 89

90 Buildig Buttos pt = wi.getmouse() if butto1.clicked(pt): # Do butto1 stuff elif butto2.clicked(pt): # Do butto2 stuff elif butto3.clicked(pt): # Do butto3 stuff The mai job of the clicked method is to determie whether a give poit is iside the rectagular butto. Pytho Programmig, 2/e 90

91 Buildig Buttos The poit is iside the butto if its x ad y coordiates lie betwee the extreme x ad y values of the rectagle. This would be easiest if the butto object had the mi ad max values of x ad y as istace variables. Pytho Programmig, 2/e 91

92 Buildig Buttos def clicked(self, p): "RETURNS true if butto active ad p is iside retur self.active ad \ self.xmi <= p.getx() <= self.xmax ad \ self.ymi <= p.gety() <= self.ymax For this fuctio to retur True, all three parts of the Boolea expressio must be true. The first part esures that oly active buttos will retur that they have bee clicked. The secod ad third parts esure that the x ad y values of the poit that was clicked fall betwee the boudaries of the rectagle. Pytho Programmig, 2/e 92

93 Buildig Buttos The oly part that is left is to write the costructor: def iit (self, wi, ceter, width, height, label): """ Creates a rectagular butto, eg: qb = Butto(myWi, Poit(30,25), 20, 10, 'Quit') """ w,h = width/2.0, height/2.0 x,y = ceter.getx(), ceter.gety() self.xmax, self.xmi = x+w, x-w self.ymax, self.ymi = y+h, y-h p1 = Poit(self.xmi, self.ymi) p2 = Poit(self.xmax, self.ymax) self.rect = Rectagle(p1,p2) self.rect.setfill('lightgray') self.rect.draw(wi) self.label = Text(ceter, label) self.label.draw(wi) self.deactivate() Buttos are positioed by providig a ceter poit, width, ad height. Pytho Programmig, 2/e 93

94 Buildig Dice The purpose of the DieView class is to graphically display the value of a die. The face of the die is a square/rectagle, ad the pips/spots o the die are circles. As before, the DieView class will have a costructor ad a method. Pytho Programmig, 2/e 94

95 Buildig Dice costructor Create a die i a widow. We will specify the widow, the ceter poit of the die, ad the size of the die as parameters. setvalue Chage the view to show a give value. The value to display will be passed as a parameter. Pytho Programmig, 2/e 95

96 Buildig Dice Clearly, the hardest part of this will be to tur o the pips o the die to represet the curret value of the die. Oe approach is to pre-place the pips, ad make them the same color as the die. Whe the spot is tured o, it will be redraw with a darker color. Pytho Programmig, 2/e 96

97 Buildig Dice A stadard die will eed seve pips -- a colum of three o the left ad right sides, ad oe i the ceter. The costructor will create the backgroud square ad the seve circles. setvalue will set the colors of the circles based o the value of the die. Pytho Programmig, 2/e 97

98 Buildig Dice # dieview.py # A widget for displayig the value of a die from graphics import * class DieView: """ DieView is a widget that displays a graphical represetatio of a stadard six-sided die.""" def iit (self, wi, ceter, size): """Create a view of a die, e.g.: d1 = GDie(myWi, Poit(40,50), 20) creates a die cetered at (40,50) havig sides of legth 20.""" # first defid some stadard values self.wi = wi self.backgroud = "white" # color of die face self.foregroud = "black" # color of the pips self.psize = 0.1 * size # radius of each pip hsize = size / 2.0 # half of size offset = 0.6 * hsize # distace from ceter to outer pip Pytho Programmig, 2/e 98

99 Buildig Dice # create a square for the face cx, cy = ceter.getx(), ceter.gety() p1 = Poit(cx-hsize, cy-hsize) p2 = Poit(cx+hsize, cy+hsize) rect = Rectagle(p1,p2) rect.draw(wi) rect.setfill(self.backgroud) # Create 7 circles for stadard pip locatios self.pip1 = self. makepip(cx-offset, cy-offset) self.pip2 = self. makepip(cx-offset, cy) self.pip3 = self. makepip(cx-offset, cy+offset) self.pip4 = self. makepip(cx, cy) self.pip5 = self. makepip(cx+offset, cy-offset) self.pip6 = self. makepip(cx+offset, cy) self.pip7 = self. makepip(cx+offset, cy+offset) self.setvalue(1) Pytho Programmig, 2/e 99

100 Buildig Dice def makepip(self, x, y): """Iteral helper method to draw a pip at (x,y)""" pip = Circle(Poit(x,y), self.psize) pip.setfill(self.backgroud) pip.setoutlie(self.backgroud) pip.draw(self.wi) retur pip def setvalue(self, value): """ Set this die to display value.""" # tur all pips off self.pip1.setfill(self.backgroud) self.pip2.setfill(self.backgroud) self.pip3.setfill(self.backgroud) self.pip4.setfill(self.backgroud) self.pip5.setfill(self.backgroud) self.pip6.setfill(self.backgroud) self.pip7.setfill(self.backgroud) Pytho Programmig, 2/e 100

101 Buildig Dice # tur correct pips o if value == 1: self.pip4.setfill(self.foregroud) elif value == 2: self.pip1.setfill(self.foregroud) self.pip7.setfill(self.foregroud) elif value == 3: self.pip1.setfill(self.foregroud) self.pip7.setfill(self.foregroud) self.pip4.setfill(self.foregroud) elif value == 4: self.pip1.setfill(self.foregroud) self.pip3.setfill(self.foregroud) self.pip5.setfill(self.foregroud) self.pip7.setfill(self.foregroud) elif value == 5: self.pip1.setfill(self.foregroud) self.pip3.setfill(self.foregroud) self.pip4.setfill(self.foregroud) self.pip5.setfill(self.foregroud) self.pip7.setfill(self.foregroud) else: self.pip1.setfill(self.foregroud) self.pip2.setfill(self.foregroud) self.pip3.setfill(self.foregroud) self.pip5.setfill(self.foregroud) self.pip6.setfill(self.foregroud) self.pip7.setfill(self.foregroud) Pytho Programmig, 2/e 101

102 Buildig Dice Thigs to otice: The size of the spots beig 1/10 of the size of the die was determied by trial ad error. We defie ad calculate various attributes of the die i the costructor ad the use them i other methods ad fuctios withi the class so that if we wated to chage the appearace, all those values ad the code to go with them is i oe place, rather tha throughout the class. Pytho Programmig, 2/e 102

103 Buildig Dice makepip is a helper fuctio to draw each of the seve pips o the die. Sice it is oly useful withi DieView, it s appropriate to make it a class method. It s ame starts with to idicate that its use is private to the class ad is ot iteded to be used outside the class. Pytho Programmig, 2/e 103

104 The Mai Program # roller.py # Graphics program to roll a pair of dice. Uses custom widgets # Butto ad GDie. from radom import radrage from graphics import GraphWi, Poit from butto import Butto from dieview import DieView def mai(): # create the applicatio widow wi = GraphWi("Dice Roller") wi.setcoords(0, 0, 10, 10) wi.setbackgroud("gree2") # Draw the iterface widgets die1 = DieView(wi, Poit(3,7), 2) die2 = DieView(wi, Poit(7,7), 2) rollbutto = Butto(wi, Poit(5,4.5), 6, 1, "Roll Dice") rollbutto.activate() quitbutto = Butto(wi, Poit(5,1), 2, 1, "Quit") Pytho Programmig, 2/e 104

105 The Mai Program # Evet loop pt = wi.getmouse() while ot quitbutto.clicked(pt): if rollbutto.clicked(pt): value1 = radrage(1,7) die1.setvalue(value1) value2 = radrage(1,7) die2.setvalue(value2) quitbutto.activate() pt = wi.getmouse() mai() # close up shop wi.close() Pytho Programmig, 2/e 105

106 The Mai Program The visual iterface is built by creatig the two DieViews ad two Buttos. The roll butto is iitially active, but the quit butto is deactivated. This forces the user to roll the dice at least oce. The evet loop is a setiel loop that gets mouse clicks ad processes them util the user clicks o the quit butto. Pytho Programmig, 2/e 106

107 The Mai Program The if withi the loop esures that the dice are rolled oly whe the user clicks the roll butto. Clickig a poit that is ot iside ay butto causes the loop to iterate without doig aythig. Pytho Programmig, 2/e 107

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 10 Part 2 The Department of Computer Science Cannonball Program Specification Let s try to write a program that simulates

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 10 The Department of Computer Science Objectives Chapter 10 Part 1 To know how defining new classes can provide structure

More information

Outline: Defining objects (Ch10)

Outline: Defining objects (Ch10) Defining objects Michael Mandel Lecture 10 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture10final.ipynb

More information

Python Programming: An Introduction To Computer Science

Python Programming: An Introduction To Computer Science Python Programming: An Introduction To Computer Science Chapter 10 Defining Classes Python Programming, 2/e 1 Objectives æ To appreciate how defining new classes can provide structure for a complex program.

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 10 Part 1 Instructor: Long Ma The Department of Computer Science Top-Down Design 2 In top-down design, a complex problem

More information

Lecture. Classes. Richard E Sarkis CSC 161: The Art of Programming

Lecture. Classes. Richard E Sarkis CSC 161: The Art of Programming Lecture Classes Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda Formalize our understanding of objects To appreciate how defining new classes and using objects can provide structure

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4

More information

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig

More information

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,

More information

Computers and Scientific Thinking

Computers and Scientific Thinking Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput

More information

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:

More information

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

The number n of subintervals times the length h of subintervals gives length of interval (b-a). Simulator with MadMath Kit: Riema Sums (Teacher s pages) I your kit: 1. GeoGebra file: Ready-to-use projector sized simulator: RiemaSumMM.ggb 2. RiemaSumMM.pdf (this file) ad RiemaSumMMEd.pdf (educator's

More information

. Written in factored form it is easy to see that the roots are 2, 2, i,

. Written in factored form it is easy to see that the roots are 2, 2, i, CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or

More information

IMP: Superposer Integrated Morphometrics Package Superposition Tool

IMP: Superposer Integrated Morphometrics Package Superposition Tool IMP: Superposer Itegrated Morphometrics Package Superpositio Tool Programmig by: David Lieber ( 03) Caisius College 200 Mai St. Buffalo, NY 4208 Cocept by: H. David Sheets, Dept. of Physics, Caisius College

More information

Python Programming: An Introduction To Computer Science

Python Programming: An Introduction To Computer Science Python Programming: An Introduction To Computer Science Chapter 10 Defining Classes Python Programming, 3/e 1 Objectives To appreciate how defining new classes can provide structure for a complex program.

More information

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4

More information

Appendix D. Controller Implementation

Appendix D. Controller Implementation COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Appedix D Cotroller Implemetatio Cotroller Implemetatios Combiatioal logic (sigle-cycle); Fiite state machie (multi-cycle, pipelied);

More information

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence _9.qxd // : AM Page Chapter 9 Sequeces, Series, ad Probability 9. Sequeces ad Series What you should lear Use sequece otatio to write the terms of sequeces. Use factorial otatio. Use summatio otatio to

More information

Overview Chapter 12 A display model

Overview Chapter 12 A display model Overview Chapter 12 A display model Why graphics? A graphics model Examples Bjare Stroustrup www.stroustrup.com/programmig 3 Why bother with graphics ad GUI? Why bother with graphics ad GUI? It s very

More information

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig

More information

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig

More information

The isoperimetric problem on the hypercube

The isoperimetric problem on the hypercube The isoperimetric problem o the hypercube Prepared by: Steve Butler November 2, 2005 1 The isoperimetric problem We will cosider the -dimesioal hypercube Q Recall that the hypercube Q is a graph whose

More information

Ones Assignment Method for Solving Traveling Salesman Problem

Ones Assignment Method for Solving Traveling Salesman Problem Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:

More information

One advantage that SONAR has over any other music-sequencing product I ve worked

One advantage that SONAR has over any other music-sequencing product I ve worked *gajedra* D:/Thomso_Learig_Projects/Garrigus_163132/z_productio/z_3B2_3D_files/Garrigus_163132_ch17.3d, 14/11/08/16:26:39, 16:26, page: 647 17 CAL 101 Oe advatage that SONAR has over ay other music-sequecig

More information

Learning to Shoot a Goal Lecture 8: Learning Models and Skills

Learning to Shoot a Goal Lecture 8: Learning Models and Skills Learig to Shoot a Goal Lecture 8: Learig Models ad Skills How do we acquire skill at shootig goals? CS 344R/393R: Robotics Bejami Kuipers Learig to Shoot a Goal The robot eeds to shoot the ball i the goal.

More information

The Magma Database file formats

The Magma Database file formats The Magma Database file formats Adrew Gaylard, Bret Pikey, ad Mart-Mari Breedt Johaesburg, South Africa 15th May 2006 1 Summary Magma is a ope-source object database created by Chris Muller, of Kasas City,

More information

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis

More information

Τεχνολογία Λογισμικού

Τεχνολογία Λογισμικού ΕΘΝΙΚΟ ΜΕΤΣΟΒΙΟ ΠΟΛΥΤΕΧΝΕΙΟ Σχολή Ηλεκτρολόγων Μηχανικών και Μηχανικών Υπολογιστών Τεχνολογία Λογισμικού, 7ο/9ο εξάμηνο 2018-2019 Τεχνολογία Λογισμικού Ν.Παπασπύρου, Αν.Καθ. ΣΗΜΜΥ, ickie@softlab.tua,gr

More information

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of

More information

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3

More information

How do we evaluate algorithms?

How do we evaluate algorithms? F2 Readig referece: chapter 2 + slides Algorithm complexity Big O ad big Ω To calculate ruig time Aalysis of recursive Algorithms Next time: Litterature: slides mostly The first Algorithm desig methods:

More information

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1 Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1 The simplest

More information

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems

More information

Software development of components for complex signal analysis on the example of adaptive recursive estimation methods.

Software development of components for complex signal analysis on the example of adaptive recursive estimation methods. Software developmet of compoets for complex sigal aalysis o the example of adaptive recursive estimatio methods. SIMON BOYMANN, RALPH MASCHOTTA, SILKE LEHMANN, DUNJA STEUER Istitute of Biomedical Egieerig

More information

Elementary Educational Computer

Elementary Educational Computer Chapter 5 Elemetary Educatioal Computer. Geeral structure of the Elemetary Educatioal Computer (EEC) The EEC coforms to the 5 uits structure defied by vo Neuma's model (.) All uits are preseted i a simplified

More information

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS) CSC165H1, Witer 018 Learig Objectives By the ed of this worksheet, you will: Aalyse the ruig time of fuctios cotaiig ested loops. 1. Nested loop variatios. Each of the followig fuctios takes as iput a

More information

CS 11 C track: lecture 1

CS 11 C track: lecture 1 CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material

More information

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016 CS 111: Program Desig I Lecture 15: Objects, Padas, Modules Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 13, 2016 OBJECTS AND DOT NOTATION Objects (Implicit i Chapter 2, Variables,

More information

CS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018

CS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018 CS 111: Program Desig I Lecture 15: Modules, Padas agai Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago March 8, 2018 PYTHON STANDARD LIBRARY & BEYOND: MODULES Extedig Pytho Every moder

More information

Threads and Concurrency in Java: Part 1

Threads and Concurrency in Java: Part 1 Cocurrecy Threads ad Cocurrecy i Java: Part 1 What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.

More information

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III GE2112 - FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III PROBLEM SOLVING AND OFFICE APPLICATION SOFTWARE Plaig the Computer Program Purpose Algorithm Flow Charts Pseudocode -Applicatio Software Packages-

More information

In this chapter, you learn the concepts and terminology of databases and

In this chapter, you learn the concepts and terminology of databases and A Itroductio to Database Developmet I this chapter, you lear the cocepts ad termiology of databases ad how to desig the tables that your forms ad reports will use. Fially, you build the actual tables used

More information

Threads and Concurrency in Java: Part 1

Threads and Concurrency in Java: Part 1 Threads ad Cocurrecy i Java: Part 1 1 Cocurrecy What every computer egieer eeds to kow about cocurrecy: Cocurrecy is to utraied programmers as matches are to small childre. It is all too easy to get bured.

More information

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup   Note: Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values

More information

CSE 111 Bio: Program Design I Class 11: loops

CSE 111 Bio: Program Design I Class 11: loops SE 111 Bio: Program Desig I lass 11: loops Radall Muroe, xkcd.com/1411/ Robert H. Sloa (S) & Rachel Poretsky (Bio) Uiversity of Illiois, hicago October 2, 2016 Pytho ets Loopy! he Pytho, Busch ardes Florida

More information

CSE 111 Bio: Program Design I Lecture 17: software development, list methods

CSE 111 Bio: Program Design I Lecture 17: software development, list methods CSE 111 Bio: Program Desig I Lecture 17: software developmet, list methods Robert H. Sloa(CS) & Rachel Poretsky(Bio) Uiversity of Illiois, Chicago October 19, 2017 NESTED LOOPS: REVIEW Geerate times table

More information

Which movie we can suggest to Anne?

Which movie we can suggest to Anne? ECOLE CENTRALE SUPELEC MASTER DSBI DECISION MODELING TUTORIAL COLLABORATIVE FILTERING AS A MODEL OF GROUP DECISION-MAKING You kow that the low-tech way to get recommedatios for products, movies, or etertaiig

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 22 Database Recovery Techiques Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio Recovery algorithms Recovery cocepts Write-ahead

More information

. Perform a geometric (ray-optics) construction (i.e., draw in the rays on the diagram) to show where the final image is formed.

. Perform a geometric (ray-optics) construction (i.e., draw in the rays on the diagram) to show where the final image is formed. MASSACHUSETTS INSTITUTE of TECHNOLOGY Departmet of Electrical Egieerig ad Computer Sciece 6.161 Moder Optics Project Laboratory 6.637 Optical Sigals, Devices & Systems Problem Set No. 1 Geometric optics

More information

Chapter 3 Classification of FFT Processor Algorithms

Chapter 3 Classification of FFT Processor Algorithms Chapter Classificatio of FFT Processor Algorithms The computatioal complexity of the Discrete Fourier trasform (DFT) is very high. It requires () 2 complex multiplicatios ad () complex additios [5]. As

More information

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19 CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.

More information

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1 COSC 1P03 Ch 7 Recursio Itroductio to Data Structures 8.1 COSC 1P03 Recursio Recursio I Mathematics factorial Fiboacci umbers defie ifiite set with fiite defiitio I Computer Sciece sytax rules fiite defiitio,

More information

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June CS 1313 010: Programmig for No-Majors, Summer 2007 Programmig Project #3: Two Little Calculatios Due by 12:00pm (oo) Wedesday Jue 27 2007 This third assigmet will give you experiece writig programs that

More information

Descriptive Statistics Summary Lists

Descriptive Statistics Summary Lists Chapter 209 Descriptive Statistics Summary Lists Itroductio This procedure is used to summarize cotiuous data. Large volumes of such data may be easily summarized i statistical lists of meas, couts, stadard

More information

Parabolic Path to a Best Best-Fit Line:

Parabolic Path to a Best Best-Fit Line: Studet Activity : Fidig the Least Squares Regressio Lie By Explorig the Relatioship betwee Slope ad Residuals Objective: How does oe determie a best best-fit lie for a set of data? Eyeballig it may be

More information

Performance Plus Software Parameter Definitions

Performance Plus Software Parameter Definitions Performace Plus+ Software Parameter Defiitios/ Performace Plus Software Parameter Defiitios Chapma Techical Note-TG-5 paramete.doc ev-0-03 Performace Plus+ Software Parameter Defiitios/2 Backgroud ad Defiitios

More information

27 Refraction, Dispersion, Internal Reflection

27 Refraction, Dispersion, Internal Reflection Chapter 7 Refractio, Dispersio, Iteral Reflectio 7 Refractio, Dispersio, Iteral Reflectio Whe we talked about thi film iterferece, we said that whe light ecouters a smooth iterface betwee two trasparet

More information

Alpha Individual Solutions MAΘ National Convention 2013

Alpha Individual Solutions MAΘ National Convention 2013 Alpha Idividual Solutios MAΘ Natioal Covetio 0 Aswers:. D. A. C 4. D 5. C 6. B 7. A 8. C 9. D 0. B. B. A. D 4. C 5. A 6. C 7. B 8. A 9. A 0. C. E. B. D 4. C 5. A 6. D 7. B 8. C 9. D 0. B TB. 570 TB. 5

More information

Fundamentals of Media Processing. Shin'ichi Satoh Kazuya Kodama Hiroshi Mo Duy-Dinh Le

Fundamentals of Media Processing. Shin'ichi Satoh Kazuya Kodama Hiroshi Mo Duy-Dinh Le Fudametals of Media Processig Shi'ichi Satoh Kazuya Kodama Hiroshi Mo Duy-Dih Le Today's topics Noparametric Methods Parze Widow k-nearest Neighbor Estimatio Clusterig Techiques k-meas Agglomerative Hierarchical

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig

More information

Pattern Recognition Systems Lab 1 Least Mean Squares

Pattern Recognition Systems Lab 1 Least Mean Squares Patter Recogitio Systems Lab 1 Least Mea Squares 1. Objectives This laboratory work itroduces the OpeCV-based framework used throughout the course. I this assigmet a lie is fitted to a set of poits usig

More information

Administrative UNSUPERVISED LEARNING. Unsupervised learning. Supervised learning 11/25/13. Final project. No office hours today

Administrative UNSUPERVISED LEARNING. Unsupervised learning. Supervised learning 11/25/13. Final project. No office hours today Admiistrative Fial project No office hours today UNSUPERVISED LEARNING David Kauchak CS 451 Fall 2013 Supervised learig Usupervised learig label label 1 label 3 model/ predictor label 4 label 5 Supervised

More information

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs

More information

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts CS 111 Gree: Program Desig I Lecture 27: Speed (cot.); partig thoughts By Nascarkig - Ow work, CC BY-SA 4.0, https://commos.wikimedia.org/w/idex.php?curid=38671041 Robert H. Sloa (CS) & Rachel Poretsky

More information

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle: Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical

More information

Goals of the Lecture UML Implementation Diagrams

Goals of the Lecture UML Implementation Diagrams Goals of the Lecture UML Implemetatio Diagrams Object-Orieted Aalysis ad Desig - Fall 1998 Preset UML Diagrams useful for implemetatio Provide examples Next Lecture Ð A variety of topics o mappig from

More information

COMP 558 lecture 6 Sept. 27, 2010

COMP 558 lecture 6 Sept. 27, 2010 Radiometry We have discussed how light travels i straight lies through space. We would like to be able to talk about how bright differet light rays are. Imagie a thi cylidrical tube ad cosider the amout

More information

Intro to Scientific Computing: Solutions

Intro to Scientific Computing: Solutions Itro to Scietific Computig: Solutios Dr. David M. Goulet. How may steps does it take to separate 3 objects ito groups of 4? We start with 5 objects ad apply 3 steps of the algorithm to reduce the pile

More information

Numerical Methods Lecture 6 - Curve Fitting Techniques

Numerical Methods Lecture 6 - Curve Fitting Techniques Numerical Methods Lecture 6 - Curve Fittig Techiques Topics motivatio iterpolatio liear regressio higher order polyomial form expoetial form Curve fittig - motivatio For root fidig, we used a give fuctio

More information

Improving Template Based Spike Detection

Improving Template Based Spike Detection Improvig Template Based Spike Detectio Kirk Smith, Member - IEEE Portlad State Uiversity petra@ee.pdx.edu Abstract Template matchig algorithms like SSE, Covolutio ad Maximum Likelihood are well kow for

More information

Baan Finance Financial Statements

Baan Finance Financial Statements Baa Fiace Fiacial Statemets Module Procedure UP041A US Documetiformatio Documet Documet code : UP041A US Documet group : User Documetatio Documet title : Fiacial Statemets Applicatio/Package : Baa Fiace

More information

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV Lecture 7 7 Refractio ad Sell s Law Readig Assigmet: Read Kipis Chapter 4 Refractio of Light, Sectio III, IV 7. History I Eglish-speakig coutries, the law of refractio is kow as Sell s Law, after the Dutch

More information

Evaluation scheme for Tracking in AMI

Evaluation scheme for Tracking in AMI A M I C o m m u i c a t i o A U G M E N T E D M U L T I - P A R T Y I N T E R A C T I O N http://www.amiproject.org/ Evaluatio scheme for Trackig i AMI S. Schreiber a D. Gatica-Perez b AMI WP4 Trackig:

More information

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8) CIS 11 Data Structures ad Algorithms with Java Fall 017 Big-Oh Notatio Tuesday, September 5 (Make-up Friday, September 8) Learig Goals Review Big-Oh ad lear big/small omega/theta otatios Practice solvig

More information

Example: Class MSDie Introduction to Graphs and NetworkX

Example: Class MSDie Introduction to Graphs and NetworkX Example: Class MSDie Introduction to Graphs and NetworkX Monday, March 30, 2009 1 Be careful whose random number generator you trust http://xkcd.com/221/ 2 1 Reminders Sample exam questions have been posted

More information

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..

More information

Location Steps and Paths

Location Steps and Paths Locatio Steps ad Paths 3 INTHIS CHAPTER Uderstadig Locatio Steps ad Paths How do locatio paths work? We took a look at locatio paths i the overview i Chapter 1, where we saw that locatio paths look much

More information

Data Structures and Algorithms. Analysis of Algorithms

Data Structures and Algorithms. Analysis of Algorithms Data Structures ad Algorithms Aalysis of Algorithms Outlie Ruig time Pseudo-code Big-oh otatio Big-theta otatio Big-omega otatio Asymptotic algorithm aalysis Aalysis of Algorithms Iput Algorithm Output

More information

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013 Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 19 Query Optimizatio Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio Query optimizatio Coducted by a query optimizer i a DBMS Goal:

More information

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Chapter The Processor Part A path Desig Itroductio CPU performace factors Istructio cout Determied by ISA ad compiler. CPI ad

More information

Data diverse software fault tolerance techniques

Data diverse software fault tolerance techniques Data diverse software fault tolerace techiques Complemets desig diversity by compesatig for desig diversity s s limitatios Ivolves obtaiig a related set of poits i the program data space, executig the

More information

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13 CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis

More information

CMPT 125 Assignment 2 Solutions

CMPT 125 Assignment 2 Solutions CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address

More information

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python CS 111: Program Desig I Lecture 19: Networks, the Web, ad gettig text from the Web i Pytho Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago April 3, 2018 Goals Lear about Iteret Lear about

More information

The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004

The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004 8 Programs ad data This publicatio forms part of a Ope Uiversity course M150 Data, Computig ad Iformatio. Details of this ad other Ope Uiversity courses ca be obtaied from the Course Iformatio ad Advice

More information

Guide to Applying Online

Guide to Applying Online Guide to Applyig Olie Itroductio Respodig to requests for additioal iformatio Reportig: submittig your moitorig or ed of grat Pledges: submittig your Itroductio This guide is to help charities submit their

More information

1.2 Binomial Coefficients and Subsets

1.2 Binomial Coefficients and Subsets 1.2. BINOMIAL COEFFICIENTS AND SUBSETS 13 1.2 Biomial Coefficiets ad Subsets 1.2-1 The loop below is part of a program to determie the umber of triagles formed by poits i the plae. for i =1 to for j =

More information

condition w i B i S maximum u i

condition w i B i S maximum u i ecture 10 Dyamic Programmig 10.1 Kapsack Problem November 1, 2004 ecturer: Kamal Jai Notes: Tobias Holgers We are give a set of items U = {a 1, a 2,..., a }. Each item has a weight w i Z + ad a utility

More information

EVALUATION OF TRIGONOMETRIC FUNCTIONS

EVALUATION OF TRIGONOMETRIC FUNCTIONS EVALUATION OF TRIGONOMETRIC FUNCTIONS Whe first exposed to trigoometric fuctios i high school studets are expected to memorize the values of the trigoometric fuctios of sie cosie taget for the special

More information

From last week. Lecture 5. Outline. Principles of programming languages

From last week. Lecture 5. Outline. Principles of programming languages Priciples of programmig laguages From last week Lecture 5 http://few.vu.l/~silvis/ppl/2007 Natalia Silvis-Cividjia e-mail: silvis@few.vu.l ML has o assigmet. Explai how to access a old bidig? Is & for

More information

Lecture 1: Introduction and Strassen s Algorithm

Lecture 1: Introduction and Strassen s Algorithm 5-750: Graduate Algorithms Jauary 7, 08 Lecture : Itroductio ad Strasse s Algorithm Lecturer: Gary Miller Scribe: Robert Parker Itroductio Machie models I this class, we will primarily use the Radom Access

More information

CS 111: Program Design I Lecture 20: Web crawling, HTML, Copyright

CS 111: Program Design I Lecture 20: Web crawling, HTML, Copyright CS 111: Program Desig I Lecture 20: Web crawlig, HTML, Copyright Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago November 8, 2016 WEB CRAWLER AGAIN Two bits of useful Pytho sytax Do't eed

More information

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Pseudocode ( 1.1) High-level descriptio of a algorithm More structured

More information

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS APPLICATION NOTE PACE175AE BUILT-IN UNCTIONS About This Note This applicatio brief is iteded to explai ad demostrate the use of the special fuctios that are built ito the PACE175AE processor. These powerful

More information

Bezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only

Bezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only Edited: Yeh-Liag Hsu (998--; recommeded: Yeh-Liag Hsu (--9; last updated: Yeh-Liag Hsu (9--7. Note: This is the course material for ME55 Geometric modelig ad computer graphics, Yua Ze Uiversity. art of

More information

Lecture 9: Exam I Review

Lecture 9: Exam I Review CS 111 (Law): Program Desig I Lecture 9: Exam I Review Robert H. Sloa & Richard Warer Uiversity of Illiois, Chicago September 22, 2016 This Class Discuss midterm topics Go over practice examples Aswer

More information

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway. Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,

More information