How to catch StopIteration?
Chris
cwitts at gmail.com
Tue Jun 17 02:49:08 EDT 2008
On Jun 17, 8:43 am, Chris <cwi... at gmail.com> wrote:
> On Jun 17, 5:50 am, ccy56... 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
>
> def collatz(n):
> r=[]
> while n>1:
> r.append(n)
> n = 3*n+1 if n%2 else n/2
> yield r
>
> i = 1
> while 1:
> try:
> last = x[:i]
> print x[:i]
> i += 1
> except StopIteration
> last.append(1)
> break
>
> You will have to control the for loop yourself otherwise the
> StopIteration is handled for you.
forgot to put
x = collatz(13)
before the while loop starts and a x.next() inside the while, but
hopefully you get the point :p
More information about the Python-list
mailing list