Recursion: - University of Delaware



Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input functionDue: Oct 11 (Note that this is a 2-week lab)This lab must be done using paired partners. You should choose a different partner than the partner you worked with previously. One student should turn in the lab, but the lab must have both students’ names on it.Create a file called lab2.py. Include as comments at the very top of the file: your name, your partner’s name, class time, TA’s name(s), and lab due date. Then include the following comments and functions:Note: Include the comments in your lab2.py file. This will make the lab easier to read and grade. You should still get into the habit of commenting every function.Note 2: Test cases for functions that generate random numbers are somewhat difficult. If possible for those cases, give a sample output, i.e., an example of what you might get if a particular random number or set of random numbers are generated. Note that the rest of your comments don’t change at all. All functions must have comments. In functions where I have included the comments, copy and paste them into your lab code.Lab Attendance Sept 28: 4 ptsLab Attendance Oct 5: 4 pts1. (3 pts) Write a function that takes as input parameters 2 strings. It outputs a string. The returned string is the two input strings concatenated together.2. (3 pts) Write a function that takes as input 2 parameters: a string and an int. It should return 1 longer string – the string you input int times. So if your input parameters were “ha” and 4, the string returned should be “hahahaha”Problem 3a (3pts).Write the following functions based on the comments, below:# Function name: min2# Input: 2 integers# Output: an integer# This function returns the smaller of the two input parameters# Test Cases: 3,7->min2->3#7,2->min2->2#3,3->min2->3Problem 3b (3 pts). #Function name: min5#Input: 5 integers#Output: 1 integer# This function should take 5 integers and return the minimum of those 5 integers. This function should be 1 line of code long#Test cases: 12,5,2,6,8 -> min5 -> 2#1,2,3,4,5-> min5 ->1#5,4,3,2,1->min5->13c (2 pts). Run min5 with strings as input parameters instead of integers. Example:# Text Cases:“dog”,”bird”,”cat”,”zebra”,”bear” -> min5 -> “bear”#“aardvark”,”bear”,”echidna”,”wombat”,”zebra”->min5->”aardvark”#“zebra”,”wombat”,”echidna”,”bear”,”aardvark”->min5->”aardvark”What did you just learn about the less than operator and strings? (Write a small comment answering that right below these test cases). 3d. (2 pts)Run min5 with the following two sets of input parameters:# Text Cases:50,3800,490,6,20805 -> min5 -> ?“50”,”3800”,”490”,”6”,”20805” -> min5 -> ?Do you get different results? Explain why you got the results you did (Hint: think of the dictionary).Recursion:Random Number GenerationPython can generate random numbers. There’s a whole library dedicated to generating random numbers. It’s called random. So if you want to generate random numbers, you must first import the random number library by placing at the top of your lab2.py file:from random import *The above line should be the top line (under your comments) in your lab2.py file. Now you can generate random numbers between x and y using randrange(x,y)For instance, if you wanted to generate a random number between 0 and 100 (not including 100) and store it in the variable randvar, you’d write the following:randvar = randrange(0,100)Remember, we do the right side first and place the value calculated by the right side into the variable on the left side. So if you use the above code to generate a random number, randrange will generate a number between 0 and 99 (inclusive). Let’s say the random number generated is 42. Then randvar will hold the number 42.To see what number is generated, you can always print it:print (randvar)(Note: when writing test cases for functions that use random numbers, you may need to give a range of answers that would be correct. So in this case, I might say:Input: 3->func-> 0…2 (inclusive)Input: 7-> func->0…6 (inclusive)Input: 100->func-> 0…99 (inclusive)NOTE: For those of you who have had programming before, this lab is to ensure sure you understand recursion. You must use recursive loops as opposed to any other type of loop for these problems.Problem 7. (5 pts)Simple dice game. Function name: DiceInput parameter: 1 integer (possibly 2, depending on how you write this) Output: an integerCalculation: This function generates two random numbers between 1 and 6 inclusive. It then calculates your current score as follows: If you roll a 1, you are done unless you roll 2 1s, in which case you add 30 points. If you roll two 3s, you lose 40 points. Otherwise, your score goes up by the addition of the two random numbers. This function will loop either 10 times or until one of the random number stopping conditions is hit. (Note: print out the random numbers generated within the function or you won’t know whether your function is working or not)Sample output:2, 65, 42, 46, 32, 34, 33, 55, 43, 35, 121Problem 88a. (4 pts) Write a function that takes as an input parameter two integers. It returns an integer. It loops. Each time it generates a random number between 1 and the second parameter. If the random number is not equal to the first parameter, the random number is returned. Otherwise, the function loops. (Note: the way to test this function is to put print statements within the function showing the random number generated. You may wish to test this with a very small range in order to make sure that it actually continues to loop when the random number is equal to the first input parameter).8b. (2 pts) (Not a loop): Write a function that takes as input parameters 4 integers. It returns a Boolean value. It checks to see if the second two parameters are the same as the first two parameters, regardless of order. In other words:3,7,3,7 ->checkvalues ->True7,4,4,7->checkvalues -> True7,8,7,4->checkvalues -> False8c. (5 pts) We’ve all heard that the lottery is a tax on people who are bad in math. You’re going to write a function that tests a simple version of this. For this lottery, you choose only 2 numbers within a range (I think the lottery’s range is from 1-40, but I could be wrong on that). The function you are going to write should take 4 input values: the two integers you’ve chosen, the possible range of values (for testing, something smaller than 40, but for the actual lottery it would be 40), and then the loop counter. It will generate 2 random numbers, and count how many times you got both random numbers right (how many times you’d win the lottery if you played loop-counter times with only 2 numbers). The function should loop loop-counter times. It should generate 2 different random numbers (using 8a to make sure that the two numbers are different). It then uses 8b to check whether the numbers are the same and, if they are, increases the count of the times you won. Note a. You may always put print statements within your functions to see what they are doing as you run them.Note b: to test your function, you can change the lottery’s range to a smaller number than 40. For instance, when I made the range 10 and looped 900 times, I won 8 times. When I made the range 40 and looped 900 times, I occasionally won once.Problem 9: (5 pts)9a. (3 pts) This (nonlooping) function takes 2 integers as input parameters, asks the user what x times y is using the input function for user input, and then returns True if the user inputs the correct value, and false otherwise as follows: #Function name: mult#input: 2 integers#output: a Boolean value#This function checks whether the value the user types in using the input function is equal to the product of the two input parameters and returns True if it is, False otherwise. #Test cases: Input parameter: 3, 7>mult2-> value entered into input function: 21- ->True#Input parameter: 6,4->mult2-> value entered into input function: 18->False#Input parameter: 0-,12>mult2-> value entered into input function: 0->True9b. (4 pts) Function name: MultTestInput: 2 integersOutput: A stringThis function uses recursion and the function written in problem 2 (mult) to see how well a student is able to do their multiplication tables. The function checks to see whether a student is able to correctly multiply every number between 2 and 12 with the first input parameter. If the student gets any answer incorrect, the function starts over with 2 times x, then 3 times x, then 4 times x, etc, where x is the first input parameter. Otherwise, the function returns a string saying, “Congratulations! You know your x multiplication tables!”Test Output (i.e., what you might see):What is 4 times 2? -> 8What is 4 times 3? -> 12What is 4 times 4? -> 16What is 4 times 5? -> 20What is 4 times 6? -> 24What is 4 times 7? -> 28What is 4 times 8? -> 32What is 4 times 9? -> 36What is 4 times 10? -> 40What is 4 times 11? -> 44What is 4 times 12? -> 48Contratulations! You know your 4 multiplication tables!What is 6 times 2? -> 12What is 6 times 3? -> 18What is 6 times 4? -> 24What is 6 times 5? -> 30What is 6 times 6? -> 34What is 6 times 2? -> 12What is 6 times 3? -> 18What is 6 times 4? -> 24What is 6 times 5? -> 30What is 6 times 6? -> 36What is 6 times 7? -> 42What is 6 times 8? -> 48What is 6 times 9? -> 54What is 6 times 10? -> 60What is 6 times 11? -> 66What is 6 times 12? -> 72Contratulations! You know your 6 multiplication tables!Problem 10:10a.(4 pts) Create a copy of your dice function that stops either when the random numbers generated create a stopping condition, or when the user chooses to stop. That means that every time, it should use the user input function to ask the user, “Do you wish to continue?” If the user says yes, the function continues as before. If no, the current score is returned. Note: the order in which things happen in this function is critical for its working properly. You don’t want to ask the user, “Do you wish to continue” if the user rolled a 1 or two 3s. Note: this function may take no input parameters, depending on how you write it.10b: (6 pts) Now create a brand new function called dicegame. This function takes 3 integers as its input parameters:, the score of the first player, the score of the second player, and the count of the number of loops. It then loops the count time. Each loop, it calls the first dice function and adds the score to the first player’s score, and then it calls the second dice function (above) and the user plays the game. Each time the loop should print out the first player’s current score and the second player’s current score. When it is done looping, it should say whether the first player or the second player won. Example:6, 64, 24, 1Do you wish to continue?yesYou rolled 5, 4Do you wish to continue?yesYou rolled 2, 6Do you wish to continue?yesYou rolled 6, 2Do you wish to continue?no2, 36, 61, 2Do you wish to continue?yesYou rolled 2, 3Do you wish to continue?yesYou rolled 5, 4Sorry, You rolled 1, 46, 41, 2Do you wish to continue?yesYou rolled 5, 3Sorry, You rolled 1, 2second player won with 47>45Problem 11: (7 pts)Function name: FundraisingInput Parameter: 1 doubleOutput: a StringDescription: You’re trying to raise 1000 for a very good cause: the Wombat Adoption Foundation. Luckily there is a sponsor who is also contributing for every donation. The wombat-loving sponsor will contribute as follows:If the donation is under 100, the sponsor will contribute .10 of that.If the donation is 100 or more but less than 250, the sponsor will contribute .25 of that donationIf the donation is 250 or more but less than 500, the sponsor will contribute .5 of that donationAnd if the donation is 500 or more, the sponsor will contribute .75 of that donation. You are writing a recursive function that raises 1000 by asking for user input, “What would you like to donate?” Then your recursive function should calculate, with the sponsor’s contribution, how much is being added to the total and add that to the total. For each donation, You should print out the donation and how much the total is at that point. The function should continue until the total is 1000 or more.Test Output:What would you like to donate? 50Donation: $50 So far we've got: $55.0What would you like to donate? 200Donation: $200 So far we've got: $305.0What would you like to donate? 400Donation: $400 So far we've got: $905.0What would you like to donate? 600Donation: $600 So far we've got: $1955.0We have $1955.0! Thanks to 4 people for their donation!Turtle: Problem 12 ( 3 pts)Function Name: CirclesInput: 1 integer: the radiusOutput: noneThis function recurses until the radius is 0 or less. Each time it draws a circle with the radius, and then recurses with a radius 3 smaller than the previous radius. You should get something like this:Problem 13: (4 pts)Function Name: SquaresInput: 3 integers: the length of the side, and the starting x and y coordinateOutput: noneThis function recurses until the length of the side is 0 or less. Each time it draws a square centered within the previous square, and then recurses with a radius 8 smaller than the previous side length. You should get something like this:Note: for this you will need turtle.penup() to lift the turtle pen off the screen, then, of course, turtle.pendown() to put it down on the screen, and you’ll need turtle.goto(x,y) which will move the pen to the x y coordinates.Problem 14: Spirograph/flowerTo do this problem, you need to know a few things about turtle’s color. Color is represented by the amount of red, the amount of green, and the amount of blue (rgb values). Each value is represented by an amount between 0 and 1. To set the color, you use the command: turtle.color(r,g,b) where r is a double between 0 and 1, g is a double between 0 and 1, and b is a double between 0 and 1.You can set turtle’s pensize with an int, e.g., turtle.pensize(3)equally, when the pen is at x,y coordinates and a circle is drawn, the x y coordinates default to the very bottom of the circle’s circumference, not the center. In order to have the circle drawn with the starting location at the same x/y coordinates but at a different angle, you rotate the direction of the turtle using either turtle.left() or turtle.right(), and the degrees you want to rotate turtle’s angle. So for instance, if you wanted to draw 6 circles like a Spirograph, you’d rotate turtle.left(60) each time and then draw another circle. Okay, now onto the drawcircles function:14a. (4 pts) drawcircles: This function draws one set of Spirograph circles. It takes 6 (yep, 6!) input parameters: one int representing the count, or number of times the loop still needs to rotate, an int representing the size of the circle, an int representing the amount the turtle should be rotated each time, and then 3 doubles, all between 0 and 1, representing the amount of red, the amount of green, and the amount of blue in the color, respectively.The function should check for the stopping condition (and, if it is at the stopping point, it should return nothing from the function, done using:returnIt should generate a random number between -.2 and .2 (random number between -20 and 20, divided by 100). And that number should be added to the amount of red. Repeat for green, and for blue. Then check to make sure that the red, green, and blue amounts are within range. If a value is < 0, it should be reset to .1. If it’s > 1, it should be reset to .9. The turtle’s color should be set to the new red/green/blue values. And a circle should be drawn. Then the loop should continue.So, if the drawcircle is called initially as:Drawcircle(6,25,60,.5,.5,.5)You should get something looking like this:14b (7 pts) Spirograph function:This function takes 3 parameters, all three are ints. The first is the count of the number of circle sets you’ll create (the drawcircle function creates 1 circle set), and the second and third are the x/y coordinates of where the circles start from. (Note: these don’t change throughout, but this function makes sure that we always start from those x/y coordinates in case the pen gets off by a pixel or two). This function loops count times (the first parameter). If it does not stop, it goes to the x/y coordinate. Note: you will want to use the following command:turtle.setheading(0) to reset the direction of the turtle to its original directionYou will then randomly choose a number between 4 and 20 for how many circles should be generated for this circle set. Once you know the number of circles, you should calculate how much the rotation should be. Finally, you should randomly generate a number between 20 and 230, which will be the size of each circle. When you have that, you should call your drawcircle function (with initial color values of .5, .5,. .5). Then you should loop with the Spirograph function.You might get something that looks like this:Problem 14 (8 pts) Rock/Paper/ScissorsCopy the following code into Lab 3. Make sure you’ve downloaded stone.gif, paper.gif, and Scissors.gif from my web page. Place them in your Python33 folder on your computer. Then write the following recursive function where indicated.import turtleimport tkinterfrom random import *tk = tkinter.Tk()canvas = tkinter.Canvas(tk, width = 500, height = 300, bg="white", bd="5")canvas.pack()def display(you,computer): print("You: " + str(you) + " computer: " + str(computer)) if you == 0: my_img=tkinter.PhotoImage(file = "stone.gif") elif you == 1: my_img=tkinter.PhotoImage(file = "paper.gif") elif you == 2: my_img=tkinter.PhotoImage(file = "Scissors.gif") canvas.create_image(70,60, anchor = tkinter.NW,image = my_img) if computer == 0: c_img=tkinter.PhotoImage(file = "stone.gif") elif computer == 1: c_img=tkinter.PhotoImage(file = "paper.gif") elif computer == 2: c_img=tkinter.PhotoImage(file = "Scissors.gif") canvas.create_image(270,60, anchor = tkinter.NW,image = c_img) tk.update()# Recursive function:# Function name: RockPaperScissors# input: 2 integers – the number of times played and the number of times won so far# output: a string – “You won x out of 10 times”, where x is the number of times you won # This function should run 10 times. Each time it should use the input function to ask you, “choose 0 for rock,1 for paper, or 2 for scissors: “. It should then generate a random number between 0 and 3 (not including 3). It should call the function display() with your choice and the computer’s choice. It should then calculate whether you won and, if so, increase the won count. The winner is determined as follows: If the user chose rock:If the computer generated rock, it’s a tieIf the computer generated paper, the user losesIf the computer generated scissors, the user winsIf the user chose paper:If the computer generated rock, the user winsIf the computer generated paper, it’s a tieIf the computer generated scissors, the user losesIf the user chose scissors:If the computer generated rock, the user losesIf the computer generated paper, the user winsIf the computer generated scissors, it’s a tieAgain, this function should recurse 10 times#YOUR RECURSIVE FUNCTION GOES HERE!def main(): print(RockPaperScissors(0,0))main()Problem 15: (7 pts) fractalsDrawing Snowflakes(sort of):We’re going to create a recursion that looks something like this:To start the recursion, realize that we’re starting with a basic line that looks like this:This is created with a line that uses the basic turtle commands:turtle.forward(x)turtle.left(60)turtle.forward(x)turtle.right(120)turtle.forward(x)turtle.left(60)turtle.forward(x)Where x is the length of each edge in the line. To recurse, we can take each piece of the line and repeat the process we just did:To recurse again, we get:If we keep recursing, we may end up with something like this:Part 1 ( 4 pts): Write the recursive function that creates the above. In the above case, the function stopped recursing (and drew) when the line length was 3.Part 2 ( 3 pts): To make a snowflake, we have to recursively draw the above, each time rotating a certain amount. I rotated 60 degrees each time. Note that this function should be recursive as well, and should stop when a count parameter gets down to 0. The angle you rotate should directly affect your count parameter. You may end up with something like this: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download