On 11/21/2013 6:17 PM, bradleybooth12...@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
[7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]
The specification does not say what the result should be when the input
is 1, but given the example above, [1] 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, [1]), (2, [2,1]),
(3, [3,10,5,16,8,4,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
else:
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
remaining error.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list