Re: A desperate lunge for on-topic-ness

2012-10-18 Thread Den
On Wednesday, October 17, 2012 11:06:43 PM UTC-7, Zero Piraeus wrote:
> :
> 
> 
> What are people's preferred strategies for dealing with lines that go
> 
> over 79 characters? A few I can think of off the bat:
> 

I personally just keep typing until my statement is finished.  This is my 
program, not PEP's.

But I have to say I'm amused by the whole question, and others related to PEP8. 
 A quick aside, the width of our roads all go back to the width of a two horse 
rig.  The suggested maximum of 80 characters goes back to teletype machines, 
and IBM cards, and character based terminals

Should that really be the basis for a suggested style now?

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: name of a sorting algorithm

2012-02-14 Thread Den
On Feb 14, 8:22 am, Arnaud Delobelle  wrote:
> On 14 February 2012 15:31, Dennis Lee Bieber  wrote:
>
> > On Tue, 14 Feb 2012 16:01:05 +0100, Jabba Laci 
> > wrote:
>
> >>Could someone please tell me what the following sorting algorithm is called?
>
> >>Let an array contain the elements a_1, a_2, ..., a_N. Then:
>
> >>for i = 1 to N-1:
> >>    for j = i+1 to N:
> >>        if a_j < a_i then swap(a_j, a_i)
>
> >        Off hand... The ancient Bubble-Sort...
>
> >http://en.wikipedia.org/wiki/Bubble_sort
>
> Ahem...
>
> No, it's not Bubble Sort.  Bubble sort only swaps adjacent terms.
>
> I don't know what this sort is called, if it even has a name.  It's a
> kind of Selection Sort, as each pass it looks for the minimum of the
> remaining unsorted items.  But it ruffles the unsorted list each pass,
> seemingly to save using an extra register to store the current minumum
> (there was a time when registers were at a premium).
>
> --
> Arnaud

I disagree.  In a bubble sort, one pointer points to the top element,
while another descents through all the other elements, swapping the
elements at the pointers when necessary.  Then the one pointer moved
down to the next element and the process repeats.  This looks like the
bubble sort to me.  It was one of the first algorithms I had to
program in my first programming class in 1969.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-05 Thread Den
On Jun 5, 7:10 am, Mark R Rivet  wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.

I use wxFormBuilder.  It seems to be most up-to-date and is as easy to
use as any others.  It also covers AUI GUIs.  It produces the class,
but you have to do a little bit of programming to actually see the
GUI.

I used wx-glade for a while.  It was easy to use, and produced ready-
to-run GUIs.  But it's old and not well kept up.  There's some new
work being done on it but it seems to be mostly housekeeping work -
how to best package it, etc.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Programmer font

2011-06-05 Thread Den
As we all know, python  uses underlines and double underlines as
significant characters.  But fonts, including programmers' fonts,
generally design underlines to run together.  This makes it hard to
identify single from double, or double from triple underlines (at
least for me).

I have modified the droid Sans Mono font to provide underlines which
may be distinguished from each other.  (I also augmented the slashed
zero to be more to my liking).   Give it a try.  If you like it,
great.  If not, no big deal.

http://code.google.com/p/droid-sans-mono-py/

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2011-08-24 Thread Den
On Aug 23, 7:46 pm, User  wrote:
> Hello all,
> Does anyone have any good resources for learning Python? I know basic
> Java and basic Python (loops, data types, if-then statements, etc), but
> I want to delve into Python further. If anyone knows of any good books,
> video tutorials, etc it would be greatly appreciated.
> Thanks,
> User

Learning Python, and Programming in Python by Lutz.  They worked for
me.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Detecting Ctrl-Alt-Del in Windows

2011-09-01 Thread Den
Obviously, this is a windows-based question.  I know that Ctrl-Alt-Del
is handled deep inside the OS, and I'm not trying to interrupt that.
But is there some way to detect that a C-A-D has been pressed?

Also, is there a corresponding key-sequence in Mac and Linux?  And how
might one detect those too?

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting Ctrl-Alt-Del in Windows

2011-09-02 Thread Den
On Sep 2, 5:27 am, sjm  wrote:
> On Sep 1, 12:52 pm, Den  wrote:
>
> > Obviously, this is a windows-based question.  I know that Ctrl-Alt-Del
> > is handled deep inside the OS, and I'm not trying to interrupt that.
> > But is there some way to detect that a C-A-D has been pressed?
>
> If you manage to write a program that can detect CTRL-ALT-DEL, please
> report it as a bug in Windows!  CTRL-ALT-DEL is Windows' "secure
> attention sequence" which must only be handled by the OS.
>
> -- Steve

I have already done that, in AutoHotKey ... or at least it used to
work.  AHK can detect when a window opened.  And when CAD was pressed
the ... well, I've forgotten what it was called ... but a window
opened asking if you wanted to open the task manager, or quit or log
off or what.  Then you would know that CAD was pressed.  There was
nothing you could do to stop it, but you could at least detect that it
had been pressed.

That's why I was wondering if there was a similar technique which
could be used in Python.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting Ctrl-Alt-Del in Windows

2011-09-02 Thread Den
On Sep 2, 5:27 am, sjm  wrote:
> On Sep 1, 12:52 pm, Den  wrote:
>
> > Obviously, this is a windows-based question.  I know that Ctrl-Alt-Del
> > is handled deep inside the OS, and I'm not trying to interrupt that.
> > But is there some way to detect that a C-A-D has been pressed?
>
> If you manage to write a program that can detect CTRL-ALT-DEL, please
> report it as a bug in Windows!  CTRL-ALT-DEL is Windows' "secure
> attention sequence" which must only be handled by the OS.
>
> -- Steve

I'm not trying to hook it or stop it, just detect it.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting Ctrl-Alt-Del in Windows

2011-09-02 Thread Den
On Sep 1, 8:52 am, Den  wrote:
> Obviously, this is a windows-based question.  I know that Ctrl-Alt-Del
> is handled deep inside the OS, and I'm not trying to interrupt that.
> But is there some way to detect that a C-A-D has been pressed?
>
> Also, is there a corresponding key-sequence in Mac and Linux?  And how
> might one detect those too?
>
> Den

