0% found this document useful (0 votes)
52 views13 pages

Homework 7 - Recursive Functions

This document provides instructions for Homework 7 on recursive functions in CS101. Students are asked to write recursive functions to compute factorial, powers of 2, and digit sums of integers. They are also instructed to create a Tkinter program that draws different faces corresponding to different user-selected emotions. Finally, students can choose to complete one of three fractal drawing programs: bubbles, Sierpinski carpet, or Sierpinski gasket. Detailed explanations are provided for the requirements and implementations of each part of the assignment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views13 pages

Homework 7 - Recursive Functions

This document provides instructions for Homework 7 on recursive functions in CS101. Students are asked to write recursive functions to compute factorial, powers of 2, and digit sums of integers. They are also instructed to create a Tkinter program that draws different faces corresponding to different user-selected emotions. Finally, students can choose to complete one of three fractal drawing programs: bubbles, Sierpinski carpet, or Sierpinski gasket. Detailed explanations are provided for the requirements and implementations of each part of the assignment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Homework 7 -- Recursive Functions

CS101 Fall 2016


The purpose of this assignment is to learn to write recursive functions. None of the
functions you write should contain any loops.
In submitting your programs into Canvas, you should have a folder as
HW7_Lastname_Firstname containing the files recfun.py, one of (bubbles.py,
carpet.py, and gasket.py). Be sure to write appropriate comments in each file. It
will also include manyfaces.py as our fun Tkinter intro.

Part 1 - Recursive Arithmetic Functions


For this part or the assignment, you'll be writing three functions that illustrate the
power of recursion. The methods will perform the following operations:

computing n factorial

computing powers of 2

finding the sum of the digits in an integer

All of these functions will be written in an application program called recfun.py. The
main program of the application will display a menu of the 3 functions, and prompt
the user to choose one. Depending on the choice, the program will then prompt the
user for the input to be passed to the function. Finally, the program will call the
function and print the result.

Find n!
Write a function that takes as a parameter an integer n and returns n!.
recursive definition of factorial is as follows:

factorial(n) =
examples:
factorial(4) --> 24
factorial(7) --> 5040

if n == 0

n * factorial(n-1)

otherwise

The

Note: factorial is a fruitful function which returns an int.

Print the powers of 2 up to n


Write a function called pow2(n) that takes as parameter an integer n and prints all
the powers of 2, one per line, up to the nth power (inclusive). You can follow this
logic for pow2(n):
1. If n is less than or equal to 0, print the number 1.
2. Otherwise, print the powers of 2 up to the (n-1)st, then print 2 n.
For example, the output from the call pow2(10) should be
1
2
4
8
16
32
64
128
256
512
1024

Find the sum of the digits in an integer n


Write a function called digit_sum(n) that takes as its parameter an integer n, and
prints the sum of the digits in the decimal representation of n. For example, the
sum of the digits in the number 23456 is 20. Use this logic:
If n is a 1-digit number, then the sum of its digits is just n itself.
If n has more than one digit, you can find the one's digit by taking n modulo 10
(e.g., 23456 % 10 = 6). If you divide n by 10, you'll have a smaller number
containing all of the digits except the one's digit (e.g., 23456 / 10 = 2345). So, you
can find the sum of all of the digits by first finding the sum of the digits in n / 10,
and then adding to it the value of the one's digit.
Note: digit_sum is a fruitful function which returns an int value.

Now, we want to write a program that asks the user how theyre doing
After saving the file, run the program and you should see a window
with a smiley face. Let me know if this does not work on your
computer.
from Tkinter import *
window = Tk()
ps2_canvas = Canvas(window, width=500, height=500)
ps2_canvas.grid(row=0, column=0)
# These next four statements are the ones you should play with for your
# program. LEAVE EVERYTHING ELSE (apart from the comments) ALONE
# draw the face
ps2_canvas.create_oval(100, 100, 400, 400, fill='yellow')
# Draw the mouth
ps2_canvas.create_arc(175, 175, 325, 325, start=225, extent=90, style=ARC)
# Draw the left eye
ps2_canvas.create_oval(200, 205, 202, 207, fill='black')
# Draw the right eye
ps2_canvas.create_oval(298, 205, 300, 207, fill='black')
# Keep this line at the end of your program
window.mainloop()

Note: the tkinter code should have window.mainloop() as a final


statement. Otherwise, the window for the smiley face will not pop up.
copy and paste the following code in the file.

Many Faces: Create a new file called manyfaces.py, then


Part 2 Tkinter Introduction

and then draws a face corresponding to the users feeling. For this part,
our program must react to at least three different emotions (first, the
program lets the user know which emotions it can react to, and then it
prompts the user for their emotion. If the user enters an emotion that
the program doesnt react to, the program must print a message to
that effect). Below, Im showing faces for happy, sad, and pensive;
however, youre most welcome to choose any three different emotions
that you like.

Feel free to change any features of the face if you like to, e.g., change
the eyes, add eyebrows, change the color of the face for specific
emotions, add ears, hair, etc. (be as creative as possible, all the
students in the two sections are going to vote to choose the
three coolest programs). Also, note that Python understands quite a
few color names. Please see the attached instructions on how the
create_oval, create_arc, and create_line functions work.

Your program must give three different results for at least


three different feelings. Youll receive an extra credit per any
additional feeling your code responds to (the face must be
different for any different feeling, and you may receive up to 2
extra points on this pset if your code responds to five different
emotions (or more)).
Ive changed the eyes and added eyebrows. You dont need to create
more elaborate eyes as in these drawings. However, if you do, youll
receive 2 extra points on this pset in addition to the other
extra points stated in the previous paragraph (If you want to
draw more elaborate eyes such as the ones in these pictures, please
define a function to draw an eye at a specific location on the face (this
function accepts ps2_canvas and 4 numbers representing the
coordinates of the eye). When you have defined the draw_eye function,
call the function and pass appropriate arguments to it to draw the left
eye. Then, call the function again with appropriate arguments passed
to it, this time to draw the right eye. Please dont simply
copy/paste a block of code written for one eye to create the
other one, no extra credits will be given in that case. Write a

function instead and call it twice to draw both eyes).

