Newbie - Trying to Help a Friend
tjreedy at udel.edu
Fri Nov 22 01:17:10 CET 2013
On 11/21/2013 6:17 PM, bradleybooth12345 at gmail.com wrote:
> Coming back to the second question
> "The collatz process is as follows. Take a positive integer n greater than 1. while n is greater than 1 repeat the following; if N is even halve it and if N is odd multiply it by 3 and add 1. The (Unsolved) collatz conjecture is that this process always terminates.
> The user should be prompted to supply the number n, and your program should build the list of values taken by sucessive iteration of the algorithm, and print it out. For example, if 7 is input your program should print the list
The specification does not say what the result should be when the input
is 1, but given the example above,  seems reasonable (rather than an
exception or ).  is ok for 0 (or negative).
> We've managed to come up with this, but obviously it's wrong.
In what way is it wrong? The answer to that tells you what to fix.
A syntax error about indentation? Fix the indentation.
> Any Idea's?
Write test code before writing the function.
for inn,out in [(0, ), (1, ), (2, [2,1]),
(7, [7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]), ]:
s = collatz(inn)
print(inn, ':', s)
if s != out:
print('is not', out)
> def collatz_sequence (n) :
> seq = [ ]
4 space indents are best; a good editor, like the one with Idle, will
convert <tab> to 4 spaces
> if n < 1 :
> return [ ]
> while n > 1:
> if n % 2 == 0:
dedent if so it lines up with else below
> n = n/2
> n = 3*n+ 1
> seq.append (n)
> return seq
does not line up with while
Once you get indents consistent, test failure should suggest the
Terry Jan Reedy
More information about the Python-list