I've been doing some more thinking on what I want.  This may be a
better explanation.  Is there a way of detecting if my program has
lost "focus" (I'm not sure the correct term)?  For example, if someone
is typing in my program, but some other program takes control (or CAD
has been pressed) I would like simply to log that.  I have no interest
in trying to hijack or interfere with anything, simply log it.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Alternative to raw_input ?

2005-02-11 Thread den
BOOGIEMAN wrote:
On Fri, 11 Feb 2005 16:35:19 +, Simon Brunning wrote:

Err, why?

It looks to ugly this way. I want to press 
any key without ENTER to continue
Did you try this:
import msvcrt
msvcrt.getch()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Return of an old friend

2011-11-28 Thread Den
On Nov 25, 2:13 am, Noah Hall  wrote:
> On Fri, Nov 25, 2011 at 5:08 AM, Matt Joiner  wrote:
> > I haven't heard of you before, but feel like I've missed out on something.
>
> > Do you (or someone else) care to link to some of your more contentious work?
>
> Ignore him, he's a troll with an unjustly inflated ego.

((laugh)) Well, that didn't take long.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pragmatics of the standard is() function

2011-11-28 Thread Den
On Nov 26, 3:01 pm, Steven D'Aprano  wrote:
> On Sat, 26 Nov 2011 22:20:36 +0100, candide wrote:
>>SNIP<<
>
> That is correct. You probably should rarely use `is`. Apart from testing
> for None, use of `is` should be rare.
>
> --
> Steven

With respect, I disagree with advice that the use of a language
construct should be rare.  All constructs should be used
*appropriately*.

While in general a particular use of a Python construct may be rare,
if the programmer is involved deeply with that rare use, then it is
NOT rare to him/her.  Thus, for a particular programmer, use of 'is'
may be quite frequent because the program they're working on requires
knowledge of object identity.

The same goes for global variables, by the way.  While it's easy to
shoot yourself in the foot with global variables, that doesn't lead to
never-use-them.  It leads to use-them-appropriately-and-carefully.

Sorry, you plucked a string of mine.  One does not throw a tool out of
your tool box because it might be dangerous.  Table saws are
incredibly dangerous, but in the hands of a skilled operator can be
competently and safely used to produce beautiful woodwork.  To say
*never* use a table saw because it's dangerous is silly.

Language constructs are put there intentionally.  Advice that they be
used *rarely* or *never* should *never* be given ((chuckle)).  Just
learn what they are, learn how they work, learn what the consequences
of misuse can be (loss of a hand, in the case of a table saw), and use
them confidently when the circumstances make them the best choice of
tool to solve your problem.

To make a long comment short (too late!!) learn the differences
between 'is' and ==, and use them appropriately.  When I was learning
Python, I found the two books by Mark Lutz to be filled with
information of such things as these.

D
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pragmatics of the standard is() function

2011-11-29 Thread Den
On Nov 29, 12:41 am, Steven D'Aprano  wrote:
> On Mon, 28 Nov 2011 11:22:09 -0800, Den wrote:
> > With respect, I disagree with advice that the use of a language
> > construct should be rare.  All constructs should be used
> > *appropriately*.
>
> And if those appropriate conditions are rare, then the use of the
> appropriate construct should also be rare. Since it is rare to need to
> care about identity, use of `is` should be rare too.
>
> This is mostly descriptive statement rather than a prescriptive one: it
> is a fact that use of `is` is much less common than use of ==, and even
> more so if you disregard the obvious case of "x is None".
>
> I am however being a little prescriptive: if somebody thinks they need to
> care about identity, chances are good -- but not certain -- that they're
> mistaken. In code that gives you the choice between writing `is` and ==,
> it is usually, but not often, a bug to write `is`. The proof of this is
> that in actual, existing code, if you swapped == and `is`, most of the
> code would stop working correctly.
>
> On the other hand if you actually do need to care about identity, then go
> for it. I'm not saying that caring about identity should be prohibited,
> only that in practice it is uncommon that you will.
>
> > While in general a particular use of a Python construct may be rare, if
> > the programmer is involved deeply with that rare use, then it is NOT
> > rare to him/her.
>
> Regardless of how common brain surgery might be to a brain surgeon, it is
> rare in general. That's all I'm saying. If you happen to work for a data
> recovery centre, then pulling the disk platter out of a hard disk drive
> might be commonplace to you, nevertheless pulling platters out of disks
> is vanishingly rare: out of tens of thousands of HDDs, perhaps only a few
> dozen will be sent to a recover centre at all.
>
> [...]
>
> > Sorry, you plucked a string of mine.  One does not throw a tool out of
> > your tool box because it might be dangerous.  Table saws are incredibly
> > dangerous, but in the hands of a skilled operator can be competently and
> > safely used to produce beautiful woodwork.  To say *never* use a table
> > saw because it's dangerous is silly.
>
> Fortunately, I didn't say "never".
>
> In the case of `is`, one shouldn't avoid using `is` because it is
> dangerous, but merely because it is the wrong thing to use. In the same
> way, the average programmer will rarely need to use the math.sinh and
> math.cosh functions, not because they are bad, evil, or dangerous, but
> because they are used for specialist purposes that most coders would
> never care about. Hell, most coders rarely use the standard trigonometric
> functions sin and cos, let alone the hyperbolic versions! This is not a
> value judgement.
>
> If I, in a misplaced sense of egalitarianism ("Emancipation for maths
> functions! Right on brothers!") decided to use sinh instead of sin
> because they looked and sounded similar, my code would almost certain be
> buggy. Likewise if I decided to use `is` instead of == because in English
> they have similar meanings, my code would probably be buggy too.
>
> Sorry to belabour the point, but we're in violent agreement here 
>
> --
> Steven

((laugh)) Yes, I believe we are.

D
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Meaning of "monkey"

2010-03-29 Thread Den
On Mar 26, 6:14 am, Luis M. González  wrote:
> Webmonkey, Greasemonkey, monkey-patching, Tracemonkey, Jägermonkey,
> Spidermonkey, Mono (monkey in spanish), codemonkey, etc, etc, etc...
>
> Monkeys everywhere.
> Sorry for the off topic question, but what does "monkey" mean in a
> nerdy-geek context??
>
> Luis

To go even more off topic, I remember Trunk Monkey commercials.

Also, I remember a web site whose intentions was to simulate monkeys
typing Shakespeare.  They had set up a distributed system where you
could contribute your computer to providing random characters, which
they compared to a selected set of Shakespeare's plays.  Just before
the site disappeared (or I lost track of it), they had received
strings representing the first maybe 15 or 20 characters of several
plays.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-01 Thread Den
On Mar 30, 10:56 am, Steve Holden  wrote:
> John Nagle wrote:
> > Chris Rebert wrote:
> >> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone 
> >> wrote:
> >>> Hi, how can I write the popular C/JAVA syntax in Python?
>
> >>> Java example:
> >>>    return (a==b) ? 'Yes' : 'No'
>
> >>> My first idea is:
> >>>    return ('No','Yes')[bool(a==b)]
>
> >>> Is there a more elegant/common python expression for this?
>
> >> Yes, Python has ternary operator-like syntax:
> >> return ('Yes' if a==b else 'No')
>
> >> Note that this requires a recent version of Python.
>
> >     Who let the dogs in?  That's awful syntax.
>
> Yes, that's deliberately awful syntax. Guido designed it that way to
> ensure that people didn't aver-use it, thereby reducing the readability
> of Python applications. Speaking purely personally I hardly ever use it,
> but don't dislike it.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
> Holden Web LLC                http://www.holdenweb.com/
> UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

I've been following this thread for a few days now.  My thoughts are
that, in view of a long known widely used syntax for this operator,
python's syntax seems like change for change sake.  If current
programing paradigm provides that particular trinary operator, why
should python's be different from the previously well known one.

For instance, no reasonable language designer would, now, use post-fix
(I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
(Just as no reasonable car designer would put the accelerator pedal on
the left.)  There are conventions which should span products.  Yes
python has the trinary operator and it's not going to change, but this
seems like a bit of petulance on the part of the designer.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: packaging multiple python scripts as Windows exe file

2010-04-14 Thread Den
On Apr 12, 3:20 pm, Alex Hall  wrote:
> Hi all,
> While my project is still suffering from major import problems, I will
> soon have to try to package it as a Windows executable file. I do not
> want an installer; I want the user to be able to run the program for
> as long as they want, then to quit (by using a command from inside the
> program) and that is it. Nothing to install, no files to copy, no
> registry editing, just start and use it until done.
>
> I know about the popular solutions for this sort of thing, but I read
> that a DLL is required, and that this dll cannot be (legally)
> distributed by myself? A few questions here:
> 1. Did I read this wrong / is this outdated? Please answer 'yes' as
> this will be a real pain to deal with.
>
> 2. If I must have it but can distribute it, where should it go so my
> program can find it?
>
> 3. If the user must download it for legal reasons, instead of me
> giving it to them, can I just have a Python script take care of it and
> put it in the same directory as the program, so the program can find
> it, or do I need to register the dll with the system? If I need to
> register, does this require admin login?
>
> Thanks as always!
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com;http://www.facebook.com/mehgcap

I'm not an expert, but there is a module called ResourcePackage
(http://resourcepackage.sourceforge.net/) which I have used to include
binary files within my python program (I use it for an image file).
It takes the binary file, makes a string out of it, then generates a
module containing that string.  You can then import that module and
access that string.  In particular, I assume you can write that string
out to a binary file and recreate the binary file.

I know this doesn't address how to make a single exe which a user can
run (I'm interested in the replies you get) but it does allow you to
carry your binary files along with your and write them out when and if
you need them.

By the way, I'd be interested to hear if there are any other such
solutions for embedding binary files in a python program.

Hope that helped.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-13 Thread Den
> ... However, the killer reason is: "it's what everybody
> else does.

If this were really true, lists would be 1-based.  I go back to
WATFOR; and Fortran (and I believe Cobol and PL/I, though I'm not
positive about them) were 1-based.  (Now that I think about it, PL/I,
knowing IBM, could probably be set to use either)  Back then, everyone
else was doing 1-based lists.

In my opinion, the reason lists are 0-based started with a lazy
programmer who decided that his own comfort (using 0-based addressing
at the machine level and not having to translate the high-level 1-
based language index into a low-level 0-based index) was paramount
over teaching the language and having it make sense in the real
world.  After all, not even Brian Kernighan thinks books start on page
0.  I'm not singling out C in this case because it is a relatively low-
level language for low-level programmers and 0-based lists make
perfect sense in that context.  But then every compiler/interpreter
programmer after that stopped caring about it.

I smile every time I see the non-nonsensical sentence "The first
thing, therefore, is in thing[0]" in a programming language learning
book or tutorial.  I laugh every time I hear someone defend that as
common sense.  Every three year old watching Sesame Street knows
counting things starts with '1', not '0'.  When you were three and you
counted your blocks, you started with '1', not '0'.  The whole rest of
the world understands that implicitly, even if their counting starts
'1', '2', 'many'.  0-based lists are NOT common sense.  They only make
sense to the programmers of computer languages, and their fanbois.

There may be loads of reasons for it, but don't throw common sense
around as one of them.

Den
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Groups

2018-02-01 Thread Jan van den Broek
On 2018-02-01, superchromix  wrote:
>
> Our own programming discussion newsgroup, located at comp.lang.idl-pvwave, 
>started receiving spam messages several months ago.
>
> Two weeks ago, access to comp.lang.idl-pvwave was blocked by Google Groups.  
>
> When trying to access comp.lang.idl-pvwave, a message is now displayed, 
>stating that the group owner needs to remove the spam, and can then apply 
>to Google in order to have access reinstated.

[Schnipp]

Personally I would see this as an improvement.
-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python developer

2022-09-30 Thread Jan van den Broek
2022-09-29, Mike Dewhirst  schrieb:
> This is an OpenPGP/MIME signed message (RFC 4880 and 3156)

Why?

[Schnipp]
-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python developer

2022-10-01 Thread Jan van den Broek
2022-10-01, Mike Dewhirst  schrieb:

>So the answer to your question is signed email is easy and if it becomes 
>popular it has potential to defeat hackers.

Yes, but I'm reading this as a usenet-message (comp.lang.python), not as 
a mail.
-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python developer

2022-10-03 Thread Jan van den Broek
2022-10-01, orzodk  schrieb:
> Jan van den Broek  writes:
>
>> 2022-10-01, Mike Dewhirst  schrieb:
>>
>>>So the answer to your question is signed email is easy and if it becomes 
>>>popular it has potential to defeat hackers.
>>
>> Yes, but I'm reading this as a usenet-message (comp.lang.python), not as 
>> a mail.
>
> You are reading a mirror of the mailing list:

I was aware of that.

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unsubscribe/can't login

2021-05-05 Thread Jan van den Broek
On 2021-05-05, Peter Otten <__pete...@web.de> wrote:

Perhaps there's something wrong on my side, but I'm
seeing this message twice:

Msg-ID: mailman.145.1620211376.3087.python-l...@python.org
Return-Path: __pete...@web.de

and

Msg-ID: mailman.146.1620211381.3087.python-l...@python.org
Return-Path: python-python-l...@m.gmane-mx.org

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unsubscribe/can't login

2021-05-05 Thread Jan van den Broek
On 2021-05-05, Peter Otten <__pete...@web.de> wrote:
> On 05/05/2021 13:03, Jan van den Broek wrote:
>> On 2021-05-05, Peter Otten <__pete...@web.de> wrote:
>> 
>> Perhaps there's something wrong on my side, but I'm
>> seeing this message twice:

[Schnipp]

> Sorry for the inconvenience.
>
> Does that happen with all my messages? I'm reading the mailing list via 
> news.gmaneio.

I can't tell if this happens with _all_ your messages, but it happened
with this reply.

Message-ID: 
Return-Path: 

and

Message-ID: 
Return-Path: <__pete...@web.de>

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] Annoying message duplication, was Re: Unsubscribe/can't login

2021-05-05 Thread Jan van den Broek
On 2021-05-05, Jim Byrnes  wrote:
> On 5/5/21 9:39 AM, Peter Otten wrote:
>> On 05/05/2021 16:10, Ethan Furman wrote:
>> 
>>> I see your messages twice (occasionally with other posters as well).  
>>> I have no idea how to fix it.?? :(
>> 
>> OK, I'll try another option from Thunderbird's context menu: Followup to 
>> Newsgroup.
>> 
>> Does that appear once or twice?
>> 
>> In theory it should go to the newsgroup only which would mirror it to 
>> the list.
>> 
>
> FWIW, none of the messages in this this thread are dupes for me and I 
> can't remember the last time I saw a dupe from you.

Are you reading this via the mailinglist or Usenet?
-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] Annoying message duplication, was Re: Unsubscribe/can't login

2021-05-05 Thread Jan van den Broek
On 2021-05-05, Peter Otten <__pete...@web.de> wrote:
> On 05/05/2021 16:10, Ethan Furman wrote:
>
>> I see your messages twice (occasionally with other posters as well).?? I 
>> have no idea how to fix it.?? :(
>
> OK, I'll try another option from Thunderbird's context menu: Followup to 
> Newsgroup.
>
> Does that appear once or twice?

Here, once.

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido van Rossum resigns as Python leader

2018-07-14 Thread Jan van den Broek
On 2018-07-13, ElChino  wrote:
>> The important question we should ask ourselves: Do we have a replacement
>> Dutch person to figure out the one obvious way to do things that may not
>> be obvious at first?
>
> Skybuck?! Also Dutch.

We try to deny that.
It'll probably lead to ending every statement in your code with "lol !".

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido van Rossum resigns as Python leader

2018-07-14 Thread Jan van den Broek
On 2018-07-13, Larry Martell  wrote:

[Schnipp]

> And while we're talking about the Dutch, why is the country called
> Holland, but then also The Netherlands, but the people are Dutch?

Be careful here, this is a somewhat delicate matter. Strictly speaking
Holland is part of Nederland (the Netherlands). Nederland is divided in 
twelve provinces[1], Noord- and ZuidHolland are two of them. Calling 
the Netherlands Holland is an guaranteed to annoy people from the 
other then.
Historical speaking, Holland was (along with Zeeland) one of the more
powerfull members in the Republic.

[1] https://nl.wikipedia.org/wiki/Bestand:NederlandseProvinciesLarge.png
-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recursive method in class

2019-09-27 Thread Jan van den Broek
On 2019-09-27, ast  wrote:
> Is it feasible to define a recursive method in a class ?
> (I don't need it, it's just a trial)
>
> Here are failing codes:
>
>
> class Test:
>  def fib(self, n):
>  if n < 2: return n
>  return fib(self, n-2) + fib(self, n-1)
  self.fib(...)

[Schnipp]

-- 
Jan v/d Broek
balgl...@dds.nl
-- 
https://mail.python.org/mailman/listinfo/python-list


__Classes and type tests

2005-10-09 Thread Brian van den Broek
Hi all,

The code below exhibits an attempt to refer to the type of a __Class 
from within a method of that class. I've been unable to figure out how 
to make it work as I want, and would appreciate any insight.

The problem emerged out of a bad design that the good folks on the 
tutor list helped me repair. With that repair, I no longer need nor 
want to do this sort of thing in actual code. But the academic issue 
"How/Can it be done?" still itches.


class _OneUnderBase(object):
  def __init__(self):
  if type(self) == _OneUnderBase:
  print "From _OneUnderBase"
  else:
  print "From subclass",

class __TwoUnderBase(object):
  def __init__(self):
  # What to write in the if type() test to secure same
  # behaviour as _OneUnderBase
  if type(self) == __TwoUnderBase:
  print "From __TwoUnderBase"
  else:
  print "From subclass",

class SubOne(_OneUnderBase):
  def __init__(self):
  super(SubOne, self).__init__()
  print "SubOne"

class SubTwo(__TwoUnderBase):
  def __init__(self):
  super(SubTwo, self).__init__()
  print "SubTwo"

s1 = SubOne()
s2 = SubTwo()


When run, this gives:

 >>>
 From subclass SubOne
Traceback (most recent call last):
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 28, in ?
 s2 = SubTwo()
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 24, in __init__
 super(SubTwo, self).__init__()
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 12, in __init__
 if type(self) == __TwoUnderBase:
NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined
 >>>

So, the _OneUnderBase version works fine. I've been unable to work out 
what to write in the __TwoUnderBase version to make it work the same.

(In case it is not clear, I'm aiming at the output:
 From subclass SubOne
 From subclass SubTwo
)

I *think* I understand how __ name mangling works when making 
references from one module to another. But I cannot work it out 
reference to the class itself from within a __ class.

Should it matter: Python 2.4.2 on Win32.

Thanks,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __Classes and type tests

2005-10-09 Thread Brian van den Broek
Fredrik Lundh said unto the world upon 2005-10-09 17:49:
> Brian van den Broek wrote:
> 
> 
>>But the academic issue "How/Can it be done?" still itches.
> 
> 
> class __TwoUnderBase(object):
>   def __init__(self):
>   if self.__class__.__name__ == "__TwoUnderBase":
>   print "From __TwoUnderBase"
>   else:
>   print "From subclass",
> 
>  

Thanks Fredrik.

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to think like a computer scientist

2005-11-13 Thread Brian van den Broek
john boy said unto the world upon 2005-11-11 22:25:
> Question for the following program: sec 5.5
>  
> def factorial (n):
>if n == 0:
>   return 1
>else:
>   recurse = factorial (n-1)
>   result = n * recurse
>   return result
>  
> How come whenever I state the function with "n" given a value it prints no 
> results in the interpreter for EX:




>  
> So instead I have to give a "print" command to make the result appear in the 
> interpreter 
> for EX:



> Is this correctshould I have to give a print command??


Hey,

I assume you mean when you run it as a script; when I run it as the 
interactive prompt, I get output:

IDLE 1.1.2
 >>> def factorial (n):
if n == 0:
  return 1
 else:
recurse = factorial (n-1)
result = n * recurse
return result

 >>> factorial(3)
6

In general, it would be bad if the interpreter decided to print 
everything you asked it to compute. The function returns the result of 
the factorial(n) call, and it is up to your code to decide what to do 
with it. If the only use is to print it, then

print factorial(3)

might be what you want. But it is also possible you'd want to store 
the result for further computation, and would find the print an 
unwanted 'feature'. So,

important_for_later = factorial(some_num)

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example?????

2005-11-13 Thread Brian van den Broek
john boy said unto the world upon 2005-11-12 19:43:
> OK...I have the following program
>  
> i = 1
> while i <= 6:
> print 2 * i,'   ',
> i = i + 1
> print
>  
> this is supposed to give you a "new" blank line after the program runs 
> instead it just gives:
> 2   4   6   8   10   12
> 
>  
> instead of:
> 2   4   6   8   10   12
>  
> 
>  
> to get the above return I have to type in "print" twice,this can't be 
> right?..ANY SUGGESTIONS?
>  
> i = 1while i <= 6:
> print 2 * i,'   ',
> i = i + 1
> print
> print


IDLE 1.1.2
 >>> def as_excepted():
print "The trailing comma makes the next print be ",
print "on the same line as this one"


 >>> as_excepted()
The trailing comma makes the next print be  on the same line as this one
 >>>


Try putting a string behind the print statement that appears not to be 
doing anything, and you will see that it is. The first print is needed 
to clear out of the looped print's comma.

If you don't like the repetition, you could:


 >>> def one_way():
for i in range(3):
print i,
print '\n'   # Explicitly request newline


 >>> one_way()
0 1 2

 >>>

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-14 Thread Brian van den Broek
Ben Bush said unto the world upon 2005-11-14 05:51:
> I have four lists:
> lisA=[1,2,3,4,5,6,9]
> lisB=[1,6,5]
> lisC=[5,6,3]
> lisD=[11,14,12,15]
> how can I write a function to compare lisB, lisC and lisD with lisA, if they
> share two continuous elements (the order does not matter), then return 1,
> otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so
> these comparison will return 1 but the comparison between lisD and lisA
> return 0.
> --
> Thanks!
> Ben Bush

Hi Ben,

the code below is tested no further than shown. And, I'm no expert -- 
I imagine there are better ways. With luck, I'll learn them in a 
follow-up from someone more skilled :-)

 >>> def list_common_continuity_comp(list1, list2):
 for item in list1:
 if item in list2:
 if item + 1 in list1 and item + 1 in list2:
 return True
 return False

 >>> lisA=[1,2,3,4,5,6,9]
 >>> lisB=[1,6,5]
 >>> lisC=[5,6,3]
 >>> lisD=[11,14,12,15]
 >>> list_common_continuity_comp(lisA, lisB)
True
 >>> list_common_continuity_comp(lisA, lisC)
True
 >>> list_common_continuity_comp(lisA, lisD)
False
 >>> list_common_continuity_comp(lisD, lisA)
False
 >>> list_common_continuity_comp(lisA, lisA)
True
 >>> list_common_continuity_comp(lisB, lisA)
True


That gets you a binary comparison. To make it a polyadic:


 >>> def multi_list_continuity_comp(list_of_lists):
 list1 = list_of_lists[0]
 for other_list in list_of_lists[1:]:
 if not list_common_continuity_comp(list1, other_list):
 return False
 return True

 >>> meta_list1 = [lisA, lisB, lisC, lisD]
 >>> meta_list2 = meta_list1[:-1]
 >>> multi_list_continuity_comp(meta_list1)
False
 >>> multi_list_continuity_comp(meta_list2)
True
 >>>


Some edge cases haven't been handled:

 >>> multi_list_continuity_comp([])

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 multi_list_continuity_comp([])
   File "", line 2, in multi_list_continuity_comp
 list1 = list_of_lists[0]
IndexError: list index out of range
 >>>

but this should get you started.

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-14 Thread Brian van den Broek
Ben Bush said unto the world upon 2005-11-14 23:20:



> 
>  On 11/14/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> 
>>Ben Bush said unto the world upon 2005-11-14 05:51:
>>
>>>I have four lists:
>>>lisA=[1,2,3,4,5,6,9]
>>>lisB=[1,6,5]
>>>lisC=[5,6,3]
>>>lisD=[11,14,12,15]
>>>how can I write a function to compare lisB, lisC and lisD with lisA, if
>>
>>they
>>
>>>share two continuous elements (the order does not matter), then return
>>
>>1,
>>
>>>otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so



>>>>>def list_common_continuity_comp(list1, list2):
>>
>>for item in list1:
>>if item in list2:
>>if item + 1 in list1 and item + 1 in list2:
>>return True
>>return False
>>



> what does the following code mean?
>  if item in list2:
> if item + 1 in list1 and item + 1 in list2:
>


Hey Ben,

first, as expected, the other two answers you received are better. :-)

Sets are much better optimized for things like membership testing than
are lists. I'm not competent to explain why; indeed, I keep
overlooking them myself :-(

Unfortunately, the indents got screwed up along the way. But the part
of my code you asked about was:

 for item in list1:
 if item in list2:
 if item + 1 in list1 and item + 1 in list2:
 return True

In some detail:

Consider each item in list1 in turn. If the item isn't in list2, move
on, as there is no chance of it meeting your test. If the item is in
list2, then it is pointful to check if your test is met. Given that
you wanted consecutive numbers, the 'if item + 1 in list1 and item + 1
in list2' condition checks if both lists (which contain item if we've
gone this far) also contain item + 1. If they do, you wanted the
function to return 1 (I changed it to True as more idiomatic). After
my for loop is a return False which we will only hit if the condition
you wanted to test was never satisfied.

Does that clarify it?

Finally, your response to Alex would have been much more useful if
you'd quoted the error rather than just asserting that you got an
error :-)

Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Brian van den Broek
Shi Mu said unto the world upon 2005-11-15 01:30:
>>Hey Ben,
>>
>>first, as expected, the other two answers you received are better. :-)
>>
>>Sets are much better optimized for things like membership testing than
>>are lists. I'm not competent to explain why; indeed, I keep
>>overlooking them myself :-(



>>
>>Best,
>>
>>Brian vdB
> 
> is it possible to modify the codes to compare the two lists with not
> necessarily consecutive numbers?
> For example,
> lisA=[1,2,5,9]
> lisB=[9,5,0]
> compare A and b will get true because the two lists have 5 and 9
> together though they are indifferent order.
> Best Regards,
> Robert
> 

Sure, but rather than repair a less than best first approach, better 
to do it with sets:

 >>> lisA=[1,2,5,9]
 >>> lisB=[9,5,0]
 >>> lisC=[9,5,0,1]
 >>> def intersection_has_two(sequence1, sequence2):
 set1, set2 = set(sequence1), set(sequence2)
 return len(set1.intersection(set2)) == 2

 >>> intersection_has_two(lisA, lisB)
True
 >>> intersection_has_two(lisA, lisC)
False

Sets make stuff easy. (I have got to remember that :-) The only reason 
to make that a function is the one liner gets a bit long for my taste:

 >>> len(set(lisA).intersection(set(lisB))) == 2
True
 >>>

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Brian van den Broek
Ben Bush said unto the world upon 2005-11-15 01:24:



> 
>  Unfortunately, the indents got screwed up along the way. But the part
> 
>>of my code you asked about was:
>>
>>for item in list1:
>>if item in list2:
>>if item + 1 in list1 and item + 1 in list2:
>>return True
>>
>>In some detail:



>>Does that clarify it?
>>
>>Finally, your response to Alex would have been much more useful if
>>you'd quoted the error rather than just asserting that you got an
>>error :-)
>>
>>Best,
>>
>>Brian vdB

Hi Ben,

first, while there are those on the list/n.g. who differ, the 
majoritarian view is that top posting isn't a good thing. At minimum, 
if someone bothered to correct it, it would be nice if in a further 
follow-up you didn't top-post again :-)

Second, you might find the tutor list really helpful. It is where I 
learned most of what I know, and I still read it more than c.l.p. It 
is very newbie friendly.

As for your question:

 >> Hi Brian,
 >
 > regarding "if item + 1 in list1 and item + 1 in list2:",
 > my understanding is this will check whether the following item in 
each list
 > is the same. How does the code permit the situation that the order 
does not
 > matter?
 > For example, for lisA and lisB, the comparison is true and the two 
lists
 > have 5 and 6 but different order.
 >  lisA=[1,2,3,4,5,6,9]
 > lisB=[1,6,5]
 >  Many Thanks!


There are two distinct issues that might be the source of your 
confusion. I will be explicit about both; pardon if only one applied.

 >>> num_list = [1, 42, 451]
 >>> for item in num_list: print item, type(item)

1 
42 
451 
 >>>

Iterating over a list as I did makes item refer to each list member in 
turn. So, item + 1 doesn't refer to the next item (except by accident 
as it were when two items are sequential ints). Rather, it refers to 
int that results from adding 1 to the int that is item.

