1. Write 3n + 1 Sequence String Generator function (1 point) In lab5.py complete the function sequence that takes one parameter: n, which is the initial value of a sequence of integers. The 3n + 1 sequence starts with an integer, n in this case, wherein each successive integer of the sequence is calculated based on these rules: 1. If the current value of n is odd, then the next number in the sequence is three times the current number plus one. 2. If the current value of n is even, then the next number in the sequence is half of the current number. Note: Make sure to use integer division. 3. Integers in the sequence are generated based the two rules above until the current number becomes 1. Your function should start with an empty string and append characters to the string as described next. The function keeps calculating the numbers in the 3n + 1 sequence, and while there are still numbers left in the sequence (meaning that the number has not reached 1 yet), it keeps appending letters to the string based on these rules: 1. If the number is divisible by 2, then append 'A' to the string. 2. If the number is divisible by 3, then append 'B' to the string. 3. If the number is divisible by 5, then append 'C' to the string. 4. If the number is divisible by 7, then append 'D' to the string. Note: The original number n also should contribute a letter (or letters) to the string. Also, append letters to your accumulating string for all conditions met above. That means, for example, if the current number is 6, the letters 'A' and 'B' will both be appended to the string, in that order. Apply the rules in the order given. For example, for the number 6, your code must append the letters in the order 'AB', not 'BA'. Note: If you find any helper functions useful, feel free to use them. In fact, I suggest that you try to define and use helper functions. This idea applies not only to this problem, but to any problem. In the end, your function should return the string generated (accumulated) by the procedure described above. If n initially is less than 1, the function returns an empty string. Example calls: sequence(4) # returns 'AA' sequence(12) # returns 'ABABBACCAAAA' sequence(24) # returns 'ABABABBACCAAAA'
Hi, Please find the code below. I have named the function "sequence_generator" which takes a number "n" as input.
def sequence_generator(n):
#if input smaller than 1 return empty string
if n<1:
return ''
output_string=''
#keep generating sequence while current number > 1
while n>1:
if n%2==0:
output_string += 'A'
if n%3==0:
output_string += 'B'
if n%5==0:
output_string += 'C'
if n%7==0:
output_string += 'D'
# if n is even then next number is half of current number
if n%2 == 0:
n = n//2
# if n is odd then next number is 3 times current number plus one.
else:
n = 3*n+1
return output_string
Get Answers For Free
Most questions answered within 1 hours.