Re: [Tutor] recursive problem

2010-09-12 Thread ALAN GAULD


> > If you do need to avoid accidentally launching  missiles then you need
> > to do some type checking - although ideally using  isinstance() instead
> > of type(). But in the majority of cases some  sensible documentation
> > and Python's culture that we are all adults here  usually means you
> > don't need to.
> 
> The last chapter I don't understand completly.
> Do i have no need for type  checking or make use of isinstance() or do I 
>misunderstood you.
> Sorry that  English is not a language I speak very well.

I'm saying that most of the time you should try working without type checking 
but there are occasions when you must do it. And if you do need to you should 
nearly always use isinstance() rather than type()

HTH,

Alan G
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-12 Thread Alan Gauld

"Roelof Wobben"  wrote

Because I follow this book "Thinking like a computer scientist" and
I have only read the chapters about strings. lists and tuples.


And that book tries to use Python to teach a general Computing
Science degree 101 course. So it teaches you what are classically
considered good practices even when these are not normal Python
practice. That doesn't make it a bad book but its not purely Pythonic.

FWIW The same is true of my tutorial - I try to teach general 
principles

rather than pure Python - but my attempt to minimise the difference
is to include examples using VBScript and Javascriopt to illustrate
alternate approaches. You pick your favourite and run with it, but
recognise the limits...

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-12 Thread Roelof Wobben




> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Sun, 12 Sep 2010 20:52:06 +0100
> Subject: Re: [Tutor] recursive problem
>
> "Roelof Wobben" wrote
>
>>>> I guess the question to ask/consider is: How can be establish
>>>> whether a
>>>> particular object supports a particular interface/set of
>>>> behaviours
>
> In general we "try" it and handle the exceptions
>
>>>> that we require? E.g. how do we most pythonically check whether
>>>> some
>>>> object "walks like a list" and "quacks like a list" without tying
>>>> such
>>>> code to explicit type checking?
>
> But the risk is that although it may quack, it does so like a missile
> launch program rather than a list - oops! :-)
>
>> With the knowlegde I have from the few chapters of thinking like
>> a computer scientist I don't know the answer to the last question.
>
> If you do need to avoid accidentally launching missiles then you need
> to do some type checking - although ideally using isinstance() instead
> of type(). But in the majority of cases some sensible documentation
> and Python's culture that we are all adults here usually means you
> don't
> need to.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello Alan, 
 
The last chapter I don't understand completly.
Do i have no need for type checking or make use of isinstance() or do I 
misunderstood you.
Sorry that English is not a language I speak very well.
 
Roelof

  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-12 Thread Alan Gauld

"Roelof Wobben"  wrote

I guess the question to ask/consider is: How can be establish 
whether a
particular object supports a particular interface/set of 
behaviours


In general we "try" it and handle the exceptions

that we require? E.g. how do we most pythonically check whether 
some
object "walks like a list" and "quacks like a list" without tying 
such

code to explicit type checking?


But the risk is that although it may quack, it does so like a missile
launch program rather than a list - oops! :-)


With the knowlegde I have from the few chapters of thinking like
a computer scientist I don't know the answer to the last question.


If you do need to avoid accidentally launching missiles then you need
to do some type checking - although ideally using isinstance() instead
of type(). But in the majority of cases some sensible documentation
and Python's culture that we are all adults here usually means you 
don't

need to.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] recursive problem

2010-09-12 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: st...@pearwood.info
> Subject: RE: [Tutor] recursive problem
> Date: Sun, 12 Sep 2010 07:58:48 +
>
>
>
>
> 
>> From: st...@pearwood.info
>> To: tutor@python.org
>> Date: Sun, 12 Sep 2010 10:10:53 +1000
>> Subject: Re: [Tutor] recursive problem
>>
>> On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:
>>
>>> So, perhaps it's an idea to call dir() on a given object and see
>>> whether the object provides the necessary methods to function, e.g.
>>> __iter__, __delitem__, __setitem__ and friends?
>>
>> There's no need to do this:
>>
>> attributes = dir(obj)
>> if '__iter__' in attributes and '__len__' in attributes:
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> when you can do this:
>>
>>
>> if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> or this:
>>
>> try:
>> obj.__iter__
>> obj.__len__
>> except AttributeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> or even
>>
>> try:
>> iter(obj)
>> len(obj)
>> except TypeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> Where possible, the last version is to be preferred, because it doesn't
>> care about internal details which might change.
>>
>>
>>
>> --
>> Steven D'Aprano
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Oke,

This is to far for me.
Im only at chapter 11 and this stuff will be in chapter 13 and further.

Roelof
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:

> So, perhaps it's an idea to call dir() on a given object and see
> whether the object provides the necessary methods to function, e.g.
> __iter__, __delitem__, __setitem__ and friends?

There's no need to do this:

attributes = dir(obj)
if '__iter__' in attributes and '__len__' in attributes:
print "Quacks like a list"
else:
print "Not like a list"


when you can do this:


if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
print "Quacks like a list"
else:
print "Not like a list"


or this:

try:
obj.__iter__
obj.__len__
except AttributeError:
print "Not like a list"
else:
print "Quacks like a list"


or even 

try:
iter(obj)
len(obj)
except TypeError:
print "Not like a list"
else:
print "Quacks like a list"


Where possible, the last version is to be preferred, because it doesn't 
care about internal details which might change.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Walter Prins
Just a quick contribution for what it's worth: One of the subjects being
implicitly talked about here is "introspection" -- you may want to google
that and see else you can find. That said, a nice article covering some of
Python's introspection features is presented here on IBM's site:
http://www.ibm.com/developerworks/library/l-pyint.html

Actually any user
that's used to doing introspection in the Python shell already has that same
tool at their disposal for programmatic introspection, e.g. the dir()
method.  (This is covered in the above article.)

