Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #5957
| References | <ira8ti$6no$1@dont-email.me> |
|---|---|
| Date | 2011-05-21 23:27 -0700 |
| Subject | Re: count strangeness |
| From | Chris Rebert <crebert@ucsd.edu> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1903.1306045726.9059.python-list@python.org> (permalink) |
On Sat, May 21, 2011 at 11:02 PM, James Stroud <jstroud@mbi.ucla.edu> wrote: > tal 65% python2.7 > Python 2.7.1 (r271:86832, May 21 2011, 22:52:14) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> class C(object): > ... def __init__(self): > ... self.data = [] > ... def doit(self, count=0): > ... for c in self.data: > ... count += c.doit(count) > ... count += 1 > ... print count > ... return count > ... > py> c = C() > py> c.data.extend([C() for i in xrange(10)]) > py> c.doit() > 1 > 2 > 4 > 8 > 16 > 32 > 64 > 128 > 256 > 512 > 1024 > 1024 > > WTF? Assuming your question is "Why is 1024 there twice?", the answer is that it was the return value of the initial c.doit() call, and the interactive interpreter outputs all non-None expression results; for example: [In the Python REPL] >>> 5 + 5 10 >>> So, you explicitly print the 1024 in your function once, and the interpreter implicitly outputs it the second time. Notice what happens when we use a statement instead of an expression: >>> final = c.doit() 1 2 4 8 16 32 64 128 256 512 1024 >>> final 1024 >>> And if we comment out the `print` in C.doit() and run your example again: >>> c = C() >>> c.data = [C() for i in xrange(10)] >>> c.doit() 1024 >>> Cheers, Chris -- http://rebertia.com
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-21 23:02 -0700
Re: count strangeness Chris Rebert <crebert@ucsd.edu> - 2011-05-21 23:27 -0700
Re: count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-21 23:32 -0700
Re: count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-21 23:39 -0700
Re: count strangeness Chris Rebert <crebert@ucsd.edu> - 2011-05-21 23:55 -0700
Re: count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-22 00:03 -0700
Re: count strangeness Peter Otten <__peter__@web.de> - 2011-05-22 08:31 +0200
Re: count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-21 23:34 -0700
Re: count strangeness Peter Otten <__peter__@web.de> - 2011-05-22 09:13 +0200
Re: count strangeness James Stroud <jstroud@mbi.ucla.edu> - 2011-05-21 23:56 -0700
Re: count strangeness Roy Smith <roy@panix.com> - 2011-05-22 09:36 -0400
csiph-web