G89.3404 - An Introduction to Cognitive Modeling - Todd M. Gureckis - Homework #1


Homework #1: Python as Art

(back to class page)

In this first homework, we'll acquire some basic python skills. Think of this homework as learning how to draw or use a paint brush. Once you have some basic technique then you'll be able to approach the later parts of the course.

Download this assignment as an interactive notebook.


Step 1: Get a pen.

(i.e., install Python/iPython Notebook on your home computer)

Good news, if your laptop is a Macintosh or Linux-based system, Python should already be installed. To run it you just need to locate the Terminal program on your computer and get into the command-line (in Applications/Utilities folder). For this class, we'll avoid text editors all together and prefer to work using iPython's notebook mode. Please read this blog post and check the link at the bottom for instructions for installing on Mac OS X. We'll try to do this in class but if you have trouble feel free to drop by my office.

If you run windows, Python doesn't come pre-installed, but is fortunately very easy to install. Go to this link and download the Python 2.7.2 Windows (binary) installer.



Step 2: Draw some scribbles.

(i.e., open an interactive python shell and enter some commands)

Ok now, you've got python, let's test it in interactive mode. Enter the following command one at a time into the python interpreter. Press shift-enter to execute the line. You can make a new cell for each line. Try to understand what each line is doing. Does anything seem odd or unexpected to you? Don't worry if you don't understand exactly why things are doing what they, are but just keep a mental note and ask in class why a particular command generated output that you did not expect.

print "hello, world"
yearsold = 25
print "I am %s years old" % yearsold
yearsold = 26
print "I am %s years old" % yearsold
yearsold = 23.45
print "I am %s years old" % yearsold
yearsold = 100.0/33.0
print "I am %s years old" % yearsold
yearsold = 100/33
print "I am %s years old" % yearsold
1+1
1+1.0
1.0+1
2*3
2*3*2
2*3*2.
1+(1/2.)
1+(1/2)
a = 1
a
print a
# this is a comment it does nothing
# after you type the '#' python ignore the rest
print "hello, world" # see
a = 1
b = 2
c = b
print "c is equal to %s" % c
b = 5
print "c is still equal to %s" % c
print "b is now equal to %s" % b
a = a + b
print "a is now equal to %s, can you figure out why?" % a
			


Step 3: Get a coffee and a free hour.

(i.e., tutorial at your own pace)

Step 4: Learn some tricks.

(i.e., do what I say)

Trick #1: Algebra

Enter the following into python in order to compute the result

(1+(2*3))+(4+5)*4            
            
Now, only by changing the location of the parenthesis make the same equation equal to 33. Boom!

Trick #2: Area

Now, write a short program that defines two (2) variables: call one 'base' and call one 'height'. Set base equal to 4. Set height equal to 6. Then, use the variables you just defined to compute the area of the triangle with the respective base and height (hint: area is one half of base times height). Store the result in another variable called 'area'. Finally, use the print command to output the value of the area variable. Change the height to a new value. Shift-enter to recompoute the area. Print the area variable again and report the new value.

Trick #3: Important!

One quirk of python is that when you divide two "integers" the value will be an integer (even if the true result should be a fraction/decimal number). THIS WILL MESS YOU UP TO NO END! Using the methods we discussed in class, show two ways to force python to treat the division of 1 by 4 as a true fraction (aka floating point number). This is one line of code. Simply divide 1 by 4 but show two different ways to make the result evaluate to the correct value of .25.



Step #4: Painting with mixed media

(i.e., manipulation strings of text rather than just numbers)

Strings store a list of characters (like text). Python provides a built-in library for manipulating strings. To use it in interactive mode, simply type

import string            
            
or add the same line to the very top of your notebook.

Ok, once you've loaded the string library, we can start manipulating strings in our program. First make a new string called 'myteststr' and set it equal to the phrase 'The crow flies at noon, so be on the watch.'