Feel free to change the greeting message and/or the message shown
when the user inputs an emotion that the program doesnt recognize.

Below is the result of a sample program:

The program greets the user and lets them know which emotions it can
react to. It then asks the user a question to see how theyre doing. The
user then enters the answer happy.

Hello, there. Im a robot that understands these emotions:


happy, sad, and pensive.
How are you doing today? happy

Then the program draws the following face as a response to the users
happy emotion.

Lets run the program again, this time, the user says theyre sad.

Hello, there. Im a robot that understands these emotions:


happy, sad, and pensive.
How are you doing today? sad

The program draws the following face:

Lets run it again. This time, lets enter pensive as our answer:
Hello, there. Im a robot that understands these emotions:
happy, sad, and pensive.
How are you doing today? pensive

The program draws the following face:

Lets run the program once again. This time, lets enter a response to
which the program doesnt know how to react:
Hello, there. Im a robot that understands these emotions:
happy, sad, and pensive.
How are you doing today? mad
Sorry, I dont recognize your input.

Part 3 - Drawing Fractal Images


For this part, your will be writing programs that will draw fractal images using
recursion. Each program will have three command line arguments indicating the
width and height of the picture, and the number of levels of recursion to use in the
picture. You will choose either 1, 2, or 3 to complete for homework. (You do
not need to complete all three.)
1. Bubbles
2. Sierpinski carpet
3. Sierpinski gasket
You'll be using the same Tkinter module as above for picture drawing, so
you may want to have a copy of your code from that assignment available
for reference.

Drawing some bubbles

You can draw a picture with the bubble pattern shown


below recursively. The basic strategy is this:
1. Draw a circle in the center of the picture. Its radius should be 1/4 the width of
the picture. Use the canvas.create_oval function that you used in homework 0
(review the notes I posted on using the create_oval function). The circle should
occupy the shaded region E in the figure to the right.
2. Then divide the picture into four equal sized regions (A, B, C, and D) as shown in
the figure to the right. Recursively draw a bubble picture in each of the four
regions.
More specifically, you will write a function with the header
def draw_bubbles(canvas, x1, y1, x2, y2, nlevels):
which draw a bubble pattern in the rectangle with (x1,y1) in the upper left corner
and (x2,y2) in the lower right corner. nlevels represents the number of levels of
recursive calls. When you make a recursive call, decrement the value of nlevels

that you pass to the method.


anything.

When the level is 0, just return without doing

A few details on writing the draw_bubbles function:


1. When you call create_oval, you pass the x and y coordinates of the upper left and
lower right corners of a bounding box (i.e. an enclosing rectangle) that the oval will
appear in. Also pass two optional parameters: width=0 (so that no outline is
drawn) and fill=(a color of your choice; I used 'cyan').
2. You'll need to determine the coordinates of the upper left and lower right corners
of each of the 5 regions in order to know what coordinates to pass to create_oval
and your recursive calls.
3. Make sure you have a base case (i.e., when nlevels == 0).
Call draw_bubbles from a program in a file called bubbles.py. The main program
should
1. prompt the user for the number of levels
2. create a Tkinter window and canvas with the code
from Tkinter import *
window=Tk()
canvas=Canvas(window,width=512,height=512,highlightthickness=0,bg='bl
ue')
canvas.grid(row=0,column=0)
3. call your bubbles function, with the arguments 0, 0, 512, 512 (these indicate
that you want your bubbles picture to fill the entire window), and the number
of levels specified by the user
4. call window.mainloop()
The following shows the result with 7 levels of recursion. With one level, there will
just be a single circle in the middle. Of course, you can use whatever colors you
like.

Drawing a carpet
Next, write a program called carpet.py which draws an image known as Sierpinski's
carpet, as shown below:

To create this drawing, divide the canvas area into a 3x3 grid. Fill in the center
section and then draw a Sierpinski carpet (with one fewer recursion levels) in each
of the remaining 8 surrounding squares.
You can use the method
canvas.create_rectangle(x1, y1, x2, y2, int y, width=0, fill=<your choice of
color>);
to draw a rectangle with no border filled with the specified color
The picture above shows a Sierpinski carpet of order 6.
As with bubbles, carpet.java should prompt the user for the number of recursion
levels, and then draw the picture.

Drawing a gasket
The next image is known as either Sierpinski's triangle or Sierpinski's gasket.
Shown below is a Sierpinski gasket of order 5:

You can draw a Sierpinski gasket as follows:


The base case (i.e., levels==0) is simply a triangle drawn inside a rectangle.
To draw a Sierpinski gasket with n recursion levels (n>0), locate 3 equal sized
rectangles (A, B, C) within the main rectangle, as shown in the figure to the right.
Draw a Sierpinski gasket with (n-1) levels in each of these three rectangles. For this
figure, all of the triangles that are drawn are of the same size, so don't draw
anything until you get to level 0.
To draw a triangle, you can use the canvas.create_polygon function. You pass it
three pairs of x-y coordinates, representing the three vertices of the triangle. For
example, the call
canvas.create_polygon(0,0,1,0,0,1,fill='yellow',width=0)
would draw a borderless yellow triangle with vertices (0,0), (1,0), and (0,1).

Call your program gasket.py. Again, the main program should prompt the user for
the number of levels, then draw the picture.

You might also like