Homework #2: Programming in Python

In this second homework, we'll extend our python skills. As mentioned in class, think of these first few homeworks and lectures as learning how to draw or use a paint brush. Once you have some basic technique then you'll be able to keep up with the later parts of the course.


Note: if you are having trouble or need help please come see me in office hours, i need feedback about how people are doing so we can calibrate how fast we go.

Exercise #1: Numbers, Variables, and Data

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.

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. Now, arrow up (alt-p on the pc) and change the height to a new value. Arrow up again and recompute the value of area. Print the area variable again and report the new value.

Next:
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). 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.

Copy and paste your interactive session into a email for both parts above to complete this part of the assignment.



Exercise #2: Working with strings

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 batch script.

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 (* thanks to Lina for pointing out that the string library doesn't provide a reverse() function!)
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.
5. Copy and paste your interactive session into a email for this part of the assignment.

Exercise #3: Drawing In Python

In this part of the assignment it may be best to use a batch script. When you are done with this part, email me your complete batch script.... I'll run it check that I can recreate the output as specified below. 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""


Exercise #4: 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!


Exercise #5: The Wave (continued from in class on Wednesday)

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). Some hints written in pseudo-python courtesy Louis and Nathaniel after class:

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]
            



Exercise #6: Post Programming Therapy

Ok, now that you have some basics down, we're going to look at a simple program that is a bit more complex than we've tried so far. In addition, this exercise should give us all some well needed therapy after learning a bunch of python. In particular we are going to develop a simple artificial intelligence. You get to name your own, but our project will be based on the ELIZA program developed in the 1960s by Joseph Weizenbaum. You can read about it on the wikipedia link above. The basic idea of ELIZA is that a lot of traditional therapy seems to involve very simple rules on the part of the therapist: namely, listen, then parrot back what you have heard in the form of a question. For example, consider the following exchange

Therapist: Do you have anything you'd like to talk about today?
Patient: Well, I've been having trouble in my marriage.
Therapist: Why do you think that is?
Patient: Well my wife loves cats more than me.
Therapist: Why do you think your wife loves cats more than you?
Patient: Well, she's kicked me out of bed to make room for the cats.
Therapist: How does that make you feel?
Patient: Angry!
Therapist: Why do you think it makes you angry?
...

Ok, so you have the basic idea. Sometimes it might seem that therapist don't add much to the conversation except to rephrase aspects of the patient's response in the form of a question. Weizenbaum wrote a simple program called ELIZA which he programmed to do exactly that. It was supposed to act as a pretend therapist. It would ask a certain set of canned questions and the user would type free-form responses. Then the ELIZA program would break apart the response of the 'patient' and create a new sentence using parts of the words from the 'patient's' response. The amazing thing was that it was pretty believable! Perhaps Weizenbaum was an incredible insightful programmer and therapist (or maybe there isn't much to this therapy business)! Anyway, since we are all probably stressed out from programming today, we're going to need some help.

In the following script, I wrote a very simple and stupid version of ELIZA called 'seliza' for 'stupid eliza'. All you have to do for this assignment is download the script and run it. When seliza asks you a question type a response. Send me a sample session with your homework. Take a look at the code for seliza and try to figure out how it works. Notice it uses random() to make the program act slightly more human-like. The entire program uses only simple pythong programming constructs we have examined so far in class like looping, random numbers, and string manipulations. For extra credit, try modifying my seliza code to make it a better therapist. The changes can be simple. How about adding more realistic responses? Anothr idea might be to make selize a little smarter about the way it "parrots" back what you say. For example, sometimes I've seen seliza say "How do you feel about the?" One simple change might be to put in some checks so seliza doesn't ask questions like that about common words like "the", "and", etc... For full credit just run seliza and tell it your python woes (send me the transcript). If you make changes send them too me too and we'll play with them in class.
SELIZA code