So, perhaps it's an idea to call dir() on a given object and see whether the
object provides the necessary methods to function, e.g. __iter__,
__delitem__, __setitem__ and friends?

Here's some code which constructs a class from scratch, which contains 2
member variables, which are made available via list indexing by implementing
__getitem__ and _setitem__ and shows how you can then use that object as if
it's a list, as least as far as the first 2 elements are concerned.  Also
does some interrogation with dir() at the end.

http://pastebin.com/rRZpbham

Hope that helps,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: st...@pearwood.info
> Subject: RE: [Tutor] recursive problem
> Date: Sat, 11 Sep 2010 18:39:31 +
>
>
>
>
> 
>> From: st...@pearwood.info
>> To: tutor@python.org
>> Date: Sun, 12 Sep 2010 04:19:57 +1000
>> Subject: Re: [Tutor] recursive problem
>>
>> On Sun, 12 Sep 2010 04:09:20 am Roelof Wobben wrote:
>>
>>>> On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
>>>>> But why is type checking then wrong.
>>>>> Lets says I want a module who must work on strings, tuple and
>>>>> lists.
>>>>
>>>> It's not *always* wrong, but let me ask you... why do you want to
>>>> *limit* the function to work on ONLY strings, tuples and lists?
>>
>>> Because I follow this book "Thinking like a computer scientist" and I
>>> have only read the chapters about strings. lists and tuples.
>>
>> Good answer!
>>
>> Don't worry about all the complications. Learn to walk first, then learn
>> to run.
>>
>>
>>
>> --
>> Steven D'Aprano
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

 Oke,

So EAFP for me is one step to far ?

Roelof
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Lie Ryan
On 09/12/10 03:18, Steven D'Aprano wrote:
> Or you could do this:
> 
> if do_this_will_succeed() and do_that_will_succeed() \
> and do_something_else_will_succeed():
> do_this()
> do_that()
> do_something_else()
> else:
> do_error()
> 
> But that hasn't done anything to prevent race conditions. So the real 
> reason people use LBYL is that they're too lazy to write hideously 
> ugly, but reliable, code, and they're just hoping that they will never 
> expose the race condition. (Often this is a pretty safe hope, but not 
> always.)

Or, probably the best alternative is to mix LBYL and EAFP, e.g.:

attempt = 0
while attempt < 10:
# first acquire the lock using EAFP
try:
lock = acquire_lock()
except FailToAcquireLock:
attempt += 1
time.sleep(1)
else:
# Now apply LBYL, since there is no point in doing
# operations that may be expensive if they will definitely
# fail by the quick check
if account_active(fromAcc) and account_active(toAcc)
and can_withdraw(fromAcc, amount):

# this operations only writes to a scratch space
withdraw(fromAcc, amount)
deposit(toAcc, amount)

# back to EAFP, since there is no way of assuring
# this with LBYL
try:
# mark the scratch space as permanent change
commit()
except CommitFailure:
raise SeriousError("this can't be happening")
else:
finally:
# LBYL:
# there is no point in releasing unacquired lock;
# should probably be done inside release_lock() so that
# calling release_lock() an unacquired lock safely does nothing
if not lock:
release_lock(lock)
else:
raise Failure("failed to acquire lock")




else:
do_error("no privilege")

release_lock(lock)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Sun, 12 Sep 2010 04:09:20 am Roelof Wobben wrote:

> > On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
> >> But why is type checking then wrong.
> >> Lets says I want a module who must work on strings, tuple and
> >> lists.
> >
> > It's not *always* wrong, but let me ask you... why do you want to
> > *limit* the function to work on ONLY strings, tuples and lists?

> Because I follow this book "Thinking like a computer scientist" and I
> have only read the chapters about strings. lists and tuples.

Good answer!

Don't worry about all the complications. Learn to walk first, then learn 
to run.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Sun, 12 Sep 2010 04:01:39 am Walter Prins wrote:

> I guess the question to ask/consider is: How can be establish whether
> a particular object supports a particular interface/set of behaviours
> that we require?  E.g. how do we most pythonically check whether some
> object "walks like a list" and "quacks like a list" without tying
> such code to explicit type checking?

isinstance(object, base_class) becomes even more useful in Python 2.6 
and beyond, because when you create a class, you can register it as a 
list even if you didn't inherit from list. You're essentially 
promising "this class will walk and quack and swim like a list".

But often you don't care that something walks, quacks, and swims like a 
list. You might only care that it walks. We can combine "Look Before 
You Leap" with duck-typing:


def swap_items(sequence):
try:
sequence[0] = sequence[0]
except Exception:
print("does not support item lookup or item assignment")
else:
for i in range(0, len(sequence)-1, 2):
sequence[i], sequence[i+1] = sequence[i+1], sequence[i]
return sequence


>>> swap_items("abcd")
does not support item lookup or item assignment
>>> swap_items(['a', 'b', 'c', 'd', 'e', 'f'])
['b', 'a', 'd', 'c', 'f', 'e']




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