1. Using slices, select the first two characters of this string.
2. Select the last two characters of the string.
3. Using the notation I showed in class (i.e. string[::-1]), reverse the string
4. Using string.split() break the string into a list of words (separate based on the space character) now, change the separator to be 't'. Output the new segments.


Boom!

Step #5: Drawing In Python

(i.e., no metaphor here. you're actually drawing!)

Using only the for loop command and print "*" write a program that will print out the following shapes when you run it. Remember for loops look like this

for i in range(5):
	print "*",
print "\n"            	
            	
and remember that you must use tabs to indent things otherwise it won't work!! Also note that print "*", (with the comma the end stops python from making a new line). Finally, you can use
print " ",
To print a blank space. Also note in the example from class where i printed a 10x10 grid, this version makes it look a little better (the version in class had too many returns at the end of each line)
for i in range(10):
	for j in range(10):
		print "*",
	print ""
	
output:
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * *
			

1. Triangle:
*
**
***
****
*****
******
*******
			


2. Half Diamond:
*
**
***
****
*****
******
*******
******
*****
****
***
**
*
			


3. Diamond:
      **
     ****
    ******
   ********
  **********
 ************
**************
 ************
  **********
   ********
    ******
     ****
      **
			


4. Super-bowl Helmet (just kidding):
			

... .zd$$$$$$$$$$$$$ec. .d$$$$$$$$$$$$$$$$$$$$$b. e$$$$$$$$$$$$$$$$$$$$$$$$$$$c z$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$. $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$c $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$L $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$r 4$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ *$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ""**$$$$$$$$$$$$$$$$$$$$$$$$$$$$$r "$$$$$$$$$$$$$$$$$$$$$$$$$$$" 3$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$"""*$$$$$$$$$$$$$$$F $$$$$L 4$$$$$$$$$$$$$$P $$$$$$bee$$$$$$$$$$$$$$" 4eeeed$$$$$$$$$$$$$$$$$$$$$$$$$$$$P .ze$$$$$$$$$$$$$$$$$$$$$* .ee$**" ^$$$$$$$$$$$$$$$*" "" "*$$$$$$$$P""


Step #6: Go pro

(use functions)

Now we will extend your previous drawing programs by creating a function, which, when called will draw a triangle of height x

Remember the general syntax for a function is
def myfunction(args):
	mycommand1
	mycommand2
	...
	return value

(the return value is optional). Your function should be called 'drawtriangle' the the only argument should be called 'height'. The program should print a triange (like the exercise above) where the number of rows is equal to height. Send me the code for your function when you have it working along with the above. To test your output, your program should output the following in response to these commands

>>>drawtriangle(5)
*
**
***
****
*****

>>>drawtriangle(7)
*
**
***
****
*****
******
*******

>>>drawtriangle(1)
*

>>>drawtriange(0)
I can't draw a height zero triangle!


Step #7: The Wave

Create a list called 'people' which is full of zeros, except the first number is a 1. Then write a simple program that steps through each element of the vector. If the "person" to the left is standing (i.e., is set to 1.0) then have this current person stand up too. If the current person is already standing then have them sit back down. On each pass through print the contents of the people list. Bonus points for making the wave go forwards and backwards (i.e., left to right then back right to left).

people = [1,0,0,0,0,0,0,0,0,0]
for each number "i"" in between 0 (the start) and the length of people (minus 1):
	if person "i" is standing up:
		make the person one to the right of person "i" stand up
		make person "i" sit down
		print people
            
also remember,
len(people)   # gives you the length of the "stadium" of people        
people[0] # this is how  you select individual "people"
people[1]
people[2]
            



Step #8: Submit to art gallery

(send to me)

In the notebook, choose File->Print View. Print it to a PDF file (in mac just say "save a pdf"). I'm sure something similar exists on PCs. On Linux, god help you. Email your code and the sequence of outputs if you are taking the class for credit. Please organize your notebook so it is readable and well documented (I can figure out what is going on.) This is an important habit to get into.