Write a script that solves the following problems. For each problem, first print
ID: 3562994 • Letter: W
Question
Write a script that solves the following problems. For each problem, first print the problem number followed by the answer to make it easier to grade. Be sure your script includes all the necessary code to produce the results. (1) Which positive integer n 20; 000 has the longest hailstone sequence? The Python function len can be used to compute the length of a list. Note: The code will run faster if you do not print lots of things. (2) How long is the hailstone sequence of the integer found in (1)? (3) What is the largest integer in the hailstone sequence for the integer found in (1)? (The Python function max can be used to compute the maximum entry of a list.)
Explanation / Answer
Code:
#!/usr/local/bin/python2.7
def hailstone(n):
seq = [n]
while n>1:
n = 3*n + 1 if n & 1 else n//2
seq.append(n)
return seq
if __name__ == '__main__':
h = hailstone(20)
print h;
print("Maximum length is %i was found for hailstone(%i) for numbers <20,000" %
max((len(hailstone(i)), i) for i in range(1,20000)))
---------------------------------------------------------------------------------------------------------------
Sample Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.