Question: PYTHON: can someone help me fix my current code? I can't figure out how to call the seq3np1 function to step 2 and use it
PYTHON: can someone help me fix my current code? I can't figure out how to call the seq3np1 function to step 2 and use it appropriately.
Step 1: Count the number of iterations it takes to get to 1 Currently, the function prints all values in the calculation until the algorithm reaches 1. We will change the nature of the function slightly by counting the number of times it takes to get to 1 and returning the count. To implement this, follow these steps in the seq3np1 function: 1. Delete the print statement. 2. Define a variable called count and initialize it to zero before the loop. 3. Within the loop, increment the count by 1, so that we can keep track of the number of times the loop executes. 4. When the loop terminates (i.e. when the sequence arrives at 1) return the count . Example: The code print(seq3np1(9)) prints the value 19 . The code print(seq3np1(10)) prints the value 6 .
Step 2: Repeat the Call to seq3np1 Repeat the call to seq3np1 using a range of values, up to and including an upper bound. 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, each time passing in a new value. Create a simple for -loop using a loop variable called start that provides values from 1 up to and including 50. Call the seq3np1 function once for each value of start . Modify the print statement to also print the value of start . An example is provided in figure 1 below.
MY CODE:
def seq3np1(n): """ Print the 3n+1 sequence from n, terminating when it reaches 1.""" count = 0 while n != 1: count +=1 if n % 2 == 0: # n is even n = n // 2 else: # n is odd n = n * 3 + 1 print("The total count is:",count) seq3np1(3)
start = 1 for i in range (1,51): var = seq3np1 (start)
print("The start value =", start, "; the return value =", var) start += 1
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