You might be thinking of list index notation instead:

 >>> index = 1
 >>> num_list[index], num_list[index + 1]
(42, 451)
 >>>

(General tip: putting a print or two in my original code would have 
cleared that up very quickly.)

So, that cleared up, are you wondering why item + 1 suffices, instead 
of both item + 1 and item - 1?

If so, consider that it the list1 has both n and n - 1 in it and we 
iterate over list1 checking each case, eventually item will refer to n 
- 1. In that case, item + 1 = n and we are covered after all. I did as 
I did in my original code thinking it was probably quicker to have 
only one test and pay the cost that there might be a quicker exit from 
the iteration were I to test both item + 1 and item - 1. f it 
mattered, I'd test for speed. Of course, if speed mattered and I could 
ever remember to use sets :-) I'd follow Alex and Duncan's suggestions 
instead!

If that doesn't clear it up, give yourself a few short lists and run 
test cases having inserted print statements to see what is going on. 
To stop it all from whizzing by too fast, put in

raw_input("Hit enter and I'll keep working")

somewhere in the loops to slow things down.

HTH,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


puzzled about class attribute resolution and mangling

2005-12-09 Thread Brian van den Broek
Hi all,

I've the following code snippet that puzzles me:

class Base(object):
 __v, u = "Base v", "Base u"
 def __init__(self):
 print self.__v, self.u

class Derived(Base):
 __v, u = "Derived v", "Derived u"
 def __init__(self):
 print self.__v, self.u
 super(Derived, self).__init__()

d = Derived()

When run (Python 2.4.2, IDLE 1.1.2), it produces:

 >>>
Derived v Derived u
Base v Derived u
 >>>

What I expected was that all four emitted strings would contain "Derived".

I conclude that there is something about the cluster of concepts at
hand this hobbyist doesn't understand :-)  I suspect that the problem 
is with my understanding of the name mangling mechanism, but then 
again, I'm the confused one.

I'd thought the point of the mangling was to make it sufficiently
difficult for client code to access the mangled name so as to
constitute a strong recommendation to leave the name alone. But, since 
the access is all from within method code, I didn't expect any 
mangling issues here. Since d is a Derived, I expected any method of d 
trying to find d.__v to first check if there is a Derived.__v and only 
then pass to Base.__v. Obviously, that's not what's happening.

So, is this behaviour entirely by design and my surprise entirely the
product of misconception or is there an element of side effect of the
mangling mechanism at issue? Or some other consideration altogether?

Thanks and best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuples use parentheses ()'s instead of something else like <>'s?

2004-12-31 Thread Brian van den Broek
Hi all,
a question about using parenthesis for tuples veered very far off topic 
before I returned from a trip and found the thread. I've a comment on 
the original topic, and then a comment off-topic even for the off-topic 
direction in which the thread ended up :-)

The on-topic:
the use of '(' and ')' for tuples really did jar me. With a background 
in set-theory, I expected tuples to look like <1, 2, 3>. It took a 
little bit to reset my brain.

I am aware that even some set theory material is starting to use rounded 
brackets for tuples. With this I can cope (barely). But, just yesterday, 
I was reading an otherwise fine book on relevance logic marred by its 
use of both angle and round brackets for tuples, with no apparent 
principle other than the coin toss determining which to use when. The 
horror!

The off-topic**2:
Alex Martelli said unto the world upon 2004-12-30 19:09:

Have you heard of Villanova, often named as the birthplace of Italian
civilization?  That's about 15 km away, where I generally go for major
grocery shopping at a hypermarket when I _do_ have a car.

Alex
'Hypermarket' is a new one to me, but seems instantly understandable. It 
also makes me very sad.

Italy isn't my country, but for the past few years I've been lucky 
enough to spend a month or so in the north each year. In the short time 
I've been doing so, I think I've been able to detect the decline of the 
small independent shops and the rampant growth of the american style 
mall, big-box store and mutilplex.

The small store to which you can walk and where you likely know the 
vendor, and even if you don't, run the real risk of having a 
conversation, seems a thing worth trying to preserve. They surely aren't 
as efficient as the north-american model, but one of the nicest things 
about Italian culture IMHO is that it appears to understand that some 
things are at least as important as efficiency.

And it is truly heart-breaking to see the beautiful countryside around 
Italian towns being defaced by large fields of blacktop.

Luddites of the world unite!
Happy New Year to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cookbook 2nd ed Credits (was Re: The Industry choice)

2005-01-04 Thread Brian van den Broek
Alex Martelli said unto the world upon 2005-01-04 11:15:
<[EMAIL PROTECTED]> wrote:

But then I have THREE published recipes!!
Does that mean that I get three free copies of the cookbook ? ;-)

...ti piacerebbe eh...?-)  Sorry, "one each", even though you have
_five_ credits.  For the curious, here's the roster of most credited
contributors (remember, significant comments we merged into other's
recipes also count!-)...:

If you wished to count only _authored_ recipes (but that's a bit
misleading, since in several recipes-as-published there is a merge of
two or three separately submitted and accepted recipes, and here I'm
counting only the first-listed-author per published-recipe...):
 1: 25 u'Luther Blissett'

...but each still gets ONE free copy...!-)
Alex
Since I'm certain Luther won't be claiming his copy ;-) perhaps we could 
auction it off?

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: DOS problem (simple fix??)

2005-01-07 Thread Brian van den Broek
Gavin Bauer said unto the world upon 2005-01-07 15:47:
My DOS window (running in windows ME) closes the second it finishes
running my programs. As you can imagine, this makes it hard to see the

Thank you, and please make all answers simple enough to be understood
by a highschool student and his father :) .
Hi Gavin,
you received some solutions. I have another, and a warning about Paul's.
The warning:
Paul suggested looking at IDLE. You should; it's a big improvement over 
notepad or the console. But, do you plan to make GUI application with 
Tkinter? If so, they will have troubles under IDLE. IDLE itself is a 
Tkinter application, so if it runs another Tkinter app, the poor beast 
gets confused about which Tkniter commands go where. (If that doesn't 
make sense, then you probably aren't yet at a place where it will 
matter. So, don't worry about it now.)

Another popular alternative is SciTe. If you are doing your code in 
notepad or an interactive window, you really do want to look into an 
alternative!

The other solution:
The exact procedure is Windows version specific, but you can change the 
behaviour of .py files when they are double clicked. Here's what I do on 
my Win version (ME), which, sadly for both of us, we share:

1) Open a file explorer window.
2) Pick Tool->Folder Options from the menu.
3) Select the File Types tab.
4) Select the .py file type in the alphabetical list of file types that 
pops up.
5) Click on the Advanced button.
6) Select the Open action.
7) It will start out with something like:

"C:\Python24\python.exe"
Put a -i immediately thereafter. Mine looks like this
"C:\Python24\python.exe" -i "%1" %*
The -i makes .py files when double-clicked within Windows. The rest has 
to do with sending command line parameters, but I'd muff it if I tried 
to say more ;-)

HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Index server

2005-01-14 Thread Marcel van den Dungen
[EMAIL PROTECTED] wrote:
Is there an Index server available in Python? For example:
I have large intranet with several servers and I would like to index
documents like  search engines do. Users then can search for a domument
in ALL intranet servers like I do on Google.
Thanks for answers
L.A.
Take a look at the following URLs:
http://www.methods.co.nz/docindexer/
http://www.divmod.org/Home/Projects/Lupy/index.html
http://www.divmod.org/Home/Projects/Pyndex/index.html
HTH,
-- Marcel
--
http://mail.python.org/mailman/listinfo/python-list


What's so funny? WAS Re: rotor replacement

2005-01-22 Thread Brian van den Broek
Paul Rubin said unto the world upon 2005-01-22 20:16:
"Fredrik Lundh" <[EMAIL PROTECTED]> writes:
You're not making any bloody sense.
oh, I make perfect sense, and I think most people here understand
why I found your little "lecture" so funny.  if you still don't get
it, maybe some- one can explain it to you.

I would appreciate it if someone did.
Hi,
no Python expert, just a hobbyist. But, I think I can take this one on:
Fredrik's contributed a lot to Python. The Standard Library book, 
several well know tools, and, I'd wager a finger, a fair bit of code 
in the standard lib. I don't think the community gives you a name like 
F-bot, but that you know a wee bit about how Python is actually used, 
etc.

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.1 - 2.4 differences

2005-01-24 Thread Brian van den Broek
"BOOGIEMAN" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

I found some e-book about Python 2.1, I want to print it but just to check
first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know 
where
can I download any newer Python related e-book, because there isn't any
published yet in my country. 
Hi,
Dive Into Python is available both as a physical book and at 
. It is reported to be a good intro for 
those with programming experience. I don't and found it quite 
readable, albeit after looking at some gentler books first.

A quick examination of my local copy has a revision date of 
2004-05-20. (There may be a more recent version at the site.) I can't 
seem to find  an indication of Python version covered, but some of the 
interactive prompts have at least the Python 2.3.2 version identifier.

HTH,
Brian vdB

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a tutorial

2005-01-26 Thread Brian van den Broek
Terry Reedy said unto the world upon 2005-01-26 14:08:
Xah the arrogant wrote, among other things,

However, there are several errors in the above that would mislead a Python 
learner.  I advise any such to ignore Xah's writings.

Terry J. Reedy
Hi all,
here's a thought:
There isn't any doubt that these 'tutorials' are generally unwelcome 
and unhelpful. Numerous people have kindly taken the time to flag some 
of the problems. So much so that any competent google of the archives 
would quickly reveal the group consensus on their instructional merit.

I submit that continued corrections and advice of this sort are 
counter-productive. I understand the good intentions behind the 
corrections. (Indeed, my own level of Python-fu is such that it is 
possible that I might have been mislead the 'tutorials' without these 
corrections; I thus appreciate the correctors' efforts.) But, such 
corrections are troll-food and make it unlikely that the 'game' of 
posting such tutorials will soon loose its magical power to amuse the 
OP. They all but ensure that there will be more such 'tutorials' to 
correct.

Could we try to ignore them in the hopes that without the light of 
attention they will wither, meanwhile trusting the many extant reviews 
and google to do their work?

(In case it isn't obvious: none of this is intended as a criticism of 
Terry or any of the others who have been 'fighting the good fight'; I 
just think a change of strategy might be in order.)

Best to all
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: naive doc question

2005-01-29 Thread Brian van den Broek
Gabriel B. said unto the world upon 2005-01-29 19:38:
Is it just me that can't find a full reference in the docs?
I wanted a list of all the methods of dict for example... where can
i find it?
Thanks, and sorry if this question is just dumb, i really can't
find it
It's just you ;-)
Try the Library Reference, section 2.3.8 Mapping Types. (Perhaps 
confusing to a newcomer, but Pythons dicts are, as yet, its only 
standard mapping types, mapping being the general comp sci concept.)

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Brian van den Broek
Grant Edwards said unto the world upon 2005-02-01 12:21:
I'm trying to figure out how to sort a list, and I've run into
a problem that that I have tripped over constantly for years:
where are the methods of basic types documented?  The only
thing I can find on a list's sort() method is in the tutorial
where it states:
   sort()
   Sort the items of the list, in place. 

Doesn't the list method would accept a callable to be used as a
comparison function?  Where is that sort of thing in the
documentation?  I've looking in the library reference, the
language reference, the global module index.
I have figured out I can do 


list.sort.__doc__
'L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1'
Hi,
I'm not positive I understand what you are looking for, but do these 
help?:




Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Basic file operation questions

2005-02-02 Thread Marcel van den Dungen
alex wrote:
Hi,
I am a beginner with python and here is my first question:
How can I read the contents of a file using a loop or something? I open
the file with file=open(filename, 'r') and what to do then? Can I use
something like
for xxx in file:
   
Thanks for help
Alex
take a look at this:
http://www.devshed.com/c/a/Python/File-Management-in-Python/
HTH,
-- Marcel
--
http://mail.python.org/mailman/listinfo/python-list


Re: returning True, False or None

2005-02-04 Thread Brian van den Broek
Alex Martelli said unto the world upon 2005-02-04 13:02:
Steven Bethard <[EMAIL PROTECTED]> wrote:

I have lists containing values that are all either True, False or None,
e.g.:
[True,  None,  None,  False]
[None,  False, False, None ]
[False, True,  True,  True ]
etc.
For a given list:
* If all values are None, the function should return None.
* If at least one value is True, the function should return True.
* Otherwise, the function should return False.
Right now, my code looks like:

This has a light code smell for me though -- can anyone see a simpler
way of writing this?

What about...:
for val in lst:
if val is not None:
return val
return None
or the somewhat fancy/clever:
for val in (x for x in lst if x is not None):
return val
return None
Alex
These don't do what the OP desired.
.>>> test_case = [False, True,  True,  True ]
.>>> def alexs_funct(lst):
.for val in lst:
.if val is not None:
.return val
.return None
>>> alexs_funct(test_case)
False
But, by the 'spec', it ought return True.
Best,
Brian vdB
A mere newbie, quite pleased with himself for finding a problem with 
'bot code -- next scheduled to occur mid 2011 :-)

--
http://mail.python.org/mailman/listinfo/python-list


Re: [noob] Error!

2005-02-04 Thread Brian van den Broek
administrata said unto the world upon 2005-02-04 17:59:
I'm programming Car Salesman Program.
It's been "3 days" learning python...
But, i got problem
Write a Car Salesman program where the user enters the base price of a
car. The program should add on a bunch of extra fees such as tax,
license, dealer prep, and destination charge. Make tax and license a
percent of the base price. The other fees should be set values.
Display the actual price of the car once all the extras are applied.
>
print "CAR SALESMAN PROGRAM"
print "\nEnter data."
base_price = int(raw_input("Base Price: "))
tax = int(raw_input("/nTax: "))
license1 = int(raw_input("License: "))
dealer = 30
charge = 5
print "Dealer Prep: ", dealer
print "Destination Charge: ", charge
actual_price = (((base_price * tax / 100) + license1 / 100) + dealer +
change
print "\n\nActual price: ", actual_price
raw_input("")
error occurs, i think the problem is in actual_price. but,
I don't know how to comebine percentage and raw_input.
help me...
thx 4 reading... :)
Hi,
a couple of general tips for seeking help:
1) "error occurs" isn't helpful. What's the error? How do you know? Is 
it that you don't get the expected output? Then show what you get and 
say what you expected. Is it that you get a traceback giving detailed 
and helpful information to track down the error? Then include those 
details in your post. (They might not make sense to you, but they will 
help helpers help you.)

2) This smells like a homework problem. If it is, say so. That way, no 
one will think you are trying to get someone to do your homework for 
you, and will be much more receptive to request for a push in the 
right direction.

Looking at the line:
actual_price = (((base_price * tax / 100) + license1 / 100) + dealer + 
change

I see you've 3 '('s, but only 2 ')'s.
Also, because of point (1), I cannot know if this is relevant to your 
sense that there is an error, but in:

(base_price * tax / 100)
you might try changing 100 to 100.0. Run these through the interpreter:
1 / 10
1 / 10.0
and consult the FAQ on www.python.org for an explanation of the 
difference.

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


broke IDLE while defining a key-binding scheme

2005-02-04 Thread Brian van den Broek
Hi all,
IDLE refuses to launch, and I believe it is because I attempted to 
define a custom key-binding that it doesn't like.

I was recently defining a custom keybinding in IDLE 1.1 under Python 
2.4 on WinMe. (I was using the simpler of the two binding definition 
interfaces.) When done, I hit the buttons for 'OK' (or however it is 
labelled -- I cannot currently check), but the definition dialog 
remained open. After several tries, I hit cancel, and IDLE terminated. 
(Whereas I expected the definition interface to close and return my to 
my unsaved :-( session.)

Afterwards, IDLE refused to launch. I tried various things, including 
reboot and eventually tried to run idle.pyw (the target of various 
shortcuts, etc.) by clicking on it. Nothing. Ran idle.py instead. The 
DOS-console this brings up displays:

Traceback (most recent call last):
  File "C:\Python24\Lib\idlelib\idle.py", line 21, in ?
idlelib.PyShell.main()
  File "C:\PYTHON24\lib\idlelib\PyShell.py", line 1355, in main
if not flist.open_shell():
  File "C:\PYTHON24\lib\idlelib\PyShell.py", line 275, in open_shell
self.pyshell = PyShell(self)
  File "C:\PYTHON24\lib\idlelib\PyShell.py", line 793, in __init__
OutputWindow.__init__(self, flist, None, None)
  File "C:\PYTHON24\lib\idlelib\OutputWindow.py", line 16, in __init__
EditorWindow.__init__(self, *args)
  File "C:\PYTHON24\lib\idlelib\EditorWindow.py", line 108, in __init__
self.apply_bindings()
  File "C:\PYTHON24\lib\idlelib\EditorWindow.py", line 774, in 
apply_bindings
text.event_add(event, *keylist)
  File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1299, in event_add
self.tk.call(args)
_tkinter.TclError: bad event type or keysym "tab"
>>>

I read through the various bits of code pointed at in the traceback. 
But, I'm a Python hobbyist, and have barely gone further than 'Hello 
World' with Tkinter. So, I don't know what to do with the information 
in the traceback.

I've looked at a number of 'IDLE won't start threads' that google 
knows about, but didn't see anything I recognized as useful. 
(Admittedly, I didn't read every single google hit :-)

Further, the last line of the traceback makes me think mine might be a 
somewhat unusual case. The keybinding I was defining when the 
excrement hit the air-conditioning was to make Shift + TAB perform a 
dedent on a region.

I did a search for files names *.p* (STAR.pSTAR for those whose 
mail-readers will take the wildcards as mark-up) modified today, 
hoping to track down the line defining the keybinding and remove it, 
but came up empty.

So, I'm at the end of what I can usefully do by way of diagnosis and 
repair.

Suggestions? (Anything gratefully received, but I favour being taught 
to fish over being fed merely for today.)

Thanks and best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: returning True, False or None

2005-02-04 Thread Brian van den Broek
Fahri Basegmez said unto the world upon 2005-02-04 23:14:
"Mick Krippendorf" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Fahri Basegmez wrote:
reduce(lambda x, y: x or y, lst)
This doesn't solve the OPs problem since

reduce(lambda x, y: x or y, [False, None])
returns None instead of False.
Mick.

You are right.
I tested None or False and it worked. I assumed order did not matter for or 
operator.

None or False returns False
False or None returns None
You know what they say about assumptions. Live and learn.
Fahri
Hi Fahri,
I don't have a reference at hand, but you might want to check the 
docs' index or do a google for short circuit python or something similar.

or works by evaluating the first value and returning it if it 
evaluates to True. Otherwise it returns the second.
>>> 0 or 42
42
>>>

Likewsie, and returns the first if it evaluates to False, otherwise it 
returns the second.
>>> [] and 42
[]
>>>

The idea is that the evaluation breaks out as soon as it has seen 
enough to determine the result. Hence, short circuit. And, instead of 
returning a Boolean, it returns the actual object flanking the 
operator. Hence, the behaviour observed.

HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-05 Thread Brian van den Broek
Steven Bethard said unto the world upon 2005-02-05 14:05:
Nick Coghlan wrote:
Steven Bethard wrote:
Yes -- help me rally behind my generic object PEP which proposes a 
Bunch type (probably to be renamed) for the Python standard lib. =)

Did you see the suggestion of 'namespace' as a name?

Yup, it's in the current PEP draft.  See the "Open Issues" section:
PEP: XXX
Title: Generic Object Data Type
Version: $Revision: 1.0 $
Last-Modified: $Date: 2004/11/29 16:00:00 $
Author: Steven Bethard <[EMAIL PROTECTED]>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 29-Nov-2004
Python-Version: 2.5
Post-History: 29-Nov-2004

Open Issues
===
What should the type be named?  Some suggestions include 'Bunch',
'Record', 'Struct' and 'Namespace'.
A quick check of the google groups archive didn't lead me to believe 
that I'm repeating old suggestions, so: how about 'Bag'?

It's has the small virtue of being short and the great virtue of 
employing a good metaphor, I think. A (loose enough) bag takes 
whatever shape you impose on it by the things that you stick into it. 
If I understand the PEP draft aright, the idea is quite similar -- a 
python object with no internal structure other than that imposed by 
what the programmer decides to put into it.

(I'm just a hobbyist, so if this suggestion clashes with some well 
established use of 'Bag' in CS terminology, well, never mind.)

Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-05 Thread Brian van den Broek
Carlos Ribeiro said unto the world upon 2005-02-05 16:35:
On Sat, 05 Feb 2005 15:59:00 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
(I'm just a hobbyist, so if this suggestion clashes with some well
established use of 'Bag' in CS terminology, well, never mind.)

There's already a well know know use for the 'bag' name, including a
recipe in Python. A bag is an arbitrary collection of objects. It's
similar to a set. The cookbook code is at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174
OK then, never mind ;-)
Thanks for the link. Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt)

2005-02-05 Thread Brian van den Broek
Daniel Bickett said unto the world upon 2005-02-05 19:46:
I was reading the "Pickling and inheritance are making me hurt"
thread, and the latest suggestion (as of this posting) was to do with
the __setstate__ and __getstate__ methods. They caught my attention
because I hadn't encountered them before, and it reminded me that in
the past I've never been able to very good, definitive documentation
on newstyle classes. Googling for it gives little python tutorials on
various sites, and even searching this newsgroup returns very specific
questions, as a rule.
Alas, the question: Does there exist a page that enumerates all of the
features of the newstyle classes, and explains what they all do? If
so, can anyone provide me with such a link?
Thanks :-)
Hi Daniel,
it doesn't yet answer the "definitive" part, but
 is worth a look.
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: A tool for Python - request for some advice

2005-06-21 Thread Brian van den Broek
TPJ said unto the world upon 21/06/2005 02:00:
> First I have to admit that my English isn't good enough. I'm still
> studying and sometimes I just can't express what I want to express.


I've graded essays in Philosophy at my university that were written by 
native speakers of English yet were substantially less clear and well 
written than your post. I don't think you will need to lead with an 
apology for your language skills in the future :-)


> A few weeks ago I've written 'Python Builder' - a bash script that
> allows anyone to download, compile (with flags given by user) and
> install Python and some external modules (e.g. wxPython, PyGTK,



> kind. My need is very special - I want to have Python, it's modules and
> sometimes documentation installed in particular place; usually
> somewhere in my home directory. My script installs some additional



> I've written this script in bash, because I thought it would be better
> to have a script which would run in environment without Python (it all
> was about installing Python anyway!). I used bash, dialog, wget... And
> now someone suggested, that I shuld use Python. That using Python would
> lead to clearer and - probably - smaller code. (I have to admit it - my
> code in bash is just messy.)
> 
> And now I'm considering this idea. Python is already present on
> (almost?) every distribution today, so why worry about it's presence?



> But, on the other hand, I'm thinking that writing in bash is more
> universal solution. I mean that requirements to run bash scripts are
> lower than requirements to run Python scripts. Could this requirements
> be decisive for some users (or is it only my imagination)? Sometimes
> users just have no access to Python (e.g. LFS, some stages of Gentoo,
> some rescue and specialized distros).



> Well, what do you think?

I'm not a sophisticated programmer (I wouldn't know a bash script if 
it bit me).

So, to make sure I've understood (the issue is my level of knowledge, 
not your level of English): you want to provide a specialized install 
script for Python (3rd party modules, non-standard locations, etc.) 
You started in bash to deal with minority cases without an extant 
Python install. But clearly, there will be a Python install by the 
time your bash script is done, or something will have gone very wrong.

That suggests implementing the custom installation work in Python, and 
having a bash script that will

1) determine if there is an existing Python install,
2) if there is not, install Python in the standard way,
3) using the now guaranteed to be there installation of Python, run 
your Python script that does all of your custom installation, and
4) if step (2) added a Python installation other than the one added by 
step (3), perhaps remove it.

Am I missing some reason why that wouldn't be a satisfactory option? 
(This is entirely possible :-)

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create our own python source repository

