Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #5966
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: count strangeness |
| Date | 2011-05-22 09:13 +0200 |
| Organization | None |
| References | <ira8ti$6no$1@dont-email.me> <mailman.1905.1306045890.9059.python-list@python.org> <iraaqg$dfi$2@dont-email.me> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1908.1306048424.9059.python-list@python.org> (permalink) |
James Stroud wrote:
> Peter Otten wrote:
>> James Stroud wrote:
>>> WTF?
>>
>> Put the code into a file, run it -- and be enlightened ;)
>
>
> tal 72% python2.7 eraseme.py
> 1
> 2
> 4
> 8tal 73% cat eraseme.py
> #! /usr/bin/env python
>
> class C:
> 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
>
> c = C()
> c.data.extend([C() for i in xrange(10)])
> c.doit()
> tal 74% python2.7 eraseme.py
> 1
> 2
> 4
> 8
> 16
> 32
> 64
> 128
> 256
> 512
> 1024
>
>
> Hmmm. It's still 1024.
>
> What am I missing?
>
> James
Like Chris I assumed that you wondered why 1024 appeared twice. It turns out
WTF is not a got a good problem description.
Now for a complete run-through, the inner c.doit() has len(c.data) == 0, so
count += c.doit(count) just adds count + 1 and you get 10 iterations:
(1) count=0, print 1, add 1
(2) count=1, print 2, add 2
(3) count=3, print 4, add 4
(4) count=7, print 8, add 8
(5) you get the idea
Another way to look at it: in your special case the inner loop can be
rewritten as
for c in self.data:
print count + 1
count += count + 1
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