Courses/Computer Science/CPSC 203/CPSC 203 Template/Labs Template/Problem Solving Week 2 - Lab 1

From wiki.ucalgary.ca
< Courses‎ | Computer Science‎ | CPSC 203‎ | CPSC 203 Template‎ | Labs Template
Revision as of 20:46, 9 November 2009 by Mhasan (talk | contribs) (Drawing on Images)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Introduction

Today's tutorial builds on the programming fundamentals covered in the last two tutorials. After completing this module, you should be comfortable in demonstrating the the following skills:

  • using functions

Additional Reading

Examples 1, 2, and 3 come from the lecture notes of Dr. Jalal Kawash

Functions

Jython uses the def statement to define functions. Functions related statements include:

 def, return

The def statement creates a function object and assigns it to a name. The return statement sends a result object back to the caller. This is optional, and if it is not present, a function exits so that control flow falls off the end of the function body.

 global

The global statement declares module-level variables that are to be assigned. By default, all names assigned in a function are local to that function and exist only while the function runs. To assign a name in the enclosing module, list functions in a global statement.

The basic syntax to define a function is the following:

def name (arg1, arg2, ... ArgN)
  statements
  return value

where name is the name of the function being defined. It is followed by an open parenthesis, a close parenthesis and a colon. The arguments inside parenthesis include a list of parameters to the procedures. The next line after the colon is the body of the function - a group of commands that form the body of the function. After you define a Jython function, it is used just like any of the built-in functions. For example:

def add(number1, number2):
  answer = number1 + number2
  return answer

To call the function above, use the following command:

x = 1
y = 2
add(x, y)
=> 3

Example 1: Receives a numberical grade as input from the user, and outputs the equivalent numerical grade.

 def grades():
   strInput = raw_input('Enter your grade: ')
   grade = int(strInput)
   print 'grade is', grade
   if grade >= 90 and grade < 100:
     print 'A'
   elif grade >=80:
     print 'B'
   elif grade >= 70:
     print 'C'
   elif grade >=60:
     print 'D'
   else:
     print 'F'

Example 2: Finds the minimum element in a list of elements

 def empty(S):
   return len(S) == 0
 def min(S):
   if empty(S):
     return 'undefined'
   else:
     min_so_far = S[0]
     for i in range(1,len(S)):
       if S[i] < min_so_far:
         min_so_far = S[i]
   return min_so_far

Example 3: Sorts a list of numbers using the selection sort algorithm

 def selectionSort(S):
   sortedS = []
   for i in range(0,len(S)):
     minElement = min(S)
     S.remove(minElement)
     sortedS.append(minElement)
   return sortedS

Drawing on Images

So we can display images now we will manipulating them. Lets start by making a red dot on a blank picture.

def makePic():
  # Make a new picture 
  newPic = makeEmptyPicture(200, 100) 
  # Get a pixel from the middle of it 
  pixel = getPixel(newPic, 100, 50) 
  # Make that pixel red 
  setColor(pixel, red) 
  # Display the result 
  show(newPic)


This is nice, but drawing a single pixel at a time is gonna be a little tedious. We can also draw lines, rectangles, ovals, and text.

def makePic():
  # Make a new picture 
  newPic = makeEmptyPicture(200, 100) 
  # Make a black line running from upper-left to lower-right 
  newPic.addLine(black, 0, 0, 200, 100)
  # Display the result 
  show(newPic)

The function addLine takes a color and four coordinates x1, y1, x2, y2, and draws a straight line in that color. Note that you call this in a slightly different way than the other functions we’ve seen so far. Don’t worry about the difference for now.

def myFunction():
  # Make a new picture 
  newPic = makeEmptyPicture(200, 100) 
  # Make a blue 30x30 square whose upper-left corner is at 10, 20 
  newPic.addRect(blue, 10, 20, 30, 30) 
  show(newPic)

The function addRect takes a color and four integers x, y, width, and height. It draws a rectangle of the given width and height with the position (x, y) as the upper left corner (see the "discussion" tab).

# Make a red oval centered at 80, 80 
newPic.addOval(red, 80, 80, 20, 10) 

The function addOval takes a color and four integers x, y, width, and height. It draws an oval whose left edge touches x, whose top edge touches y, and with the given width and height. To make a circle, just make width and height equal.

# Make a new color of mostly red and green, with a little blue 
myColor = makeColor(196, 181, 84) 

The function makeColor takes three integers red, green, and blue, and returns a new color. This way you can make your own colors if you know their red, green, and blue intensities! (0, 0, 0) is black, (255, 255, 255) is white, and (255, 0, 0) is red. (Note: you can also pick a color using the pickAColor() function.)

# Print a friendly message in that new color 
newPic.addText(myColor, 30, 80, "Hello world!") 

The function addText takes a color, two coordinates x and y, and a string. It then writes that string starting at those coordinates in that color.

# Display the results 
show(newPic) 
# Save the results to a new file 
writePictureTo(newPic, "test.jpg")

The function writePictureTo takes a picture and a filename and writes the picture to that file. Be sure to include the extension “.jpg” so that other programs can recognize the file type.