2005-06-21 Thread Brian van den Broek
Michele Simionato said unto the world upon 21/06/2005 07:58:
> qwwee:
> 
>>for a certain argument I'd prefer an application fully
>>explained (also if not covering all the features) to a more general
>>tutorial with only brief and unrelated code snippets.
>>Unfortunately, that's not the way things are normally done, because it
>>is much harder to build a useful application and fully comment it
> 
> 
> A part the Cookbook, I know of at least two Python books taking the
> approach you describe:
> 
> 1. Dive into Python (Pilgrim)
> 2. Programming Python (Lutz)
> 
> Dive into Python is free (and even translated in Italian on
> www.python.it, IIRC)
> 
>   Michele Simionato
> 

Not free, but:

Practical Python, published by the same press as the Pilgrim, steps 
through incremental approaches to large (by book standards) 
applications. From the author's site:

"Hetland devotes the second half of the book to project development, 
taking great care to choose a series of ten increasingly complex 
applications that are of timely and wide-ranging interest to 
burgeoning and expert developers alike. Project focus includes 
automated document conversion, newsgroup administration, graphical PDF 
document generation, remote document maintenance, the creation of a 
peer-to-peer system with XML-RPC, database integration, and GUI and 
game development.
"
http://hetland.org/writing/practical-python/

best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does one write a function that increments a number?

2005-06-24 Thread Brian van den Broek
[EMAIL PROTECTED] said unto the world upon 25/06/2005 01:41:
> Wait... so this means it is impossible to write a function that
> increments an integer without turning the integer into a list?
> 

Well, one of these options will probably suit:

 >>> def increment_counter(data):
... data += 1
... return data
...
 >>> counter = 0
 >>> counter = increment_counter(counter)
 >>> counter
1

Or, if you only care about one counter, don't like the 
return/assignment form, and don't mind all the cool kids frowning on 
the use of global:


 >>> counter = 0
 >>> def increment_counter():
... global counter
... counter += 1
... 
 >>> counter
0
 >>> increment_counter()
 >>> counter
1
 >>>


Nicest might be using a class, where you keep a clean namespace, and 
don't have the return/assignment form:

 >>> class My_class(object):
... def __init__(self):
... self.counter = 0
... def increment_counter(self):
... self.counter += 1
... 
 >>> my_object = My_class()
 >>> my_object.counter
0
 >>> my_object.increment_counter()
 >>> my_object.counter
1
 >>>

This also lets you have multiple independent counters:

 >>> my_other_object = My_class()
 >>> my_other_object.counter
0
 >>> my_other_object.increment_counter()
 >>> my_other_object.increment_counter()
 >>> my_other_object.counter
2
 >>> my_object.counter
1
 >>>

Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Excellent Site for Developers

2005-06-25 Thread Brian van den Broek
Brian said unto the world upon 25/06/2005 10:50:
> Do Re Mi chel La Si Do wrote:
> 
>>rather... super troll
> 
> 
> 100% Agreed.
> 
> Can anyone say, "This looks like spam... Feels like spam... and is about 
> as useful here in the Python forums as spam -- therfore my conclusion is 
> that his VB message probably IS SPAM."  :-D
> 
> Brian
> ---

What would settle it is finding out if it floats :-)

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [offtopic] Re: Set of Dictionary

2005-06-26 Thread Brian van den Broek
James Dennett said unto the world upon 26/06/2005 03:51:
> Steven D'Aprano wrote:
> 
> 
>>On Thu, 16 Jun 2005 21:21:50 +0300, Konstantin Veretennicov wrote:
>>
>>
>>
>>>On 6/16/05, Vibha Tripathi <[EMAIL PROTECTED]> wrote:
>>>
>>>
I need sets as sets in mathematics:
>>>
>>>That's tough. First of all, mathematical sets can be infinite. It's
>>>just too much memory :)
>>>Software implementations can't fully match mathematical abstractions.
>>
>>
>>:-)
>>
>>But lists can be as long as you like, if you have enough memory. 
> 
> 
> But you never have enough memory to store, for example,
> a list of all the prime integers (not using a regular list,
> anyway).


An even better example is the set of reals in the interval (0, 1). 
Even an idealized Turing machine with (countably) infinite memory will 
choke on that :-)




>>Standard Set Theory disallows various constructions, otherwise you get
>>paradoxes.
>>
>>For example, Russell's Paradox: the set S of all sets that are not an
>>element of themselves. Then S should be a set. If S is an element of
>>itself, then it belongs in set S. But if it is in set S, then it is an
>>element of itself and it is not an element of S. Contradiction.
>>
>>The price mathematicians pay to avoid paradoxes like that is that some
>>sets do not exist. For instance, there exists no universal set (the set
>>of all sets), no set of all cardinal numbers, etc.
>>
>>So even in mathematics, it is not true that sets can contain anything.
> 
> 
> See "Set Theory With a Universal Set" by T. Forster, which covers
> some set theories in which there *is* a set of all things, and
> in which Russell's paradox is avoided in other ways (such as by
> restricting the comprehension axioms).
> 
> (Sorry for drifting offtopic, I happen to find non-standard
> set theories interesting and thought that some others here
> might too.)
> 
> -- James


So do I :-)

Do you know of non-well-founded set theory (non-standard set theory 
which allows sets A, such that A is in A)? Not really on point for any 
of the above, but being on topic is in the rear view mirror, anyway :-)




Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which kid's beginners programming - Python or Forth?

2005-06-27 Thread Brian van den Broek
BORT said unto the world upon 27/06/2005 23:16:
> Please forgive me if this is TOO newbie-ish.
> 
> I am toying with the idea of teaching my ten year old a little about
> programming.  I started my search with something like "best FREE
> programming language for kids."  After MUCH clicking and high-level
> scanning, I am looking at Python and Forth.  Both have advocates that
> say each is a great approach to learning computers.



> [NOTE: This is not a troll.  I'm geting ready to bark up a tree and I
> prefer to avoid the wrong one. I am cross-posting.]
> 
> Thanks


Hi,

I don't know a thing about Forth. I'm a hobbyist programmer with 
enough Python , and a "tourist's" level of a few other languages. So, 
no pro here :-) Qualifying done:

A great thing about Python is the community. Roy Smith's stats 
comparing mailing list activity is useful data. I would also add that 
with the leading and closing bits of your post, it seems like perhaps 
you've seen an ugly flame or two in the past, no? Well, this is a very 
friendly place by 'net standards. One can get flamed in 
comp.lang.python, but you have to work at it. Hard.

Another good community resource would be the Tutor mailing list -- 
there are a core group of posters who are very good at explaining 
things in a patient and novice-friendly way (and a number of 
intermediate folks like myself who sometimes ask, sometimes answer): 
.

A useful (and free) book aimed at high school students is How to Think 
Like a Computer Scientist: Learning with Python 
. Though an adult when I came 
to Python, I found it useful while first starting and a bit 
intimidated by the prospect. It quickly got me to a place where 
reading "grown up" books like Learning Python was easy enough.

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to compress a folder and all of its sub directories and files into a zip file?

2005-06-28 Thread Brian van den Broek
could ildg said unto the world upon 28/06/2005 03:29:
> but the file is just stored,
> and not compressed.
> 
> On 6/28/05, could ildg <[EMAIL PROTECTED]> wrote:
> 
>>Thank you,
>>it works~~
>>
>>On 6/29/05, Peter Szinek <[EMAIL PROTECTED]> wrote:
>>
>>>Hi,
>>>
>>>What about this:
>>>
>>>import os,zipfile
>>>from os.path import join
>>>
>>>
>>>zip = zipfile.ZipFile("myzipfile.zip", 'w')
>>>for root, dirs, files in os.walk('.'):
>>> for fileName in files:
>>> zip.write(join(root,fileName))
>>>zip.close()
>>>
>>>Maybe it zips also the myzipfile.zip ;-)
>>>Probably this is not needed, so an additional test (something like
>>>fileName != 'myfile.zip' would be needed.
>>>
>>>HTH,
>>>Peter
>>>
>>>could ildg wrote:
>>>
I want to compress a folder and all of its sub files including empty folders
into a zip file. what's the pythonic way to do this?

Thanks in advance.
>>>
>>>

This thread got me to read the relevant docs:

7.18.1 ZipFile Objects
"class ZipFile( file[, mode[, compression]])
 Open a ZIP file, where file can be either a path to a file (a 
string) or a file-like object. The mode parameter should be 'r' to 
read an existing file, 'w' to truncate and write a new file, or 'a' to 
append to an existing file. For mode is 'a' and file refers to an 
existing ZIP file, then additional files are added to it. If file does 
not refer to a ZIP file, then a new ZIP archive is appended to the 
file. This is meant for adding a ZIP archive to another file, such as 
python.exe. Using

cat myzip.zip >> python.exe

 also works, and at least WinZip can read such files. compression 
is the ZIP compression method to use when writing the archive, and 
should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause 
RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib 
module is not available, RuntimeError is also raised. The default is 
ZIP_STORED."
http://docs.python.org/lib/zipfile-objects.html

So, it would appear that compression requires a 3rd party module, not 
included in Python (and not present on my Windows box).

I'm presently filing a bug suggesting this be made a touch more 
explicit in the zlib docs.

Best to all,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to compress a folder and all of its sub directories and filesinto a zip file?

2005-06-28 Thread Brian van den Broek
Fredrik Lundh said unto the world upon 28/06/2005 08:04:
> Brian van den Broek wrote:
> 
> 
>>So, it would appear that compression requires a 3rd party module, not
>>included in Python (and not present on my Windows box).
> 
> 
> where did you get your Windows Python?  afaik, the zlib module has been
> included in all major Python binary distributions since 1.5.2 or so...
> 
>  

This is embarrassing :-[

I felt quite certain that I'd correctly typed 'import zlib' and 
received an import error. I'm going to have to plead a bad case of 3am 
goggles.

Off to retract a spurious bug I filed ...

Thanks Fredrik.

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Explain My Problem

2005-06-29 Thread Brian van den Broek
[EMAIL PROTECTED] said unto the world upon 29/06/2005 03:11:
> Code:
> 
> #The Guess My Number Game
> 
> import random
> num = ""
> guess = ""
> counter = 7
> num = random.randrange(1, 100)
> print "I'm thinking of a whole number from 1 to 100."
> print "You have ", counter, " chances left to guess the number."
> print
> guess = int(raw_input("Your guess is: "))
> while counter != 0:
> if guess == num:
> print "You guessed the number, ", num, " in ", counter-6, "
> guesses!"
> elif guess > num:
> counter = counter - 1
> print
> print "The number is less than your guess."
> print "You have ", counter, " chances left to guess the
> number."
> guess = int(raw_input("Your guess is: "))
> else:
> counter = counter - 1
> print
> print "The number is greater than your guess."
> print "You have", counter, " chances left to guess the number."
> guess = (raw_input("Your guess is "))
> if counter == 0:
> print "You idiot, my number was", num,"!"
> print "YOU LOSE!"
> raw_input("Hit the enter key to exit.")
> 
> 
> Two things wrong happen:
> - Dialogue switches from saying "number is greater" to "number is
> less", regardless of guess
> - Lets user guess when user has no more guesses left in "counter"
> variable.
> 
> Please explain to me what's wrong with my program.
> 

Well, you have some logic problems, and they are harder to see because 
of some structural problems.

Notice that in your elif and else branches you repeat logic? Or 
rather, almost repeat logic :-) (You left of the conversion to int on 
one of the calls to raw_input.)

You also had the problem that if the user was right, they'd be told so 
quite a few times ;-)

And, you weren't keeping track of the guesses properly.

Compare yours with the code below. I've moved things around, 
eliminated the duplication (and near duplication), removed the 
pointless initial assignments to num and guess, closed the infinite 
loop, and built the strings differently.

import random

counter = 7
num = random.randrange(1, 100)

print "I'm thinking of a whole number from 1 to 100."

while counter != 0:
 print "You have %s chances left to guess the number." %counter
 guess = int(raw_input("Your guess is: "))
 counter = counter - 1

 if guess == num:
 print "You guessed the number, %s in %s guesses!" %(num, 
7-counter)
 break # else it will print success msg forever

 elif guess > num:
 print "\nThe number is less than your guess."

 else:
 print "\nThe number is greater than your guess."

if counter == 0:
 print "You idiot, my number was %s!" %num
 print "YOU LOSE!"
 raw_input("Hit the enter key to exit.")


This still assumes a co-operative user. (Try entering "one" and see 
what happens.) "1 chances" looks goofy, too. You might want to think 
about fixing that.

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I have a question.

2005-06-30 Thread Brian van den Broek
Nathan Pinno said unto the world upon 30/06/2005 11:22:
> 
>   Hi all,
> 
>   Does Python have a random function? If so, can you show me an example
> using it?
> 
>   Thanks,
>   Nathan Pinno
>   http://www.npinnowebsite.ca/

 >>> import random
 >>> print "It took %s seconds to find the module named random by 
looking at the docs" %random.random()
It took 0.31385101929 seconds to find the module named random by 
looking at the docs
 >>>


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programmers Contest: Fit pictures on a page

2005-07-01 Thread Brian van den Broek
Peter Hansen said unto the world upon 01/07/2005 11:47:
> Dan Sommers wrote:
> 
>>Peter Hansen <[EMAIL PROTECTED]> wrote:
>>
>>>This problem is well suited to the abilities of genetic algorithms,
>>>and this would probably be an excellent way to learn more about them,
>>>even if you don't get the best solution.
>>
>>There's some sort of irony or something in there about not writing the
>>best genetic algorithm, but I can't quite put my finger on it.
> 
> 
> Maybe your irony sensor is getting muddled over the fact that genetic 
> algorithms generally *don't* find the best solutions, just relatively 
> good ones.  They aren't an exhaustive search, they're basically a random 
> search with some features thought to focus the search on more fruitful 
> parts of the solution space, thus optimizing it.  Unless *my* irony 
> processors are malfunctioning, I don't think there's anything ironic 
> about this.  (If anything it looks like the exact opposite of irony, to me.)
> 
> -Peter

Well, I found it ironic, but only when you add that the genetic 
algorithm approach came up in the context of a "best fit" problem. 
Survival of the fittest indeed :-)

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programmers Contest: Fit pictures on a page

2005-07-01 Thread Brian van den Broek
Robert Kern said unto the world upon 01/07/2005 17:24:
> Brian van den Broek wrote:
> 
> 
>>Well, I found it ironic, but only when you add that the genetic 
>>algorithm approach came up in the context of a "best fit" problem. 
>>Survival of the fittest indeed :-)
> 
> 
> Optimization codes don't always succeed. What's the irony?
> 

Well, the punning on 'fit' (fittest in the sense of "most suitable, or 
best adapted", appropriate to Darwinian theory vs. fit in the sense of 
"to be of the right measure or proper shape and size for") amused me.