> From: st...@pearwood.info
> To: tutor@python.org
> Date: Sun, 12 Sep 2010 04:03:43 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
>
>> But why is type checking then wrong.
>> Lets says I want a module who must work on strings, tuple and lists.
>
> It's not *always* wrong, but let me ask you... why do you want to
> *limit* the function to work on ONLY strings, tuples and lists?
>
> The Python philosophy is "duck typing" -- if it walks like a duck, and
> swims like a duck, it is close enough to a duck that we don't care that
> it's not actually a duck, but a goose.
>
> Here's an example:
>
>
> def f1(x):
> if type(x) is int or type(x) is float:
> print("x + 1 = %s" % (x+1))
> else:
> print("x is not a number")
>
>
> def f2(x):
> try:
> print("x + 1 = %s" % (x+1))
> except (ValueError, TypeError):
> print("x is not a number")
>
>>>> f1(3)
> x + 1 = 4
>>>> from decimal import Decimal
>>>> f1(Decimal(3))
> x is not a number
>>>> f2(Decimal(3))
> x + 1 = 4
>
> Function f1 makes the assumption that only ints and floats can be added,
> and so it gives the wrong results with Decimal numbers. But function f2
> uses "duck typing" -- it doesn't care what sort of number x is, only
> that it can be added.
>
>
>
>> Can I then use EAFP ?
>>
>> Without type checking I never know which one is used now.
>
>
> Going back to type-checking... sometimes you can't avoid it. Sometimes
> you use it because it is easier, and you don't care enough to write
> more complicated code. Sometimes you really do care what the type is:
>
>>>> "abc"[2.0]
> Traceback (most recent call last):
> File "", line 1, in 
> TypeError: string indices must be integers
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello Steven,
 
Because I follow this book "Thinking like a computer scientist" and I have only 
read the chapters about strings. lists and tuples.

Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Lie Ryan
On 09/12/10 04:01, Walter Prins wrote:
> I guess the question to ask/consider is: How can be establish whether a
> particular object supports a particular interface/set of behaviours that
> we require?  E.g. how do we most pythonically check whether some object
> "walks like a list" and "quacks like a list" without tying such code to
> explicit type checking?

In Python? By treating it like a list; and shooting the duck in their
webby feet when it doesn't act like a list.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: wpr...@gmail.com
> Subject: RE: [Tutor] recursive problem
> Date: Sat, 11 Sep 2010 18:05:12 +
>
>
>
>
> 
>> Date: Sat, 11 Sep 2010 19:01:39 +0100
>> Subject: Re: [Tutor] recursive problem
>> From: wpr...@gmail.com
>> To: rabidpoob...@gmail.com
>> CC: rwob...@hotmail.com; tutor@python.org
>>
>>
>> That's the whole point! You don't WANT to know what type it is. You
>> want to just use it how you want, an if it behaves properly, who cares
>> what type it is?
>>
>> See when you type check you are forcing the user to use those types.
>> What if they want to derive a subclass from list? Is there really a
>> reason why you should prevent them from using that subclass with your
>> function?
>> If there is a valid reason, type checking is fine. But if there isn't,
>> type checking is just making your code more inflexible.
>>
>>
>> Well, I would submit that if were going to do type checking in such a
>> context you'd probably check for a base class, so deriving a subclass
>> wouldn't break entirely. Your point still stands however, we don't
>> even want to require from users to derive from class list. We'd be
>> quite happy to work with any object that "walks like a list" and
>> "quacks like a list", that's the beauty of duck typing...
>>
>> I guess the question to ask/consider is: How can be establish whether a
>> particular object supports a particular interface/set of behaviours
>> that we require? E.g. how do we most pythonically check whether some
>> object "walks like a list" and "quacks like a list" without tying such
>> code to explicit type checking?
>>
>> Walter
>
> Exactly what I mean.
>
> With the knowlegde I have from the few chapters of thinking like a computer 
> scientist I don't know the answer to the last question.
>
>
> Roelof
>
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:

> But why is type checking then wrong.
> Lets says I want a module who must work on strings, tuple and lists.

It's not *always* wrong, but let me ask you... why do you want to 
*limit* the function to work on ONLY strings, tuples and lists?

The Python philosophy is "duck typing" -- if it walks like a duck, and 
swims like a duck, it is close enough to a duck that we don't care that 
it's not actually a duck, but a goose.

Here's an example:


def f1(x):
if type(x) is int or type(x) is float:
print("x + 1 = %s" % (x+1))
else:
print("x is not a number")


def f2(x):
try:
print("x + 1 = %s" % (x+1))
except (ValueError, TypeError):
print("x is not a number")

>>> f1(3)
x + 1 = 4
>>> from decimal import Decimal
>>> f1(Decimal(3))
x is not a number
>>> f2(Decimal(3))
x + 1 = 4

Function f1 makes the assumption that only ints and floats can be added, 
and so it gives the wrong results with Decimal numbers. But function f2 
uses "duck typing" -- it doesn't care what sort of number x is, only 
that it can be added.



> Can I then use EAFP ?
>
> Without type checking I never know which one is used now.


Going back to type-checking... sometimes you can't avoid it. Sometimes 
you use it because it is easier, and you don't care enough to write 
more complicated code. Sometimes you really do care what the type is:

>>> "abc"[2.0]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: string indices must be integers



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Walter Prins
> That's the whole point! You don't WANT to know what type it is. You want to
> just use it how you want, an if it behaves properly, who cares what type it
> is?
>
> See when you type check you are forcing the user to use those types. What
> if they want to derive a subclass from list? Is there really a reason why
> you should prevent them from using that subclass with your function?
> If there is a valid reason, type checking is fine. But if there isn't, type
> checking is just making your code more inflexible.
>
>
Well, I would submit that if were going to do type checking in such a
context you'd probably check for a base class, so deriving a subclass
wouldn't break entirely.  Your point still stands however, we don't even
want to require from users to derive from class list.  We'd be quite happy
to work with any object that "walks like a list" and "quacks like a list",
that's the beauty of duck typing...

I guess the question to ask/consider is: How can be establish whether a
particular object supports a particular interface/set of behaviours that we
require?  E.g. how do we most pythonically check whether some object "walks
like a list" and "quacks like a list" without tying such code to explicit
type checking?

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Luke Paireepinart

On Sep 11, 2010, at 12:40 PM, Roelof Wobben  wrote:

> 
> 
> 
> 
>> From: st...@pearwood.info
>> To: tutor@python.org
>> Date: Sun, 12 Sep 2010 03:27:42 +1000
>> Subject: Re: [Tutor] recursive problem
>> 
>> On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:
>> 
>>> But that hasn't done anything to prevent race conditions. So the real
>>> reason people use LBYL is that they're too lazy to write hideously
>>> ugly, but reliable, code, and they're just hoping that they will
>>> never expose the race condition. (Often this is a pretty safe hope,
>>> but not always.)
>> 
>> http://en.wikipedia.org/wiki/Ostrich_algorithm
>> 
>> 
>> --
>> Steven D'Aprano
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
> 
> Oke,
> 
> But why is type checking then wrong.
> Lets says I want a module who must work on strings, tuple and lists.
> 
> Can I then use EAFP ?
> 
> Without type checking I never know which one is used now.
> 
> Roelof
>   

That's the whole point! You don't WANT to know what type it is. You want to 
just use it how you want, an if it behaves properly, who cares what type it is?

See when you type check you are forcing the user to use those types. What if 
they want to derive a subclass from list? Is there really a reason why you 
should prevent them from using that subclass with your function?
If there is a valid reason, type checking is fine. But if there isn't, type 
checking is just making your code more inflexible.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




> From: st...@pearwood.info
> To: tutor@python.org
> Date: Sun, 12 Sep 2010 03:27:42 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:
>
>> But that hasn't done anything to prevent race conditions. So the real
>> reason people use LBYL is that they're too lazy to write hideously
>> ugly, but reliable, code, and they're just hoping that they will
>> never expose the race condition. (Often this is a pretty safe hope,
>> but not always.)
>
> http://en.wikipedia.org/wiki/Ostrich_algorithm
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Oke,
 
But why is type checking then wrong.
Lets says I want a module who must work on strings, tuple and lists.
 
Can I then use EAFP ?
 
Without type checking I never know which one is used now.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:

> But that hasn't done anything to prevent race conditions. So the real
> reason people use LBYL is that they're too lazy to write hideously
> ugly, but reliable, code, and they're just hoping that they will
> never expose the race condition. (Often this is a pretty safe hope,
> but not always.)

http://en.wikipedia.org/wiki/Ostrich_algorithm


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




> From: st...@pearwood.info
> To: tutor@python.org
> Date: Sun, 12 Sep 2010 03:18:19 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Fri, 10 Sep 2010 09:30:23 pm Ewald Horn wrote:
>
>> While EAFP is great, it's not
>> always the best way to proceed.
>
> That, at least, is correct. But what you say next is not:
>
>> Sometimes you want programs to be
>> very robust and secure, this is where LBYL comes in - it is quite
>> often used in online transaction processing and other areas where
>> absolute certainty is more important than any other consideration.
>
> If what you are saying is correct, and I doubt seriously that it is,
> then chances are good that they're not succeeding in their aim.
>
>> EAFP tends to use less code and is faster to use, while LBYL
>> principles makes your program more bulletproof.
>
> That's almost 100% backwards.
>
> Let's take a simple example: you want to open a file, and deal with the
> case of the file being missing:
>
> filename = 'myfile.txt' # whatever...
> fp = open(filename)
> do_something_with(fp)
>
> Let's add some error checking. With EAFP, you get this:
>
> try:
> fp = open(filename)
> except IOError:
> handle_error()
>
>
> With LBYL, you get:
>
> if os.path.exists(filename):
> fp = open(filename)
> else:
> handle_error()
>
>
> The amount of code is about the same, but the try...except block
> automatically handles a whole slew of errors -- missing files,
> permission denied, bad file names, corrupt disks, all sorts of things
> that would be difficult or tedious to Look Before You Leap. Some of
> these things -- like disk corruption -- you simply can't check ahead of
> time. There is no way of knowing if a file is corrupt without actually
> opening and/or reading from it.
>
> It gets worse. Your computer is a multitasking system. Virtually all
> computers are these days, yes, even the iPhone. Even if os.path.exists
> returns True, there is no guarantee that the file will still be there a
> millisecond later when you try to open it. Perhaps the operating
> system, or some other process, has deleted the file or renamed it.
> That's a bug waiting to happen -- a "race condition".
>
> So if you're silly, you write this:
>
> if os.path.exists(filename):
> try:
> fp = open(filename)
> except IOError:
> handle_error()
> else:
> handle_error()
>
> If you're sensible, you realise that for reliable, secure code, checking
> for existence *before* opening the file is a waste of time and energy.
> It's barely acceptable for quick and dirty scripts, certainly not for
> high reliability applications.
>
> This is not the only sort of race condition. Imagine you're writing one
> of these high reliability online transactions you talked about, and you
> want to transfer money from one account to another:
>
> amount = 1000.00
> if balance>= amount:
> transfer(old_account, new_account, amount)
> else:
> insufficient_balance()
>
>
> Wait a second... that looks almost exactly like the LBYL code above, and
> it is vulnerable to the same sort of race condition if multiple
> processes can connect to the account at the same time. Does your bank
> allow you to log in twice? Does it have automatic transfers? If so,
> then one process can be transferring money while the other is checking
> the balance, and you have a bug waiting to happen.
>
> In practice, the banks allow accounts to become temporarily overdrawn,
> and often charge you for the privilege. And they write complicated code
> that looks like this:
>
>
> lock_id = lock_account() # Stop anything else from transferring funds.
> while lock_id == 0
> # Lock failed, wait a second and try again.
> time.sleep(1)
> lock_id = lock_account()
> if number_of_attempts()> 10:
> handle_error("internal error, please try again")
> # Now it's safe to check the balance.
> if balance>= amount:
> transfer(old_account, new_account, amount, lock_id)
> else:
> insufficient_balance()
> # Don't forget to unlock the account, or there will be trouble later!
> errcode = unlock_account(lock_id)
> if errcode != 0:
> # This should never happen. If it does, it might mean the lock ID
> # is incorrect (how?), but probably means the database is corrupt.
> log_serious_error(errcode, lock_id)
>
>
> It's ugly and error-prone, but it's also a kind of EAFP: instead of
> checking whether a lock is available, and then taking it, you just try
> to acquire a lock, and deal with the consequences of not receiving one
&

Re: [Tutor] recursive problem

2010-09-11 Thread Steven D'Aprano
On Fri, 10 Sep 2010 09:30:23 pm Ewald Horn wrote:

> While EAFP is great, it's not
> always the best way to proceed. 

That, at least, is correct. But what you say next is not:

> Sometimes you want programs to be 
> very robust and secure, this is where LBYL comes in - it is quite
> often used in online transaction processing and other areas where
> absolute certainty is more important than any other consideration.

If what you are saying is correct, and I doubt seriously that it is, 
then chances are good that they're not succeeding in their aim.

> EAFP tends to use less code and is faster to use, while LBYL
> principles makes your program more bulletproof.

That's almost 100% backwards.

Let's take a simple example: you want to open a file, and deal with the 
case of the file being missing:

filename = 'myfile.txt'  # whatever...
fp = open(filename)
do_something_with(fp)

Let's add some error checking. With EAFP, you get this:

try:
fp = open(filename)
except IOError:
handle_error()


With LBYL, you get:

if os.path.exists(filename):
fp = open(filename)
else:
handle_error()


The amount of code is about the same, but the try...except block 
automatically handles a whole slew of errors -- missing files, 
permission denied, bad file names, corrupt disks, all sorts of things 
that would be difficult or tedious to Look Before You Leap. Some of 
these things -- like disk corruption -- you simply can't check ahead of 
time. There is no way of knowing if a file is corrupt without actually 
opening and/or reading from it.

It gets worse. Your computer is a multitasking system. Virtually all 
computers are these days, yes, even the iPhone. Even if os.path.exists 
returns True, there is no guarantee that the file will still be there a 
millisecond later when you try to open it. Perhaps the operating 
system, or some other process, has deleted the file or renamed it. 
That's a bug waiting to happen -- a "race condition".

So if you're silly, you write this:

if os.path.exists(filename):
try:
fp = open(filename)
except IOError:
handle_error()
else:
handle_error()

If you're sensible, you realise that for reliable, secure code, checking 
for existence *before* opening the file is a waste of time and energy. 
It's barely acceptable for quick and dirty scripts, certainly not for 
high reliability applications.

This is not the only sort of race condition. Imagine you're writing one 
of these high reliability online transactions you talked about, and you 
want to transfer money from one account to another:

amount = 1000.00
if balance >= amount:
transfer(old_account, new_account, amount)
else:
insufficient_balance()


Wait a second... that looks almost exactly like the LBYL code above, and 
it is vulnerable to the same sort of race condition if multiple 
processes can connect to the account at the same time. Does your bank 
allow you to log in twice? Does it have automatic transfers? If so, 
then one process can be transferring money while the other is checking 
the balance, and you have a bug waiting to happen.

In practice, the banks allow accounts to become temporarily overdrawn, 
and often charge you for the privilege. And they write complicated code 
that looks like this:


lock_id = lock_account()  # Stop anything else from transferring funds.
while lock_id == 0
# Lock failed, wait a second and try again.
time.sleep(1)
lock_id = lock_account()
if number_of_attempts() > 10:
handle_error("internal error, please try again")
# Now it's safe to check the balance.
if balance >= amount:
transfer(old_account, new_account, amount, lock_id)
else:
insufficient_balance()
# Don't forget to unlock the account, or there will be trouble later!
errcode = unlock_account(lock_id)
if errcode != 0:
# This should never happen. If it does, it might mean the lock ID 
# is incorrect (how?), but probably means the database is corrupt.
log_serious_error(errcode, lock_id)


It's ugly and error-prone, but it's also a kind of EAFP: instead of 
checking whether a lock is available, and then taking it, you just try 
to acquire a lock, and deal with the consequences of not receiving one 
if it fails. The only difference is that you're manually checking an 
error code rather than catching an exception.

Whatever mechanism is used for EAFP, it is most often shorter, simpler, 
more reliable and safer than LBYL.

So why would anyone ever use LBYL? Well, sometimes it is more convenient 
for quick and dirty scripts, such as using os.path.exists. But more 
importantly, sometimes you need a transaction to apply in full, or not 
at all. You can't do this:

try:
do_this()
do_that()
do_something_else()
except Exception:
do_error()


because if do_this() succeeds and do_that() fails, you might leave your 
data is a seriously inconsistent or broken state. You could do this:


failed = False
save_state()
try:
do_this()
try:
do_that(

Re: [Tutor] recursive problem

2010-09-10 Thread Ewald Horn
On 10 September 2010 13:14, Roelof Wobben  wrote:

>  Hello ,
>
> So my book teach me the wrong principle.
> But can everything programmed on Eafp.
>
> If you dont know if something is a list, a tuple or a string, you can get a
> lot of nested try except think.
>
> Roelof
>

Hi Roelof,

I don't think EAFP is wrong, and neither is LBYL, it all depends on the
circumstances. Python makes it easy to use EAFP, especially compared to
languages like Java or C++. While EAFP is great, it's not always the best
way to proceed. Sometimes you want programs to be very robust and secure,
this is where LBYL comes in - it is quite often used in online transaction
processing and other areas where absolute certainty is more important than
any other consideration.

EAFP tends to use less code and is faster to use, while LBYL principles
makes your program more bulletproof.  For now, I suggest you stick to the
EAFP principles, it's not wrong and it's one of the reasons I like Python so
much - it allows you to focus on solving a particular problem and does not
expect you to jump through a number of hoops to just get something simple
done.

And, before you ask, you can indeed follow LBYL principles in Python if you
want to, but you only have to do it if you really want to, not because the
compiler forces you to.

Consider these principles to be tools in your toolkit, sometimes you need a
hammer, other times a saw, each tool (principle) is suited to a particular
situation. Go ahead and try both, you will find one works better in a given
scenario than the other.

Regards
Ewald
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-10 Thread Roelof Wobben

Hello , 

 

So my book teach me the wrong principle.

But can everything programmed on Eafp.

 

If you dont know if something is a list, a tuple or a string, you can get a lot 
of nested try except think.

 

Roelof


 


Subject: Re: [Tutor] recursive problem
From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 15:32:44 -0500
To: rwob...@hotmail.com


No you misunderstood me. Eafp is a python design principle. lbyl is common in 
older languages. Please reply all in the future so our discussion takes place 
on the list instead of just between us.

Sent from my iPhone

On Sep 9, 2010, at 1:31 PM, Roelof Wobben  wrote:




Oke, 
 
So If I understand you right LBYL is more the python way.
Wierd that the book im following (Thinking like a computer scientist) is more 
EAFP.
 
Roelof

 


Subject: Re: [Tutor] recursive problem
From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 13:24:06 -0500
To: rwob...@hotmail.com


It's easier to ask for forgiveness than permission vs. Look before you leap. An 
example of LBYL would be checking the type of a variable before you use it. 
EAFP would be just using the variable, and if something goes wrong, handle the 
exception. It's a core tenet of python software design and goes hand in hand w/ 
duck typing and other principles.

Sent from my iPhone

On Sep 9, 2010, at 1:16 PM, Roelof Wobben  wrote:





 Sorry. 
 
Im also new to Python and programming.
 
What does EAFP and LBYL mean ?
 
Roelof
 


From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 12:59:46 -0500
To: joel.goldst...@gmail.com
CC: tutor@python.org
Subject: Re: [Tutor] recursive problem


Nope Joel, that's what I meant. Remember EAFP over LBYL! I'm not sure the best 
way to make sure the object is iterable though.

Sent from my iPhone

On Sep 9, 2010, at 11:41 AM, Joel Goldstick  wrote:







On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano  wrote:




On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
>
> wrote:
> > Shouldn't there be a way to do this without type checking? Duck
> > typing!
> >
> > Your post got me thinking.  Maybe better to test if the object can
> > return
> an iter method.  If it throws an error, then look at its value.  If
> it doesn't, then its a list or a tuple


It's not clear what you mean by "return an iter method". Taken
literally, that would imply the object is a function. I think you
mean "*has* an iter method" -- except that's not right either:

>>> [].iter
Traceback (most recent call last):
 File "", line 1, in 
AttributeError: 'list' object has no attribute 'iter'


Perhaps you mean an object which can be passed to iter(), but lots of
objects can do that, not just lists and tuples:

>>> iter("not a list or tuple")

>>> iter({1: None, 2: "a", 4: 5})



I was googling, and found that if an object has an __iter__ method it will 
return it.  If not it will throw an error.  You are right about more than lists 
and tuples being iterable.  But, in this thread, it was brought up that 
checking type may not be pythonic.  If you wanted to use the same code to find 
values in a nested list of any objects, you could dispense with the type 
checking and just see if it is iterable.


I'm new to python.  Am I off base? 



--
Steven D'Aprano



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


-- 
Joel Goldstick



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

___ Tutor maillist - 
Tutor@python.org To unsubscribe or change subscription options: 
http://mail.python.org/mailman/listinfo/tutor   
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Luke Paireepinart
Nope Joel, that's what I meant. Remember EAFP over LBYL! I'm not sure the best 
way to make sure the object is iterable though.

Sent from my iPhone

On Sep 9, 2010, at 11:41 AM, Joel Goldstick  wrote:

> 
> 
> On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano  wrote:
> On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> > On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
> >
> > wrote:
> > > Shouldn't there be a way to do this without type checking? Duck
> > > typing!
> > >
> > > Your post got me thinking.  Maybe better to test if the object can
> > > return
> > an iter method.  If it throws an error, then look at its value.  If
> > it doesn't, then its a list or a tuple
> 
> 
> It's not clear what you mean by "return an iter method". Taken
> literally, that would imply the object is a function. I think you
> mean "*has* an iter method" -- except that's not right either:
> 
> >>> [].iter
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: 'list' object has no attribute 'iter'
> 
> 
> Perhaps you mean an object which can be passed to iter(), but lots of
> objects can do that, not just lists and tuples:
> 
> >>> iter("not a list or tuple")
> 
> >>> iter({1: None, 2: "a", 4: 5})
> 
> 
> 
> I was googling, and found that if an object has an __iter__ method it will 
> return it.  If not it will throw an error.  You are right about more than 
> lists and tuples being iterable.  But, in this thread, it was brought up that 
> checking type may not be pythonic.  If you wanted to use the same code to 
> find values in a nested list of any objects, you could dispense with the type 
> checking and just see if it is iterable.
> 
> I'm new to python.  Am I off base? 
> 
> 
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -- 
> Joel Goldstick
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Joel Goldstick
On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano wrote:

> On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> > On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
> >
> > wrote:
> > > Shouldn't there be a way to do this without type checking? Duck
> > > typing!
> > >
> > > Your post got me thinking.  Maybe better to test if the object can
> > > return
> > an iter method.  If it throws an error, then look at its value.  If
> > it doesn't, then its a list or a tuple
>
>
> It's not clear what you mean by "return an iter method". Taken
> literally, that would imply the object is a function. I think you
> mean "*has* an iter method" -- except that's not right either:
>
> >>> [].iter
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: 'list' object has no attribute 'iter'
>
>
> Perhaps you mean an object which can be passed to iter(), but lots of
> objects can do that, not just lists and tuples:
>
> >>> iter("not a list or tuple")
> 
> >>> iter({1: None, 2: "a", 4: 5})
> 
>
>
> I was googling, and found that if an object has an __iter__ method it will
> return it.  If not it will throw an error.  You are right about more than
> lists and tuples being iterable.  But, in this thread, it was brought up
> that checking type may not be pythonic.  If you wanted to use the same code
> to find values in a nested list of any objects, you could dispense with the
> type checking and just see if it is iterable.
>

I'm new to python.  Am I off base?

>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Steven D'Aprano
On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
>
> wrote:
> > Shouldn't there be a way to do this without type checking? Duck
> > typing!
> >
> > Your post got me thinking.  Maybe better to test if the object can
> > return
> an iter method.  If it throws an error, then look at its value.  If
> it doesn't, then its a list or a tuple


It's not clear what you mean by "return an iter method". Taken 
literally, that would imply the object is a function. I think you 
mean "*has* an iter method" -- except that's not right either:

>>> [].iter
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'iter'


Perhaps you mean an object which can be passed to iter(), but lots of 
objects can do that, not just lists and tuples:

>>> iter("not a list or tuple")

>>> iter({1: None, 2: "a", 4: 5})






-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Francesco Loffredo

On 09/09/2010 17.05, Joel Goldstick wrote:



On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
mailto:rabidpoob...@gmail.com>> wrote:

Shouldn't there be a way to do this without type checking? Duck typing!

Your post got me thinking.  Maybe better to test if the object can
return an iter method.  If it throws an error, then look at its value.
If it doesn't, then its a list or a tuple


... Oh, my ...

I think type checking is simpler. Maybe not that duckly, but...

Francesco

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3121 -  Data di rilascio: 
09/08/10 08:07:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Joel Goldstick
On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
wrote:

> Shouldn't there be a way to do this without type checking? Duck typing!
>
> Your post got me thinking.  Maybe better to test if the object can return
an iter method.  If it throws an error, then look at its value.  If it
doesn't, then its a list or a tuple
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Luke Paireepinart
Shouldn't there be a way to do this without type checking? Duck typing!

Sent from my iPhone

On Sep 9, 2010, at 7:33 AM, Joel Goldstick  wrote:

> 
> 
> On Thu, Sep 9, 2010 at 7:59 AM, Shashwat Anand  
> wrote:
> 
> 
> On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben  wrote:
> 
>  
> From: anand.shash...@gmail.com
> Date: Thu, 9 Sep 2010 15:08:10 +0530
> Subject: Re: [Tutor] recursive problem
> To: rwob...@hotmail.com
> CC: tutor@python.org
> 
> 
> 
> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben  wrote:
> Hello, 
>  
> I have this :
>  
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
> for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>  
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
> 
> What you are trying to do is walk through the list.  If you get a value and 
> not another list, check if it is the value you are counting.  If it is, added 
> it to your count.
> When you are done walking, return  your count.  If you get another list, walk 
> through the list 
> So here is my stab at the code 
>  14   count = 0   
> # set your count to 0
>  15 for element in nested_num_list:   
>   # walk through each element
>  16 if type(element) == type([]):
>  17 count += recursive_count(target, element)  # 
> since its another list start anew and add the count result to what you 
> already have
>  18 elif element == target:   
> # its a value, so check if its YOUR value, and if it is, increment 
> your counter
>  19 count += 1
>  20 #print element, count
>  21 return count  
># must be done.  You get here each time you walk thru a list
>  22 
> 
>  
>  
> Now I get this message :
>  
> UnboundLocalError: local variable 'count' referenced before assignment
> 
> It is because you are doing count = count + 1
> But where is count defined.
>  
>  
> But if I do this :
>  
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
>   count = 0 
>   for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>  
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>  
> The count will always be 0 if a nested list is being found.
>  
> What's the python way to solve this 
> 
> I am not sure what do you want to achieve by this ?
> What is the problem statement ?
>  
> The problem statement is that I must count how many times the target is in 
> the nested_list.
> So I thougt that every nested list the function is called again so this list 
> is also iterated.
> 
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9, 2, 
> 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
> 
> 
> 
> -- 
> ~l0nwlf
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Joel Goldstick
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Joel Goldstick
On Thu, Sep 9, 2010 at 7:59 AM, Shashwat Anand wrote:

>
>
> On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben  wrote:
>
>>
>>
>> --
>> From: anand.shash...@gmail.com
>> Date: Thu, 9 Sep 2010 15:08:10 +0530
>> Subject: Re: [Tutor] recursive problem
>> To: rwob...@hotmail.com
>> CC: tutor@python.org
>>
>>
>>
>> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben wrote:
>>
>> Hello,
>>
>> I have this :
>>
>> def recursive_count(target, nested_num_list):
>> """
>>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>>   4
>>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>>   2
>>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>>   0
>>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>>   6
>> """
>> for element in nested_num_list:
>> if type(element) == type([]):
>>test = recursive_count(target, element)
>> print element, target
>> if element == target :
>>count = count + 1
>> return count
>>
>> if __name__ == "__main__":
>> import doctest
>> doctest.testmod()
>>
>>
What you are trying to do is walk through the list.  If you get a value and
not another list, check if it is the value you are counting.  If it is,
added it to your count.
When you are done walking, return  your count.  If you get another list,
walk through the list

> So here is my stab at the code
>>
>>  14   count =
0
# set your count to 0
 15 for element in
nested_num_list: # walk through each
element
 16 if type(element) == type([]):
 17 count += recursive_count(target, element)  #
since its another list start anew and add the count result to what you
already have
 18 elif element ==
target:   # its a value, so
check if its YOUR value, and if it is, increment your counter
 19 count += 1
 20 #print element, count
 21 return
count #
must be done.  You get here each time you walk thru a list
 22



>
>> Now I get this message :
>>
>> UnboundLocalError: local variable 'count' referenced before assignment
>>
>>
>> It is because you are doing count = count + 1
>> But where is count defined.
>>
>>
>>
>> But if I do this :
>>
>> def recursive_count(target, nested_num_list):
>> """
>>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>>   4
>>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>>   2
>>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>>   0
>>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>>   6
>> """
>>   count = 0
>>   for element in nested_num_list:
>> if type(element) == type([]):
>>test = recursive_count(target, element)
>> print element, target
>> if element == target :
>>count = count + 1
>> return count
>>
>> if __name__ == "__main__":
>> import doctest
>> doctest.testmod()
>>
>> The count will always be 0 if a nested list is being found.
>>
>> What's the python way to solve this
>>
>>
>> I am not sure what do you want to achieve by this ?
>> What is the problem statement ?
>>
>> The problem statement is that I must count how many times the target is in
>> the nested_list.
>> So I thougt that every nested list the function is called again so this
>> list is also iterated.
>>
>
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
> 2, 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
>
>
>
> --
> ~l0nwlf
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Walter Prins
On 9 September 2010 12:59, Shashwat Anand  wrote:

>
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
> 2, 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
>
>
This is fine except that the excercise probably has to do with introducing
recursion and scoping, which is unfortunately defeated by this solution.

Roelof, look at what you do with the result of the recursive call  which you
currently assign to test and otherwise ignore -- you want to add this to
count and/or return it...

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Shashwat Anand
On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben  wrote:

>
>
> --
> From: anand.shash...@gmail.com
> Date: Thu, 9 Sep 2010 15:08:10 +0530
> Subject: Re: [Tutor] recursive problem
> To: rwob...@hotmail.com
> CC: tutor@python.org
>
>
>
> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben  wrote:
>
> Hello,
>
> I have this :
>
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
> for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
>
> Now I get this message :
>
> UnboundLocalError: local variable 'count' referenced before assignment
>
>
> It is because you are doing count = count + 1
> But where is count defined.
>
>
>
> But if I do this :
>
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
>   count = 0
>   for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
> The count will always be 0 if a nested list is being found.
>
> What's the python way to solve this
>
>
> I am not sure what do you want to achieve by this ?
> What is the problem statement ?
>
> The problem statement is that I must count how many times the target is in
> the nested_list.
> So I thougt that every nested list the function is called again so this
> list is also iterated.
>

Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
2, 1,13, 2, 8, 2, 6 ]
Now count for n; flatten.count(n)



