You will begin with a program that asks the user to enter a sequence of values and tells the user if each value is even or odd.
You will then modify this program to automatically generate the terms of a famous numerical sequence.
The Collatz sequence works as follows.
You start by choosing a positive integer N. Then:
Here is an example, where the initial value of N is 6:
6, 3, 10, 5, 16, 8, 4, 2, 1
Make sure you understand how this sequence was generated, given the starting value of 6. Then answer Question 1 in your writeup.
You will write a program that allows the user to choose the value of N, and we will generate all the subsequent terms of the sequence.
It has not been mathematically proven that this sequence will always reach 1 and terminate. However, no one has yet found a value of N that fails to eventually reach 1.
xkcd's take:
''' Program: CS 115 Lab 6a Author: Your name Description: This program will ask the user for a value and tell the user whether the value is even or odd. ''' def main(): N = int(input('Enter a number: ')) if N % 2 == 1: print(N, 'is odd.') else: print(N, 'is even.') main()
if N % 2 == 1: # Compute the next term in the Collatz sequence for odd N, and set N to that value. else: # Compute the next term in the Collatz sequence for even N, and set N to that value. # Print the new value of N.
Note: you should use integer division (//) instead of floating-point division (/) so that the values appear as integers.
For example:
Enter a number: 8
The next term is 4.
or:
Enter a number: 3
The next term is 10.
while ...: if ... else ... print ...
The while loop condition should evaluate to True until you have finished the sequence, and then it should become False. Remember that the sequence ends when N reaches 1. The condition does not need to be long and involved -- it can be very short.
If you accidentally write an infinite loop, you can press Ctrl-C to force-quit your program.
Enter a number: 8
The next term is 4.
The next term is 2.
The next term is 1.
Enter a number: 6
The next term is 3.
The next term is 10.
The next term is 5.
The next term is 16.
The next term is 8.
The next term is 4.
The next term is 2.
The next term is 1.