There is at least shades of irony in that the best fit in the 
Darwinian sense appropriate to genetic algorithms needn't be the best 
fit in the sense of proper size and shape. So, in suitable 
circumstances, the meaning of "best fit" in one sense being the 
opposite of what was intended in the other. (As in, my sense that it 
was ironic didn't reside solely in the genetic algorithm's possible 
failure to find the optimal solution, but how the semantic ambiguity 
of fit plugs into that in the context of the original problem.) I'd 
call that at least semi-irony.

(Yes, I get that the best fit for both evolutionary theory and the 
genetic algorithm isn't the absolutely best adapted, but best adapted 
as measured relative to the contrast class of available 
alternatives--a local maximum if you like.)

All in all, I wish I'd not hit send in the first place. This is 
perilously close to sending me into fits ;-)

Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bad Math

2005-07-01 Thread Brian van den Broek
Patrick Rutkowski said unto the world upon 01/07/2005 23:56:
> I started reading a python book today, one example was:
> 
> 
4 / (2.0 + 3)
> 
> 0.8
> 
> My input/output was:
> 
> 
4 (2.0 + 3)
> 
> 0.80004
> 
> Something smells fishy here... whats up?
> 
> --python 2.4.1




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie question from Nathan.

2005-07-01 Thread Brian van den Broek
Nathan Pinno said unto the world upon 02/07/2005 02:25:
> 
>   Hi all.
> 
>   How do I make the computer generate 4 random numbers for the guess? I want
> to know because I'm writing a computer program in Python like the game
> MasterMind.
> 
>   Thanks.
> 
>   -- 
>   Nathan Pinno
>   http://www.npinnowebsite.ca/

Hi Nathan,

do you know how to make a program doing anything 4 times? If so, do 
that :-)

Here's one way:

 >>> import random
 >>> def get_master_mind_guess():
... guess = []
... for i in range(4):
... guess.append(random.random())
... return guess
...
 >>> get_master_mind_guess()
[0.21236215888513332, 0.096166729147619479, 0.037667620585694728, 
0.77529759474635485]
 >>>

I doubt you need numbers between 0 and 1, but adjust to suit.

I'd also suggest that you might find the Tutor list of real help. 
. Nothing wrong with 
not knowing how to do stuff like this -- few were born knowing, after 
all -- but the Tutor list specializes in answering in a way targeted 
to beginners. It's where I learned much of what I know.

Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bad Math

2005-07-02 Thread Brian van den Broek
Patrick Rutkowski said unto the world upon 02/07/2005 09:25:
> On 7/2/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> 
>>Patrick Rutkowski said unto the world upon 02/07/2005 00:12:
>>
>>>That's... annoying, to say the least. And my number 4/5 was a rational
>>>number too; I can understand how when doing 1/3 things can get funky.
>>>Really though... 4/5 = 0.8 right on the nose, whats up?
>>>
>>>I read that 
>>>http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate
>>>I'd like to find out more, is there anyway for this issue to be
>>>circumvented? That "is within a reasonable limit check" seams like way
>>>too much just to get a proper result from something simple like 4/5.
>>>
>>>
>>
>>Hi Patrick,
>>
>>my quick piece of code became something I thought might someday be
>>useful. So, I expanded it with tests, and sanity checks, etc. It
>>doesnt' yet have the full functionality I'd like (see docstrings), but
>>I won't get to fixing it anytime real soon.
>>
>>So, in case you are interested, it is attached. It allows you to
>>compute the value of a rational[*] as expressed in any base, 1 < base
>>< 37, to arbitrary precision.




> I just got up and read your mail. However, I'm going away for the day
> so I didn't have time to look over your code. Thanks for the advice
> and explanations, they really helped. I understand the problem now...
> /me waves fist a base 2 fractions. If your code can fix it, then
> that's pretty great! What was that "import decimal" idea you proposed?
> Does it contain some functions that can sanely work with floating
> points? I'm not a new programmer, but my main arena is the simple side
> of Java, so I'm not really too far along yet.
> 
> Hoping Python will be fun,
> Patrick Rutkowski
> 
> P.S. I responded to the list this time.


Hi all,

:-(

Patrick had originally posted with the "why is Python getting the math 
wrong?" floating point issue. I'd responded to him with the FAQ link. 
He wrote back privately (top of quoting above). I replied privately 
and explained that the "better" behaviour of 4/5.0 as compared to 
1/3.0 is a product of base 10 representation. To substantiate this, I 
coded up something (incomplete) to represent rationals in arbitrary 
bases, for base 1< base < 37, and sent it privately.

Patrick then replied to the message with that code to the list :-( I'd 
not intended it to be posted publicly, not out of any code hoarding 
impulse, but from thinking it isn't good enough to put forth to the 
world. (I'm only a hobbyist.) But, since the decision to put it out 
there was taken for me, if anyone read the code, I'd appreciate 
comments. (The code is in the msg to which this is a reply -- it is 
long enough I didn't want to post it twice.)

Thanks, and best to all,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


precision problems in base conversion of rational numbers

2005-07-04 Thread Brian van den Broek
Hi all,

I guess it is more of a maths question than a programming one, but it 
involves use of the decimal module, so here goes:

As a self-directed learning exercise I've been working on a script to 
convert numbers to arbitrary bases. It aims to take any of whole 
numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
m whole) and floating points (the best I can do for reals), and 
convert them to any base between 2 and 36, to desired precision.

I'm pretty close but I know I am not handling the precision quite 
right. Nothing other than understanding hangs on it, but, that's 
enough :-)

To do all this I'm using the decimal module (for the first time) and 
I've been setting the precision with

decimal.getcontext().prec = max(getcontext().prec,
 x * self.precision )

This is in my class's __init__ method before I convert every number to 
Decimal type and self.precision is at this point an int passed.

The first term is to be sure not to reduce precision anywhere else. In 
the last term I'd started off with x = 1, and that works well enough 
for "small" cases (i.e. cases where I demanded a relatively low degree 
of precision in the output).

I've no idea how to work out what x should be in general. (I realize 
the answer may be a function of my choice of algorithm. If it is 
needed, I'm happy to extract the relevant chunks of code in a 
follow-up -- this is long already.)

For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base 
17 to 80 places (i.e. self.precision = 80) I get:

 >>> print Rational_in_base_n(345, 756, 17, 80)
0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB

(Rational_in_base_n(numerator, denominator, base, precision) is the 
rational specific subclass. When I convert the result back to decimal 
notation by hand it agrees with the correct answer to as many places 
as I cared to check.)

I've discovered empirically that I have to set getcontext.prec = 99 or 
greater (i.e. x >= 1.2375) to get
0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C

(I do feel safe in assuming that is the right answer. :-)

How would I go about working out what degree of precision for the 
decimal module's context is needed to get n 'digits' of precision in 
an expression of base m in general? (I've no formal training in Comp 
Sci, nor in the relevant branches of mathematics.)

Thanks and best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Brian van den Broek
Terry Hancock said unto the world upon 05/07/2005 11:49:
> On Monday 04 July 2005 06:11 am, Brian van den Broek wrote:
> 
>>As a self-directed learning exercise I've been working on a script to 
>>convert numbers to arbitrary bases. It aims to take any of whole 
>>numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
>>m whole) and floating points (the best I can do for reals), and 
>>convert them to any base between 2 and 36, to desired precision.

Thanks to Terry and mensanator for the replies.

To consolidate, I respond to Terry in-line and then add some response 
to mensanator at the end.


> Interesting, I'd like to see that.

I'd like it to be seen :-)  I will soon send my current version in a 
private email.


>>I'm pretty close but I know I am not handling the precision quite 
>>right. Nothing other than understanding hangs on it, but, that's 
>>enough :-)
> 
> 
> Okay.  You do understand that many numbers that can be exactly
> represented in one base cannot be in another?

Indeed. The original impetus for writing this was to substantiate my 
claim in an off-list conversation that whether a given rational had a 
repeating or terminating expansion was a function of the base of 
representation. In particular, that 1 / n in base n is 0.1


> E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating
> decimal: 0.333  And of course, there are infinitely many
> other examples.

The exact example I used in my off-list exchange :-)
(No "great minds" claim, sadly, as it is the natural example.)





> Needless to say, the conventional floating point numbers in Python
> are actually stored as *binary*, which is why there is a "decimal"
> module (which is new).
> 
> If you're going to be converting between bases anyway, it probably
> makes little difference whether you are using the decimal module
> or not, of course.  You'll have the same problems the conventional
> float numbers do.

It may be a function of the algorithm I picked, but I am almost 
certain that I switched to employing Decimals after finding a 
substantial inaccuracy with a purely float logic. I will likely get 
around to switching back to floats late tonight to confirm my 
recollection.


> Getting back to your precision problem: I bet if you simply
> evaluate the error term as I have above, and then convert *that* into
> your base of choice, you will be able to tell how many places are
> correct in the conversion.
> 
> That is to, say, stop think about "number of places" and instead
> think about "representation error".  That number is a real property
> of the data which can be represented in any base.  Then you can
> convert it to number of places in the representation process.

A useful "cognitive correction", thanks :-)


> e.g. 0.05 has 6 places behind the zero in decimal, how many
> does base3(0.05)? --- that's the accuracy of the statement
> 
> 0.3 base10 ~= 0.1 base3 +- base3(0.05 base10)
> 
> Roughly, we know that 0.05 = 10^-5 / 2.  The same term
> in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved
> using logarithms, but I'll "leave that as an excercise for the reader",
> because I'm too lazy to go look it up, and I've forgotten the
> details. ;-)

Thanks. mensanator provided the actual formula for my case. I had a 
"magic number" in my code by which I multiplied my desired level of 
"number of places in the representation" to obtain the value for 
decimal.getcontext.prec.

mensanator wrote:

> The value you want for x is log(17)/log(10) =
> 1.2304489213782739285401698943283

where x was my "magic number". I've not had a chance to think it 
through yet, but I feel confident that given the formula, I'll be able 
to work out *why* that is the formula I need.

So, thanks for that, too.

mensanator also pointed out an inaccuracy in my posted example. I had 
345 / 756 represented in base 17 to 80 digits, and came up with a 
repeating expansion. It was pointed out that I should have rounded up 
the last 'digit' ['17-it' ? :-) ]. Indeed. I'd been concentrating on 
getting the conversion logic right before adding logic to deal with 
rounding and should have mentioned my result was not a rounded one, 
but merely a truncation of the infinite expansion. Thanks for the 
correction / reminder to add the logic.

> I hope this is helpful, though,
> Terry

Indeed, both your's and mensanator's. Thanks to both. Best to all,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Brian van den Broek
Alessandro Brollo said unto the world upon 07/07/2005 03:24:
> Far from a professional programmer, I'm simply a
> newbie Python user. Two basic questions:
> 
> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?



Check out the Tutor list 

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An absolute Newbie question

2005-07-10 Thread Brian van den Broek
wpog said unto the world upon 10/07/2005 12:41:
> Hello,
> 
> I have a question about using "IDLE", and that is whenever I start write my  
> own program in the "Python Shell" it will automatically execute whatever 
> command I have written, for example: >>> print 'Hello World"
> 
> So, how to I get it to not execute, so that I can write a program that has 
> ordinary executable functions, and stuff like that?
> 
> I do have some experience with Turbo Pascal, and so I'm hoping that this 
> will be an even easier language to learn, and thus far it does seem so, but 
> I need to get past this first;-).
> 
> Thanks in advance,
> 
> wpog

Take a look at .

But the quick answer:

Launch IDLE.
File Menu -> New Window
Type away. (Be sure to explicitly save with the py or pyw extension, 
as IDLE does not add it for you.)

HTH,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-12 Thread Brian van den Broek
Ric Da Force said unto the world upon 12/07/2005 02:43:
> Hi,
> 
> I have a string such as 'C1, C2, C3'.   Without assuming that each bit of 
> text is of fixed size, what is the easiest way to change this list so that 
> it reads:
> 'C1, C2 and C3' regardless of the length of the string.
> 
> Regards and sorry for the newbie question,
> 
> Ric 
> 

Hi Ric,

the rsplit method of strings should get you going:

 >>> data = "the first bit, then the second, finally the third"
 >>> chunks = data.rsplit(',', 1)
 >>> chunks
['the first bit, then the second', ' finally the third']
 >>>

Best,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.4 Recent File list not working

2005-07-13 Thread Brian van den Broek
Larry Bates said unto the world upon 13/07/2005 15:54:
> I recently upgraded from 2.2 to 2.4 (ActiveState for Windows).
> I was accustomed to having the most recent 10 files that I had
> edited show up under File menu under Recent.  After upgrading
> these don't seem to be saved after exiting.  I tried changing
> the number in the Preferences, but nothing seems to do any
> good.
> 
> Has anyone else had this problem?  Any ideas how I might fix
> it?
> 
> Thanks in advance for your assistance.
> Regards,
> Larry Bates


Larry,

You'd do better to specify just what program isn't maintaining the 
list. PythonWin? (That comes with the ActiveState Python for Windows, 
I believe.) IDLE?

Either way, works for me with www.python.org Python 2.4.1 and the 
version of PythonWin from build 204 of pywin32 extensions.

If no other answers are forthcoming, you might want to try any support 
or user's lists for the ActiveState Python distribution.

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems with python 2.4 help

2005-07-15 Thread Brian van den Broek
[EMAIL PROTECTED] said unto the world upon 15/07/2005 14:50:
> I've noticed that the listings in help don't take you to correct topic.
> 
> anyone else have this problem?  Is there a fix?
> 

I'm not sure from your question what exact problem you are 
experiencing. Do you mean:

IDLE 1.1.1
 >>> help()

Welcome to Python 2.4!  This is the online help utility.



help> topics

Here is a list of available topics.  Enter any topic name to get more 
help.

ASSERTION   DELETIONLOOPING SEQUENCES

DEBUGGING   LITERALSSEQUENCEMETHODS2

help> LOOPING

Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found.  If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.

help>


If so, I posted a similar question a year or so ago to the tutor list. 
I believe that when I resolved it I posted details about the resolution.

I've since got a new computer, and just redid it now to check. Just 
download the html version of the docs and then, as per the 
instructions above, set an environment variable to point to them. (On 
WinXP: Control Panel->System-Advanced->Env. Var. When I had WinME, a 
line in autoexec.bat)

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive python session spool/save-log command?

2005-07-20 Thread Brian van den Broek
Robert Kern said unto the world upon 2005-07-20 21:15:
> S. M. Tuttle wrote:
> 
>>I'm going to be teaching an introductory course on Python
>>in the Fall, so I am hurriedly trying to both learn
>>Python and prepare the course during the next few weeks.
>>
>>I'm curious if there is a command that allows everything from
>>that point on in a python interactive session to be
>>saved/spooled/forked/logged into a text file of the user's choice.
> 
> 
> IPython is an interactive interpreter that will log all input to a file.
> 
> http://ipython.scipy.org/
> 

If your students are more likely to feel comfortable with an interface 
with things right there for the clicking, IDLE allows for the 
interactive prompt windows to be saved. IDLE's bundled with Python, so 
less to install to boot.

Best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between " and '

2005-07-22 Thread Brian van den Broek
Andrew Dalke said unto the world upon 2005-07-22 13:30:
> François Pinard wrote:
> 
>>There is no strong reason to use one and avoid the other.  Yet, while
>>representing strings, Python itself has a _preference_ for single
>>quotes. 
> 
> 
> I use "double quoted strings" in almost all cases because I
> think it's easier to see than 'single quoted quotes'.
> 
>   Andrew
>   [EMAIL PROTECTED]
> 

I prefer the look of '''single triple''' to """double triple""" but a 
while back I noticed pydoc doesn't work as well with single triple 
quotes. When I posted here, Kent Johnson was kind enough to tease out 
of me what I was on about and file a bug: 


Best to all,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-07 Thread Brian van den Broek
Alex Martelli said unto the world upon 2005-02-06 18:06:
Brian van den Broek <[EMAIL PROTECTED]> wrote:
   ...
(I'm just a hobbyist, so if this suggestion clashes with some well 
established use of 'Bag' in CS terminology, well, never mind.)

Yep: a Bag is a more common and neater name for a "multiset" -- a
set-like container which holds each item ``a certain number of times''
(you can alternatively see it as a mapping from items to counts of
number of times the item is held).
Alex
Thanks for that info. I've yet to check the link to the Bag cookbook 
recipe that Carlos Ribeiro posted for me 
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174>, but 
now I definitely will! (When I first learned of Python's set type, I 
was disappointed there wasn't also a multi-set type.)

Thanks and best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


RESOLVED broke IDLE while defining a key-binding scheme

2005-02-07 Thread Brian van den Broek
Brian van den Broek said unto the world upon 2005-02-04 22:21:
Hi all,
IDLE refuses to launch, and I believe it is because I attempted to 
define a custom key-binding that it doesn't like.

shortcuts, etc.) by clicking on it. Nothing. Ran idle.py instead 
> . The DOS-console this brings up displays:
Traceback (most recent call last):

  File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1299, in event_add
self.tk.call(args)
_tkinter.TclError: bad event type or keysym "tab"
 >>>

For future googler's and to stave off any unnecessary replies, on a 
different thread about IDLE problems <http://tinyurl.com/4bl45> Peter 
Otten posted the information that allowed me to resolve this. (It was 
a matter of finding the custom key-binding that I'd defined which made 
IDLE choke and removing it.)

So, thanks Peter!
Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to run IDLE Under Windows

2005-02-07 Thread Brian van den Broek
Peter Otten said unto the world upon 2005-02-07 09:14:
Jonathan Polley wrote:

I have one account on a WindowsXP machine that refuses to run IDLE (or
any other python script that uses Tk).  Other people can login to that
PC and IDLE runs just fine, so it is not an installation issue.  When
the person who has the problem logs into another PC the problem follows
them.  Any ideas as to what might me wrong?

Perhaps your configuration files contain bad data:
"""
# IDLE reads several config files to determine user preferences.  This
# file is the default config file for general idle settings.

Peter
Thanks for posting that, Peter. It helped me work out my problem that 
I posted about a few days back .

Could I ask where did you get the content from? I've searched my HDD 
for some of the contained phrases with the Windows tools I have at my 
disposal, but didn't manage to find the text you posted. (If I'd been 
able to find it, I'd have been able to solve my problem days ago.)

Thanks and best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: python code with indention

2005-02-07 Thread Brian van den Broek
Xah Lee said unto the world upon 2005-02-07 14:39:
is it possible to write python code without any indentation?
 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html
print "It would seem it is indeed possible."
print
print "Note: although I know this, I don't consider myself an "
print "accomplished Pythoner."
print
print "In the face of that, "
print "I know enough not to post Python 'tutorials'."
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-07 Thread Brian van den Broek
Steve Holden said unto the world upon 2005-02-07 17:51:
Alexander Zatvornitskiy wrote:
Привет Alex!
05 февраля 2005 в 17:00, Alex Martelli в своем письме к All писал:

 AM> to all intents and purposes working "as if"
 AM> it was a declaration.  If I had to vote about the one worst formal
 AM> defect of Python, it would surely be 'global'.
Second worsest - 'def'? :)
The reason global is a wart can clearly be seen in the following example:
 >>> x = 3
 >>> def f(tf, v):
 ...   if tf:
 ... global x
 ...   x = v
 ...
 >>> f(0, 5)
 >>> x
5
 >>>
This makes it apparent that the global statement is *not* executable, 
the only one in the language that is not.

regards
 Steve
Hi,
Steve's example makes my brain hurt. :-)
I'd appreciate it if someone could tell me if I am understanding the 
example correctly. (My grasp of the terminology and issues at play is 
a bit shaky.)

Let me simplify Steve's example to:
.def hurts_my_brain(v):
.if False: # unlike Steve's eg, ensuring that the
.global x  # nested block is never hit at runtime
.x = v
(I checked, and it works the same as the original eg, modulo change of 
function name.)

Is the right way to understand it in this vicinity:
At compile time (by which I mean when the Python bytecode is built) 
the global statement is hit and has the effect of `bumping up' the 
function local name `x' to the module namespace, making the function 
local name `x' synonymous with the module global name `x'. At runtime, 
the `global x' is never reached, but it has already, at compile time, 
had its effect on the nature of the function object hurts_my_brain. 
Further, if the function had instead said 'if True:' the global 
statement would have been reached at runtime, but would have been 
without effect due to this, having already been `used up' in the 
creation of the bytecode.

Can it then be further (truly :-) ) said that
if False:
# thousands of lines of code here
would effect the structure of the function object's bytecode, but not 
its behaviour when run? Or, at most, would cause a performance effect 
due to the bytecode being bloated by thousands of line's worth of code 
that would never get executed?

Thanks for any confirmation of my understanding / rectification of 
same. Best,

Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python - resources and ideas

2005-02-08 Thread Brian van den Broek
[EMAIL PROTECTED] (Cody Houston) said unto the world upon
2005-02-08 05:06:
Hi. What is the best way to learn Python? None of the local schools
near me teach any courses on the topic. Thanks.
--
Cody Houston
[EMAIL PROTECTED]
Hi Cody,
rec.photo.equipment.35mm? -- kind of an odd follow-up for a post to
com.lang.python.
First thing is to learn to ask better questions. It is a bit hard for
anyone to know what to say without knowing your background and level
of experience with computers and programming.
 contains a lot of
very good advice on this.
As for actual learning resources, did you look at www.python.org at
all? (Or search the archives of this group?) The python site has a few
pages of links that speak directly to your question.
But, some concrete suggestions:
The most useful resources for me (I'm still learning, too) was the
Tutor list .
A free book that starts very slow (it is aimed at high-school
students) is 
I started with that, until I had a bit of a sense of things (Python is
my first language since some BASIC quite some time ago). The Learning
Python helped a lot .
Best,
Brian vdB


--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-08 Thread Brian van den Broek
Brian van den Broek said unto the world upon 2005-02-07 20:36:
Steve Holden said unto the world upon 2005-02-07 17:51:

The reason global is a wart can clearly be seen in the following example:
 >>> x = 3
 >>> def f(tf, v):
 ...   if tf:
 ... global x
 ...   x = v
 ...
 >>> f(0, 5)
 >>> x
5
 >>>

Hi,
Steve's example makes my brain hurt. :-)
I'd appreciate it if someone could tell me if I am understanding the 
example correctly. (My grasp of the terminology and issues at play is a 
bit shaky.)

Thanks for any confirmation of my understanding / rectification of same. 
Best,

Brian vdB
Thanks to everyone whose contributed to this sub-thread! I've learned 
a lot. :-)

And, for posterity, some one wrote me off-list to correct my claim
that in
if False:
# thousands of lines of code here
the thousands of lines "would never get executed". Simplifying their 
example, they pointed out:

>>> False = 'evil trickery'
>>> if False:
... print 'Surprise!'
...
Surprise!
>>>
Which leads me naturally to the differences between 'if False:' and 
'if ):' that Duncan Booth pointed to. (Where'd I put the Tylenol.)

Thanks again to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto, cls, wait commands

2005-02-10 Thread Brian van den Broek
BOOGIEMAN said unto the world upon 2005-02-10 16:06:
OK, thanks all
Here's presentation of my advanced programming skills :)

import os
import time
os.system("cls")
number = 78
guess = 0
while guess != number:
guess = input("Guess number: ")
  
if guess > number:
print "Lower"
time.sleep(3)
os.system("cls")

elif guess < number:  
print "Higher"
time.sleep(3)
os.system("cls")

print "That's the number !"
---
BTW, I'm thinking to replace lines "time.sleep(3)"
with something like "Press any key to guess again"
How do I do that ?
Also I wanted to put at the end something like
"Do you want to guess again ?" and then "GOTO" start
of program, but since there is no such command in Python
what are my possible solutions ?
Hi,
I'm no expert and I owe much of whatever I know to the Python Tutor 
list. I'd suggest you check it out 
.

As for your situation, I'd do something like this untested code:
guess = input("Guess number: ")
while guess != number:
print `Nope.'
guess = raw_input('Guess again? (Enter q for quit)')
if guess.lower() == 'q':  # .lower() ensures 'Q' will match
print `Quitter!'
break
if guess > number:
# stuff here
if guess < number:
# different stuff here
raw_input is safer than input as it prevents malicious code from 
ruining your day.

A while loop is the usual way to repeat something until some condition 
is met. Here it repeats until guess == number. Another common idiom is

while True:
# do some stuff
if some_condition:  # some condition being True signals the
break   # need to break out of the loop
I game to Python 10'ish years after I'd programmed some in BASIC and 
then not again. It took me a while to grok goto-less coding, too :-)

HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unit Testing in Python

2005-02-10 Thread Brian van den Broek
rhat said unto the world upon 2005-02-10 21:10:
Hi Everyone,
I've recently been reading some articles about unit-testing in Python
[1] [2], but I am a bit confused: where do I go to get started with
this? I tried googling for "unittest" but all I've found are some old
links to projects that already use it, and the older (as the articles
put it) PyUnit project. I'm sorry if this is a obvious question or one
that has already been answered, but unit-testing sounds interesting and
I'm not sure where to start.
Thanks,
Ryan Kaulakis
Hi,
I've just started learning about testing and TDD, but I found the 
following recent articles and blog posts useful:






(Your footnotes didn't come through, so these might not be new to you.)
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


win32gui bug: where to report it?

2005-02-15 Thread George van den Driessche
It's taken me ages to find out why my window, built out of win32all, wasn't
receiving any messages. Eventually I found the answer here:

http://mail.python.org/pipermail/python-list/2001-October/069451.html

The important point being:
> IIRC you have to pass the return value of the RegisterClass() call (which
> is an atom) to the CreateWindowEx() function as the second parameter
> (lpClassName).
... in other words, you can pass the name of your window class as the second
parameter, but it will silently fail to work. (This holds for CreateWindow
too.)

This is a bug for which it is pretty much impossible to work out the
workaround without being told it, so I'd like to put the workaround in a
more easily-found place. But where? win32all doesn't seem to have much
documentation, much less a bug database.

In case anyone else needs to find this message by searching, some keywords
are: win32all, win32gui, WNDCLASS, RegisterClass, CreateWindow,
CreateWindowEx

George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with tutor mailing

2005-02-16 Thread Brian van den Broek
administrata said unto the world upon 2005-02-16 16:11:
i'm using tutor maling...
i e-mail some questions to tutor and
get answers.
but, i frequently get mails which aren't related with my question.
how should i stop it?
You do know it's a mailing list that you've subscribed too, right?
As in, people post and you get their posts, not just replies to your 
own messages.

You could read it via gmane and read only the replies to your threads 
-- though I am not sure if you can post to Tutor without being a 
subscriber.

I do get the downside of subscribing -- at the very least, you've got 
to put up with long questions posted by me ;-)

But, I'd encourage you to remain subscribed. I am certainly no expert 
(as today's Tutor traffic can attest). But, much of what I know I 
learned by reading other people's questions and the answers to them.

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: duplicate docstrings

2005-02-19 Thread Brian van den Broek
Steven Bethard said unto the world upon 2005-02-18 13:58:
I have two classes that implement the same interface, e.g. something like:
class C(object):
def foo(self):
"""Foo things"""
...
def bar(self):
"""Bar things"""
...
def baz(self):
"""Baz things in a C manner"""
...
class D(object):
def foo(self):
"""Foo things"""
...
def bar(self):
"""Bar things"""
...
def baz(self):
"""Baz things in a D manner"""
...
It bothers me that I'm basically writing the same docstrings multiple 
times.  I guess what I really want to do is just write the docstrings 
for the interface I'm describing, and only supply docstrings in the 
classes when they need to differ from the interface docstrings.

Is there a good way to do this?  If it's necessary, I can have C and D 
inherit from another class...

STeVe
Hi, I'm new to thinking in classes, and may not have understood your 
need. But does this help:

IDLE 1.1
>>> class Spam:
'''I'm a very spammy docstring'''
pass
>>> class Ham:
__doc__ = Spam.__doc__

>>> help(Ham)
Help on class Ham in module __main__:
class Ham
 |  I'm a very spammy docstring
>>>
best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: NOOB coding help....

2005-02-22 Thread Brian van den Broek
Igorati said unto the world upon 2005-02-22 03:51:
#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
numbers = [ ] 
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
def getint():
 return int(raw_input('Number? '))

numbers = sorted(iter(getint, 0))
numbers
[2, 3, 5, 7]
def variable_median(x):
 
 return sorted(x)[len(x)//2]
def variable_mode(x):
 
 counts = {}
 for item in x:
 counts[x] = counts.get(x, 0) + 1
 
 return sorted(counts, key=counts.__getitem__, reverse=True)[0]


s = variableMean(numbers)
y = variableMedian(numbers)
t = variableMode (numbers)
import pickle
pickle.dump((s, y, t), file('avg.pickle', 'w'))
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
print 'Please enter Yes or No:'
if raw_input == yes:
f = open("avg.py","r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
I got the error:
Traceback (most recent call last):
  File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 9, in ?
numbers = sorted(iter(getint, 0))
  File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 7, in
getint
return int(raw_input('Number? '))
TypeError: 'str' object is not callable
and this one for my if statement:
Traceback (most recent call last):
  File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 39, in ?
if raw_input == Yes:
NameError: name 'Yes' is not defined
I cannot understand how I can define yes so that when they type yes the
data is printed out. Also if they type no how do I make the program do
nothing. Or is that just infered.
Hi,
have you tried examining the objects you are trying to put together to 
see why they might not fit?

For instance, look what happens when you run this, entering 42 at the 
prompt:

ri = raw_input('Gimme!')
print type(ri)
print type(int(ri))
print ri == 42
print ri == '42'
name_not_defined_in_this_code
Does looking at the output of that help?
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Selective HTML doc generation

2005-02-23 Thread Brian van den Broek
Graham said unto the world upon 2005-02-23 09:42:
Hi. I'm looking for a documentation generation tool (such as pydoc,
epydoc, happydoc, etc.) that will allow me to filter what it includes
in
it's output.
I only want the reader to know about classes and methods in my package
if if the classes have docstrings. I've got a large package that is
used
by relatively non-technical users (and yet they write Python!) that
documents the public API with docstrings. I don't want to clutter their
view of the world with links to the package's internal classes and
documentation that covers things like __special__ methods.
Anybody know of anything that let's you do it? I realise I may end up
doing some hacking here but don't want to repeat work unnecessarily.
Cheers,
Graham
Hi Graham,
 I'm not at all an expert 
OK, that out of the way:
I recently wanted pydoc to display information about my methods whose 
names started with one or more underscores, so that I could see in the 
docs for the objects in my first bigger than small project.

I managed with a small change to the visiblename function of pydoc.py.
It looks to me that this is also the place where you'd want to put in 
code to filter for only treating objects with docstrings. *How* to do 
that is something I've not read enough of pydoc.py to speak to.

Omitting special methods is easy, though. The code says:
# Private names are hidden, but special names are displayed.
if name.startswith('__') and name.endswith('__'): return 1
So, just change the 1 to a 0. (The `private' logic is a few lines 
down.) Easy :-)

Hope that is at least of some help. Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Selective HTML doc generation

2005-02-24 Thread Brian van den Broek
Graham Ashton said unto the world upon 2005-02-24 04:54:
Thanks Brian, much appreciated. Looks quite straightforward.
Graham
Hi Graham,
glad it helped -- I think this marks the first time I've given a 
useful answer to a non-trivial question on comp.lang.python. :-)


G:
Hi. I'm looking for a documentation generation tool (such as pydoc,
epydoc, happydoc, etc.) that will allow me to filter what it includes
in it's output.
I only want the reader to know about classes and methods in my package
if if the classes have docstrings.
B:
Pointed Graham to to the visiblename function of pydoc.py, where I 
recently made a small change to get it to display `private' methods, 
and hypothesized that would be where he'd want to start in order to 
modify pydoc to meet his needs.


Before I responded, I tried for a bit to write the code to filter for 
only those objects with docstrings like you wanted. I'm fairly new to 
programming and wasn't able to work out exactly what code is needed. 
(My skill level is such that it isn't quite so straight-forward to me :-)

Would you be willing to post what you did to make it work? I think I'd 
learn something, having bounced off when making a (gentle) push on the 
problem.

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help running external program

2005-02-27 Thread Brian van den Broek
Rigga said unto the world upon 2005-02-27 15:04:
Tim Jarman wrote:

No, the r was the point - it's there to tell Python not to do any escaping
on the string. Try it again with the r and see what happens.
Brilliant!!!  that works a treat thankyou!!, where on earth did you find out
about the 'r'  any pointers to documentation appreciated.
Thanks 

RiGGa


Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trees

2005-02-27 Thread Brian van den Broek
Alex Le Dain said unto the world upon 2005-02-27 19:54:
 > Would this be for a GUI toolkit or maybe using a standard
 > class scheme?
Sorry, yes I should have been more specific. I meant a non-GUI, standard 
class scheme. I want to use the scheme to hold a structure in memory and 
retrieve/add information to it.

I've had a couple of goes myself but get a bit confuesd about whether I 
should use recursion to be able to get the children (and all 
"sub"-children) of a/the parent.

cheers, Alex.
Hi Alex,
I've been working on a set of tools for dealing with a tree structure.
I am no python expert -- in fact, the program I am working on is my
first serious us of classes. Anyway, though I've not been following
your thread, I also think that perhaps you might find the code I have
of some use. Use caution though; newbie code below :-)
I am working with a data format from a shareware application that puts
the tree in a flat text file, where each node has a header section,
including a unique node id and a level indicator. (Level 0 for the
root, level 1 for the roots children, etc.) My code is a work in
progress and not heavily tested, but it seems to work :-) I've a class
Tree_file with a .nodes attribute which is a list of Node objects (in
top-down tree order). It has a method:
.# leading periods to preserve indentation
.def update_family(self):
.'''Starting from node, updates each nodes .children and
descendants set.'''
.for node in self.nodes:
.node.get_children(self)
.for node in self.nodes:
.node.get_descendants()
My Node class has methods giving each node object a node.id and
node.level (both ints). The other relevant attributes are
node.children, and node.descendants (both sets).
(I've got reasons to often process just a node's children, rather than
 all descendants; thus, it makes sense for my program to have the two
attributes.)
The two relevant methods are:
.def get_children(self, parent_file):
.'''Sets the node's .children set attribute.
.
.Scans the list of Node objects in parent_file.nodes until self
.node is found (by comparison of node.id attributes). Then the
.capture_children flag is set to True, and, for each node exactly
.one node.level deeper, that deeper node is added to the
.self.children set. This goes on until the first node not below
.the self node is found.
.'''
.capture_children = False
.children = set()
.
.for node in parent_file.nodes:
.if capture_children and not node.level > self.level:
.break
.if capture_children and node.level == self.level + 1:
.children.add(node)
.if self.id == node.id:
.capture_children = True
.
.self.children = children
and
.def get_descendants(self):
.'''Updates each nodes .descendants set to current value.
.
.Recursive call of get_descendants on a node's children, adding
.all to the .descendants set (of the target node).
.'''
.descendants = self.children.copy()
.for node in self.children:
.node.get_descendants()
.for n in node.descendants:
.descendants.add(n)
.self.descendants = descendants
Anyway, all caveats notwithstanding, I hope that is of some use to
you. Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 removes None data type?

2005-03-07 Thread Brian van den Broek
Steven Bethard said unto the world upon 2005-03-07 11:55:
Warren Postma wrote:
Michael Hoffman wrote:
The fact that True and False are not constants?

Yowza.
a = True
b = False
False = a
True = b
if (1==2)==True:
print "Doom"

Why stop there when you can really cause some doom:
py> import __builtin__ as bltin
py> bltin.True, bltin.False = bltin.False, bltin.True
As an example of what doom this causes, try typing it at the interactive 
prompt, and then see if you can enter anything else.  I can't -- the 
prompt just locks up.  Woo-hoo!  Another way to shoot myself (and my 
users) in the foot! =)

STeVe
Hi all,
just tried this in IDLE:
IDLE 1.1
>>> import __builtin__ as bltin
>>> bltin.True, bltin.False = bltin.False, bltin.True
>>>  RESTART 


The restart was done by IDLE itself -- poor thing just gave up. So, it 
looks like Steve has found a `commit suicide' command for an IDLE 
shell :-)

Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: using the set command

2005-03-11 Thread Brian van den Broek
Leeds, Mark said unto the world upon 2005-03-11 20:03:
Do I have to import something
In order to use the set command ?
I am trying to use it but
I keep getting an error.
 

 Mark
The answer depends upon which version of Python you are using. That 
information, along with the error message would be most handy for 
those who wish to help you.

Python 2.4 has the set datatype as a builtin.
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter WEIRDNESS or Python WEIRDNESS?

2005-03-11 Thread Brian van den Broek
steve said unto the world upon 2005-03-12 00:06:
In a nutshell, my problem is that I am getting this runtime error, and
I have no clue why.  Please bear in mind its my first python program:
"localvariable 'currentAbility' referenced before asignment"
in this function which is a callback for a button:
def nextThing():
if lookingAtAbilities == 1:
currentAbility = currentAbility + 1
if currentAbility not in ability:
currentAbility = 0
clearScreen()
ability[currentAbility].draw(currentAbility)
drawMainButtons()
else:
currentCreature = currentCreature + 1
if currentCreature not in creature:
currentCreature = 0
clearScreen()
creature[currentCreature].draw(currentCreature)
drawMainButtons()
now the thing is, both lookingAtAbilities  and  currentAbility are
global variables.  In fact, they are both assigned at the same part of
the program, right at the start.  yet lookingAtAbilities  is
recognized as a global by this function, and currentAbility is not,
generating this runtime error.
here is the structure of the code:

This has me flumoxed
thanks if you can work it out,
Steve
Hi Steve,
While both lookingAtAbilities and currentAbility are names in the 
global namespace, nextThing() doesn't know that ;-).

The first mention of if lookingAtAbilities in nextThing() is:
.if lookingAtAbilities == 1:
This is a reference to the name, so the interpreter fetches 
lookingAtAbilities value from the first namespace in which it finds 
such a name. (The global namespace.)

By contrast, the first mention of currentAbility is:
.currentAbility = currentAbility + 1
So, the interpreter `creates' (I am a bit fuzzy on the terminology and 
not an accomplished Pythoner) a name in the function local namespace 
and then looks to see what value to point the name at. When it sees it 
should have currentAbility (a name without a value as yet) point to
currentAbility + 1, it barfs.

One way to fix it, is to put `global currentAbility' at the top of 
your function definition. (Many frown on globals as it messes with the 
namespaces, and gives bad mojo.)

Another would be to pass currentAbility in to your function as an 
argument.

Yet another (and probably the best) would be to wrap your code into a 
class and then reference self.currentAbility.

Still another (but one not so good for clarity or beauty) would be to 
put a line like:
temp = currentAbility # temp a name to reference global scope name
  # before assignment to follow.

Perhaps more expert voices will chime in and say better things. :-)
HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter WEIRDNESS or Python WEIRDNESS?

2005-03-12 Thread Brian van den Broek
steve said unto the world upon 2005-03-12 18:46:
Brian van den Broek <[EMAIL PROTECTED]> wrote in message news:<[EMAIL 
PROTECTED]>...
steve said unto the world upon 2005-03-12 00:06:
In a nutshell, my problem is that I am getting this runtime error, and
I have no clue why.  Please bear in mind its my first python program:
"localvariable 'currentAbility' referenced before asignment"
in this function which is a callback for a button:
now the thing is, both lookingAtAbilities  and  currentAbility are
global variables.  In fact, they are both assigned at the same part of
the program, right at the start.  yet lookingAtAbilities  is
recognized as a global by this function, and currentAbility is not,
generating this runtime error.
here is the structure of the code:

This has me flumoxed
thanks if you can work it out,
Steve
Hi Steve,
While both lookingAtAbilities and currentAbility are names in the 
global namespace, nextThing() doesn't know that ;-).

The first mention of if lookingAtAbilities in nextThing() is:
.if lookingAtAbilities == 1:
This is a reference to the name, so the interpreter fetches 
lookingAtAbilities value from the first namespace in which it finds 
such a name. (The global namespace.)

By contrast, the first mention of currentAbility is:
.currentAbility = currentAbility + 1
So, the interpreter `creates' (I am a bit fuzzy on the terminology and 
not an accomplished Pythoner) a name in the function local namespace 
and then looks to see what value to point the name at. When it sees it 
should have currentAbility (a name without a value as yet) point to
currentAbility + 1, it barfs.

Thanks to both of you, this has fixed the problem.  I wouldnt have
guessed that in a million years.
Hi Steve,
you're welcome. I'm just glad I've finally understood enough to offer 
helpful answers :-) (Though note the self-correction at the end of 
this post.)

But it leads me to ask what is the use of something being in the
gloabl namespace if it cant be accessed globally?
I think that your question shows there is some residual confusion. 
Things in the global namespace can be accessed just fine. The issue 
with your code was that, while you had a global name currentAbility in 
the global namespace sitting around just waiting to be accessed, your 
first use of that name in your function was to assign it.

Assignments are by default to names in the local namespace. If you'd 
put the global line in, you'd have told the interpreter to make the 
assignment in the global scope. Without this, your function told the 
interpreter to create a new name in the local namespace and make it 
refer to the object to the right of the '=' which, in your case, was 
not well-defined.

There is a certain logic to making assignments be assignments within 
the active namepace by default. There may be a deeper reason, but I 
don't know it. (To anyone more expert: if there is, I'd love to learn it).

I also find the continual need for objects to reference their own
variables by prefixing 'self' annoying.  It seems that Python is the
reverse of my assuptions.  whats the rationale for that?
The self prefix is just a conventional way of indicating a reference 
to the current class instance. I hated it at first too. Python is my 
first language since some BASIC long ago and the selfs were one reason 
I steered clear of OOP at first. But, a few evenings of programming 
with classes (a recent thing for me) and the aversion went away. So: 
give it a bit of time; you might get so you aren't bothered by them.

I should also note there was some residual confusion in what I wrote, too:
Still another (but one not so good for clarity or beauty) would be to 
put a line like:
temp = currentAbility # temp a name to reference global scope name
  # before assignment to follow.
This won't work. Witness:
>>> a = 42
>>> def my_mistake():
... temp = a
... a = a * 2
... 
>>> my_mistake()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in my_mistake
UnboundLocalError: local variable 'a' referenced before assignment
>>>
Sorry 'bout that :-[
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: try / except not worknig correctly

2005-03-12 Thread Brian van den Broek
'@'.join([..join(['fred', 'dixon']), ..join(['gmail', 'com'])]) said
unto the world upon 2005-03-12 19:20:
the code below will not execute the except section when i enter a
number.
what am i missing ?
#
.while 1:
.   print 'Pump Protection ? '
.   #line 133
.try:
.myInput = raw_input('A B C D E F G H I J K L ? ')
.myInput = string.upper(myInput)
.if myInput == 'A':break #
.if myInput == 'B':break #
.if myInput == 'C':break #
.if myInput == 'D':break #
.if myInput == 'E':break #
.if myInput == 'F':break #
.if myInput == 'G':break #
.if myInput == 'H':break #
.if myInput == 'I':break #
.if myInput == 'J':break #
.if myInput == 'K':break #
.if myInput == 'L':break #
.except ValueError:
. print "Oops! That was no valid number.  Try again..."
. pass
.'s are to preserve indents.
fred
Hi fred,
You are missing that raw_input returns a string.
PythonWin 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] 
on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) 
- see 'Help/About PythonWin' for further copyright information.
example = raw_input('Give me a number!')
Give me a number!42
type(example)


I am also not sure why you expected a ValueError:
>>> import string
>>> a = 42
>>> string.upper(a)
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\PYTHON24\lib\string.py", line 235, in upper
return s.upper()
AttributeError: 'int' object has no attribute 'upper'
>>>
Additionally, string methods are often preferred to the string module:
>>> b = 'lower'
>>> b.upper()
'LOWER'
>>>
You might also want to test
if myInput in ('A', 'B', 'C', 'etc'):
.break
instead of your chain of if tests.
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >