How to catch StopIteration?
Nick Craig-Wood
nick at craig-wood.com
Tue Jun 17 11:31:34 EDT 2008
ccy56781 at gmail.com <ccy56781 at gmail.com> wrote:
> I'm writing to see calcuration process.
> And so, I can't catch StopIteration...
>
> What is mistake?
>
> def collatz(n):
> r=[]
> while n>1:
> r.append(n)
> n = 3*n+1 if n%2 else n/2
> yield r
>
> for i, x in enumerate(collatz(13)):
> try:
> last = x[:i+1]
> print x[:i+1]
> except StopIteration:
> print last.appnd(1)
>
> Output:
> [13]
> [13, 40]
> [13, 40, 20]
> [13, 40, 20, 10]
> [13, 40, 20, 10, 5]
> [13, 40, 20, 10, 5, 16]
> [13, 40, 20, 10, 5, 16, 8]
> [13, 40, 20, 10, 5, 16, 8, 4]
> [13, 40, 20, 10, 5, 16, 8, 4, 2]
> last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] # i want this
> list
I would have thought you want this...
>>> for i, x in enumerate(collatz(13)):
... last = x[:i+1]
... print x[:i+1]
... else:
... last.append(1)
... print last
...
[13]
[13, 40]
[13, 40, 20]
[13, 40, 20, 10]
[13, 40, 20, 10, 5]
[13, 40, 20, 10, 5, 16]
[13, 40, 20, 10, 5, 16, 8]
[13, 40, 20, 10, 5, 16, 8, 4]
[13, 40, 20, 10, 5, 16, 8, 4, 2]
[13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list