-- 
~l0nwlf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Roelof Wobben


 


From: anand.shash...@gmail.com
Date: Thu, 9 Sep 2010 15:08:10 +0530
Subject: Re: [Tutor] recursive problem
To: rwob...@hotmail.com
CC: tutor@python.org




On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben  wrote:


Hello, 
 
I have this :
 
def recursive_count(target, nested_num_list):
"""
  >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
  >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
  >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
  >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6
"""
for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count
 
if __name__ == "__main__":
import doctest
doctest.testmod()
 
 
Now I get this message :
 
UnboundLocalError: local variable 'count' referenced before assignment


It is because you are doing count = count + 1
But where is count defined.
 


 
But if I do this :
 
def recursive_count(target, nested_num_list):
"""
  >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
  >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
  >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
  >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6
"""
  count = 0 
  for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count
 
if __name__ == "__main__":
import doctest
doctest.testmod()
 
The count will always be 0 if a nested list is being found.
 
What's the python way to solve this 


I am not sure what do you want to achieve by this ?
What is the problem statement ?
 
The problem statement is that I must count how many times the target is in the 
nested_list.
So I thougt that every nested list the function is called again so this list is 
also iterated.
 
Roelof
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-09 Thread Shashwat Anand
On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben  wrote:

>  Hello,
>
> I have this :
>
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
> for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
>
> Now I get this message :
>
> UnboundLocalError: local variable 'count' referenced before assignment
>

It is because you are doing count = count + 1
But where is count defined.


>
> But if I do this :
>
> def recursive_count(target, nested_num_list):
> """
>   >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>   4
>   >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>   2
>   >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>   0
>   >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>   6
> """
>   count = 0
>   for element in nested_num_list:
> if type(element) == type([]):
>test = recursive_count(target, element)
> print element, target
> if element == target :
>count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
> The count will always be 0 if a nested list is being found.
>
> What's the python way to solve this
>

I am not sure what do you want to achieve by this ?
What is the problem statement ?


>
> Roelof
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
~l0nwlf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] recursive problem

2010-09-09 Thread Roelof Wobben

Hello, 

 

I have this :

 

def recursive_count(target, nested_num_list):
"""
  >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
  >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
  >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
  >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6
"""
for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count

 

if __name__ == "__main__":
import doctest
doctest.testmod()

 

 

Now I get this message :

 

UnboundLocalError: local variable 'count' referenced before assignment

 

But if I do this :

 

def recursive_count(target, nested_num_list):
"""
  >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
  >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
  >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
  >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6
"""
  count = 0 

  for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count

 

if __name__ == "__main__":
import doctest
doctest.testmod()

 

The count will always be 0 if a nested list is being found.

 

What's the python way to solve this 

 

Roelof

 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor