Question

In: Computer Science

def seq3np1(n): """ Print the 3n+1 sequence from n, terminating when it reaches 1. args: n...

def seq3np1(n):

""" Print the 3n+1 sequence from n, terminating when it reaches 1. args: n (int) starting value for 3n+1 sequence return: None """

while(n != 1):

print(n)

if(n % 2) == 0: # n is even

n = n // 2 else: # n is odd

n = n * 3 + 1

print(n) # the last print is 1

def main():

seq3np1(3)

main()

Using the provided code, alter the function as follows:

  1. First, delete the print statements in the function

  2. Now we will need a local variable to keep track of the count.

    1. It would make sense to call it count.

    2. It will need to be initialized to 0 before we begin the loop.

  3. Once inside the loop, we will need to update count by 1 (increment), so that we can keep track of the number of iterations.

When the loop terminates (we get to 1), return the value of count.

This demonstrates an important pattern of computation called a counter (note that it is a type of accumulator). The variable count is initialized to 0 and then incremented each time the loop body is executed. When the loop exits, count contains the result — the total number of times the loop body was executed.

Since the function now returns a value, we will need to call the function inside of a print statement or save the result in a variable for later printing in order to see the result.

Now that we have a function that can return the number of iterations required to get to 1, we can use it to check a wide range of starting values. In fact, instead of just doing one value at a time, we can call the function iteratively in our main, each time passing in a new value. The algorithm for your main is as follows:

  1. Ask the user for a value to use for the upper bound of your range

    1. You must verify that the value is positive, since your function will not work on negative values. If the value is not positive, you should END the program.

  2. Create a for loop using an iteration variable called start that provides values from 1 up to (and including) the user supplied upper bound.

  3. Call the seq3np1 function once for each value of start.

  4. Write a print statement that prints the value of start and the number of iterations.

Part B

Next we will write a new function (not in the main) that will take an upper bound value and use the turtle graphics library to a line graph the number of iterations, where the x axis is the upper bound and the y axis is the number of iterations. This provides an interesting visual that allows you to see the relative number of iterations for each value. You will need to:

  • Use a variable to keep track of the maximum number of iterations

  • Use the turtle library’s Screen command setworldcoordinates

    • You can use the command to resize the window and make your graph re-scale according to the values you are graphing.

  • Use a turtle to write out the largest number of iterations required to get to 1 in the sequence so far.

Scanning this list of results causes us to ask the following question: What is the longest sequence? The easiest way to compute this is to keep track of the largest count seen so far. Each time we generate a new count, we check to see if it is larger than what we think is the largest. If it is greater, we update our largest so far and go on to the next count. At the end of the process, the largest seen so far is the largest number of iterations we used to generate a sequence.

We can also use this value to update the y axis of the world coordinate. You can initialize your world coordinates to (0, 0, 10, 10), but then update them each time you get a new x value and new y value that is greater than the current max. You will need to update the graph using setworldcoordinates on every iteration (review the documentation before proceeding):

  • positive x axis should be the current value of the loop iterator + 10

    • we are just adding +10 to give a little room so we can see our results more easily

  • The positive y axis should be the max_so_far value + 10

  • The negative x and y values should both be 0

In other words, the world coordinates should grow with your graph. Below is the basic algorithm:

  1. The number of iterations (the upper limit) should be a parameter to your function

  2. Create a turtle and a window.

  3. Create an additional turtle object to write out the maximum data

    1. You will have two turtle objects, each completing their own task

  4. Set the world coordinates to (0,0,10,10)

  5. Create a variable call max_so_far and initialize it to zero

    1. place this initialization outside the for loop so that it only happens once

  6. Write a for loop using the number of iterations (the upper limit) that was passed as a parameter

  7. Now, inside the for loop, save the result of the seq3np1 function in a variable called result

  8. Then we can check result to see if it is greater than max_so_far

    1. If so, update max_so_far with the new, greater value

    2. Using your writer turtle, clear the previous text if necessary

  9. Add a label, “Maximum so far: <iteration>, <result>” using the turtles write() command to write the iteration and result in the upper left corner of the screen (you can just use the max_so_far value as the y coordinate for your label)

    1. Set the world coordinates of the screen to the current iteration + 10 and the max_so_far + 10 values.

    2. Make sure you review the turtle’s write() command. It doesn’t work the same as print. You will have to create a single string before writing.

  10. Graph the result with your turtle. Hint: you are graphing on an x,y coordinate plane. You are trying to make a graph of the max number of iterations that the seqn3p1() function runs for. What do you think would make good x and y values for a graph of this data?

Solutions

Expert Solution

Working code implemented in Python and appropriate comments provided for better understanding.

Source Code for main.py:

import turtle

def seq3np1(n):
""" Print the 3n+1 sequence from n, terminating when it reaches 1.

args: n [int] - starting value for 3n+1 sequence

return: count [int] - the number of iterations the loop executed until n = 1.
"""
count = 0
while(n != 1):
if(n % 2) == 0: # n is even
n = n // 2
else: # n is odd
n = n * 3 + 1
count += 1
return count

def drawGraph(iteration):
""" Draws a graph with a positive integer on the x-axis, and the number of iterations it takes for the 3n+1 sequence to bring that integer to 1 on the y-axis. The graph actively marks where the current maximum value is.

args: iteration [int] - the upper bound of the function as inputed by the user in Part A

return: none.
"""
grapher = turtle.Turtle()
grapher.speed(0)
grapher.up()
grapher.goto(0,0)
grapher.down()

writer = turtle.Turtle()
writer.speed(0)

wn = turtle.Screen()
wn.setworldcoordinates(0, 0, 10, 10)

max_so_far = 0

for i in range(1, iteration + 1):
result = seq3np1(i)
print("The number " + str(i) + " has " + str(result) + " iterations.")

if result > max_so_far:
max_so_far = result
writer.clear()
writer.up()
writer.goto(i, max_so_far)
# I intentionally place the turtle at the point of the max because I personally think it looks better there instead of the top left corner. (pls don't take points off.)
writer.write("Maximum so far: " + str(max_so_far))

wn.setworldcoordinates(0, 0, i + 10, max_so_far + 10)
grapher.goto(i, result)

wn.exitonclick()

def main():

##### PART A #####

upper = int(input("Please enter an upper bound for the function: "))
start = 1
while (start < upper):
start += 1
count = seq3np1(start)
print("The number " + str(start) + " has " + str(count) + " iterations.")

##### PART B #####

drawGraph(upper)

main()

Code Screenshots:

Sample Output Screenshots:


Related Solutions

def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2:...
def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2: print("./") print("*") print(".\\") elif n == 3: print("../") print("./") print("*") print(".\\") print("..\\") elif n == 4: print(".../") annoying_valley(3) print("...\\") elif n == 5: print("..../") annoying_valley(4) print("....\\") elif n == 6: print("...../") annoying_valley(5) print(".....\\") else: print("." * (n - 1) + "/") annoying_valley(n - 1) print("." * (n - 1) + "\\") def annoying_int_sequence(n): if n == 0: return [] elif n == 1: return...
For the sequence a n = 8n 3n + 6 , n = 1,2,3,4, a) does...
For the sequence a n = 8n 3n + 6 , n = 1,2,3,4, a) does the sequence converge or diverge? Why? If it converges, what exactly does it converge to?
Find the value of ∑(−1)^n/(3n+1) from n=0 to ∞
Find the value of ∑(−1)^n/(3n+1) from n=0 to ∞
1- Show that (n^3+3n^2+3n+1) / (n+1) is O (n2 ). Use the definition and proof of...
1- Show that (n^3+3n^2+3n+1) / (n+1) is O (n2 ). Use the definition and proof of big-O notation. 2- Prove using the definition of Omega notation that either 8 n is Ω (5 n ) or not. please help be with both
Derive the Sackur-Tetrode equation starting from the multiplicity givenin Ch. 2: Ω =(1/N!)(V^{N}/h^{3N})(pi^{3N/2}/3N^{2}!)(2mU)^{3N/2} The Sackur-Tetrode equation...
Derive the Sackur-Tetrode equation starting from the multiplicity givenin Ch. 2: Ω =(1/N!)(V^{N}/h^{3N})(pi^{3N/2}/3N^{2}!)(2mU)^{3N/2} The Sackur-Tetrode equation is: S=Nk[ln((V/N)((4pi*m*U)/(3Nh^{2}))^{3/2})+(5/2)]
A rock weighing 25-N is thrown vertically into the air from ground level. when it reaches...
A rock weighing 25-N is thrown vertically into the air from ground level. when it reaches 15.0 m above ground, it is traveling at 25.0 m/s upward. Use the work-energy to find: a) the rock's speed just as it left the ground b) its maximum height
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2:...
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2: return 2 if n == 3: return 6 if n == 4: return 4 * annoying_factorial(3) if n == 5: return 5 * annoying_factorial(4) if n == 6: return 6 * annoying_factorial(5) else: return n * annoying_factorial(n-1) def annoying_fibonacci(n): if n==0: return 0 if n==1: return 1 if n==2: return 1 if n==3: return 2 if n==4: return annoying_fibonacci(4-1)+annoying_fibonacci(4-2) if n==5: return annoying_fibonacci(5-1)+annoying_fibonacci(5-2) if...
6a. Show that 2/n = 1/3n + 5/3n and use this identity to obtain the unit...
6a. Show that 2/n = 1/3n + 5/3n and use this identity to obtain the unit fraction decompositions of 2/25 , 2/65 , and 2/85 as given in the 2/n table in the Rhind Mathematical Papyrus. 6b. Show that 2/mn = 1/ (m ((m+n)/ 2 )) + 1/ (n ((m+n)/ 2 )) and use this identity to obtain the unit fraction decompositions of 2/7 , 2/35 , and 2/91 as given in the 2/n table in the Rhind Mathematical Papyrus....
import sys var = 1 print(var) def function1(myVar):     print(myVar)     var = myVar + 1...
import sys var = 1 print(var) def function1(myVar):     print(myVar)     var = myVar + 1     print(var)     function2(var) def function2(myVar):     print(myVar)     var = myVar + 1     print(var)     function3(var) def function3(myVar):     print(myVar)     var = myVar + 1     print(var) def main(argv):     var = 10     print(var)     function1(var) if __name__=="__main__":     main(sys.argv) 1. As the program runs, what is the first line that will be interpreted by Python, and what action will...
Set up a for loop to print values from n down to 1 with at most...
Set up a for loop to print values from n down to 1 with at most 5 values per line. For example, when n is 7 then the output is shown below: 7    6    5    4    3 2    1 C++ code
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT