How to catch StopIteration?

ccy56781 at gmail.com ccy56781 at gmail.com
Mon Jun 16 23:50:15 EDT 2008


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



More information about the Python-list mailing list